ipfw3: dummynet dispatch back to the same cpu
[dragonfly.git] / crypto / openssh / ssh-pkcs11.c
blobc96be3bd2c3f6986914e2be509bda5ff0658faac
1 /* $OpenBSD: ssh-pkcs11.c,v 1.14 2014/06/24 01:13:21 djm Exp $ */
2 /*
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.
18 #include "includes.h"
20 #ifdef ENABLE_PKCS11
22 #include <sys/types.h>
23 #ifdef HAVE_SYS_TIME_H
24 # include <sys/time.h>
25 #endif
26 #include <stdarg.h>
27 #include <stdio.h>
29 #include <string.h>
30 #include <dlfcn.h>
32 #include "openbsd-compat/sys-queue.h"
34 #include <openssl/x509.h>
36 #define CRYPTOKI_COMPAT
37 #include "pkcs11.h"
39 #include "log.h"
40 #include "misc.h"
41 #include "key.h"
42 #include "ssh-pkcs11.h"
43 #include "xmalloc.h"
45 struct pkcs11_slotinfo {
46 CK_TOKEN_INFO token;
47 CK_SESSION_HANDLE session;
48 int logged_in;
51 struct pkcs11_provider {
52 char *name;
53 void *handle;
54 CK_FUNCTION_LIST *function_list;
55 CK_INFO info;
56 CK_ULONG nslots;
57 CK_SLOT_ID *slotlist;
58 struct pkcs11_slotinfo *slotinfo;
59 int valid;
60 int refcount;
61 TAILQ_ENTRY(pkcs11_provider) next;
64 TAILQ_HEAD(, pkcs11_provider) pkcs11_providers;
66 struct pkcs11_key {
67 struct pkcs11_provider *provider;
68 CK_ULONG slotidx;
69 int (*orig_finish)(RSA *rsa);
70 RSA_METHOD rsa_method;
71 char *keyid;
72 int keyid_len;
75 int pkcs11_interactive = 0;
77 int
78 pkcs11_init(int interactive)
80 pkcs11_interactive = interactive;
81 TAILQ_INIT(&pkcs11_providers);
82 return (0);
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.
91 static void
92 pkcs11_provider_finalize(struct pkcs11_provider *p)
94 CK_RV rv;
95 CK_ULONG i;
97 debug("pkcs11_provider_finalize: %p refcount %d valid %d",
98 p, p->refcount, p->valid);
99 if (!p->valid)
100 return;
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);
109 p->valid = 0;
110 p->function_list = NULL;
111 dlclose(p->handle);
115 * remove a reference to the provider.
116 * called when a key gets destroyed or when the provider is unregistered.
118 static void
119 pkcs11_provider_unref(struct pkcs11_provider *p)
121 debug("pkcs11_provider_unref: %p refcount %d", p, p->refcount);
122 if (--p->refcount <= 0) {
123 if (p->valid)
124 error("pkcs11_provider_unref: %p still valid", p);
125 free(p->slotlist);
126 free(p->slotinfo);
127 free(p);
131 /* unregister all providers, keys might still point to the providers */
132 void
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))
153 return (p);
155 return (NULL);
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);
168 return (0);
170 return (-1);
173 /* openssl callback for freeing an RSA key */
174 static int
175 pkcs11_rsa_finish(RSA *rsa)
177 struct pkcs11_key *k11;
178 int rv = -1;
180 if ((k11 = RSA_get_app_data(rsa)) != NULL) {
181 if (k11->orig_finish)
182 rv = k11->orig_finish(rsa);
183 if (k11->provider)
184 pkcs11_provider_unref(k11->provider);
185 free(k11->keyid);
186 free(k11);
188 return (rv);
191 /* find a single 'obj' for given attributes */
192 static int
193 pkcs11_find(struct pkcs11_provider *p, CK_ULONG slotidx, CK_ATTRIBUTE *attr,
194 CK_ULONG nattr, CK_OBJECT_HANDLE *obj)
196 CK_FUNCTION_LIST *f;
197 CK_SESSION_HANDLE session;
198 CK_ULONG nfound = 0;
199 CK_RV rv;
200 int ret = -1;
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);
206 return (-1);
208 if ((rv = f->C_FindObjects(session, obj, 1, &nfound)) != CKR_OK ||
209 nfound != 1) {
210 debug("C_FindObjects failed (nfound %lu nattr %lu): %lu",
211 nfound, nattr, rv);
212 } else
213 ret = 0;
214 if ((rv = f->C_FindObjectsFinal(session)) != CKR_OK)
215 error("C_FindObjectsFinal failed: %lu", rv);
216 return (ret);
219 /* openssl callback doing the actual signing operation */
220 static int
221 pkcs11_rsa_private_encrypt(int flen, const u_char *from, u_char *to, RSA *rsa,
222 int padding)
224 struct pkcs11_key *k11;
225 struct pkcs11_slotinfo *si;
226 CK_FUNCTION_LIST *f;
227 CK_OBJECT_HANDLE obj;
228 CK_ULONG tlen = 0;
229 CK_RV rv;
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) },
237 {CKA_ID, NULL, 0},
238 {CKA_SIGN, NULL, sizeof(true_val) }
240 char *pin, prompt[1024];
241 int rval = -1;
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);
248 return (-1);
250 if (!k11->provider || !k11->provider->valid) {
251 error("no pkcs11 (valid) provider for rsa %p", rsa);
252 return (-1);
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");
259 return (-1);
261 snprintf(prompt, sizeof(prompt), "Enter PIN for '%s': ",
262 si->token.label);
263 pin = read_passphrase(prompt, RP_ALLOW_EOF);
264 if (pin == NULL)
265 return (-1); /* bail out */
266 if ((rv = f->C_Login(si->session, CKU_USER,
267 (u_char *)pin, strlen(pin))) != CKR_OK) {
268 free(pin);
269 error("C_Login failed: %lu", rv);
270 return (-1);
272 free(pin);
273 si->logged_in = 1;
275 key_filter[1].pValue = k11->keyid;
276 key_filter[1].ulValueLen = k11->keyid_len;
277 /* try to find object w/CKA_SIGN first, retry w/o */
278 if (pkcs11_find(k11->provider, k11->slotidx, key_filter, 3, &obj) < 0 &&
279 pkcs11_find(k11->provider, k11->slotidx, key_filter, 2, &obj) < 0) {
280 error("cannot find private key");
281 } else if ((rv = f->C_SignInit(si->session, &mech, obj)) != CKR_OK) {
282 error("C_SignInit failed: %lu", rv);
283 } else {
284 /* XXX handle CKR_BUFFER_TOO_SMALL */
285 tlen = RSA_size(rsa);
286 rv = f->C_Sign(si->session, (CK_BYTE *)from, flen, to, &tlen);
287 if (rv == CKR_OK)
288 rval = tlen;
289 else
290 error("C_Sign failed: %lu", rv);
292 return (rval);
295 static int
296 pkcs11_rsa_private_decrypt(int flen, const u_char *from, u_char *to, RSA *rsa,
297 int padding)
299 return (-1);
302 /* redirect private key operations for rsa key to pkcs11 token */
303 static int
304 pkcs11_rsa_wrap(struct pkcs11_provider *provider, CK_ULONG slotidx,
305 CK_ATTRIBUTE *keyid_attrib, RSA *rsa)
307 struct pkcs11_key *k11;
308 const RSA_METHOD *def = RSA_get_default_method();
310 k11 = xcalloc(1, sizeof(*k11));
311 k11->provider = provider;
312 provider->refcount++; /* provider referenced by RSA key */
313 k11->slotidx = slotidx;
314 /* identify key object on smartcard */
315 k11->keyid_len = keyid_attrib->ulValueLen;
316 k11->keyid = xmalloc(k11->keyid_len);
317 memcpy(k11->keyid, keyid_attrib->pValue, k11->keyid_len);
318 k11->orig_finish = def->finish;
319 memcpy(&k11->rsa_method, def, sizeof(k11->rsa_method));
320 k11->rsa_method.name = "pkcs11";
321 k11->rsa_method.rsa_priv_enc = pkcs11_rsa_private_encrypt;
322 k11->rsa_method.rsa_priv_dec = pkcs11_rsa_private_decrypt;
323 k11->rsa_method.finish = pkcs11_rsa_finish;
324 RSA_set_method(rsa, &k11->rsa_method);
325 RSA_set_app_data(rsa, k11);
326 return (0);
329 /* remove trailing spaces */
330 static void
331 rmspace(u_char *buf, size_t len)
333 size_t i;
335 if (!len)
336 return;
337 for (i = len - 1; i > 0; i--)
338 if (i == len - 1 || buf[i] == ' ')
339 buf[i] = '\0';
340 else
341 break;
345 * open a pkcs11 session and login if required.
346 * if pin == NULL we delay login until key use
348 static int
349 pkcs11_open_session(struct pkcs11_provider *p, CK_ULONG slotidx, char *pin)
351 CK_RV rv;
352 CK_FUNCTION_LIST *f;
353 CK_SESSION_HANDLE session;
354 int login_required;
356 f = p->function_list;
357 login_required = p->slotinfo[slotidx].token.flags & CKF_LOGIN_REQUIRED;
358 if (pin && login_required && !strlen(pin)) {
359 error("pin required");
360 return (-1);
362 if ((rv = f->C_OpenSession(p->slotlist[slotidx], CKF_RW_SESSION|
363 CKF_SERIAL_SESSION, NULL, NULL, &session))
364 != CKR_OK) {
365 error("C_OpenSession failed: %lu", rv);
366 return (-1);
368 if (login_required && pin) {
369 if ((rv = f->C_Login(session, CKU_USER,
370 (u_char *)pin, strlen(pin))) != CKR_OK) {
371 error("C_Login failed: %lu", rv);
372 if ((rv = f->C_CloseSession(session)) != CKR_OK)
373 error("C_CloseSession failed: %lu", rv);
374 return (-1);
376 p->slotinfo[slotidx].logged_in = 1;
378 p->slotinfo[slotidx].session = session;
379 return (0);
383 * lookup public keys for token in slot identified by slotidx,
384 * add 'wrapped' public keys to the 'keysp' array and increment nkeys.
385 * keysp points to an (possibly empty) array with *nkeys keys.
387 static int pkcs11_fetch_keys_filter(struct pkcs11_provider *, CK_ULONG,
388 CK_ATTRIBUTE [], CK_ATTRIBUTE [3], Key ***, int *)
389 __attribute__((__bounded__(__minbytes__,4, 3 * sizeof(CK_ATTRIBUTE))));
391 static int
392 pkcs11_fetch_keys(struct pkcs11_provider *p, CK_ULONG slotidx,
393 Key ***keysp, int *nkeys)
395 CK_OBJECT_CLASS pubkey_class = CKO_PUBLIC_KEY;
396 CK_OBJECT_CLASS cert_class = CKO_CERTIFICATE;
397 CK_ATTRIBUTE pubkey_filter[] = {
398 { CKA_CLASS, NULL, sizeof(pubkey_class) }
400 CK_ATTRIBUTE cert_filter[] = {
401 { CKA_CLASS, NULL, sizeof(cert_class) }
403 CK_ATTRIBUTE pubkey_attribs[] = {
404 { CKA_ID, NULL, 0 },
405 { CKA_MODULUS, NULL, 0 },
406 { CKA_PUBLIC_EXPONENT, NULL, 0 }
408 CK_ATTRIBUTE cert_attribs[] = {
409 { CKA_ID, NULL, 0 },
410 { CKA_SUBJECT, NULL, 0 },
411 { CKA_VALUE, NULL, 0 }
413 pubkey_filter[0].pValue = &pubkey_class;
414 cert_filter[0].pValue = &cert_class;
416 if (pkcs11_fetch_keys_filter(p, slotidx, pubkey_filter, pubkey_attribs,
417 keysp, nkeys) < 0 ||
418 pkcs11_fetch_keys_filter(p, slotidx, cert_filter, cert_attribs,
419 keysp, nkeys) < 0)
420 return (-1);
421 return (0);
424 static int
425 pkcs11_key_included(Key ***keysp, int *nkeys, Key *key)
427 int i;
429 for (i = 0; i < *nkeys; i++)
430 if (key_equal(key, (*keysp)[i]))
431 return (1);
432 return (0);
435 static int
436 pkcs11_fetch_keys_filter(struct pkcs11_provider *p, CK_ULONG slotidx,
437 CK_ATTRIBUTE filter[], CK_ATTRIBUTE attribs[3],
438 Key ***keysp, int *nkeys)
440 Key *key;
441 RSA *rsa;
442 X509 *x509;
443 EVP_PKEY *evp;
444 int i;
445 const u_char *cp;
446 CK_RV rv;
447 CK_OBJECT_HANDLE obj;
448 CK_ULONG nfound;
449 CK_SESSION_HANDLE session;
450 CK_FUNCTION_LIST *f;
452 f = p->function_list;
453 session = p->slotinfo[slotidx].session;
454 /* setup a filter the looks for public keys */
455 if ((rv = f->C_FindObjectsInit(session, filter, 1)) != CKR_OK) {
456 error("C_FindObjectsInit failed: %lu", rv);
457 return (-1);
459 while (1) {
460 /* XXX 3 attributes in attribs[] */
461 for (i = 0; i < 3; i++) {
462 attribs[i].pValue = NULL;
463 attribs[i].ulValueLen = 0;
465 if ((rv = f->C_FindObjects(session, &obj, 1, &nfound)) != CKR_OK
466 || nfound == 0)
467 break;
468 /* found a key, so figure out size of the attributes */
469 if ((rv = f->C_GetAttributeValue(session, obj, attribs, 3))
470 != CKR_OK) {
471 error("C_GetAttributeValue failed: %lu", rv);
472 continue;
474 /* check that none of the attributes are zero length */
475 if (attribs[0].ulValueLen == 0 ||
476 attribs[1].ulValueLen == 0 ||
477 attribs[2].ulValueLen == 0) {
478 continue;
480 /* allocate buffers for attributes */
481 for (i = 0; i < 3; i++)
482 attribs[i].pValue = xmalloc(attribs[i].ulValueLen);
484 * retrieve ID, modulus and public exponent of RSA key,
485 * or ID, subject and value for certificates.
487 rsa = NULL;
488 if ((rv = f->C_GetAttributeValue(session, obj, attribs, 3))
489 != CKR_OK) {
490 error("C_GetAttributeValue failed: %lu", rv);
491 } else if (attribs[1].type == CKA_MODULUS ) {
492 if ((rsa = RSA_new()) == NULL) {
493 error("RSA_new failed");
494 } else {
495 rsa->n = BN_bin2bn(attribs[1].pValue,
496 attribs[1].ulValueLen, NULL);
497 rsa->e = BN_bin2bn(attribs[2].pValue,
498 attribs[2].ulValueLen, NULL);
500 } else {
501 cp = attribs[2].pValue;
502 if ((x509 = X509_new()) == NULL) {
503 error("X509_new failed");
504 } else if (d2i_X509(&x509, &cp, attribs[2].ulValueLen)
505 == NULL) {
506 error("d2i_X509 failed");
507 } else if ((evp = X509_get_pubkey(x509)) == NULL ||
508 evp->type != EVP_PKEY_RSA ||
509 evp->pkey.rsa == NULL) {
510 debug("X509_get_pubkey failed or no rsa");
511 } else if ((rsa = RSAPublicKey_dup(evp->pkey.rsa))
512 == NULL) {
513 error("RSAPublicKey_dup");
515 if (x509)
516 X509_free(x509);
518 if (rsa && rsa->n && rsa->e &&
519 pkcs11_rsa_wrap(p, slotidx, &attribs[0], rsa) == 0) {
520 key = key_new(KEY_UNSPEC);
521 key->rsa = rsa;
522 key->type = KEY_RSA;
523 key->flags |= SSHKEY_FLAG_EXT;
524 if (pkcs11_key_included(keysp, nkeys, key)) {
525 key_free(key);
526 } else {
527 /* expand key array and add key */
528 *keysp = xrealloc(*keysp, *nkeys + 1,
529 sizeof(Key *));
530 (*keysp)[*nkeys] = key;
531 *nkeys = *nkeys + 1;
532 debug("have %d keys", *nkeys);
534 } else if (rsa) {
535 RSA_free(rsa);
537 for (i = 0; i < 3; i++)
538 free(attribs[i].pValue);
540 if ((rv = f->C_FindObjectsFinal(session)) != CKR_OK)
541 error("C_FindObjectsFinal failed: %lu", rv);
542 return (0);
545 /* register a new provider, fails if provider already exists */
547 pkcs11_add_provider(char *provider_id, char *pin, Key ***keyp)
549 int nkeys, need_finalize = 0;
550 struct pkcs11_provider *p = NULL;
551 void *handle = NULL;
552 CK_RV (*getfunctionlist)(CK_FUNCTION_LIST **);
553 CK_RV rv;
554 CK_FUNCTION_LIST *f = NULL;
555 CK_TOKEN_INFO *token;
556 CK_ULONG i;
558 *keyp = NULL;
559 if (pkcs11_provider_lookup(provider_id) != NULL) {
560 error("provider already registered: %s", provider_id);
561 goto fail;
563 /* open shared pkcs11-libarary */
564 if ((handle = dlopen(provider_id, RTLD_NOW)) == NULL) {
565 error("dlopen %s failed: %s", provider_id, dlerror());
566 goto fail;
568 if ((getfunctionlist = dlsym(handle, "C_GetFunctionList")) == NULL) {
569 error("dlsym(C_GetFunctionList) failed: %s", dlerror());
570 goto fail;
572 p = xcalloc(1, sizeof(*p));
573 p->name = xstrdup(provider_id);
574 p->handle = handle;
575 /* setup the pkcs11 callbacks */
576 if ((rv = (*getfunctionlist)(&f)) != CKR_OK) {
577 error("C_GetFunctionList failed: %lu", rv);
578 goto fail;
580 p->function_list = f;
581 if ((rv = f->C_Initialize(NULL)) != CKR_OK) {
582 error("C_Initialize failed: %lu", rv);
583 goto fail;
585 need_finalize = 1;
586 if ((rv = f->C_GetInfo(&p->info)) != CKR_OK) {
587 error("C_GetInfo failed: %lu", rv);
588 goto fail;
590 rmspace(p->info.manufacturerID, sizeof(p->info.manufacturerID));
591 rmspace(p->info.libraryDescription, sizeof(p->info.libraryDescription));
592 debug("manufacturerID <%s> cryptokiVersion %d.%d"
593 " libraryDescription <%s> libraryVersion %d.%d",
594 p->info.manufacturerID,
595 p->info.cryptokiVersion.major,
596 p->info.cryptokiVersion.minor,
597 p->info.libraryDescription,
598 p->info.libraryVersion.major,
599 p->info.libraryVersion.minor);
600 if ((rv = f->C_GetSlotList(CK_TRUE, NULL, &p->nslots)) != CKR_OK) {
601 error("C_GetSlotList failed: %lu", rv);
602 goto fail;
604 if (p->nslots == 0) {
605 error("no slots");
606 goto fail;
608 p->slotlist = xcalloc(p->nslots, sizeof(CK_SLOT_ID));
609 if ((rv = f->C_GetSlotList(CK_TRUE, p->slotlist, &p->nslots))
610 != CKR_OK) {
611 error("C_GetSlotList failed: %lu", rv);
612 goto fail;
614 p->slotinfo = xcalloc(p->nslots, sizeof(struct pkcs11_slotinfo));
615 p->valid = 1;
616 nkeys = 0;
617 for (i = 0; i < p->nslots; i++) {
618 token = &p->slotinfo[i].token;
619 if ((rv = f->C_GetTokenInfo(p->slotlist[i], token))
620 != CKR_OK) {
621 error("C_GetTokenInfo failed: %lu", rv);
622 continue;
624 rmspace(token->label, sizeof(token->label));
625 rmspace(token->manufacturerID, sizeof(token->manufacturerID));
626 rmspace(token->model, sizeof(token->model));
627 rmspace(token->serialNumber, sizeof(token->serialNumber));
628 debug("label <%s> manufacturerID <%s> model <%s> serial <%s>"
629 " flags 0x%lx",
630 token->label, token->manufacturerID, token->model,
631 token->serialNumber, token->flags);
632 /* open session, login with pin and retrieve public keys */
633 if (pkcs11_open_session(p, i, pin) == 0)
634 pkcs11_fetch_keys(p, i, keyp, &nkeys);
636 if (nkeys > 0) {
637 TAILQ_INSERT_TAIL(&pkcs11_providers, p, next);
638 p->refcount++; /* add to provider list */
639 return (nkeys);
641 error("no keys");
642 /* don't add the provider, since it does not have any keys */
643 fail:
644 if (need_finalize && (rv = f->C_Finalize(NULL)) != CKR_OK)
645 error("C_Finalize failed: %lu", rv);
646 if (p) {
647 free(p->slotlist);
648 free(p->slotinfo);
649 free(p);
651 if (handle)
652 dlclose(handle);
653 return (-1);
656 #else
659 pkcs11_init(int interactive)
661 return (0);
664 void
665 pkcs11_terminate(void)
667 return;
670 #endif /* ENABLE_PKCS11 */