Annotation of src/usr.bin/ssh/ssh-pkcs11.c, Revision 1.7
1.7 ! djm 1: /* $OpenBSD: ssh-pkcs11.c,v 1.6 2010/06/08 21:32:19 markus Exp $ */
1.1 markus 2: /*
3: * Copyright (c) 2010 Markus Friedl. All rights reserved.
4: *
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.
8: *
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.
16: */
17:
18: #include <sys/types.h>
19: #include <sys/queue.h>
20: #include <stdarg.h>
21: #include <stdio.h>
22:
23: #include <string.h>
24: #include <dlfcn.h>
25:
26: #define CRYPTOKI_COMPAT
27: #include "pkcs11.h"
28:
29: #include "log.h"
30: #include "misc.h"
31: #include "key.h"
32: #include "ssh-pkcs11.h"
33: #include "xmalloc.h"
34:
35: struct pkcs11_slotinfo {
36: CK_TOKEN_INFO token;
37: CK_SESSION_HANDLE session;
38: int logged_in;
39: };
40:
41: struct pkcs11_provider {
42: char *name;
43: void *handle;
44: CK_FUNCTION_LIST *function_list;
45: CK_INFO info;
46: CK_ULONG nslots;
47: CK_SLOT_ID *slotlist;
48: struct pkcs11_slotinfo *slotinfo;
49: int valid;
50: int refcount;
51: TAILQ_ENTRY(pkcs11_provider) next;
52: };
53:
54: TAILQ_HEAD(, pkcs11_provider) pkcs11_providers;
55:
56: struct pkcs11_key {
57: struct pkcs11_provider *provider;
58: CK_ULONG slotidx;
59: int (*orig_finish)(RSA *rsa);
60: RSA_METHOD rsa_method;
61: char *keyid;
62: int keyid_len;
63: };
64:
65: int pkcs11_interactive = 0;
66:
67: int
68: pkcs11_init(int interactive)
69: {
70: pkcs11_interactive = interactive;
71: TAILQ_INIT(&pkcs11_providers);
72: return (0);
73: }
74:
75: /*
76: * finalize a provider shared libarary, it's no longer usable.
77: * however, there might still be keys referencing this provider,
78: * so the actuall freeing of memory is handled by pkcs11_provider_unref().
79: * this is called when a provider gets unregistered.
80: */
81: static void
82: pkcs11_provider_finalize(struct pkcs11_provider *p)
83: {
84: CK_RV rv;
85: CK_ULONG i;
86:
87: debug("pkcs11_provider_finalize: %p refcount %d valid %d",
88: p, p->refcount, p->valid);
89: if (!p->valid)
90: return;
91: for (i = 0; i < p->nslots; i++) {
92: if (p->slotinfo[i].session &&
93: (rv = p->function_list->C_CloseSession(
94: p->slotinfo[i].session)) != CKR_OK)
95: error("C_CloseSession failed: %lu", rv);
96: }
97: if ((rv = p->function_list->C_Finalize(NULL)) != CKR_OK)
98: error("C_Finalize failed: %lu", rv);
99: p->valid = 0;
100: p->function_list = NULL;
1.3 deraadt 101: #ifdef HAVE_DLOPEN
1.1 markus 102: dlclose(p->handle);
1.3 deraadt 103: #endif
1.1 markus 104: }
105:
106: /*
107: * remove a reference to the provider.
108: * called when a key gets destroyed or when the provider is unregistered.
109: */
110: static void
111: pkcs11_provider_unref(struct pkcs11_provider *p)
112: {
113: debug("pkcs11_provider_unref: %p refcount %d", p, p->refcount);
114: if (--p->refcount <= 0) {
115: if (p->valid)
116: error("pkcs11_provider_unref: %p still valid", p);
1.7 ! djm 117: free(p->slotlist);
! 118: free(p->slotinfo);
! 119: free(p);
1.1 markus 120: }
121: }
122:
123: /* unregister all providers, keys might still point to the providers */
124: void
125: pkcs11_terminate(void)
126: {
127: struct pkcs11_provider *p;
128:
129: while ((p = TAILQ_FIRST(&pkcs11_providers)) != NULL) {
130: TAILQ_REMOVE(&pkcs11_providers, p, next);
131: pkcs11_provider_finalize(p);
132: pkcs11_provider_unref(p);
133: }
134: }
135:
136: /* lookup provider by name */
137: static struct pkcs11_provider *
138: pkcs11_provider_lookup(char *provider_id)
139: {
140: struct pkcs11_provider *p;
141:
142: TAILQ_FOREACH(p, &pkcs11_providers, next) {
143: debug("check %p %s", p, p->name);
144: if (!strcmp(provider_id, p->name))
145: return (p);
146: }
147: return (NULL);
148: }
149:
150: /* unregister provider by name */
151: int
152: pkcs11_del_provider(char *provider_id)
153: {
154: struct pkcs11_provider *p;
155:
156: if ((p = pkcs11_provider_lookup(provider_id)) != NULL) {
157: TAILQ_REMOVE(&pkcs11_providers, p, next);
158: pkcs11_provider_finalize(p);
159: pkcs11_provider_unref(p);
160: return (0);
161: }
162: return (-1);
163: }
164:
165: /* openssl callback for freeing an RSA key */
166: static int
167: pkcs11_rsa_finish(RSA *rsa)
168: {
169: struct pkcs11_key *k11;
170: int rv = -1;
171:
172: if ((k11 = RSA_get_app_data(rsa)) != NULL) {
173: if (k11->orig_finish)
174: rv = k11->orig_finish(rsa);
175: if (k11->provider)
176: pkcs11_provider_unref(k11->provider);
1.7 ! djm 177: free(k11->keyid);
! 178: free(k11);
1.1 markus 179: }
180: return (rv);
181: }
182:
1.5 markus 183: /* find a single 'obj' for given attributes */
184: static int
185: pkcs11_find(struct pkcs11_provider *p, CK_ULONG slotidx, CK_ATTRIBUTE *attr,
186: CK_ULONG nattr, CK_OBJECT_HANDLE *obj)
187: {
188: CK_FUNCTION_LIST *f;
189: CK_SESSION_HANDLE session;
190: CK_ULONG nfound = 0;
191: CK_RV rv;
192: int ret = -1;
193:
194: f = p->function_list;
195: session = p->slotinfo[slotidx].session;
196: if ((rv = f->C_FindObjectsInit(session, attr, nattr)) != CKR_OK) {
197: error("C_FindObjectsInit failed (nattr %lu): %lu", nattr, rv);
198: return (-1);
199: }
200: if ((rv = f->C_FindObjects(session, obj, 1, &nfound)) != CKR_OK ||
201: nfound != 1) {
202: debug("C_FindObjects failed (nfound %lu nattr %lu): %lu",
203: nfound, nattr, rv);
204: } else
205: ret = 0;
206: if ((rv = f->C_FindObjectsFinal(session)) != CKR_OK)
207: error("C_FindObjectsFinal failed: %lu", rv);
208: return (ret);
209: }
210:
1.1 markus 211: /* openssl callback doing the actual signing operation */
212: static int
213: pkcs11_rsa_private_encrypt(int flen, const u_char *from, u_char *to, RSA *rsa,
214: int padding)
215: {
216: struct pkcs11_key *k11;
217: struct pkcs11_slotinfo *si;
218: CK_FUNCTION_LIST *f;
219: CK_OBJECT_HANDLE obj;
1.5 markus 220: CK_ULONG tlen = 0;
1.1 markus 221: CK_RV rv;
222: CK_OBJECT_CLASS private_key_class = CKO_PRIVATE_KEY;
223: CK_BBOOL true = CK_TRUE;
224: CK_MECHANISM mech = {
225: CKM_RSA_PKCS, NULL_PTR, 0
226: };
227: CK_ATTRIBUTE key_filter[] = {
228: {CKA_CLASS, &private_key_class, sizeof(private_key_class) },
229: {CKA_ID, NULL, 0},
230: {CKA_SIGN, &true, sizeof(true) }
231: };
232: char *pin, prompt[1024];
233: int rval = -1;
234:
235: if ((k11 = RSA_get_app_data(rsa)) == NULL) {
236: error("RSA_get_app_data failed for rsa %p", rsa);
237: return (-1);
238: }
239: if (!k11->provider || !k11->provider->valid) {
240: error("no pkcs11 (valid) provider for rsa %p", rsa);
241: return (-1);
242: }
243: f = k11->provider->function_list;
244: si = &k11->provider->slotinfo[k11->slotidx];
245: if ((si->token.flags & CKF_LOGIN_REQUIRED) && !si->logged_in) {
246: if (!pkcs11_interactive) {
247: error("need pin");
248: return (-1);
249: }
250: snprintf(prompt, sizeof(prompt), "Enter PIN for '%s': ",
251: si->token.label);
252: pin = read_passphrase(prompt, RP_ALLOW_EOF);
253: if (pin == NULL)
254: return (-1); /* bail out */
255: if ((rv = f->C_Login(si->session, CKU_USER, pin, strlen(pin)))
256: != CKR_OK) {
1.7 ! djm 257: free(pin);
1.1 markus 258: error("C_Login failed: %lu", rv);
259: return (-1);
260: }
1.7 ! djm 261: free(pin);
1.1 markus 262: si->logged_in = 1;
263: }
264: key_filter[1].pValue = k11->keyid;
265: key_filter[1].ulValueLen = k11->keyid_len;
1.5 markus 266: /* try to find object w/CKA_SIGN first, retry w/o */
267: if (pkcs11_find(k11->provider, k11->slotidx, key_filter, 3, &obj) < 0 &&
268: pkcs11_find(k11->provider, k11->slotidx, key_filter, 2, &obj) < 0) {
269: error("cannot find private key");
1.1 markus 270: } else if ((rv = f->C_SignInit(si->session, &mech, obj)) != CKR_OK) {
271: error("C_SignInit failed: %lu", rv);
272: } else {
273: /* XXX handle CKR_BUFFER_TOO_SMALL */
274: tlen = RSA_size(rsa);
275: rv = f->C_Sign(si->session, (CK_BYTE *)from, flen, to, &tlen);
276: if (rv == CKR_OK)
277: rval = tlen;
278: else
279: error("C_Sign failed: %lu", rv);
280: }
281: return (rval);
282: }
283:
284: static int
285: pkcs11_rsa_private_decrypt(int flen, const u_char *from, u_char *to, RSA *rsa,
286: int padding)
287: {
288: return (-1);
289: }
290:
291: /* redirect private key operations for rsa key to pkcs11 token */
292: static int
293: pkcs11_rsa_wrap(struct pkcs11_provider *provider, CK_ULONG slotidx,
294: CK_ATTRIBUTE *keyid_attrib, RSA *rsa)
295: {
296: struct pkcs11_key *k11;
297: const RSA_METHOD *def = RSA_get_default_method();
298:
299: k11 = xcalloc(1, sizeof(*k11));
300: k11->provider = provider;
301: provider->refcount++; /* provider referenced by RSA key */
302: k11->slotidx = slotidx;
303: /* identify key object on smartcard */
304: k11->keyid_len = keyid_attrib->ulValueLen;
305: k11->keyid = xmalloc(k11->keyid_len);
306: memcpy(k11->keyid, keyid_attrib->pValue, k11->keyid_len);
307: k11->orig_finish = def->finish;
308: memcpy(&k11->rsa_method, def, sizeof(k11->rsa_method));
309: k11->rsa_method.name = "pkcs11";
310: k11->rsa_method.rsa_priv_enc = pkcs11_rsa_private_encrypt;
311: k11->rsa_method.rsa_priv_dec = pkcs11_rsa_private_decrypt;
312: k11->rsa_method.finish = pkcs11_rsa_finish;
313: RSA_set_method(rsa, &k11->rsa_method);
314: RSA_set_app_data(rsa, k11);
315: return (0);
316: }
317:
318: /* remove trailing spaces */
319: static void
320: rmspace(char *buf, size_t len)
321: {
322: size_t i;
323:
324: if (!len)
325: return;
326: for (i = len - 1; i > 0; i--)
327: if (i == len - 1 || buf[i] == ' ')
328: buf[i] = '\0';
329: else
330: break;
331: }
332:
333: /*
334: * open a pkcs11 session and login if required.
335: * if pin == NULL we delay login until key use
336: */
337: static int
338: pkcs11_open_session(struct pkcs11_provider *p, CK_ULONG slotidx, char *pin)
339: {
340: CK_RV rv;
341: CK_FUNCTION_LIST *f;
342: CK_SESSION_HANDLE session;
343: int login_required;
344:
345: f = p->function_list;
346: login_required = p->slotinfo[slotidx].token.flags & CKF_LOGIN_REQUIRED;
347: if (pin && login_required && !strlen(pin)) {
348: error("pin required");
349: return (-1);
350: }
351: if ((rv = f->C_OpenSession(p->slotlist[slotidx], CKF_RW_SESSION|
352: CKF_SERIAL_SESSION, NULL, NULL, &session))
353: != CKR_OK) {
354: error("C_OpenSession failed: %lu", rv);
355: return (-1);
356: }
357: if (login_required && pin) {
358: if ((rv = f->C_Login(session, CKU_USER, pin, strlen(pin)))
359: != CKR_OK) {
360: error("C_Login failed: %lu", rv);
361: if ((rv = f->C_CloseSession(session)) != CKR_OK)
362: error("C_CloseSession failed: %lu", rv);
363: return (-1);
364: }
365: p->slotinfo[slotidx].logged_in = 1;
366: }
367: p->slotinfo[slotidx].session = session;
368: return (0);
369: }
370:
371: /*
372: * lookup public keys for token in slot identified by slotidx,
373: * add 'wrapped' public keys to the 'keysp' array and increment nkeys.
374: * keysp points to an (possibly empty) array with *nkeys keys.
375: */
376: static int
377: pkcs11_fetch_keys(struct pkcs11_provider *p, CK_ULONG slotidx, Key ***keysp,
378: int *nkeys)
379: {
380: Key *key;
381: RSA *rsa;
382: int i;
383: CK_RV rv;
384: CK_OBJECT_HANDLE obj;
385: CK_ULONG nfound;
386: CK_SESSION_HANDLE session;
387: CK_FUNCTION_LIST *f;
388: CK_OBJECT_CLASS pubkey_class = CKO_PUBLIC_KEY;
389: CK_ATTRIBUTE pubkey_filter[] = {
390: { CKA_CLASS, &pubkey_class, sizeof(pubkey_class) }
391: };
392: CK_ATTRIBUTE attribs[] = {
393: { CKA_ID, NULL, 0 },
394: { CKA_MODULUS, NULL, 0 },
395: { CKA_PUBLIC_EXPONENT, NULL, 0 }
396: };
397:
398: f = p->function_list;
399: session = p->slotinfo[slotidx].session;
400: /* setup a filter the looks for public keys */
401: if ((rv = f->C_FindObjectsInit(session, pubkey_filter, 1)) != CKR_OK) {
402: error("C_FindObjectsInit failed: %lu", rv);
403: return (-1);
404: }
405: while (1) {
406: /* XXX 3 attributes in attribs[] */
407: for (i = 0; i < 3; i++) {
408: attribs[i].pValue = NULL;
409: attribs[i].ulValueLen = 0;
410: }
411: if ((rv = f->C_FindObjects(session, &obj, 1, &nfound)) != CKR_OK
412: || nfound == 0)
413: break;
414: /* found a key, so figure out size of the attributes */
415: if ((rv = f->C_GetAttributeValue(session, obj, attribs, 3))
416: != CKR_OK) {
417: error("C_GetAttributeValue failed: %lu", rv);
418: continue;
419: }
1.6 markus 420: /* check that none of the attributes are zero length */
421: if (attribs[0].ulValueLen == 0 ||
422: attribs[1].ulValueLen == 0 ||
423: attribs[2].ulValueLen == 0) {
424: continue;
425: }
426: /* allocate buffers for attributes */
1.1 markus 427: for (i = 0; i < 3; i++)
428: attribs[i].pValue = xmalloc(attribs[i].ulValueLen);
429: /* retrieve ID, modulus and public exponent of RSA key */
430: if ((rv = f->C_GetAttributeValue(session, obj, attribs, 3))
431: != CKR_OK) {
432: error("C_GetAttributeValue failed: %lu", rv);
433: } else if ((rsa = RSA_new()) == NULL) {
434: error("RSA_new failed");
435: } else {
436: rsa->n = BN_bin2bn(attribs[1].pValue,
437: attribs[1].ulValueLen, NULL);
438: rsa->e = BN_bin2bn(attribs[2].pValue,
439: attribs[2].ulValueLen, NULL);
440: if (rsa->n && rsa->e &&
441: pkcs11_rsa_wrap(p, slotidx, &attribs[0], rsa) == 0) {
442: key = key_new(KEY_UNSPEC);
443: key->rsa = rsa;
444: key->type = KEY_RSA;
445: key->flags |= KEY_FLAG_EXT;
446: /* expand key array and add key */
447: *keysp = xrealloc(*keysp, *nkeys + 1,
448: sizeof(Key *));
449: (*keysp)[*nkeys] = key;
450: *nkeys = *nkeys + 1;
451: debug("have %d keys", *nkeys);
452: } else {
453: RSA_free(rsa);
454: }
455: }
456: for (i = 0; i < 3; i++)
1.7 ! djm 457: free(attribs[i].pValue);
1.1 markus 458: }
459: if ((rv = f->C_FindObjectsFinal(session)) != CKR_OK)
460: error("C_FindObjectsFinal failed: %lu", rv);
461: return (0);
462: }
463:
1.2 markus 464: #ifdef HAVE_DLOPEN
1.1 markus 465: /* register a new provider, fails if provider already exists */
466: int
467: pkcs11_add_provider(char *provider_id, char *pin, Key ***keyp)
468: {
469: int nkeys, need_finalize = 0;
470: struct pkcs11_provider *p = NULL;
471: void *handle = NULL;
472: CK_RV (*getfunctionlist)(CK_FUNCTION_LIST **);
473: CK_RV rv;
474: CK_FUNCTION_LIST *f = NULL;
475: CK_TOKEN_INFO *token;
476: CK_ULONG i;
477:
478: *keyp = NULL;
479: if (pkcs11_provider_lookup(provider_id) != NULL) {
480: error("provider already registered: %s", provider_id);
481: goto fail;
482: }
483: /* open shared pkcs11-libarary */
484: if ((handle = dlopen(provider_id, RTLD_NOW)) == NULL) {
485: error("dlopen %s failed: %s", provider_id, dlerror());
486: goto fail;
487: }
488: if ((getfunctionlist = dlsym(handle, "C_GetFunctionList")) == NULL) {
489: error("dlsym(C_GetFunctionList) failed: %s", dlerror());
490: goto fail;
491: }
492: p = xcalloc(1, sizeof(*p));
493: p->name = xstrdup(provider_id);
494: p->handle = handle;
495: /* setup the pkcs11 callbacks */
496: if ((rv = (*getfunctionlist)(&f)) != CKR_OK) {
497: error("C_GetFunctionList failed: %lu", rv);
498: goto fail;
499: }
500: p->function_list = f;
501: if ((rv = f->C_Initialize(NULL)) != CKR_OK) {
502: error("C_Initialize failed: %lu", rv);
503: goto fail;
504: }
505: need_finalize = 1;
506: if ((rv = f->C_GetInfo(&p->info)) != CKR_OK) {
507: error("C_GetInfo failed: %lu", rv);
508: goto fail;
509: }
510: rmspace(p->info.manufacturerID, sizeof(p->info.manufacturerID));
511: rmspace(p->info.libraryDescription, sizeof(p->info.libraryDescription));
512: debug("manufacturerID <%s> cryptokiVersion %d.%d"
513: " libraryDescription <%s> libraryVersion %d.%d",
514: p->info.manufacturerID,
515: p->info.cryptokiVersion.major,
516: p->info.cryptokiVersion.minor,
517: p->info.libraryDescription,
518: p->info.libraryVersion.major,
519: p->info.libraryVersion.minor);
520: if ((rv = f->C_GetSlotList(CK_TRUE, NULL, &p->nslots)) != CKR_OK) {
521: error("C_GetSlotList failed: %lu", rv);
522: goto fail;
523: }
524: if (p->nslots == 0) {
525: error("no slots");
526: goto fail;
527: }
528: p->slotlist = xcalloc(p->nslots, sizeof(CK_SLOT_ID));
529: if ((rv = f->C_GetSlotList(CK_TRUE, p->slotlist, &p->nslots))
530: != CKR_OK) {
531: error("C_GetSlotList failed: %lu", rv);
532: goto fail;
533: }
534: p->slotinfo = xcalloc(p->nslots, sizeof(struct pkcs11_slotinfo));
535: p->valid = 1;
536: nkeys = 0;
537: for (i = 0; i < p->nslots; i++) {
538: token = &p->slotinfo[i].token;
539: if ((rv = f->C_GetTokenInfo(p->slotlist[i], token))
540: != CKR_OK) {
541: error("C_GetTokenInfo failed: %lu", rv);
542: continue;
543: }
544: rmspace(token->label, sizeof(token->label));
545: rmspace(token->manufacturerID, sizeof(token->manufacturerID));
546: rmspace(token->model, sizeof(token->model));
547: rmspace(token->serialNumber, sizeof(token->serialNumber));
548: debug("label <%s> manufacturerID <%s> model <%s> serial <%s>"
549: " flags 0x%lx",
550: token->label, token->manufacturerID, token->model,
551: token->serialNumber, token->flags);
552: /* open session, login with pin and retrieve public keys */
553: if (pkcs11_open_session(p, i, pin) == 0)
554: pkcs11_fetch_keys(p, i, keyp, &nkeys);
555: }
556: if (nkeys > 0) {
557: TAILQ_INSERT_TAIL(&pkcs11_providers, p, next);
558: p->refcount++; /* add to provider list */
559: return (nkeys);
560: }
561: error("no keys");
562: /* don't add the provider, since it does not have any keys */
563: fail:
564: if (need_finalize && (rv = f->C_Finalize(NULL)) != CKR_OK)
565: error("C_Finalize failed: %lu", rv);
566: if (p) {
1.7 ! djm 567: free(p->slotlist);
! 568: free(p->slotinfo);
! 569: free(p);
1.1 markus 570: }
571: if (handle)
572: dlclose(handle);
573: return (-1);
574: }
1.2 markus 575: #else
576: int
577: pkcs11_add_provider(char *provider_id, char *pin, Key ***keyp)
578: {
579: error("dlopen() not supported");
580: return (-1);
581: }
582: #endif