Skip to content

Commit 8b0da8c

Browse files
committed
Introduce generic keypair generation interface and engine ctrl command
As discussed in OpenSC#379 and OpenSC#378 we need a generic interface that supports multiple algorithms for key generation. Attempt was made to create a new keygen method and register it in PKCS11_pkey_meths() in p11_pkey.c (so that it's possible to generate keys using OpenSSL's EVP_PKEY_* API) but multiple design issues appeared. How and where do you pass the key ID, token label and alike was the first question. As suggested by the maintainer here: OpenSC#379 (comment), app_data from EVP_PKEY_CTX was (mis)used and that worked well. The reason why this approach was abandoned is because a good (or bad) way to get a handle of the PKCS11_CTX_private, that is necessary for the Cryptoki call, was not found. The way other operations work is that they rely on the key being loaded *_first_* through ENGINE_load_public(private)_key because this is when the PKCS11_CTX gets initialized and a handle to PKCS11_OBJECT_private gets set to the ex_data of the underlying key. Key generation obviously cannot rely on that mechanism since key doesn't yet exist. Instead, a generic PKCS11_generate_key interface was made that takes a structure describing the key generation algorithm. For now it only contains simple options like curve name for ECC or number of bits for RSA key generation. This interface can then be used as any other PKCS11 wrapper interface or using the ENGINE control commands. Using it with ENGINE control commands is demonstrated in the new tests/keygen.c file. Code for ECC keygen was taken from: OpenSC#379 and reworked to compile and work with some new additions to libp11 i.e. templates.
1 parent 53d65dc commit 8b0da8c

11 files changed

+543
-32
lines changed

src/eng_back.c

+60
Original file line numberDiff line numberDiff line change
@@ -890,6 +890,64 @@ EVP_PKEY *ctx_load_privkey(ENGINE_CTX *ctx, const char *s_key_id,
890890
return PKCS11_get_private_key(key);
891891
}
892892

893+
static int ctx_keygen(ENGINE_CTX *ctx, void *p)
894+
{
895+
int rv = 1;
896+
int i;
897+
PKCS11_KGEN_ATTRS *kg_attrs = p;
898+
PKCS11_SLOT* slot = NULL;
899+
900+
pthread_mutex_lock(&ctx->lock);
901+
/* Delayed libp11 initialization */
902+
if (ctx_init_libp11_unlocked(ctx)) {
903+
ENGerr(ENG_F_CTX_LOAD_OBJECT, ENG_R_INVALID_PARAMETER);
904+
goto done;
905+
}
906+
907+
// Take the first token that has a matching label
908+
// TODO: make this more intelligent
909+
for (i = 0; i < ctx->slot_count; ++i) {
910+
slot = ctx->slot_list + i;
911+
if (slot && slot->token && slot->token->initialized &&
912+
slot->token->label &&
913+
!strncmp(slot->token->label, kg_attrs->token_label, 32)) {
914+
break;
915+
}
916+
}
917+
918+
if (i == ctx->slot_count) {
919+
ctx_log(ctx, 0, "Initialized token with matching label not found...\n");
920+
goto done;
921+
}
922+
923+
if (!ctx->force_login) {
924+
ERR_clear_error();
925+
rv = PKCS11_generate_key(slot->token, kg_attrs);
926+
if (rv == 0) {
927+
goto done;
928+
}
929+
}
930+
931+
// Try with logging in
932+
ERR_clear_error();
933+
if (slot->token->loginRequired) {
934+
if (!ctx_login(ctx, slot, slot->token,
935+
NULL, NULL)) {
936+
ctx_log(ctx, 0, "Login to token failed, returning 0...\n");
937+
rv = 1;
938+
goto done;
939+
}
940+
rv = PKCS11_generate_key(slot->token, kg_attrs);
941+
if (rv < 0) {
942+
ctx_log(ctx, 0, "Failed to generate a key pair on the token."
943+
" Error code: %d\n", rv);
944+
}
945+
}
946+
947+
done:
948+
pthread_mutex_unlock(&ctx->lock);
949+
return rv ? 0 : 1;
950+
}
893951
/******************************************************************************/
894952
/* Engine ctrl request handling */
895953
/******************************************************************************/
@@ -1008,6 +1066,8 @@ int ctx_engine_ctrl(ENGINE_CTX *ctx, int cmd, long i, void *p, void (*f)())
10081066
return ctx_ctrl_force_login(ctx);
10091067
case CMD_RE_ENUMERATE:
10101068
return ctx_enumerate_slots(ctx, ctx->pkcs11_ctx);
1069+
case CMD_KEYGEN:
1070+
return ctx_keygen(ctx, p);
10111071
default:
10121072
ENGerr(ENG_F_CTX_ENGINE_CTRL, ENG_R_UNKNOWN_COMMAND);
10131073
break;

src/eng_front.c

+4
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,10 @@ static const ENGINE_CMD_DEFN engine_cmd_defns[] = {
7979
"RE_ENUMERATE",
8080
"re enumerate slots",
8181
ENGINE_CMD_FLAG_NO_INPUT},
82+
{CMD_KEYGEN,
83+
"KEYGEN",
84+
"Generate asymmetric key pair",
85+
ENGINE_CMD_FLAG_INTERNAL},
8286
{0, NULL, NULL, 0}
8387
};
8488

src/engine.h

+1
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@
5252
#define CMD_SET_CALLBACK_DATA (ENGINE_CMD_BASE + 8)
5353
#define CMD_FORCE_LOGIN (ENGINE_CMD_BASE+9)
5454
#define CMD_RE_ENUMERATE (ENGINE_CMD_BASE+10)
55+
#define CMD_KEYGEN (ENGINE_CMD_BASE+11)
5556

5657
typedef struct st_engine_ctx ENGINE_CTX; /* opaque */
5758

src/libp11-int.h

+10-5
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,9 @@ extern int ERR_load_CKR_strings(void);
125125
pkcs11_strdup((char *) s, sizeof(s))
126126
extern char *pkcs11_strdup(char *, size_t);
127127

128+
/* Hex to bin */
129+
extern int pkcs11_hex_to_bin(const char *, unsigned char *, size_t *);
130+
128131
/* Emulate the OpenSSL 1.1 getters */
129132
#if OPENSSL_VERSION_NUMBER < 0x10100003L || ( defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x3000000L )
130133
#define EVP_PKEY_get0_RSA(key) ((key)->pkey.rsa)
@@ -307,12 +310,14 @@ extern int pkcs11_store_certificate(PKCS11_SLOT_private *, X509 * x509,
307310
extern int pkcs11_seed_random(PKCS11_SLOT_private *, const unsigned char *s, unsigned int s_len);
308311
extern int pkcs11_generate_random(PKCS11_SLOT_private *, unsigned char *r, unsigned int r_len);
309312

310-
/* Internal implementation of deprecated features */
311-
312313
/* Generate and store a private key on the token */
313-
extern int pkcs11_generate_key(PKCS11_SLOT_private *tpriv,
314-
int algorithm, unsigned int bits,
315-
char *label, unsigned char* id, size_t id_len);
314+
extern int pkcs11_rsa_keygen(PKCS11_SLOT_private *tpriv,
315+
unsigned int bits, char *label, unsigned char* id, size_t id_len);
316+
317+
extern int pkcs11_ec_keygen(PKCS11_SLOT_private *tpriv,
318+
const char *curve , char *label, unsigned char* id, size_t id_len);
319+
320+
/* Internal implementation of deprecated features */
316321

317322
/* Get the RSA key modulus size (in bytes) */
318323
extern int pkcs11_get_key_size(PKCS11_OBJECT_private *);

src/libp11.h

+30-15
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,25 @@ typedef struct PKCS11_ctx_st {
111111
void *_private;
112112
} PKCS11_CTX;
113113

114+
typedef struct PKCS11_ec_kgen_st {
115+
const char *curve;
116+
} PKCS11_EC_KGEN;
117+
118+
typedef struct PKCS11_rsa_kgen_st {
119+
unsigned int bits;
120+
} PKCS11_RSA_KGEN;
121+
122+
typedef struct PKCS11_kgen_attrs_st {
123+
int type;
124+
union {
125+
PKCS11_EC_KGEN *ec;
126+
PKCS11_RSA_KGEN *rsa;
127+
} kgen;
128+
char *token_label;
129+
char *key_label;
130+
char *key_id;
131+
} PKCS11_KGEN_ATTRS;
132+
114133
/**
115134
* Create a new libp11 context
116135
*
@@ -387,6 +406,17 @@ extern int PKCS11_store_certificate(PKCS11_TOKEN * token, X509 * x509,
387406
char *label, unsigned char *id, size_t id_len,
388407
PKCS11_CERT **ret_cert);
389408

409+
/**
410+
* Generate key pair on the token
411+
*
412+
* @param token on which the key should be generated
413+
* @param kgen_attrs struct describing key generation (selection of algorithm,
414+
* algorithm parameters...)
415+
* @retval 0 on success
416+
* @retval negative number on error
417+
*/
418+
extern int PKCS11_generate_key(PKCS11_TOKEN *token, PKCS11_KGEN_ATTRS *kgen_attrs);
419+
390420
/* Access the random number generator */
391421
extern int PKCS11_seed_random(PKCS11_SLOT *slot, const unsigned char *s, unsigned int s_len);
392422
extern int PKCS11_generate_random(PKCS11_SLOT *slot, unsigned char *r, unsigned int r_len);
@@ -443,21 +473,6 @@ extern void ERR_load_PKCS11_strings(void);
443473
* duplicate the functionality OpenSSL provides for EVP_PKEY objects
444474
*/
445475

446-
/**
447-
* Generate a private key on the token
448-
*
449-
* @param token token returned by PKCS11_find_token()
450-
* @param algorithm IGNORED (still here for backward compatibility)
451-
* @param bits size of the modulus in bits
452-
* @param label label for this key
453-
* @param id bytes to use as the id value
454-
* @param id_len length of the id value
455-
* @retval 0 success
456-
* @retval -1 error
457-
*/
458-
P11_DEPRECATED_FUNC extern int PKCS11_generate_key(PKCS11_TOKEN * token,
459-
int algorithm, unsigned int bits,
460-
char *label, unsigned char* id, size_t id_len);
461476

462477
/* Get the RSA key modulus size (in bytes) */
463478
P11_DEPRECATED_FUNC extern int PKCS11_get_key_size(PKCS11_KEY *);

src/p11_front.c

+24-6
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
1717
*/
1818

19+
#include <string.h>
20+
1921
#include "libp11-int.h"
2022

2123
/* The following exported functions are *not* implemented here:
@@ -367,18 +369,34 @@ int PKCS11_set_ui_method(PKCS11_CTX *pctx, UI_METHOD *ui_method, void *ui_user_d
367369
return pkcs11_set_ui_method(ctx, ui_method, ui_user_data);
368370
}
369371

370-
/* External interface to the deprecated features */
371-
372-
int PKCS11_generate_key(PKCS11_TOKEN *token,
373-
int algorithm, unsigned int bits,
374-
char *label, unsigned char *id, size_t id_len)
372+
int PKCS11_generate_key(PKCS11_TOKEN *token, PKCS11_KGEN_ATTRS *kg)
375373
{
376374
PKCS11_SLOT_private *slot = PRIVSLOT(token->slot);
377375
if (check_slot_fork(slot) < 0)
378376
return -1;
379-
return pkcs11_generate_key(slot, algorithm, bits, label, id, id_len);
377+
unsigned char out[128] = {0};
378+
size_t key_id_len = 0;
379+
if (kg && kg->key_id) {
380+
key_id_len = strlen(kg->key_id);
381+
if (key_id_len > 127) {
382+
return -2;
383+
}
384+
pkcs11_hex_to_bin(kg->key_id, out, &key_id_len);
385+
}
386+
switch(kg->type) {
387+
case EVP_PKEY_RSA:
388+
return pkcs11_rsa_keygen(slot, kg->kgen.rsa->bits,
389+
kg->key_label, out, key_id_len);
390+
case EVP_PKEY_EC:
391+
return pkcs11_ec_keygen(slot, kg->kgen.ec->curve,
392+
kg->key_label, out, key_id_len);
393+
default:
394+
return -3;
395+
}
380396
}
381397

398+
/* External interface to the deprecated features */
399+
382400
int PKCS11_get_key_size(PKCS11_KEY *pkey)
383401
{
384402
PKCS11_OBJECT_private *key = PRIVKEY(pkey);

src/p11_key.c

+90-4
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,7 @@ int pkcs11_reload_object(PKCS11_OBJECT_private *obj)
252252
/**
253253
* Generate a key pair directly on token
254254
*/
255-
int pkcs11_generate_key(PKCS11_SLOT_private *slot, int algorithm, unsigned int bits,
255+
int pkcs11_rsa_keygen(PKCS11_SLOT_private *slot, unsigned int bits,
256256
char *label, unsigned char* id, size_t id_len) {
257257

258258
PKCS11_CTX_private *ctx = slot->ctx;
@@ -266,10 +266,8 @@ int pkcs11_generate_key(PKCS11_SLOT_private *slot, int algorithm, unsigned int b
266266
CK_OBJECT_HANDLE pub_key_obj, priv_key_obj;
267267
int rv;
268268

269-
(void)algorithm; /* squash the unused parameter warning */
270-
271269
if (pkcs11_get_session(slot, 1, &session))
272-
return -1;
270+
return -10;
273271

274272
/* pubkey attributes */
275273
pkcs11_addattr(&pubtmpl, CKA_ID, id, id_len);
@@ -310,6 +308,94 @@ int pkcs11_generate_key(PKCS11_SLOT_private *slot, int algorithm, unsigned int b
310308
return 0;
311309
}
312310

311+
int pkcs11_ec_keygen(PKCS11_SLOT_private *slot, const char *curve,
312+
char *label, unsigned char *id, size_t id_len)
313+
{
314+
PKCS11_CTX_private *ctx = slot->ctx;
315+
CK_SESSION_HANDLE session;
316+
PKCS11_TEMPLATE pubtmpl = {0}, privtmpl = {0};
317+
CK_MECHANISM mechanism = {
318+
CKM_EC_KEY_PAIR_GEN, NULL_PTR, 0
319+
};
320+
321+
CK_OBJECT_HANDLE pub_key_obj, priv_key_obj;
322+
int rv;
323+
324+
unsigned char *ecdsa_params = NULL;
325+
int ecdsa_params_len = 0;
326+
unsigned char *tmp = NULL;
327+
ASN1_OBJECT *curve_obj = NULL;
328+
int curve_nid = NID_undef;
329+
330+
if (pkcs11_get_session(slot, 1, &session)) {
331+
return -20;
332+
}
333+
334+
curve_nid = EC_curve_nist2nid(curve);
335+
if (curve_nid == NID_undef)
336+
curve_nid = OBJ_sn2nid(curve);
337+
if (curve_nid == NID_undef)
338+
curve_nid = OBJ_ln2nid(curve);
339+
if (curve_nid == NID_undef)
340+
return -21;
341+
342+
curve_obj = OBJ_nid2obj(curve_nid);
343+
if (!curve_obj)
344+
return -22;
345+
ecdsa_params_len = i2d_ASN1_OBJECT(curve_obj, NULL);
346+
ecdsa_params = (unsigned char *)OPENSSL_malloc(ecdsa_params_len);
347+
if (!ecdsa_params)
348+
return -23;
349+
tmp = ecdsa_params;
350+
i2d_ASN1_OBJECT(curve_obj, &tmp);
351+
352+
/* pubkey attributes */
353+
pkcs11_addattr(&pubtmpl, CKA_ID, id, id_len);
354+
if (label)
355+
pkcs11_addattr_s(&pubtmpl, CKA_LABEL, label);
356+
pkcs11_addattr_bool(&pubtmpl, CKA_TOKEN, TRUE);
357+
pkcs11_addattr_bool(&pubtmpl, CKA_DERIVE, TRUE);
358+
pkcs11_addattr_bool(&pubtmpl, CKA_WRAP, FALSE);
359+
pkcs11_addattr_bool(&pubtmpl, CKA_VERIFY, TRUE);
360+
pkcs11_addattr_bool(&pubtmpl, CKA_VERIFY_RECOVER, FALSE);
361+
pkcs11_addattr_bool(&pubtmpl, CKA_ENCRYPT, FALSE);
362+
pkcs11_addattr(&pubtmpl, CKA_ECDSA_PARAMS, ecdsa_params, ecdsa_params_len);
363+
364+
/* privkey attributes */
365+
pkcs11_addattr(&privtmpl, CKA_ID, id, id_len);
366+
if (label)
367+
pkcs11_addattr_s(&privtmpl, CKA_LABEL, label);
368+
pkcs11_addattr_bool(&privtmpl, CKA_TOKEN, TRUE);
369+
pkcs11_addattr_bool(&privtmpl, CKA_PRIVATE, TRUE);
370+
pkcs11_addattr_bool(&privtmpl, CKA_SENSITIVE, TRUE);
371+
pkcs11_addattr_bool(&privtmpl, CKA_DERIVE, TRUE);
372+
pkcs11_addattr_bool(&privtmpl, CKA_UNWRAP, FALSE);
373+
pkcs11_addattr_bool(&privtmpl, CKA_SIGN, TRUE);
374+
pkcs11_addattr_bool(&privtmpl, CKA_DECRYPT, FALSE);
375+
376+
/* call the pkcs11 module to create the key pair */
377+
rv = CRYPTOKI_call(ctx, C_GenerateKeyPair(
378+
session,
379+
&mechanism,
380+
pubtmpl.attrs,
381+
pubtmpl.nattr,
382+
privtmpl.attrs,
383+
privtmpl.nattr,
384+
&pub_key_obj,
385+
&priv_key_obj
386+
));
387+
388+
pkcs11_put_session(slot, session);
389+
390+
/* zap all memory allocated when building the template */
391+
pkcs11_zap_attrs(&privtmpl);
392+
pkcs11_zap_attrs(&pubtmpl);
393+
OPENSSL_free(ecdsa_params);
394+
395+
CRYPTOKI_checkerr(CKR_F_PKCS11_GENERATE_KEY, rv);
396+
return 0;
397+
}
398+
313399
/*
314400
* Store a private key on the token
315401
*/

0 commit comments

Comments
 (0)