Annotation of src/usr.bin/ssh/ssh-pkcs11.c, Revision 1.4
1.4 ! djm 1: /* $OpenBSD$ */
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);
117: xfree(p->slotlist);
118: xfree(p->slotinfo);
119: xfree(p);
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);
177: if (k11->keyid)
178: xfree(k11->keyid);
179: xfree(k11);
180: }
181: return (rv);
182: }
183:
184: /* openssl callback doing the actual signing operation */
185: static int
186: pkcs11_rsa_private_encrypt(int flen, const u_char *from, u_char *to, RSA *rsa,
187: int padding)
188: {
189: struct pkcs11_key *k11;
190: struct pkcs11_slotinfo *si;
191: CK_FUNCTION_LIST *f;
192: CK_OBJECT_HANDLE obj;
193: CK_ULONG tlen = 0, nfound = 0;
194: CK_RV rv;
195: CK_OBJECT_CLASS private_key_class = CKO_PRIVATE_KEY;
196: CK_BBOOL true = CK_TRUE;
197: CK_MECHANISM mech = {
198: CKM_RSA_PKCS, NULL_PTR, 0
199: };
200: CK_ATTRIBUTE key_filter[] = {
201: {CKA_CLASS, &private_key_class, sizeof(private_key_class) },
202: {CKA_ID, NULL, 0},
203: {CKA_SIGN, &true, sizeof(true) }
204: };
205: char *pin, prompt[1024];
206: int rval = -1;
207:
208: if ((k11 = RSA_get_app_data(rsa)) == NULL) {
209: error("RSA_get_app_data failed for rsa %p", rsa);
210: return (-1);
211: }
212: if (!k11->provider || !k11->provider->valid) {
213: error("no pkcs11 (valid) provider for rsa %p", rsa);
214: return (-1);
215: }
216: f = k11->provider->function_list;
217: si = &k11->provider->slotinfo[k11->slotidx];
218: if ((si->token.flags & CKF_LOGIN_REQUIRED) && !si->logged_in) {
219: if (!pkcs11_interactive) {
220: error("need pin");
221: return (-1);
222: }
223: snprintf(prompt, sizeof(prompt), "Enter PIN for '%s': ",
224: si->token.label);
225: pin = read_passphrase(prompt, RP_ALLOW_EOF);
226: if (pin == NULL)
227: return (-1); /* bail out */
228: if ((rv = f->C_Login(si->session, CKU_USER, pin, strlen(pin)))
229: != CKR_OK) {
230: xfree(pin);
231: error("C_Login failed: %lu", rv);
232: return (-1);
233: }
234: xfree(pin);
235: si->logged_in = 1;
236: }
237: key_filter[1].pValue = k11->keyid;
238: key_filter[1].ulValueLen = k11->keyid_len;
239: if ((rv = f->C_FindObjectsInit(si->session, key_filter, 3)) != CKR_OK) {
240: error("C_FindObjectsInit failed: %lu", rv);
241: return (-1);
242: }
243: if ((rv = f->C_FindObjects(si->session, &obj, 1, &nfound)) != CKR_OK ||
244: nfound != 1) {
245: error("C_FindObjects failed (%lu nfound): %lu", nfound, rv);
246: } else if ((rv = f->C_SignInit(si->session, &mech, obj)) != CKR_OK) {
247: error("C_SignInit failed: %lu", rv);
248: } else {
249: /* XXX handle CKR_BUFFER_TOO_SMALL */
250: tlen = RSA_size(rsa);
251: rv = f->C_Sign(si->session, (CK_BYTE *)from, flen, to, &tlen);
252: if (rv == CKR_OK)
253: rval = tlen;
254: else
255: error("C_Sign failed: %lu", rv);
256: }
257: if ((rv = f->C_FindObjectsFinal(si->session)) != CKR_OK)
258: error("C_FindObjectsFinal failed: %lu", rv);
259: return (rval);
260: }
261:
262: static int
263: pkcs11_rsa_private_decrypt(int flen, const u_char *from, u_char *to, RSA *rsa,
264: int padding)
265: {
266: return (-1);
267: }
268:
269: /* redirect private key operations for rsa key to pkcs11 token */
270: static int
271: pkcs11_rsa_wrap(struct pkcs11_provider *provider, CK_ULONG slotidx,
272: CK_ATTRIBUTE *keyid_attrib, RSA *rsa)
273: {
274: struct pkcs11_key *k11;
275: const RSA_METHOD *def = RSA_get_default_method();
276:
277: k11 = xcalloc(1, sizeof(*k11));
278: k11->provider = provider;
279: provider->refcount++; /* provider referenced by RSA key */
280: k11->slotidx = slotidx;
281: /* identify key object on smartcard */
282: k11->keyid_len = keyid_attrib->ulValueLen;
283: k11->keyid = xmalloc(k11->keyid_len);
284: memcpy(k11->keyid, keyid_attrib->pValue, k11->keyid_len);
285: k11->orig_finish = def->finish;
286: memcpy(&k11->rsa_method, def, sizeof(k11->rsa_method));
287: k11->rsa_method.name = "pkcs11";
288: k11->rsa_method.rsa_priv_enc = pkcs11_rsa_private_encrypt;
289: k11->rsa_method.rsa_priv_dec = pkcs11_rsa_private_decrypt;
290: k11->rsa_method.finish = pkcs11_rsa_finish;
291: RSA_set_method(rsa, &k11->rsa_method);
292: RSA_set_app_data(rsa, k11);
293: return (0);
294: }
295:
296: /* remove trailing spaces */
297: static void
298: rmspace(char *buf, size_t len)
299: {
300: size_t i;
301:
302: if (!len)
303: return;
304: for (i = len - 1; i > 0; i--)
305: if (i == len - 1 || buf[i] == ' ')
306: buf[i] = '\0';
307: else
308: break;
309: }
310:
311: /*
312: * open a pkcs11 session and login if required.
313: * if pin == NULL we delay login until key use
314: */
315: static int
316: pkcs11_open_session(struct pkcs11_provider *p, CK_ULONG slotidx, char *pin)
317: {
318: CK_RV rv;
319: CK_FUNCTION_LIST *f;
320: CK_SESSION_HANDLE session;
321: int login_required;
322:
323: f = p->function_list;
324: login_required = p->slotinfo[slotidx].token.flags & CKF_LOGIN_REQUIRED;
325: if (pin && login_required && !strlen(pin)) {
326: error("pin required");
327: return (-1);
328: }
329: if ((rv = f->C_OpenSession(p->slotlist[slotidx], CKF_RW_SESSION|
330: CKF_SERIAL_SESSION, NULL, NULL, &session))
331: != CKR_OK) {
332: error("C_OpenSession failed: %lu", rv);
333: return (-1);
334: }
335: if (login_required && pin) {
336: if ((rv = f->C_Login(session, CKU_USER, pin, strlen(pin)))
337: != CKR_OK) {
338: error("C_Login failed: %lu", rv);
339: if ((rv = f->C_CloseSession(session)) != CKR_OK)
340: error("C_CloseSession failed: %lu", rv);
341: return (-1);
342: }
343: p->slotinfo[slotidx].logged_in = 1;
344: }
345: p->slotinfo[slotidx].session = session;
346: return (0);
347: }
348:
349: /*
350: * lookup public keys for token in slot identified by slotidx,
351: * add 'wrapped' public keys to the 'keysp' array and increment nkeys.
352: * keysp points to an (possibly empty) array with *nkeys keys.
353: */
354: static int
355: pkcs11_fetch_keys(struct pkcs11_provider *p, CK_ULONG slotidx, Key ***keysp,
356: int *nkeys)
357: {
358: Key *key;
359: RSA *rsa;
360: int i;
361: CK_RV rv;
362: CK_OBJECT_HANDLE obj;
363: CK_ULONG nfound;
364: CK_SESSION_HANDLE session;
365: CK_FUNCTION_LIST *f;
366: CK_OBJECT_CLASS pubkey_class = CKO_PUBLIC_KEY;
367: CK_ATTRIBUTE pubkey_filter[] = {
368: { CKA_CLASS, &pubkey_class, sizeof(pubkey_class) }
369: };
370: CK_ATTRIBUTE attribs[] = {
371: { CKA_ID, NULL, 0 },
372: { CKA_MODULUS, NULL, 0 },
373: { CKA_PUBLIC_EXPONENT, NULL, 0 }
374: };
375:
376: f = p->function_list;
377: session = p->slotinfo[slotidx].session;
378: /* setup a filter the looks for public keys */
379: if ((rv = f->C_FindObjectsInit(session, pubkey_filter, 1)) != CKR_OK) {
380: error("C_FindObjectsInit failed: %lu", rv);
381: return (-1);
382: }
383: while (1) {
384: /* XXX 3 attributes in attribs[] */
385: for (i = 0; i < 3; i++) {
386: attribs[i].pValue = NULL;
387: attribs[i].ulValueLen = 0;
388: }
389: if ((rv = f->C_FindObjects(session, &obj, 1, &nfound)) != CKR_OK
390: || nfound == 0)
391: break;
392: /* found a key, so figure out size of the attributes */
393: if ((rv = f->C_GetAttributeValue(session, obj, attribs, 3))
394: != CKR_OK) {
395: error("C_GetAttributeValue failed: %lu", rv);
396: continue;
397: }
398: /* allocate buffers for attributes, XXX check ulValueLen? */
399: for (i = 0; i < 3; i++)
400: attribs[i].pValue = xmalloc(attribs[i].ulValueLen);
401: /* retrieve ID, modulus and public exponent of RSA key */
402: if ((rv = f->C_GetAttributeValue(session, obj, attribs, 3))
403: != CKR_OK) {
404: error("C_GetAttributeValue failed: %lu", rv);
405: } else if ((rsa = RSA_new()) == NULL) {
406: error("RSA_new failed");
407: } else {
408: rsa->n = BN_bin2bn(attribs[1].pValue,
409: attribs[1].ulValueLen, NULL);
410: rsa->e = BN_bin2bn(attribs[2].pValue,
411: attribs[2].ulValueLen, NULL);
412: if (rsa->n && rsa->e &&
413: pkcs11_rsa_wrap(p, slotidx, &attribs[0], rsa) == 0) {
414: key = key_new(KEY_UNSPEC);
415: key->rsa = rsa;
416: key->type = KEY_RSA;
417: key->flags |= KEY_FLAG_EXT;
418: /* expand key array and add key */
419: *keysp = xrealloc(*keysp, *nkeys + 1,
420: sizeof(Key *));
421: (*keysp)[*nkeys] = key;
422: *nkeys = *nkeys + 1;
423: debug("have %d keys", *nkeys);
424: } else {
425: RSA_free(rsa);
426: }
427: }
428: for (i = 0; i < 3; i++)
429: xfree(attribs[i].pValue);
430: }
431: if ((rv = f->C_FindObjectsFinal(session)) != CKR_OK)
432: error("C_FindObjectsFinal failed: %lu", rv);
433: return (0);
434: }
435:
1.2 markus 436: #ifdef HAVE_DLOPEN
1.1 markus 437: /* register a new provider, fails if provider already exists */
438: int
439: pkcs11_add_provider(char *provider_id, char *pin, Key ***keyp)
440: {
441: int nkeys, need_finalize = 0;
442: struct pkcs11_provider *p = NULL;
443: void *handle = NULL;
444: CK_RV (*getfunctionlist)(CK_FUNCTION_LIST **);
445: CK_RV rv;
446: CK_FUNCTION_LIST *f = NULL;
447: CK_TOKEN_INFO *token;
448: CK_ULONG i;
449:
450: *keyp = NULL;
451: if (pkcs11_provider_lookup(provider_id) != NULL) {
452: error("provider already registered: %s", provider_id);
453: goto fail;
454: }
455: /* open shared pkcs11-libarary */
456: if ((handle = dlopen(provider_id, RTLD_NOW)) == NULL) {
457: error("dlopen %s failed: %s", provider_id, dlerror());
458: goto fail;
459: }
460: if ((getfunctionlist = dlsym(handle, "C_GetFunctionList")) == NULL) {
461: error("dlsym(C_GetFunctionList) failed: %s", dlerror());
462: goto fail;
463: }
464: p = xcalloc(1, sizeof(*p));
465: p->name = xstrdup(provider_id);
466: p->handle = handle;
467: /* setup the pkcs11 callbacks */
468: if ((rv = (*getfunctionlist)(&f)) != CKR_OK) {
469: error("C_GetFunctionList failed: %lu", rv);
470: goto fail;
471: }
472: p->function_list = f;
473: if ((rv = f->C_Initialize(NULL)) != CKR_OK) {
474: error("C_Initialize failed: %lu", rv);
475: goto fail;
476: }
477: need_finalize = 1;
478: if ((rv = f->C_GetInfo(&p->info)) != CKR_OK) {
479: error("C_GetInfo failed: %lu", rv);
480: goto fail;
481: }
482: rmspace(p->info.manufacturerID, sizeof(p->info.manufacturerID));
483: rmspace(p->info.libraryDescription, sizeof(p->info.libraryDescription));
484: debug("manufacturerID <%s> cryptokiVersion %d.%d"
485: " libraryDescription <%s> libraryVersion %d.%d",
486: p->info.manufacturerID,
487: p->info.cryptokiVersion.major,
488: p->info.cryptokiVersion.minor,
489: p->info.libraryDescription,
490: p->info.libraryVersion.major,
491: p->info.libraryVersion.minor);
492: if ((rv = f->C_GetSlotList(CK_TRUE, NULL, &p->nslots)) != CKR_OK) {
493: error("C_GetSlotList failed: %lu", rv);
494: goto fail;
495: }
496: if (p->nslots == 0) {
497: error("no slots");
498: goto fail;
499: }
500: p->slotlist = xcalloc(p->nslots, sizeof(CK_SLOT_ID));
501: if ((rv = f->C_GetSlotList(CK_TRUE, p->slotlist, &p->nslots))
502: != CKR_OK) {
503: error("C_GetSlotList failed: %lu", rv);
504: goto fail;
505: }
506: p->slotinfo = xcalloc(p->nslots, sizeof(struct pkcs11_slotinfo));
507: p->valid = 1;
508: nkeys = 0;
509: for (i = 0; i < p->nslots; i++) {
510: token = &p->slotinfo[i].token;
511: if ((rv = f->C_GetTokenInfo(p->slotlist[i], token))
512: != CKR_OK) {
513: error("C_GetTokenInfo failed: %lu", rv);
514: continue;
515: }
516: rmspace(token->label, sizeof(token->label));
517: rmspace(token->manufacturerID, sizeof(token->manufacturerID));
518: rmspace(token->model, sizeof(token->model));
519: rmspace(token->serialNumber, sizeof(token->serialNumber));
520: debug("label <%s> manufacturerID <%s> model <%s> serial <%s>"
521: " flags 0x%lx",
522: token->label, token->manufacturerID, token->model,
523: token->serialNumber, token->flags);
524: /* open session, login with pin and retrieve public keys */
525: if (pkcs11_open_session(p, i, pin) == 0)
526: pkcs11_fetch_keys(p, i, keyp, &nkeys);
527: }
528: if (nkeys > 0) {
529: TAILQ_INSERT_TAIL(&pkcs11_providers, p, next);
530: p->refcount++; /* add to provider list */
531: return (nkeys);
532: }
533: error("no keys");
534: /* don't add the provider, since it does not have any keys */
535: fail:
536: if (need_finalize && (rv = f->C_Finalize(NULL)) != CKR_OK)
537: error("C_Finalize failed: %lu", rv);
538: if (p) {
539: if (p->slotlist)
540: xfree(p->slotlist);
541: if (p->slotinfo)
542: xfree(p->slotinfo);
543: xfree(p);
544: }
545: if (handle)
546: dlclose(handle);
547: return (-1);
548: }
1.2 markus 549: #else
550: int
551: pkcs11_add_provider(char *provider_id, char *pin, Key ***keyp)
552: {
553: error("dlopen() not supported");
554: return (-1);
555: }
556: #endif