Skip to content

Commit fb885ab

Browse files
authored
Patch keygen (#2)
* 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. * Add a comment that explains "type" member. Since openssl uses #defines for identifying operations and libp11 already uses these identifiers, we keep using these for consistency.
1 parent 53d65dc commit fb885ab

11 files changed

+562
-32
lines changed

src/eng_back.c

+65
Original file line numberDiff line numberDiff line change
@@ -890,6 +890,69 @@ 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+
if (p == NULL)
896+
return 0;
897+
int rv = 1;
898+
unsigned int i;
899+
PKCS11_KGEN_ATTRS *kg_attrs = p;
900+
PKCS11_SLOT* slot = NULL;
901+
902+
pthread_mutex_lock(&ctx->lock);
903+
/* Delayed libp11 initialization */
904+
if (ctx_init_libp11_unlocked(ctx)) {
905+
ENGerr(ENG_F_CTX_LOAD_OBJECT, ENG_R_INVALID_PARAMETER);
906+
goto done;
907+
}
908+
909+
// Take the first token that has a matching label
910+
for (i = 0; i < ctx->slot_count; ++i) {
911+
slot = ctx->slot_list + i;
912+
if (slot && slot->token && slot->token->initialized &&
913+
slot->token->label &&
914+
!strncmp(slot->token->label, kg_attrs->token_label, 32)) {
915+
break;
916+
}
917+
}
918+
919+
if (i == ctx->slot_count) {
920+
ctx_log(ctx, 0, "Initialized token with matching label not found...\n");
921+
goto done;
922+
}
923+
924+
/* If login is not forced, try to generate key without logging in first.
925+
* PKCS11_generate_key will fail if login is required so function will
926+
* continue and try to login first
927+
*/
928+
if (!ctx->force_login) {
929+
ERR_clear_error();
930+
rv = PKCS11_generate_key(slot->token, kg_attrs);
931+
if (rv == 0) {
932+
goto done;
933+
}
934+
}
935+
936+
// Try with logging in
937+
ERR_clear_error();
938+
if (slot->token->loginRequired) {
939+
if (!ctx_login(ctx, slot, slot->token,
940+
NULL, NULL)) {
941+
ctx_log(ctx, 0, "Login to token failed, returning 0...\n");
942+
rv = 1;
943+
goto done;
944+
}
945+
rv = PKCS11_generate_key(slot->token, kg_attrs);
946+
if (rv < 0) {
947+
ctx_log(ctx, 0, "Failed to generate a key pair on the token."
948+
" Error code: %d\n", rv);
949+
}
950+
}
951+
952+
done:
953+
pthread_mutex_unlock(&ctx->lock);
954+
return rv ? 0 : 1;
955+
}
893956
/******************************************************************************/
894957
/* Engine ctrl request handling */
895958
/******************************************************************************/
@@ -1008,6 +1071,8 @@ int ctx_engine_ctrl(ENGINE_CTX *ctx, int cmd, long i, void *p, void (*f)())
10081071
return ctx_ctrl_force_login(ctx);
10091072
case CMD_RE_ENUMERATE:
10101073
return ctx_enumerate_slots(ctx, ctx->pkcs11_ctx);
1074+
case CMD_KEYGEN:
1075+
return ctx_keygen(ctx, p);
10111076
default:
10121077
ENGerr(ENG_F_CTX_ENGINE_CTRL, ENG_R_UNKNOWN_COMMAND);
10131078
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, const char *label, unsigned char* id, size_t id_len);
316+
317+
extern int pkcs11_ec_keygen(PKCS11_SLOT_private *tpriv,
318+
const char *curve , const 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

+33-15
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,28 @@ 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+
/* Key generation type from OpenSSL. Given the union below this should
124+
* be either EVP_PKEY_EC or EVP_PKEY_RSA
125+
*/
126+
int type;
127+
union {
128+
PKCS11_EC_KGEN *ec;
129+
PKCS11_RSA_KGEN *rsa;
130+
} kgen;
131+
const char *token_label;
132+
const char *key_label;
133+
const char *key_id;
134+
} PKCS11_KGEN_ATTRS;
135+
114136
/**
115137
* Create a new libp11 context
116138
*
@@ -387,6 +409,17 @@ extern int PKCS11_store_certificate(PKCS11_TOKEN * token, X509 * x509,
387409
char *label, unsigned char *id, size_t id_len,
388410
PKCS11_CERT **ret_cert);
389411

412+
/**
413+
* Generate key pair on the token
414+
*
415+
* @param token on which the key should be generated
416+
* @param kgen_attrs struct describing key generation (selection of algorithm,
417+
* algorithm parameters...)
418+
* @retval 0 on success
419+
* @retval negative number on error
420+
*/
421+
extern int PKCS11_generate_key(PKCS11_TOKEN *token, PKCS11_KGEN_ATTRS *kgen_attrs);
422+
390423
/* Access the random number generator */
391424
extern int PKCS11_seed_random(PKCS11_SLOT *slot, const unsigned char *s, unsigned int s_len);
392425
extern int PKCS11_generate_random(PKCS11_SLOT *slot, unsigned char *r, unsigned int r_len);
@@ -443,21 +476,6 @@ extern void ERR_load_PKCS11_strings(void);
443476
* duplicate the functionality OpenSSL provides for EVP_PKEY objects
444477
*/
445478

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);
461479

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

src/p11_front.c

+26-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,36 @@ 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
{
374+
if (token == NULL || kg == NULL)
375+
return -1;
376376
PKCS11_SLOT_private *slot = PRIVSLOT(token->slot);
377377
if (check_slot_fork(slot) < 0)
378378
return -1;
379-
return pkcs11_generate_key(slot, algorithm, bits, label, id, id_len);
379+
unsigned char out[128] = {0};
380+
size_t key_id_len = 0;
381+
if (kg->key_id) {
382+
key_id_len = strnlen(kg->key_id, 128);
383+
if (key_id_len == 128) {
384+
return -1;
385+
}
386+
pkcs11_hex_to_bin(kg->key_id, out, &key_id_len);
387+
}
388+
switch(kg->type) {
389+
case EVP_PKEY_RSA:
390+
return pkcs11_rsa_keygen(slot, kg->kgen.rsa->bits,
391+
kg->key_label, out, key_id_len);
392+
case EVP_PKEY_EC:
393+
return pkcs11_ec_keygen(slot, kg->kgen.ec->curve,
394+
kg->key_label, out, key_id_len);
395+
default:
396+
return -1;
397+
}
380398
}
381399

400+
/* External interface to the deprecated features */
401+
382402
int PKCS11_get_key_size(PKCS11_KEY *pkey)
383403
{
384404
PKCS11_OBJECT_private *key = PRIVKEY(pkey);

src/p11_key.c

+90-4
Original file line numberDiff line numberDiff line change
@@ -252,8 +252,8 @@ 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,
256-
char *label, unsigned char* id, size_t id_len) {
255+
int pkcs11_rsa_keygen(PKCS11_SLOT_private *slot, unsigned int bits,
256+
const char *label, unsigned char* id, size_t id_len) {
257257

258258
PKCS11_CTX_private *ctx = slot->ctx;
259259
CK_SESSION_HANDLE session;
@@ -266,8 +266,6 @@ 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))
272270
return -1;
273271

@@ -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+
const 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 -1;
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 -1;
341+
342+
curve_obj = OBJ_nid2obj(curve_nid);
343+
if (!curve_obj)
344+
return -1;
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 -1;
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, FALSE);
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)