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