]> CyberLeo.Net >> Repos - FreeBSD/releng/10.0.git/blob - crypto/openssh/ssh-pkcs11.c
- Copy stable/10 (r259064) to releng/10.0 as part of the
[FreeBSD/releng/10.0.git] / crypto / openssh / ssh-pkcs11.c
1 /* $OpenBSD: ssh-pkcs11.c,v 1.8 2013/07/12 00:20:00 djm Exp $ */
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 "includes.h"
19
20 #ifdef ENABLE_PKCS11
21
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>
28
29 #include <string.h>
30 #include <dlfcn.h>
31
32 #include "openbsd-compat/sys-queue.h"
33
34 #define CRYPTOKI_COMPAT
35 #include "pkcs11.h"
36
37 #include "log.h"
38 #include "misc.h"
39 #include "key.h"
40 #include "ssh-pkcs11.h"
41 #include "xmalloc.h"
42
43 struct pkcs11_slotinfo {
44         CK_TOKEN_INFO           token;
45         CK_SESSION_HANDLE       session;
46         int                     logged_in;
47 };
48
49 struct pkcs11_provider {
50         char                    *name;
51         void                    *handle;
52         CK_FUNCTION_LIST        *function_list;
53         CK_INFO                 info;
54         CK_ULONG                nslots;
55         CK_SLOT_ID              *slotlist;
56         struct pkcs11_slotinfo  *slotinfo;
57         int                     valid;
58         int                     refcount;
59         TAILQ_ENTRY(pkcs11_provider) next;
60 };
61
62 TAILQ_HEAD(, pkcs11_provider) pkcs11_providers;
63
64 struct pkcs11_key {
65         struct pkcs11_provider  *provider;
66         CK_ULONG                slotidx;
67         int                     (*orig_finish)(RSA *rsa);
68         RSA_METHOD              rsa_method;
69         char                    *keyid;
70         int                     keyid_len;
71 };
72
73 int pkcs11_interactive = 0;
74
75 int
76 pkcs11_init(int interactive)
77 {
78         pkcs11_interactive = interactive;
79         TAILQ_INIT(&pkcs11_providers);
80         return (0);
81 }
82
83 /*
84  * finalize a provider shared libarary, it's no longer usable.
85  * however, there might still be keys referencing this provider,
86  * so the actuall freeing of memory is handled by pkcs11_provider_unref().
87  * this is called when a provider gets unregistered.
88  */
89 static void
90 pkcs11_provider_finalize(struct pkcs11_provider *p)
91 {
92         CK_RV rv;
93         CK_ULONG i;
94
95         debug("pkcs11_provider_finalize: %p refcount %d valid %d",
96             p, p->refcount, p->valid);
97         if (!p->valid)
98                 return;
99         for (i = 0; i < p->nslots; i++) {
100                 if (p->slotinfo[i].session &&
101                     (rv = p->function_list->C_CloseSession(
102                     p->slotinfo[i].session)) != CKR_OK)
103                         error("C_CloseSession failed: %lu", rv);
104         }
105         if ((rv = p->function_list->C_Finalize(NULL)) != CKR_OK)
106                 error("C_Finalize failed: %lu", rv);
107         p->valid = 0;
108         p->function_list = NULL;
109         dlclose(p->handle);
110 }
111
112 /*
113  * remove a reference to the provider.
114  * called when a key gets destroyed or when the provider is unregistered.
115  */
116 static void
117 pkcs11_provider_unref(struct pkcs11_provider *p)
118 {
119         debug("pkcs11_provider_unref: %p refcount %d", p, p->refcount);
120         if (--p->refcount <= 0) {
121                 if (p->valid)
122                         error("pkcs11_provider_unref: %p still valid", p);
123                 free(p->slotlist);
124                 free(p->slotinfo);
125                 free(p);
126         }
127 }
128
129 /* unregister all providers, keys might still point to the providers */
130 void
131 pkcs11_terminate(void)
132 {
133         struct pkcs11_provider *p;
134
135         while ((p = TAILQ_FIRST(&pkcs11_providers)) != NULL) {
136                 TAILQ_REMOVE(&pkcs11_providers, p, next);
137                 pkcs11_provider_finalize(p);
138                 pkcs11_provider_unref(p);
139         }
140 }
141
142 /* lookup provider by name */
143 static struct pkcs11_provider *
144 pkcs11_provider_lookup(char *provider_id)
145 {
146         struct pkcs11_provider *p;
147
148         TAILQ_FOREACH(p, &pkcs11_providers, next) {
149                 debug("check %p %s", p, p->name);
150                 if (!strcmp(provider_id, p->name))
151                         return (p);
152         }
153         return (NULL);
154 }
155
156 /* unregister provider by name */
157 int
158 pkcs11_del_provider(char *provider_id)
159 {
160         struct pkcs11_provider *p;
161
162         if ((p = pkcs11_provider_lookup(provider_id)) != NULL) {
163                 TAILQ_REMOVE(&pkcs11_providers, p, next);
164                 pkcs11_provider_finalize(p);
165                 pkcs11_provider_unref(p);
166                 return (0);
167         }
168         return (-1);
169 }
170
171 /* openssl callback for freeing an RSA key */
172 static int
173 pkcs11_rsa_finish(RSA *rsa)
174 {
175         struct pkcs11_key       *k11;
176         int rv = -1;
177
178         if ((k11 = RSA_get_app_data(rsa)) != NULL) {
179                 if (k11->orig_finish)
180                         rv = k11->orig_finish(rsa);
181                 if (k11->provider)
182                         pkcs11_provider_unref(k11->provider);
183                 free(k11->keyid);
184                 free(k11);
185         }
186         return (rv);
187 }
188
189 /* find a single 'obj' for given attributes */
190 static int
191 pkcs11_find(struct pkcs11_provider *p, CK_ULONG slotidx, CK_ATTRIBUTE *attr,
192     CK_ULONG nattr, CK_OBJECT_HANDLE *obj)
193 {
194         CK_FUNCTION_LIST        *f;
195         CK_SESSION_HANDLE       session;
196         CK_ULONG                nfound = 0;
197         CK_RV                   rv;
198         int                     ret = -1;
199
200         f = p->function_list;
201         session = p->slotinfo[slotidx].session;
202         if ((rv = f->C_FindObjectsInit(session, attr, nattr)) != CKR_OK) {
203                 error("C_FindObjectsInit failed (nattr %lu): %lu", nattr, rv);
204                 return (-1);
205         }
206         if ((rv = f->C_FindObjects(session, obj, 1, &nfound)) != CKR_OK ||
207             nfound != 1) {
208                 debug("C_FindObjects failed (nfound %lu nattr %lu): %lu",
209                     nfound, nattr, rv);
210         } else
211                 ret = 0;
212         if ((rv = f->C_FindObjectsFinal(session)) != CKR_OK)
213                 error("C_FindObjectsFinal failed: %lu", rv);
214         return (ret);
215 }
216
217 /* openssl callback doing the actual signing operation */
218 static int
219 pkcs11_rsa_private_encrypt(int flen, const u_char *from, u_char *to, RSA *rsa,
220     int padding)
221 {
222         struct pkcs11_key       *k11;
223         struct pkcs11_slotinfo  *si;
224         CK_FUNCTION_LIST        *f;
225         CK_OBJECT_HANDLE        obj;
226         CK_ULONG                tlen = 0;
227         CK_RV                   rv;
228         CK_OBJECT_CLASS         private_key_class = CKO_PRIVATE_KEY;
229         CK_BBOOL                true_val = CK_TRUE;
230         CK_MECHANISM            mech = {
231                 CKM_RSA_PKCS, NULL_PTR, 0
232         };
233         CK_ATTRIBUTE            key_filter[] = {
234                 {CKA_CLASS, NULL, sizeof(private_key_class) },
235                 {CKA_ID, NULL, 0},
236                 {CKA_SIGN, NULL, sizeof(true_val) }
237         };
238         char                    *pin, prompt[1024];
239         int                     rval = -1;
240
241         /* some compilers complain about non-constant initializer so we
242            use NULL in CK_ATTRIBUTE above and set the values here */
243         key_filter[0].pValue = &private_key_class;
244         key_filter[2].pValue = &true_val;
245
246         if ((k11 = RSA_get_app_data(rsa)) == NULL) {
247                 error("RSA_get_app_data failed for rsa %p", rsa);
248                 return (-1);
249         }
250         if (!k11->provider || !k11->provider->valid) {
251                 error("no pkcs11 (valid) provider for rsa %p", rsa);
252                 return (-1);
253         }
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);
260                 }
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);
271                 }
272                 free(pin);
273                 si->logged_in = 1;
274         }
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);
291         }
292         return (rval);
293 }
294
295 static int
296 pkcs11_rsa_private_decrypt(int flen, const u_char *from, u_char *to, RSA *rsa,
297     int padding)
298 {
299         return (-1);
300 }
301
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)
306 {
307         struct pkcs11_key       *k11;
308         const RSA_METHOD        *def = RSA_get_default_method();
309
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);
327 }
328
329 /* remove trailing spaces */
330 static void
331 rmspace(u_char *buf, size_t len)
332 {
333         size_t i;
334
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;
342 }
343
344 /*
345  * open a pkcs11 session and login if required.
346  * if pin == NULL we delay login until key use
347  */
348 static int
349 pkcs11_open_session(struct pkcs11_provider *p, CK_ULONG slotidx, char *pin)
350 {
351         CK_RV                   rv;
352         CK_FUNCTION_LIST        *f;
353         CK_SESSION_HANDLE       session;
354         int                     login_required;
355
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);
361         }
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);
367         }
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);
375                 }
376                 p->slotinfo[slotidx].logged_in = 1;
377         }
378         p->slotinfo[slotidx].session = session;
379         return (0);
380 }
381
382 /*
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.
386  */
387 static int
388 pkcs11_fetch_keys(struct pkcs11_provider *p, CK_ULONG slotidx, Key ***keysp,
389     int *nkeys)
390 {
391         Key                     *key;
392         RSA                     *rsa;
393         int                     i;
394         CK_RV                   rv;
395         CK_OBJECT_HANDLE        obj;
396         CK_ULONG                nfound;
397         CK_SESSION_HANDLE       session;
398         CK_FUNCTION_LIST        *f;
399         CK_OBJECT_CLASS         pubkey_class = CKO_PUBLIC_KEY;
400         CK_ATTRIBUTE            pubkey_filter[] = {
401                 { CKA_CLASS, NULL, sizeof(pubkey_class) }
402         };
403         CK_ATTRIBUTE            attribs[] = {
404                 { CKA_ID, NULL, 0 },
405                 { CKA_MODULUS, NULL, 0 },
406                 { CKA_PUBLIC_EXPONENT, NULL, 0 }
407         };
408
409         /* some compilers complain about non-constant initializer so we
410            use NULL in CK_ATTRIBUTE above and set the value here */
411         pubkey_filter[0].pValue = &pubkey_class;
412
413         f = p->function_list;
414         session = p->slotinfo[slotidx].session;
415         /* setup a filter the looks for public keys */
416         if ((rv = f->C_FindObjectsInit(session, pubkey_filter, 1)) != CKR_OK) {
417                 error("C_FindObjectsInit failed: %lu", rv);
418                 return (-1);
419         }
420         while (1) {
421                 /* XXX 3 attributes in attribs[] */
422                 for (i = 0; i < 3; i++) {
423                         attribs[i].pValue = NULL;
424                         attribs[i].ulValueLen = 0;
425                 }
426                 if ((rv = f->C_FindObjects(session, &obj, 1, &nfound)) != CKR_OK
427                     || nfound == 0)
428                         break;
429                 /* found a key, so figure out size of the attributes */
430                 if ((rv = f->C_GetAttributeValue(session, obj, attribs, 3))
431                     != CKR_OK) {
432                         error("C_GetAttributeValue failed: %lu", rv);
433                         continue;
434                 }
435                 /* check that none of the attributes are zero length */
436                 if (attribs[0].ulValueLen == 0 ||
437                     attribs[1].ulValueLen == 0 ||
438                     attribs[2].ulValueLen == 0) {
439                         continue;
440                 }
441                 /* allocate buffers for attributes */
442                 for (i = 0; i < 3; i++)
443                         attribs[i].pValue = xmalloc(attribs[i].ulValueLen);
444                 /* retrieve ID, modulus and public exponent of RSA key */
445                 if ((rv = f->C_GetAttributeValue(session, obj, attribs, 3))
446                     != CKR_OK) {
447                         error("C_GetAttributeValue failed: %lu", rv);
448                 } else if ((rsa = RSA_new()) == NULL) {
449                         error("RSA_new failed");
450                 } else {
451                         rsa->n = BN_bin2bn(attribs[1].pValue,
452                             attribs[1].ulValueLen, NULL);
453                         rsa->e = BN_bin2bn(attribs[2].pValue,
454                             attribs[2].ulValueLen, NULL);
455                         if (rsa->n && rsa->e &&
456                             pkcs11_rsa_wrap(p, slotidx, &attribs[0], rsa) == 0) {
457                                 key = key_new(KEY_UNSPEC);
458                                 key->rsa = rsa;
459                                 key->type = KEY_RSA;
460                                 key->flags |= KEY_FLAG_EXT;
461                                 /* expand key array and add key */
462                                 *keysp = xrealloc(*keysp, *nkeys + 1,
463                                     sizeof(Key *));
464                                 (*keysp)[*nkeys] = key;
465                                 *nkeys = *nkeys + 1;
466                                 debug("have %d keys", *nkeys);
467                         } else {
468                                 RSA_free(rsa);
469                         }
470                 }
471                 for (i = 0; i < 3; i++)
472                         free(attribs[i].pValue);
473         }
474         if ((rv = f->C_FindObjectsFinal(session)) != CKR_OK)
475                 error("C_FindObjectsFinal failed: %lu", rv);
476         return (0);
477 }
478
479 /* register a new provider, fails if provider already exists */
480 int
481 pkcs11_add_provider(char *provider_id, char *pin, Key ***keyp)
482 {
483         int nkeys, need_finalize = 0;
484         struct pkcs11_provider *p = NULL;
485         void *handle = NULL;
486         CK_RV (*getfunctionlist)(CK_FUNCTION_LIST **);
487         CK_RV rv;
488         CK_FUNCTION_LIST *f = NULL;
489         CK_TOKEN_INFO *token;
490         CK_ULONG i;
491
492         *keyp = NULL;
493         if (pkcs11_provider_lookup(provider_id) != NULL) {
494                 error("provider already registered: %s", provider_id);
495                 goto fail;
496         }
497         /* open shared pkcs11-libarary */
498         if ((handle = dlopen(provider_id, RTLD_NOW)) == NULL) {
499                 error("dlopen %s failed: %s", provider_id, dlerror());
500                 goto fail;
501         }
502         if ((getfunctionlist = dlsym(handle, "C_GetFunctionList")) == NULL) {
503                 error("dlsym(C_GetFunctionList) failed: %s", dlerror());
504                 goto fail;
505         }
506         p = xcalloc(1, sizeof(*p));
507         p->name = xstrdup(provider_id);
508         p->handle = handle;
509         /* setup the pkcs11 callbacks */
510         if ((rv = (*getfunctionlist)(&f)) != CKR_OK) {
511                 error("C_GetFunctionList failed: %lu", rv);
512                 goto fail;
513         }
514         p->function_list = f;
515         if ((rv = f->C_Initialize(NULL)) != CKR_OK) {
516                 error("C_Initialize failed: %lu", rv);
517                 goto fail;
518         }
519         need_finalize = 1;
520         if ((rv = f->C_GetInfo(&p->info)) != CKR_OK) {
521                 error("C_GetInfo failed: %lu", rv);
522                 goto fail;
523         }
524         rmspace(p->info.manufacturerID, sizeof(p->info.manufacturerID));
525         rmspace(p->info.libraryDescription, sizeof(p->info.libraryDescription));
526         debug("manufacturerID <%s> cryptokiVersion %d.%d"
527             " libraryDescription <%s> libraryVersion %d.%d",
528             p->info.manufacturerID,
529             p->info.cryptokiVersion.major,
530             p->info.cryptokiVersion.minor,
531             p->info.libraryDescription,
532             p->info.libraryVersion.major,
533             p->info.libraryVersion.minor);
534         if ((rv = f->C_GetSlotList(CK_TRUE, NULL, &p->nslots)) != CKR_OK) {
535                 error("C_GetSlotList failed: %lu", rv);
536                 goto fail;
537         }
538         if (p->nslots == 0) {
539                 error("no slots");
540                 goto fail;
541         }
542         p->slotlist = xcalloc(p->nslots, sizeof(CK_SLOT_ID));
543         if ((rv = f->C_GetSlotList(CK_TRUE, p->slotlist, &p->nslots))
544             != CKR_OK) {
545                 error("C_GetSlotList failed: %lu", rv);
546                 goto fail;
547         }
548         p->slotinfo = xcalloc(p->nslots, sizeof(struct pkcs11_slotinfo));
549         p->valid = 1;
550         nkeys = 0;
551         for (i = 0; i < p->nslots; i++) {
552                 token = &p->slotinfo[i].token;
553                 if ((rv = f->C_GetTokenInfo(p->slotlist[i], token))
554                     != CKR_OK) {
555                         error("C_GetTokenInfo failed: %lu", rv);
556                         continue;
557                 }
558                 rmspace(token->label, sizeof(token->label));
559                 rmspace(token->manufacturerID, sizeof(token->manufacturerID));
560                 rmspace(token->model, sizeof(token->model));
561                 rmspace(token->serialNumber, sizeof(token->serialNumber));
562                 debug("label <%s> manufacturerID <%s> model <%s> serial <%s>"
563                     " flags 0x%lx",
564                     token->label, token->manufacturerID, token->model,
565                     token->serialNumber, token->flags);
566                 /* open session, login with pin and retrieve public keys */
567                 if (pkcs11_open_session(p, i, pin) == 0)
568                         pkcs11_fetch_keys(p, i, keyp, &nkeys);
569         }
570         if (nkeys > 0) {
571                 TAILQ_INSERT_TAIL(&pkcs11_providers, p, next);
572                 p->refcount++;  /* add to provider list */
573                 return (nkeys);
574         }
575         error("no keys");
576         /* don't add the provider, since it does not have any keys */
577 fail:
578         if (need_finalize && (rv = f->C_Finalize(NULL)) != CKR_OK)
579                 error("C_Finalize failed: %lu", rv);
580         if (p) {
581                 free(p->slotlist);
582                 free(p->slotinfo);
583                 free(p);
584         }
585         if (handle)
586                 dlclose(handle);
587         return (-1);
588 }
589
590 #else
591
592 int
593 pkcs11_init(int interactive)
594 {
595         return (0);
596 }
597
598 void
599 pkcs11_terminate(void)
600 {
601         return;
602 }
603
604 #endif /* ENABLE_PKCS11 */