1 /* $OpenBSD: ssh-pkcs11.c,v 1.26 2018/02/07 02:06:51 jsing Exp $ */
3 * Copyright (c) 2010 Markus Friedl. All rights reserved.
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
22 #include <sys/types.h>
23 #ifdef HAVE_SYS_TIME_H
24 # include <sys/time.h>
32 #include "openbsd-compat/sys-queue.h"
34 #include <openssl/x509.h>
36 #define CRYPTOKI_COMPAT
42 #include "ssh-pkcs11.h"
45 struct pkcs11_slotinfo {
47 CK_SESSION_HANDLE session;
51 struct pkcs11_provider {
54 CK_FUNCTION_LIST *function_list;
58 struct pkcs11_slotinfo *slotinfo;
61 TAILQ_ENTRY(pkcs11_provider) next;
64 TAILQ_HEAD(, pkcs11_provider) pkcs11_providers;
67 struct pkcs11_provider *provider;
69 int (*orig_finish)(RSA *rsa);
70 RSA_METHOD *rsa_method;
75 int pkcs11_interactive = 0;
78 pkcs11_init(int interactive)
80 pkcs11_interactive = interactive;
81 TAILQ_INIT(&pkcs11_providers);
86 * finalize a provider shared libarary, it's no longer usable.
87 * however, there might still be keys referencing this provider,
88 * so the actuall freeing of memory is handled by pkcs11_provider_unref().
89 * this is called when a provider gets unregistered.
92 pkcs11_provider_finalize(struct pkcs11_provider *p)
97 debug("pkcs11_provider_finalize: %p refcount %d valid %d",
98 p, p->refcount, p->valid);
101 for (i = 0; i < p->nslots; i++) {
102 if (p->slotinfo[i].session &&
103 (rv = p->function_list->C_CloseSession(
104 p->slotinfo[i].session)) != CKR_OK)
105 error("C_CloseSession failed: %lu", rv);
107 if ((rv = p->function_list->C_Finalize(NULL)) != CKR_OK)
108 error("C_Finalize failed: %lu", rv);
110 p->function_list = NULL;
115 * remove a reference to the provider.
116 * called when a key gets destroyed or when the provider is unregistered.
119 pkcs11_provider_unref(struct pkcs11_provider *p)
121 debug("pkcs11_provider_unref: %p refcount %d", p, p->refcount);
122 if (--p->refcount <= 0) {
124 error("pkcs11_provider_unref: %p still valid", p);
131 /* unregister all providers, keys might still point to the providers */
133 pkcs11_terminate(void)
135 struct pkcs11_provider *p;
137 while ((p = TAILQ_FIRST(&pkcs11_providers)) != NULL) {
138 TAILQ_REMOVE(&pkcs11_providers, p, next);
139 pkcs11_provider_finalize(p);
140 pkcs11_provider_unref(p);
144 /* lookup provider by name */
145 static struct pkcs11_provider *
146 pkcs11_provider_lookup(char *provider_id)
148 struct pkcs11_provider *p;
150 TAILQ_FOREACH(p, &pkcs11_providers, next) {
151 debug("check %p %s", p, p->name);
152 if (!strcmp(provider_id, p->name))
158 /* unregister provider by name */
160 pkcs11_del_provider(char *provider_id)
162 struct pkcs11_provider *p;
164 if ((p = pkcs11_provider_lookup(provider_id)) != NULL) {
165 TAILQ_REMOVE(&pkcs11_providers, p, next);
166 pkcs11_provider_finalize(p);
167 pkcs11_provider_unref(p);
173 /* openssl callback for freeing an RSA key */
175 pkcs11_rsa_finish(RSA *rsa)
177 struct pkcs11_key *k11;
180 if ((k11 = RSA_get_app_data(rsa)) != NULL) {
181 if (k11->orig_finish)
182 rv = k11->orig_finish(rsa);
184 pkcs11_provider_unref(k11->provider);
191 /* find a single 'obj' for given attributes */
193 pkcs11_find(struct pkcs11_provider *p, CK_ULONG slotidx, CK_ATTRIBUTE *attr,
194 CK_ULONG nattr, CK_OBJECT_HANDLE *obj)
197 CK_SESSION_HANDLE session;
202 f = p->function_list;
203 session = p->slotinfo[slotidx].session;
204 if ((rv = f->C_FindObjectsInit(session, attr, nattr)) != CKR_OK) {
205 error("C_FindObjectsInit failed (nattr %lu): %lu", nattr, rv);
208 if ((rv = f->C_FindObjects(session, obj, 1, &nfound)) != CKR_OK ||
210 debug("C_FindObjects failed (nfound %lu nattr %lu): %lu",
214 if ((rv = f->C_FindObjectsFinal(session)) != CKR_OK)
215 error("C_FindObjectsFinal failed: %lu", rv);
219 /* openssl callback doing the actual signing operation */
221 pkcs11_rsa_private_encrypt(int flen, const u_char *from, u_char *to, RSA *rsa,
224 struct pkcs11_key *k11;
225 struct pkcs11_slotinfo *si;
227 CK_OBJECT_HANDLE obj;
230 CK_OBJECT_CLASS private_key_class = CKO_PRIVATE_KEY;
231 CK_BBOOL true_val = CK_TRUE;
232 CK_MECHANISM mech = {
233 CKM_RSA_PKCS, NULL_PTR, 0
235 CK_ATTRIBUTE key_filter[] = {
236 {CKA_CLASS, NULL, sizeof(private_key_class) },
238 {CKA_SIGN, NULL, sizeof(true_val) }
240 char *pin = NULL, prompt[1024];
243 key_filter[0].pValue = &private_key_class;
244 key_filter[2].pValue = &true_val;
246 if ((k11 = RSA_get_app_data(rsa)) == NULL) {
247 error("RSA_get_app_data failed for rsa %p", rsa);
250 if (!k11->provider || !k11->provider->valid) {
251 error("no pkcs11 (valid) provider for rsa %p", rsa);
254 f = k11->provider->function_list;
255 si = &k11->provider->slotinfo[k11->slotidx];
256 if ((si->token.flags & CKF_LOGIN_REQUIRED) && !si->logged_in) {
257 if (!pkcs11_interactive) {
258 error("need pin entry%s", (si->token.flags &
259 CKF_PROTECTED_AUTHENTICATION_PATH) ?
260 " on reader keypad" : "");
263 if (si->token.flags & CKF_PROTECTED_AUTHENTICATION_PATH)
264 verbose("Deferring PIN entry to reader keypad.");
266 snprintf(prompt, sizeof(prompt),
267 "Enter PIN for '%s': ", si->token.label);
268 pin = read_passphrase(prompt, RP_ALLOW_EOF);
270 return (-1); /* bail out */
272 rv = f->C_Login(si->session, CKU_USER, (u_char *)pin,
273 (pin != NULL) ? strlen(pin) : 0);
275 explicit_bzero(pin, strlen(pin));
278 if (rv != CKR_OK && rv != CKR_USER_ALREADY_LOGGED_IN) {
279 error("C_Login failed: %lu", rv);
284 key_filter[1].pValue = k11->keyid;
285 key_filter[1].ulValueLen = k11->keyid_len;
286 /* try to find object w/CKA_SIGN first, retry w/o */
287 if (pkcs11_find(k11->provider, k11->slotidx, key_filter, 3, &obj) < 0 &&
288 pkcs11_find(k11->provider, k11->slotidx, key_filter, 2, &obj) < 0) {
289 error("cannot find private key");
290 } else if ((rv = f->C_SignInit(si->session, &mech, obj)) != CKR_OK) {
291 error("C_SignInit failed: %lu", rv);
293 /* XXX handle CKR_BUFFER_TOO_SMALL */
294 tlen = RSA_size(rsa);
295 rv = f->C_Sign(si->session, (CK_BYTE *)from, flen, to, &tlen);
299 error("C_Sign failed: %lu", rv);
305 pkcs11_rsa_private_decrypt(int flen, const u_char *from, u_char *to, RSA *rsa,
311 /* redirect private key operations for rsa key to pkcs11 token */
313 pkcs11_rsa_wrap(struct pkcs11_provider *provider, CK_ULONG slotidx,
314 CK_ATTRIBUTE *keyid_attrib, RSA *rsa)
316 struct pkcs11_key *k11;
317 const RSA_METHOD *def = RSA_get_default_method();
319 k11 = xcalloc(1, sizeof(*k11));
320 k11->provider = provider;
321 provider->refcount++; /* provider referenced by RSA key */
322 k11->slotidx = slotidx;
323 /* identify key object on smartcard */
324 k11->keyid_len = keyid_attrib->ulValueLen;
325 if (k11->keyid_len > 0) {
326 k11->keyid = xmalloc(k11->keyid_len);
327 memcpy(k11->keyid, keyid_attrib->pValue, k11->keyid_len);
329 k11->orig_finish = RSA_meth_get_finish(def);
331 if ((k11->rsa_method = RSA_meth_new("pkcs11", RSA_meth_get_flags(def))) == NULL)
333 RSA_meth_set_priv_enc(k11->rsa_method, pkcs11_rsa_private_encrypt);
334 RSA_meth_set_priv_dec(k11->rsa_method, pkcs11_rsa_private_decrypt);
335 RSA_meth_set_finish(k11->rsa_method, pkcs11_rsa_finish);
337 RSA_set_method(rsa, k11->rsa_method);
338 RSA_set_app_data(rsa, k11);
342 /* remove trailing spaces */
344 rmspace(u_char *buf, size_t len)
350 for (i = len - 1; i > 0; i--)
351 if (i == len - 1 || buf[i] == ' ')
358 * open a pkcs11 session and login if required.
359 * if pin == NULL we delay login until key use
362 pkcs11_open_session(struct pkcs11_provider *p, CK_ULONG slotidx, char *pin)
366 CK_SESSION_HANDLE session;
369 f = p->function_list;
370 login_required = p->slotinfo[slotidx].token.flags & CKF_LOGIN_REQUIRED;
371 if (pin && login_required && !strlen(pin)) {
372 error("pin required");
375 if ((rv = f->C_OpenSession(p->slotlist[slotidx], CKF_RW_SESSION|
376 CKF_SERIAL_SESSION, NULL, NULL, &session))
378 error("C_OpenSession failed: %lu", rv);
381 if (login_required && pin) {
382 rv = f->C_Login(session, CKU_USER,
383 (u_char *)pin, strlen(pin));
384 if (rv != CKR_OK && rv != CKR_USER_ALREADY_LOGGED_IN) {
385 error("C_Login failed: %lu", rv);
386 if ((rv = f->C_CloseSession(session)) != CKR_OK)
387 error("C_CloseSession failed: %lu", rv);
390 p->slotinfo[slotidx].logged_in = 1;
392 p->slotinfo[slotidx].session = session;
397 * lookup public keys for token in slot identified by slotidx,
398 * add 'wrapped' public keys to the 'keysp' array and increment nkeys.
399 * keysp points to an (possibly empty) array with *nkeys keys.
401 static int pkcs11_fetch_keys_filter(struct pkcs11_provider *, CK_ULONG,
402 CK_ATTRIBUTE [], CK_ATTRIBUTE [3], struct sshkey ***, int *)
403 __attribute__((__bounded__(__minbytes__,4, 3 * sizeof(CK_ATTRIBUTE))));
406 pkcs11_fetch_keys(struct pkcs11_provider *p, CK_ULONG slotidx,
407 struct sshkey ***keysp, int *nkeys)
409 CK_OBJECT_CLASS pubkey_class = CKO_PUBLIC_KEY;
410 CK_OBJECT_CLASS cert_class = CKO_CERTIFICATE;
411 CK_ATTRIBUTE pubkey_filter[] = {
412 { CKA_CLASS, NULL, sizeof(pubkey_class) }
414 CK_ATTRIBUTE cert_filter[] = {
415 { CKA_CLASS, NULL, sizeof(cert_class) }
417 CK_ATTRIBUTE pubkey_attribs[] = {
419 { CKA_MODULUS, NULL, 0 },
420 { CKA_PUBLIC_EXPONENT, NULL, 0 }
422 CK_ATTRIBUTE cert_attribs[] = {
424 { CKA_SUBJECT, NULL, 0 },
425 { CKA_VALUE, NULL, 0 }
427 pubkey_filter[0].pValue = &pubkey_class;
428 cert_filter[0].pValue = &cert_class;
430 if (pkcs11_fetch_keys_filter(p, slotidx, pubkey_filter, pubkey_attribs,
432 pkcs11_fetch_keys_filter(p, slotidx, cert_filter, cert_attribs,
439 pkcs11_key_included(struct sshkey ***keysp, int *nkeys, struct sshkey *key)
443 for (i = 0; i < *nkeys; i++)
444 if (sshkey_equal(key, (*keysp)[i]))
450 pkcs11_fetch_keys_filter(struct pkcs11_provider *p, CK_ULONG slotidx,
451 CK_ATTRIBUTE filter[], CK_ATTRIBUTE attribs[3],
452 struct sshkey ***keysp, int *nkeys)
461 CK_OBJECT_HANDLE obj;
463 CK_SESSION_HANDLE session;
466 f = p->function_list;
467 session = p->slotinfo[slotidx].session;
468 /* setup a filter the looks for public keys */
469 if ((rv = f->C_FindObjectsInit(session, filter, 1)) != CKR_OK) {
470 error("C_FindObjectsInit failed: %lu", rv);
474 /* XXX 3 attributes in attribs[] */
475 for (i = 0; i < 3; i++) {
476 attribs[i].pValue = NULL;
477 attribs[i].ulValueLen = 0;
479 if ((rv = f->C_FindObjects(session, &obj, 1, &nfound)) != CKR_OK
482 /* found a key, so figure out size of the attributes */
483 if ((rv = f->C_GetAttributeValue(session, obj, attribs, 3))
485 error("C_GetAttributeValue failed: %lu", rv);
489 * Allow CKA_ID (always first attribute) to be empty, but
490 * ensure that none of the others are zero length.
491 * XXX assumes CKA_ID is always first.
493 if (attribs[1].ulValueLen == 0 ||
494 attribs[2].ulValueLen == 0) {
497 /* allocate buffers for attributes */
498 for (i = 0; i < 3; i++) {
499 if (attribs[i].ulValueLen > 0) {
500 attribs[i].pValue = xmalloc(
501 attribs[i].ulValueLen);
506 * retrieve ID, modulus and public exponent of RSA key,
507 * or ID, subject and value for certificates.
510 if ((rv = f->C_GetAttributeValue(session, obj, attribs, 3))
512 error("C_GetAttributeValue failed: %lu", rv);
513 } else if (attribs[1].type == CKA_MODULUS ) {
514 if ((rsa = RSA_new()) == NULL) {
515 error("RSA_new failed");
517 BIGNUM *n=NULL, *e=NULL;
520 if (n == NULL || e == NULL)
521 error("BN_new alloc failed");
522 if (BN_bin2bn(attribs[1].pValue,
523 attribs[1].ulValueLen, n) == NULL ||
524 BN_bin2bn(attribs[2].pValue,
525 attribs[2].ulValueLen, e) == NULL)
526 error("BN_bin2bn failed");
527 if (RSA_set0_key(rsa, n, e, NULL) == 0)
528 error("RSA_set0_key failed");
532 cp = attribs[2].pValue;
533 if ((x509 = X509_new()) == NULL) {
534 error("X509_new failed");
535 } else if (d2i_X509(&x509, &cp, attribs[2].ulValueLen)
537 error("d2i_X509 failed");
538 } else if ((evp = X509_get_pubkey(x509)) == NULL ||
539 EVP_PKEY_id(evp) != EVP_PKEY_RSA ||
540 EVP_PKEY_get0_RSA(evp) == NULL) {
541 debug("X509_get_pubkey failed or no rsa");
542 } else if ((rsa = RSAPublicKey_dup(EVP_PKEY_get0_RSA(evp)))
544 error("RSAPublicKey_dup");
550 RSA_get0_key(rsa, &n, &e, NULL);
552 pkcs11_rsa_wrap(p, slotidx, &attribs[0], rsa) == 0) {
553 if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
554 fatal("sshkey_new failed");
557 key->flags |= SSHKEY_FLAG_EXT;
558 if (pkcs11_key_included(keysp, nkeys, key)) {
561 /* expand key array and add key */
562 *keysp = xrecallocarray(*keysp, *nkeys,
563 *nkeys + 1, sizeof(struct sshkey *));
564 (*keysp)[*nkeys] = key;
566 debug("have %d keys", *nkeys);
572 for (i = 0; i < 3; i++)
573 free(attribs[i].pValue);
575 if ((rv = f->C_FindObjectsFinal(session)) != CKR_OK)
576 error("C_FindObjectsFinal failed: %lu", rv);
580 /* register a new provider, fails if provider already exists */
582 pkcs11_add_provider(char *provider_id, char *pin, struct sshkey ***keyp)
584 int nkeys, need_finalize = 0;
585 struct pkcs11_provider *p = NULL;
587 CK_RV (*getfunctionlist)(CK_FUNCTION_LIST **);
589 CK_FUNCTION_LIST *f = NULL;
590 CK_TOKEN_INFO *token;
594 if (pkcs11_provider_lookup(provider_id) != NULL) {
595 debug("%s: provider already registered: %s",
596 __func__, provider_id);
599 /* open shared pkcs11-libarary */
600 if ((handle = dlopen(provider_id, RTLD_NOW)) == NULL) {
601 error("dlopen %s failed: %s", provider_id, dlerror());
604 if ((getfunctionlist = dlsym(handle, "C_GetFunctionList")) == NULL) {
605 error("dlsym(C_GetFunctionList) failed: %s", dlerror());
608 p = xcalloc(1, sizeof(*p));
609 p->name = xstrdup(provider_id);
611 /* setup the pkcs11 callbacks */
612 if ((rv = (*getfunctionlist)(&f)) != CKR_OK) {
613 error("C_GetFunctionList for provider %s failed: %lu",
617 p->function_list = f;
618 if ((rv = f->C_Initialize(NULL)) != CKR_OK) {
619 error("C_Initialize for provider %s failed: %lu",
624 if ((rv = f->C_GetInfo(&p->info)) != CKR_OK) {
625 error("C_GetInfo for provider %s failed: %lu",
629 rmspace(p->info.manufacturerID, sizeof(p->info.manufacturerID));
630 rmspace(p->info.libraryDescription, sizeof(p->info.libraryDescription));
631 debug("provider %s: manufacturerID <%s> cryptokiVersion %d.%d"
632 " libraryDescription <%s> libraryVersion %d.%d",
634 p->info.manufacturerID,
635 p->info.cryptokiVersion.major,
636 p->info.cryptokiVersion.minor,
637 p->info.libraryDescription,
638 p->info.libraryVersion.major,
639 p->info.libraryVersion.minor);
640 if ((rv = f->C_GetSlotList(CK_TRUE, NULL, &p->nslots)) != CKR_OK) {
641 error("C_GetSlotList failed: %lu", rv);
644 if (p->nslots == 0) {
645 debug("%s: provider %s returned no slots", __func__,
649 p->slotlist = xcalloc(p->nslots, sizeof(CK_SLOT_ID));
650 if ((rv = f->C_GetSlotList(CK_TRUE, p->slotlist, &p->nslots))
652 error("C_GetSlotList for provider %s failed: %lu",
656 p->slotinfo = xcalloc(p->nslots, sizeof(struct pkcs11_slotinfo));
659 for (i = 0; i < p->nslots; i++) {
660 token = &p->slotinfo[i].token;
661 if ((rv = f->C_GetTokenInfo(p->slotlist[i], token))
663 error("C_GetTokenInfo for provider %s slot %lu "
664 "failed: %lu", provider_id, (unsigned long)i, rv);
667 if ((token->flags & CKF_TOKEN_INITIALIZED) == 0) {
668 debug2("%s: ignoring uninitialised token in "
669 "provider %s slot %lu", __func__,
670 provider_id, (unsigned long)i);
673 rmspace(token->label, sizeof(token->label));
674 rmspace(token->manufacturerID, sizeof(token->manufacturerID));
675 rmspace(token->model, sizeof(token->model));
676 rmspace(token->serialNumber, sizeof(token->serialNumber));
677 debug("provider %s slot %lu: label <%s> manufacturerID <%s> "
678 "model <%s> serial <%s> flags 0x%lx",
679 provider_id, (unsigned long)i,
680 token->label, token->manufacturerID, token->model,
681 token->serialNumber, token->flags);
682 /* open session, login with pin and retrieve public keys */
683 if (pkcs11_open_session(p, i, pin) == 0)
684 pkcs11_fetch_keys(p, i, keyp, &nkeys);
687 TAILQ_INSERT_TAIL(&pkcs11_providers, p, next);
688 p->refcount++; /* add to provider list */
691 debug("%s: provider %s returned no keys", __func__, provider_id);
692 /* don't add the provider, since it does not have any keys */
694 if (need_finalize && (rv = f->C_Finalize(NULL)) != CKR_OK)
695 error("C_Finalize for provider %s failed: %lu",
710 pkcs11_init(int interactive)
716 pkcs11_terminate(void)
721 #endif /* ENABLE_PKCS11 */