Skip to content

Commit

Permalink
Patch keygen (#2)
Browse files Browse the repository at this point in the history
* 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.
  • Loading branch information
istepic committed Dec 5, 2022
1 parent 53d65dc commit fb885ab
Show file tree
Hide file tree
Showing 11 changed files with 562 additions and 32 deletions.
65 changes: 65 additions & 0 deletions src/eng_back.c
Original file line number Diff line number Diff line change
Expand Up @@ -890,6 +890,69 @@ EVP_PKEY *ctx_load_privkey(ENGINE_CTX *ctx, const char *s_key_id,
return PKCS11_get_private_key(key);
}

static int ctx_keygen(ENGINE_CTX *ctx, void *p)
{
if (p == NULL)
return 0;
int rv = 1;
unsigned int i;
PKCS11_KGEN_ATTRS *kg_attrs = p;
PKCS11_SLOT* slot = NULL;

pthread_mutex_lock(&ctx->lock);
/* Delayed libp11 initialization */
if (ctx_init_libp11_unlocked(ctx)) {
ENGerr(ENG_F_CTX_LOAD_OBJECT, ENG_R_INVALID_PARAMETER);
goto done;
}

// Take the first token that has a matching label
for (i = 0; i < ctx->slot_count; ++i) {
slot = ctx->slot_list + i;
if (slot && slot->token && slot->token->initialized &&
slot->token->label &&
!strncmp(slot->token->label, kg_attrs->token_label, 32)) {
break;
}
}

if (i == ctx->slot_count) {
ctx_log(ctx, 0, "Initialized token with matching label not found...\n");
goto done;
}

/* If login is not forced, try to generate key without logging in first.
* PKCS11_generate_key will fail if login is required so function will
* continue and try to login first
*/
if (!ctx->force_login) {
ERR_clear_error();
rv = PKCS11_generate_key(slot->token, kg_attrs);
if (rv == 0) {
goto done;
}
}

// Try with logging in
ERR_clear_error();
if (slot->token->loginRequired) {
if (!ctx_login(ctx, slot, slot->token,
NULL, NULL)) {
ctx_log(ctx, 0, "Login to token failed, returning 0...\n");
rv = 1;
goto done;
}
rv = PKCS11_generate_key(slot->token, kg_attrs);
if (rv < 0) {
ctx_log(ctx, 0, "Failed to generate a key pair on the token."
" Error code: %d\n", rv);
}
}

done:
pthread_mutex_unlock(&ctx->lock);
return rv ? 0 : 1;
}
/******************************************************************************/
/* Engine ctrl request handling */
/******************************************************************************/
Expand Down Expand Up @@ -1008,6 +1071,8 @@ int ctx_engine_ctrl(ENGINE_CTX *ctx, int cmd, long i, void *p, void (*f)())
return ctx_ctrl_force_login(ctx);
case CMD_RE_ENUMERATE:
return ctx_enumerate_slots(ctx, ctx->pkcs11_ctx);
case CMD_KEYGEN:
return ctx_keygen(ctx, p);
default:
ENGerr(ENG_F_CTX_ENGINE_CTRL, ENG_R_UNKNOWN_COMMAND);
break;
Expand Down
4 changes: 4 additions & 0 deletions src/eng_front.c
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,10 @@ static const ENGINE_CMD_DEFN engine_cmd_defns[] = {
"RE_ENUMERATE",
"re enumerate slots",
ENGINE_CMD_FLAG_NO_INPUT},
{CMD_KEYGEN,
"KEYGEN",
"Generate asymmetric key pair",
ENGINE_CMD_FLAG_INTERNAL},
{0, NULL, NULL, 0}
};

Expand Down
1 change: 1 addition & 0 deletions src/engine.h
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
#define CMD_SET_CALLBACK_DATA (ENGINE_CMD_BASE + 8)
#define CMD_FORCE_LOGIN (ENGINE_CMD_BASE+9)
#define CMD_RE_ENUMERATE (ENGINE_CMD_BASE+10)
#define CMD_KEYGEN (ENGINE_CMD_BASE+11)

typedef struct st_engine_ctx ENGINE_CTX; /* opaque */

Expand Down
15 changes: 10 additions & 5 deletions src/libp11-int.h
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,9 @@ extern int ERR_load_CKR_strings(void);
pkcs11_strdup((char *) s, sizeof(s))
extern char *pkcs11_strdup(char *, size_t);

/* Hex to bin */
extern int pkcs11_hex_to_bin(const char *, unsigned char *, size_t *);

/* Emulate the OpenSSL 1.1 getters */
#if OPENSSL_VERSION_NUMBER < 0x10100003L || ( defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x3000000L )
#define EVP_PKEY_get0_RSA(key) ((key)->pkey.rsa)
Expand Down Expand Up @@ -307,12 +310,14 @@ extern int pkcs11_store_certificate(PKCS11_SLOT_private *, X509 * x509,
extern int pkcs11_seed_random(PKCS11_SLOT_private *, const unsigned char *s, unsigned int s_len);
extern int pkcs11_generate_random(PKCS11_SLOT_private *, unsigned char *r, unsigned int r_len);

/* Internal implementation of deprecated features */

/* Generate and store a private key on the token */
extern int pkcs11_generate_key(PKCS11_SLOT_private *tpriv,
int algorithm, unsigned int bits,
char *label, unsigned char* id, size_t id_len);
extern int pkcs11_rsa_keygen(PKCS11_SLOT_private *tpriv,
unsigned int bits, const char *label, unsigned char* id, size_t id_len);

extern int pkcs11_ec_keygen(PKCS11_SLOT_private *tpriv,
const char *curve , const char *label, unsigned char* id, size_t id_len);

/* Internal implementation of deprecated features */

/* Get the RSA key modulus size (in bytes) */
extern int pkcs11_get_key_size(PKCS11_OBJECT_private *);
Expand Down
48 changes: 33 additions & 15 deletions src/libp11.h
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,28 @@ typedef struct PKCS11_ctx_st {
void *_private;
} PKCS11_CTX;

typedef struct PKCS11_ec_kgen_st {
const char *curve;
} PKCS11_EC_KGEN;

typedef struct PKCS11_rsa_kgen_st {
unsigned int bits;
} PKCS11_RSA_KGEN;

typedef struct PKCS11_kgen_attrs_st {
/* Key generation type from OpenSSL. Given the union below this should
* be either EVP_PKEY_EC or EVP_PKEY_RSA
*/
int type;
union {
PKCS11_EC_KGEN *ec;
PKCS11_RSA_KGEN *rsa;
} kgen;
const char *token_label;
const char *key_label;
const char *key_id;
} PKCS11_KGEN_ATTRS;

/**
* Create a new libp11 context
*
Expand Down Expand Up @@ -387,6 +409,17 @@ extern int PKCS11_store_certificate(PKCS11_TOKEN * token, X509 * x509,
char *label, unsigned char *id, size_t id_len,
PKCS11_CERT **ret_cert);

/**
* Generate key pair on the token
*
* @param token on which the key should be generated
* @param kgen_attrs struct describing key generation (selection of algorithm,
* algorithm parameters...)
* @retval 0 on success
* @retval negative number on error
*/
extern int PKCS11_generate_key(PKCS11_TOKEN *token, PKCS11_KGEN_ATTRS *kgen_attrs);

/* Access the random number generator */
extern int PKCS11_seed_random(PKCS11_SLOT *slot, const unsigned char *s, unsigned int s_len);
extern int PKCS11_generate_random(PKCS11_SLOT *slot, unsigned char *r, unsigned int r_len);
Expand Down Expand Up @@ -443,21 +476,6 @@ extern void ERR_load_PKCS11_strings(void);
* duplicate the functionality OpenSSL provides for EVP_PKEY objects
*/

/**
* Generate a private key on the token
*
* @param token token returned by PKCS11_find_token()
* @param algorithm IGNORED (still here for backward compatibility)
* @param bits size of the modulus in bits
* @param label label for this key
* @param id bytes to use as the id value
* @param id_len length of the id value
* @retval 0 success
* @retval -1 error
*/
P11_DEPRECATED_FUNC extern int PKCS11_generate_key(PKCS11_TOKEN * token,
int algorithm, unsigned int bits,
char *label, unsigned char* id, size_t id_len);

/* Get the RSA key modulus size (in bytes) */
P11_DEPRECATED_FUNC extern int PKCS11_get_key_size(PKCS11_KEY *);
Expand Down
32 changes: 26 additions & 6 deletions src/p11_front.c
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/

#include <string.h>

#include "libp11-int.h"

/* The following exported functions are *not* implemented here:
Expand Down Expand Up @@ -367,18 +369,36 @@ int PKCS11_set_ui_method(PKCS11_CTX *pctx, UI_METHOD *ui_method, void *ui_user_d
return pkcs11_set_ui_method(ctx, ui_method, ui_user_data);
}

/* External interface to the deprecated features */

int PKCS11_generate_key(PKCS11_TOKEN *token,
int algorithm, unsigned int bits,
char *label, unsigned char *id, size_t id_len)
int PKCS11_generate_key(PKCS11_TOKEN *token, PKCS11_KGEN_ATTRS *kg)
{
if (token == NULL || kg == NULL)
return -1;
PKCS11_SLOT_private *slot = PRIVSLOT(token->slot);
if (check_slot_fork(slot) < 0)
return -1;
return pkcs11_generate_key(slot, algorithm, bits, label, id, id_len);
unsigned char out[128] = {0};
size_t key_id_len = 0;
if (kg->key_id) {
key_id_len = strnlen(kg->key_id, 128);
if (key_id_len == 128) {
return -1;
}
pkcs11_hex_to_bin(kg->key_id, out, &key_id_len);
}
switch(kg->type) {
case EVP_PKEY_RSA:
return pkcs11_rsa_keygen(slot, kg->kgen.rsa->bits,
kg->key_label, out, key_id_len);
case EVP_PKEY_EC:
return pkcs11_ec_keygen(slot, kg->kgen.ec->curve,
kg->key_label, out, key_id_len);
default:
return -1;
}
}

/* External interface to the deprecated features */

int PKCS11_get_key_size(PKCS11_KEY *pkey)
{
PKCS11_OBJECT_private *key = PRIVKEY(pkey);
Expand Down
94 changes: 90 additions & 4 deletions src/p11_key.c
Original file line number Diff line number Diff line change
Expand Up @@ -252,8 +252,8 @@ int pkcs11_reload_object(PKCS11_OBJECT_private *obj)
/**
* Generate a key pair directly on token
*/
int pkcs11_generate_key(PKCS11_SLOT_private *slot, int algorithm, unsigned int bits,
char *label, unsigned char* id, size_t id_len) {
int pkcs11_rsa_keygen(PKCS11_SLOT_private *slot, unsigned int bits,
const char *label, unsigned char* id, size_t id_len) {

PKCS11_CTX_private *ctx = slot->ctx;
CK_SESSION_HANDLE session;
Expand All @@ -266,8 +266,6 @@ int pkcs11_generate_key(PKCS11_SLOT_private *slot, int algorithm, unsigned int b
CK_OBJECT_HANDLE pub_key_obj, priv_key_obj;
int rv;

(void)algorithm; /* squash the unused parameter warning */

if (pkcs11_get_session(slot, 1, &session))
return -1;

Expand Down Expand Up @@ -310,6 +308,94 @@ int pkcs11_generate_key(PKCS11_SLOT_private *slot, int algorithm, unsigned int b
return 0;
}

int pkcs11_ec_keygen(PKCS11_SLOT_private *slot, const char *curve,
const char *label, unsigned char *id, size_t id_len)
{
PKCS11_CTX_private *ctx = slot->ctx;
CK_SESSION_HANDLE session;
PKCS11_TEMPLATE pubtmpl = {0}, privtmpl = {0};
CK_MECHANISM mechanism = {
CKM_EC_KEY_PAIR_GEN, NULL_PTR, 0
};

CK_OBJECT_HANDLE pub_key_obj, priv_key_obj;
int rv;

unsigned char *ecdsa_params = NULL;
int ecdsa_params_len = 0;
unsigned char *tmp = NULL;
ASN1_OBJECT *curve_obj = NULL;
int curve_nid = NID_undef;

if (pkcs11_get_session(slot, 1, &session)) {
return -1;
}

curve_nid = EC_curve_nist2nid(curve);
if (curve_nid == NID_undef)
curve_nid = OBJ_sn2nid(curve);
if (curve_nid == NID_undef)
curve_nid = OBJ_ln2nid(curve);
if (curve_nid == NID_undef)
return -1;

curve_obj = OBJ_nid2obj(curve_nid);
if (!curve_obj)
return -1;
ecdsa_params_len = i2d_ASN1_OBJECT(curve_obj, NULL);
ecdsa_params = (unsigned char *)OPENSSL_malloc(ecdsa_params_len);
if (!ecdsa_params)
return -1;
tmp = ecdsa_params;
i2d_ASN1_OBJECT(curve_obj, &tmp);

/* pubkey attributes */
pkcs11_addattr(&pubtmpl, CKA_ID, id, id_len);
if (label)
pkcs11_addattr_s(&pubtmpl, CKA_LABEL, label);
pkcs11_addattr_bool(&pubtmpl, CKA_TOKEN, TRUE);
pkcs11_addattr_bool(&pubtmpl, CKA_DERIVE, FALSE);
pkcs11_addattr_bool(&pubtmpl, CKA_WRAP, FALSE);
pkcs11_addattr_bool(&pubtmpl, CKA_VERIFY, TRUE);
pkcs11_addattr_bool(&pubtmpl, CKA_VERIFY_RECOVER, FALSE);
pkcs11_addattr_bool(&pubtmpl, CKA_ENCRYPT, FALSE);
pkcs11_addattr(&pubtmpl, CKA_ECDSA_PARAMS, ecdsa_params, ecdsa_params_len);

/* privkey attributes */
pkcs11_addattr(&privtmpl, CKA_ID, id, id_len);
if (label)
pkcs11_addattr_s(&privtmpl, CKA_LABEL, label);
pkcs11_addattr_bool(&privtmpl, CKA_TOKEN, TRUE);
pkcs11_addattr_bool(&privtmpl, CKA_PRIVATE, TRUE);
pkcs11_addattr_bool(&privtmpl, CKA_SENSITIVE, TRUE);
pkcs11_addattr_bool(&privtmpl, CKA_DERIVE, TRUE);
pkcs11_addattr_bool(&privtmpl, CKA_UNWRAP, FALSE);
pkcs11_addattr_bool(&privtmpl, CKA_SIGN, TRUE);
pkcs11_addattr_bool(&privtmpl, CKA_DECRYPT, FALSE);

/* call the pkcs11 module to create the key pair */
rv = CRYPTOKI_call(ctx, C_GenerateKeyPair(
session,
&mechanism,
pubtmpl.attrs,
pubtmpl.nattr,
privtmpl.attrs,
privtmpl.nattr,
&pub_key_obj,
&priv_key_obj
));

pkcs11_put_session(slot, session);

/* zap all memory allocated when building the template */
pkcs11_zap_attrs(&privtmpl);
pkcs11_zap_attrs(&pubtmpl);
OPENSSL_free(ecdsa_params);

CRYPTOKI_checkerr(CKR_F_PKCS11_GENERATE_KEY, rv);
return 0;
}

/*
* Store a private key on the token
*/
Expand Down
Loading

0 comments on commit fb885ab

Please sign in to comment.