No empty .Rs/.Re
[netbsd-mini2440.git] / crypto / dist / heimdal / lib / hx509 / ks_p11.c
blobf1638c51c307dba4ad468be917e232391d4271c9
1 /*
2 * Copyright (c) 2004 - 2006 Kungliga Tekniska Högskolan
3 * (Royal Institute of Technology, Stockholm, Sweden).
4 * All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of the Institute nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
34 #include "hx_locl.h"
35 __RCSID("$Heimdal: ks_p11.c 22071 2007-11-14 20:04:50Z lha $"
36 "$NetBSD$");
37 #ifdef HAVE_DLFCN_H
38 #include <dlfcn.h>
39 #endif
41 #ifdef HAVE_DLOPEN
43 #include "pkcs11.h"
45 struct p11_slot {
46 int flags;
47 #define P11_SESSION 1
48 #define P11_SESSION_IN_USE 2
49 #define P11_LOGIN_REQ 4
50 #define P11_LOGIN_DONE 8
51 #define P11_TOKEN_PRESENT 16
52 CK_SESSION_HANDLE session;
53 CK_SLOT_ID id;
54 CK_BBOOL token;
55 char *name;
56 hx509_certs certs;
57 char *pin;
58 struct {
59 CK_MECHANISM_TYPE_PTR list;
60 CK_ULONG num;
61 CK_MECHANISM_INFO_PTR *infos;
62 } mechs;
65 struct p11_module {
66 void *dl_handle;
67 CK_FUNCTION_LIST_PTR funcs;
68 CK_ULONG num_slots;
69 unsigned int refcount;
70 struct p11_slot *slot;
73 #define P11FUNC(module,f,args) (*(module)->funcs->C_##f)args
75 static int p11_get_session(hx509_context,
76 struct p11_module *,
77 struct p11_slot *,
78 hx509_lock,
79 CK_SESSION_HANDLE *);
80 static int p11_put_session(struct p11_module *,
81 struct p11_slot *,
82 CK_SESSION_HANDLE);
83 static void p11_release_module(struct p11_module *);
85 static int p11_list_keys(hx509_context,
86 struct p11_module *,
87 struct p11_slot *,
88 CK_SESSION_HANDLE,
89 hx509_lock,
90 hx509_certs *);
96 struct p11_rsa {
97 struct p11_module *p;
98 struct p11_slot *slot;
99 CK_OBJECT_HANDLE private_key;
100 CK_OBJECT_HANDLE public_key;
103 static int
104 p11_rsa_public_encrypt(int flen,
105 const unsigned char *from,
106 unsigned char *to,
107 RSA *rsa,
108 int padding)
110 return -1;
113 static int
114 p11_rsa_public_decrypt(int flen,
115 const unsigned char *from,
116 unsigned char *to,
117 RSA *rsa,
118 int padding)
120 return -1;
124 static int
125 p11_rsa_private_encrypt(int flen,
126 const unsigned char *from,
127 unsigned char *to,
128 RSA *rsa,
129 int padding)
131 struct p11_rsa *p11rsa = RSA_get_app_data(rsa);
132 CK_OBJECT_HANDLE key = p11rsa->private_key;
133 CK_SESSION_HANDLE session;
134 CK_MECHANISM mechanism;
135 CK_ULONG ck_sigsize;
136 int ret;
138 if (padding != RSA_PKCS1_PADDING)
139 return -1;
141 memset(&mechanism, 0, sizeof(mechanism));
142 mechanism.mechanism = CKM_RSA_PKCS;
144 ck_sigsize = RSA_size(rsa);
146 ret = p11_get_session(NULL, p11rsa->p, p11rsa->slot, NULL, &session);
147 if (ret)
148 return -1;
150 ret = P11FUNC(p11rsa->p, SignInit, (session, &mechanism, key));
151 if (ret != CKR_OK) {
152 p11_put_session(p11rsa->p, p11rsa->slot, session);
153 return -1;
156 ret = P11FUNC(p11rsa->p, Sign,
157 (session, (CK_BYTE *)from, flen, to, &ck_sigsize));
158 p11_put_session(p11rsa->p, p11rsa->slot, session);
159 if (ret != CKR_OK)
160 return -1;
162 return ck_sigsize;
165 static int
166 p11_rsa_private_decrypt(int flen, const unsigned char *from, unsigned char *to,
167 RSA * rsa, int padding)
169 struct p11_rsa *p11rsa = RSA_get_app_data(rsa);
170 CK_OBJECT_HANDLE key = p11rsa->private_key;
171 CK_SESSION_HANDLE session;
172 CK_MECHANISM mechanism;
173 CK_ULONG ck_sigsize;
174 int ret;
176 if (padding != RSA_PKCS1_PADDING)
177 return -1;
179 memset(&mechanism, 0, sizeof(mechanism));
180 mechanism.mechanism = CKM_RSA_PKCS;
182 ck_sigsize = RSA_size(rsa);
184 ret = p11_get_session(NULL, p11rsa->p, p11rsa->slot, NULL, &session);
185 if (ret)
186 return -1;
188 ret = P11FUNC(p11rsa->p, DecryptInit, (session, &mechanism, key));
189 if (ret != CKR_OK) {
190 p11_put_session(p11rsa->p, p11rsa->slot, session);
191 return -1;
194 ret = P11FUNC(p11rsa->p, Decrypt,
195 (session, (CK_BYTE *)from, flen, to, &ck_sigsize));
196 p11_put_session(p11rsa->p, p11rsa->slot, session);
197 if (ret != CKR_OK)
198 return -1;
200 return ck_sigsize;
203 static int
204 p11_rsa_init(RSA *rsa)
206 return 1;
209 static int
210 p11_rsa_finish(RSA *rsa)
212 struct p11_rsa *p11rsa = RSA_get_app_data(rsa);
213 p11_release_module(p11rsa->p);
214 free(p11rsa);
215 return 1;
218 static const RSA_METHOD p11_rsa_pkcs1_method = {
219 "hx509 PKCS11 PKCS#1 RSA",
220 p11_rsa_public_encrypt,
221 p11_rsa_public_decrypt,
222 p11_rsa_private_encrypt,
223 p11_rsa_private_decrypt,
224 NULL,
225 NULL,
226 p11_rsa_init,
227 p11_rsa_finish,
229 NULL,
230 NULL,
231 NULL
238 static int
239 p11_mech_info(hx509_context context,
240 struct p11_module *p,
241 struct p11_slot *slot,
242 int num)
244 CK_ULONG i;
245 int ret;
247 ret = P11FUNC(p, GetMechanismList, (slot->id, NULL_PTR, &i));
248 if (ret) {
249 hx509_set_error_string(context, 0, HX509_PKCS11_NO_MECH,
250 "Failed to get mech list count for slot %d",
251 num);
252 return HX509_PKCS11_NO_MECH;
254 if (i == 0) {
255 hx509_set_error_string(context, 0, HX509_PKCS11_NO_MECH,
256 "no mech supported for slot %d", num);
257 return HX509_PKCS11_NO_MECH;
259 slot->mechs.list = calloc(i, sizeof(slot->mechs.list[0]));
260 if (slot->mechs.list == NULL) {
261 hx509_set_error_string(context, 0, ENOMEM,
262 "out of memory");
263 return ENOMEM;
265 slot->mechs.num = i;
266 ret = P11FUNC(p, GetMechanismList, (slot->id, slot->mechs.list, &i));
267 if (ret) {
268 hx509_set_error_string(context, 0, HX509_PKCS11_NO_MECH,
269 "Failed to get mech list for slot %d",
270 num);
271 return HX509_PKCS11_NO_MECH;
273 assert(i == slot->mechs.num);
275 slot->mechs.infos = calloc(i, sizeof(*slot->mechs.infos));
276 if (slot->mechs.list == NULL) {
277 hx509_set_error_string(context, 0, ENOMEM,
278 "out of memory");
279 return ENOMEM;
282 for (i = 0; i < slot->mechs.num; i++) {
283 slot->mechs.infos[i] = calloc(1, sizeof(*(slot->mechs.infos[0])));
284 if (slot->mechs.infos[i] == NULL) {
285 hx509_set_error_string(context, 0, ENOMEM,
286 "out of memory");
287 return ENOMEM;
289 ret = P11FUNC(p, GetMechanismInfo, (slot->id, slot->mechs.list[i],
290 slot->mechs.infos[i]));
291 if (ret) {
292 hx509_set_error_string(context, 0, HX509_PKCS11_NO_MECH,
293 "Failed to get mech info for slot %d",
294 num);
295 return HX509_PKCS11_NO_MECH;
299 return 0;
302 static int
303 p11_init_slot(hx509_context context,
304 struct p11_module *p,
305 hx509_lock lock,
306 CK_SLOT_ID id,
307 int num,
308 struct p11_slot *slot)
310 CK_SESSION_HANDLE session;
311 CK_SLOT_INFO slot_info;
312 CK_TOKEN_INFO token_info;
313 int ret, i;
315 slot->certs = NULL;
316 slot->id = id;
318 ret = P11FUNC(p, GetSlotInfo, (slot->id, &slot_info));
319 if (ret) {
320 hx509_set_error_string(context, 0, HX509_PKCS11_TOKEN_CONFUSED,
321 "Failed to init PKCS11 slot %d",
322 num);
323 return HX509_PKCS11_TOKEN_CONFUSED;
326 for (i = sizeof(slot_info.slotDescription) - 1; i > 0; i--) {
327 char c = slot_info.slotDescription[i];
328 if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\0')
329 continue;
330 i++;
331 break;
334 asprintf(&slot->name, "%.*s",
335 i, slot_info.slotDescription);
337 if ((slot_info.flags & CKF_TOKEN_PRESENT) == 0)
338 return 0;
340 ret = P11FUNC(p, GetTokenInfo, (slot->id, &token_info));
341 if (ret) {
342 hx509_set_error_string(context, 0, HX509_PKCS11_NO_TOKEN,
343 "Failed to init PKCS11 slot %d "
344 "with error 0x08x",
345 num, ret);
346 return HX509_PKCS11_NO_TOKEN;
348 slot->flags |= P11_TOKEN_PRESENT;
350 if (token_info.flags & CKF_LOGIN_REQUIRED)
351 slot->flags |= P11_LOGIN_REQ;
353 ret = p11_get_session(context, p, slot, lock, &session);
354 if (ret)
355 return ret;
357 ret = p11_mech_info(context, p, slot, num);
358 if (ret)
359 goto out;
361 ret = p11_list_keys(context, p, slot, session, lock, &slot->certs);
362 out:
363 p11_put_session(p, slot, session);
365 return ret;
368 static int
369 p11_get_session(hx509_context context,
370 struct p11_module *p,
371 struct p11_slot *slot,
372 hx509_lock lock,
373 CK_SESSION_HANDLE *psession)
375 CK_RV ret;
377 if (slot->flags & P11_SESSION_IN_USE)
378 _hx509_abort("slot already in session");
380 if (slot->flags & P11_SESSION) {
381 slot->flags |= P11_SESSION_IN_USE;
382 *psession = slot->session;
383 return 0;
386 ret = P11FUNC(p, OpenSession, (slot->id,
387 CKF_SERIAL_SESSION,
388 NULL,
389 NULL,
390 &slot->session));
391 if (ret != CKR_OK) {
392 if (context)
393 hx509_set_error_string(context, 0, HX509_PKCS11_OPEN_SESSION,
394 "Failed to OpenSession for slot id %d "
395 "with error: 0x%08x",
396 (int)slot->id, ret);
397 return HX509_PKCS11_OPEN_SESSION;
400 slot->flags |= P11_SESSION;
403 * If we have have to login, and haven't tried before and have a
404 * prompter or known to work pin code.
406 * This code is very conversative and only uses the prompter in
407 * the hx509_lock, the reason is that it's bad to try many
408 * passwords on a pkcs11 token, it might lock up and have to be
409 * unlocked by a administrator.
411 * XXX try harder to not use pin several times on the same card.
414 if ( (slot->flags & P11_LOGIN_REQ)
415 && (slot->flags & P11_LOGIN_DONE) == 0
416 && (lock || slot->pin))
418 hx509_prompt prompt;
419 char pin[20];
420 char *str;
422 slot->flags |= P11_LOGIN_DONE;
424 if (slot->pin == NULL) {
426 memset(&prompt, 0, sizeof(prompt));
428 asprintf(&str, "PIN code for %s: ", slot->name);
429 prompt.prompt = str;
430 prompt.type = HX509_PROMPT_TYPE_PASSWORD;
431 prompt.reply.data = pin;
432 prompt.reply.length = sizeof(pin);
434 ret = hx509_lock_prompt(lock, &prompt);
435 if (ret) {
436 free(str);
437 if (context)
438 hx509_set_error_string(context, 0, ret,
439 "Failed to get pin code for slot "
440 "id %d with error: %d",
441 (int)slot->id, ret);
442 return ret;
444 free(str);
445 } else {
446 strlcpy(pin, slot->pin, sizeof(pin));
449 ret = P11FUNC(p, Login, (slot->session, CKU_USER,
450 (unsigned char*)pin, strlen(pin)));
451 if (ret != CKR_OK) {
452 if (context)
453 hx509_set_error_string(context, 0, HX509_PKCS11_LOGIN,
454 "Failed to login on slot id %d "
455 "with error: 0x%08x",
456 (int)slot->id, ret);
457 p11_put_session(p, slot, slot->session);
458 return HX509_PKCS11_LOGIN;
460 if (slot->pin == NULL) {
461 slot->pin = strdup(pin);
462 if (slot->pin == NULL) {
463 if (context)
464 hx509_set_error_string(context, 0, ENOMEM,
465 "out of memory");
466 p11_put_session(p, slot, slot->session);
467 return ENOMEM;
470 } else
471 slot->flags |= P11_LOGIN_DONE;
473 slot->flags |= P11_SESSION_IN_USE;
475 *psession = slot->session;
477 return 0;
480 static int
481 p11_put_session(struct p11_module *p,
482 struct p11_slot *slot,
483 CK_SESSION_HANDLE session)
485 if ((slot->flags & P11_SESSION_IN_USE) == 0)
486 _hx509_abort("slot not in session");
487 slot->flags &= ~P11_SESSION_IN_USE;
489 return 0;
492 static int
493 iterate_entries(hx509_context context,
494 struct p11_module *p, struct p11_slot *slot,
495 CK_SESSION_HANDLE session,
496 CK_ATTRIBUTE *search_data, int num_search_data,
497 CK_ATTRIBUTE *query, int num_query,
498 int (*func)(hx509_context,
499 struct p11_module *, struct p11_slot *,
500 CK_SESSION_HANDLE session,
501 CK_OBJECT_HANDLE object,
502 void *, CK_ATTRIBUTE *, int), void *ptr)
504 CK_OBJECT_HANDLE object;
505 CK_ULONG object_count;
506 int ret, i;
508 ret = P11FUNC(p, FindObjectsInit, (session, search_data, num_search_data));
509 if (ret != CKR_OK) {
510 return -1;
512 while (1) {
513 ret = P11FUNC(p, FindObjects, (session, &object, 1, &object_count));
514 if (ret != CKR_OK) {
515 return -1;
517 if (object_count == 0)
518 break;
520 for (i = 0; i < num_query; i++)
521 query[i].pValue = NULL;
523 ret = P11FUNC(p, GetAttributeValue,
524 (session, object, query, num_query));
525 if (ret != CKR_OK) {
526 return -1;
528 for (i = 0; i < num_query; i++) {
529 query[i].pValue = malloc(query[i].ulValueLen);
530 if (query[i].pValue == NULL) {
531 ret = ENOMEM;
532 goto out;
535 ret = P11FUNC(p, GetAttributeValue,
536 (session, object, query, num_query));
537 if (ret != CKR_OK) {
538 ret = -1;
539 goto out;
542 ret = (*func)(context, p, slot, session, object, ptr, query, num_query);
543 if (ret)
544 goto out;
546 for (i = 0; i < num_query; i++) {
547 if (query[i].pValue)
548 free(query[i].pValue);
549 query[i].pValue = NULL;
552 out:
554 for (i = 0; i < num_query; i++) {
555 if (query[i].pValue)
556 free(query[i].pValue);
557 query[i].pValue = NULL;
560 ret = P11FUNC(p, FindObjectsFinal, (session));
561 if (ret != CKR_OK) {
562 return -2;
566 return 0;
569 static BIGNUM *
570 getattr_bn(struct p11_module *p,
571 struct p11_slot *slot,
572 CK_SESSION_HANDLE session,
573 CK_OBJECT_HANDLE object,
574 unsigned int type)
576 CK_ATTRIBUTE query;
577 BIGNUM *bn;
578 int ret;
580 query.type = type;
581 query.pValue = NULL;
582 query.ulValueLen = 0;
584 ret = P11FUNC(p, GetAttributeValue,
585 (session, object, &query, 1));
586 if (ret != CKR_OK)
587 return NULL;
589 query.pValue = malloc(query.ulValueLen);
591 ret = P11FUNC(p, GetAttributeValue,
592 (session, object, &query, 1));
593 if (ret != CKR_OK) {
594 free(query.pValue);
595 return NULL;
597 bn = BN_bin2bn(query.pValue, query.ulValueLen, NULL);
598 free(query.pValue);
600 return bn;
603 static int
604 collect_private_key(hx509_context context,
605 struct p11_module *p, struct p11_slot *slot,
606 CK_SESSION_HANDLE session,
607 CK_OBJECT_HANDLE object,
608 void *ptr, CK_ATTRIBUTE *query, int num_query)
610 struct hx509_collector *collector = ptr;
611 hx509_private_key key;
612 heim_octet_string localKeyId;
613 int ret;
614 RSA *rsa;
615 struct p11_rsa *p11rsa;
617 localKeyId.data = query[0].pValue;
618 localKeyId.length = query[0].ulValueLen;
620 ret = _hx509_private_key_init(&key, NULL, NULL);
621 if (ret)
622 return ret;
624 rsa = RSA_new();
625 if (rsa == NULL)
626 _hx509_abort("out of memory");
629 * The exponent and modulus should always be present according to
630 * the pkcs11 specification, but some smartcards leaves it out,
631 * let ignore any failure to fetch it.
633 rsa->n = getattr_bn(p, slot, session, object, CKA_MODULUS);
634 rsa->e = getattr_bn(p, slot, session, object, CKA_PUBLIC_EXPONENT);
636 p11rsa = calloc(1, sizeof(*p11rsa));
637 if (p11rsa == NULL)
638 _hx509_abort("out of memory");
640 p11rsa->p = p;
641 p11rsa->slot = slot;
642 p11rsa->private_key = object;
644 p->refcount++;
645 if (p->refcount == 0)
646 _hx509_abort("pkcs11 refcount to high");
648 RSA_set_method(rsa, &p11_rsa_pkcs1_method);
649 ret = RSA_set_app_data(rsa, p11rsa);
650 if (ret != 1)
651 _hx509_abort("RSA_set_app_data");
653 _hx509_private_key_assign_rsa(key, rsa);
655 ret = _hx509_collector_private_key_add(context,
656 collector,
657 hx509_signature_rsa(),
658 key,
659 NULL,
660 &localKeyId);
662 if (ret) {
663 _hx509_private_key_free(&key);
664 return ret;
666 return 0;
669 static void
670 p11_cert_release(hx509_cert cert, void *ctx)
672 struct p11_module *p = ctx;
673 p11_release_module(p);
677 static int
678 collect_cert(hx509_context context,
679 struct p11_module *p, struct p11_slot *slot,
680 CK_SESSION_HANDLE session,
681 CK_OBJECT_HANDLE object,
682 void *ptr, CK_ATTRIBUTE *query, int num_query)
684 struct hx509_collector *collector = ptr;
685 hx509_cert cert;
686 int ret;
688 if ((CK_LONG)query[0].ulValueLen == -1 ||
689 (CK_LONG)query[1].ulValueLen == -1)
691 return 0;
694 ret = hx509_cert_init_data(context, query[1].pValue,
695 query[1].ulValueLen, &cert);
696 if (ret)
697 return ret;
699 p->refcount++;
700 if (p->refcount == 0)
701 _hx509_abort("pkcs11 refcount to high");
703 _hx509_cert_set_release(cert, p11_cert_release, p);
706 heim_octet_string data;
708 data.data = query[0].pValue;
709 data.length = query[0].ulValueLen;
711 _hx509_set_cert_attribute(context,
712 cert,
713 oid_id_pkcs_9_at_localKeyId(),
714 &data);
717 if ((CK_LONG)query[2].ulValueLen != -1) {
718 char *str;
720 asprintf(&str, "%.*s",
721 (int)query[2].ulValueLen, (char *)query[2].pValue);
722 if (str) {
723 hx509_cert_set_friendly_name(cert, str);
724 free(str);
728 ret = _hx509_collector_certs_add(context, collector, cert);
729 hx509_cert_free(cert);
731 return ret;
735 static int
736 p11_list_keys(hx509_context context,
737 struct p11_module *p,
738 struct p11_slot *slot,
739 CK_SESSION_HANDLE session,
740 hx509_lock lock,
741 hx509_certs *certs)
743 struct hx509_collector *collector;
744 CK_OBJECT_CLASS key_class;
745 CK_ATTRIBUTE search_data[] = {
746 {CKA_CLASS, NULL, 0},
748 CK_ATTRIBUTE query_data[3] = {
749 {CKA_ID, NULL, 0},
750 {CKA_VALUE, NULL, 0},
751 {CKA_LABEL, NULL, 0}
753 int ret;
755 search_data[0].pValue = &key_class;
756 search_data[0].ulValueLen = sizeof(key_class);
758 if (lock == NULL)
759 lock = _hx509_empty_lock;
761 ret = _hx509_collector_alloc(context, lock, &collector);
762 if (ret)
763 return ret;
765 key_class = CKO_PRIVATE_KEY;
766 ret = iterate_entries(context, p, slot, session,
767 search_data, 1,
768 query_data, 1,
769 collect_private_key, collector);
770 if (ret)
771 goto out;
773 key_class = CKO_CERTIFICATE;
774 ret = iterate_entries(context, p, slot, session,
775 search_data, 1,
776 query_data, 3,
777 collect_cert, collector);
778 if (ret)
779 goto out;
781 ret = _hx509_collector_collect_certs(context, collector, &slot->certs);
783 out:
784 _hx509_collector_free(collector);
786 return ret;
790 static int
791 p11_init(hx509_context context,
792 hx509_certs certs, void **data, int flags,
793 const char *residue, hx509_lock lock)
795 CK_C_GetFunctionList getFuncs;
796 struct p11_module *p;
797 char *list, *str;
798 int ret;
800 *data = NULL;
802 list = strdup(residue);
803 if (list == NULL)
804 return ENOMEM;
806 p = calloc(1, sizeof(*p));
807 if (p == NULL) {
808 free(list);
809 return ENOMEM;
812 p->refcount = 1;
814 str = strchr(list, ',');
815 if (str)
816 *str++ = '\0';
817 while (str) {
818 char *strnext;
819 strnext = strchr(str, ',');
820 if (strnext)
821 *strnext++ = '\0';
822 #if 0
823 if (strncasecmp(str, "slot=", 5) == 0)
824 p->selected_slot = atoi(str + 5);
825 #endif
826 str = strnext;
829 p->dl_handle = dlopen(list, RTLD_NOW);
830 free(list);
831 if (p->dl_handle == NULL) {
832 ret = HX509_PKCS11_LOAD;
833 hx509_set_error_string(context, 0, ret,
834 "Failed to open %s: %s", list, dlerror());
835 goto out;
838 getFuncs = dlsym(p->dl_handle, "C_GetFunctionList");
839 if (getFuncs == NULL) {
840 ret = HX509_PKCS11_LOAD;
841 hx509_set_error_string(context, 0, ret,
842 "C_GetFunctionList missing in %s: %s",
843 list, dlerror());
844 goto out;
847 ret = (*getFuncs)(&p->funcs);
848 if (ret) {
849 ret = HX509_PKCS11_LOAD;
850 hx509_set_error_string(context, 0, ret,
851 "C_GetFunctionList failed in %s", list);
852 goto out;
855 ret = P11FUNC(p, Initialize, (NULL_PTR));
856 if (ret != CKR_OK) {
857 ret = HX509_PKCS11_TOKEN_CONFUSED;
858 hx509_set_error_string(context, 0, ret,
859 "Failed initialize the PKCS11 module");
860 goto out;
863 ret = P11FUNC(p, GetSlotList, (FALSE, NULL, &p->num_slots));
864 if (ret) {
865 ret = HX509_PKCS11_TOKEN_CONFUSED;
866 hx509_set_error_string(context, 0, ret,
867 "Failed to get number of PKCS11 slots");
868 goto out;
871 if (p->num_slots == 0) {
872 ret = HX509_PKCS11_NO_SLOT;
873 hx509_set_error_string(context, 0, ret,
874 "Selected PKCS11 module have no slots");
875 goto out;
880 CK_SLOT_ID_PTR slot_ids;
881 int i, num_tokens = 0;
883 slot_ids = malloc(p->num_slots * sizeof(*slot_ids));
884 if (slot_ids == NULL) {
885 hx509_clear_error_string(context);
886 ret = ENOMEM;
887 goto out;
890 ret = P11FUNC(p, GetSlotList, (FALSE, slot_ids, &p->num_slots));
891 if (ret) {
892 free(slot_ids);
893 hx509_set_error_string(context, 0, HX509_PKCS11_TOKEN_CONFUSED,
894 "Failed getting slot-list from "
895 "PKCS11 module");
896 ret = HX509_PKCS11_TOKEN_CONFUSED;
897 goto out;
900 p->slot = calloc(p->num_slots, sizeof(p->slot[0]));
901 if (p->slot == NULL) {
902 free(slot_ids);
903 hx509_set_error_string(context, 0, ENOMEM,
904 "Failed to get memory for slot-list");
905 ret = ENOMEM;
906 goto out;
909 for (i = 0; i < p->num_slots; i++) {
910 ret = p11_init_slot(context, p, lock, slot_ids[i], i, &p->slot[i]);
911 if (ret)
912 break;
913 if (p->slot[i].flags & P11_TOKEN_PRESENT)
914 num_tokens++;
916 free(slot_ids);
917 if (ret)
918 goto out;
919 if (num_tokens == 0) {
920 ret = HX509_PKCS11_NO_TOKEN;
921 goto out;
925 *data = p;
927 return 0;
928 out:
929 p11_release_module(p);
930 return ret;
933 static void
934 p11_release_module(struct p11_module *p)
936 int i;
938 if (p->refcount == 0)
939 _hx509_abort("pkcs11 refcount to low");
940 if (--p->refcount > 0)
941 return;
943 for (i = 0; i < p->num_slots; i++) {
944 if (p->slot[i].flags & P11_SESSION_IN_USE)
945 _hx509_abort("pkcs11 module release while session in use");
946 if (p->slot[i].flags & P11_SESSION) {
947 int ret;
949 ret = P11FUNC(p, CloseSession, (p->slot[i].session));
950 if (ret != CKR_OK)
954 if (p->slot[i].name)
955 free(p->slot[i].name);
956 if (p->slot[i].pin) {
957 memset(p->slot[i].pin, 0, strlen(p->slot[i].pin));
958 free(p->slot[i].pin);
960 if (p->slot[i].mechs.num) {
961 free(p->slot[i].mechs.list);
963 if (p->slot[i].mechs.infos) {
964 int j;
966 for (j = 0 ; j < p->slot[i].mechs.num ; j++)
967 free(p->slot[i].mechs.infos[j]);
968 free(p->slot[i].mechs.infos);
972 free(p->slot);
974 if (p->funcs)
975 P11FUNC(p, Finalize, (NULL));
977 if (p->dl_handle)
978 dlclose(p->dl_handle);
980 memset(p, 0, sizeof(*p));
981 free(p);
984 static int
985 p11_free(hx509_certs certs, void *data)
987 struct p11_module *p = data;
988 int i;
990 for (i = 0; i < p->num_slots; i++) {
991 if (p->slot[i].certs)
992 hx509_certs_free(&p->slot[i].certs);
994 p11_release_module(p);
995 return 0;
998 struct p11_cursor {
999 hx509_certs certs;
1000 void *cursor;
1003 static int
1004 p11_iter_start(hx509_context context,
1005 hx509_certs certs, void *data, void **cursor)
1007 struct p11_module *p = data;
1008 struct p11_cursor *c;
1009 int ret, i;
1011 c = malloc(sizeof(*c));
1012 if (c == NULL) {
1013 hx509_clear_error_string(context);
1014 return ENOMEM;
1016 ret = hx509_certs_init(context, "MEMORY:pkcs11-iter", 0, NULL, &c->certs);
1017 if (ret) {
1018 free(c);
1019 return ret;
1022 for (i = 0 ; i < p->num_slots; i++) {
1023 if (p->slot[i].certs == NULL)
1024 continue;
1025 ret = hx509_certs_merge(context, c->certs, p->slot[i].certs);
1026 if (ret) {
1027 hx509_certs_free(&c->certs);
1028 free(c);
1029 return ret;
1033 ret = hx509_certs_start_seq(context, c->certs, &c->cursor);
1034 if (ret) {
1035 hx509_certs_free(&c->certs);
1036 free(c);
1037 return 0;
1039 *cursor = c;
1041 return 0;
1044 static int
1045 p11_iter(hx509_context context,
1046 hx509_certs certs, void *data, void *cursor, hx509_cert *cert)
1048 struct p11_cursor *c = cursor;
1049 return hx509_certs_next_cert(context, c->certs, c->cursor, cert);
1052 static int
1053 p11_iter_end(hx509_context context,
1054 hx509_certs certs, void *data, void *cursor)
1056 struct p11_cursor *c = cursor;
1057 int ret;
1058 ret = hx509_certs_end_seq(context, c->certs, c->cursor);
1059 hx509_certs_free(&c->certs);
1060 free(c);
1061 return ret;
1064 #define MECHFLAG(x) { "unknown-flag-" #x, x }
1065 static struct units mechflags[] = {
1066 MECHFLAG(0x80000000),
1067 MECHFLAG(0x40000000),
1068 MECHFLAG(0x20000000),
1069 MECHFLAG(0x10000000),
1070 MECHFLAG(0x08000000),
1071 MECHFLAG(0x04000000),
1072 {"ec-compress", 0x2000000 },
1073 {"ec-uncompress", 0x1000000 },
1074 {"ec-namedcurve", 0x0800000 },
1075 {"ec-ecparameters", 0x0400000 },
1076 {"ec-f-2m", 0x0200000 },
1077 {"ec-f-p", 0x0100000 },
1078 {"derive", 0x0080000 },
1079 {"unwrap", 0x0040000 },
1080 {"wrap", 0x0020000 },
1081 {"genereate-key-pair", 0x0010000 },
1082 {"generate", 0x0008000 },
1083 {"verify-recover", 0x0004000 },
1084 {"verify", 0x0002000 },
1085 {"sign-recover", 0x0001000 },
1086 {"sign", 0x0000800 },
1087 {"digest", 0x0000400 },
1088 {"decrypt", 0x0000200 },
1089 {"encrypt", 0x0000100 },
1090 MECHFLAG(0x00080),
1091 MECHFLAG(0x00040),
1092 MECHFLAG(0x00020),
1093 MECHFLAG(0x00010),
1094 MECHFLAG(0x00008),
1095 MECHFLAG(0x00004),
1096 MECHFLAG(0x00002),
1097 {"hw", 0x0000001 },
1098 { NULL, 0x0000000 }
1100 #undef MECHFLAG
1102 static int
1103 p11_printinfo(hx509_context context,
1104 hx509_certs certs,
1105 void *data,
1106 int (*func)(void *, const char *),
1107 void *ctx)
1109 struct p11_module *p = data;
1110 int i, j;
1112 _hx509_pi_printf(func, ctx, "pkcs11 driver with %d slot%s",
1113 p->num_slots, p->num_slots > 1 ? "s" : "");
1115 for (i = 0; i < p->num_slots; i++) {
1116 struct p11_slot *s = &p->slot[i];
1118 _hx509_pi_printf(func, ctx, "slot %d: id: %d name: %s flags: %08x",
1119 i, (int)s->id, s->name, s->flags);
1121 _hx509_pi_printf(func, ctx, "number of supported mechanisms: %lu",
1122 (unsigned long)s->mechs.num);
1123 for (j = 0; j < s->mechs.num; j++) {
1124 const char *mechname = "unknown";
1125 char flags[256], unknownname[40];
1126 #define MECHNAME(s,n) case s: mechname = n; break
1127 switch(s->mechs.list[j]) {
1128 MECHNAME(CKM_RSA_PKCS_KEY_PAIR_GEN, "rsa-pkcs-key-pair-gen");
1129 MECHNAME(CKM_RSA_PKCS, "rsa-pkcs");
1130 MECHNAME(CKM_RSA_X_509, "rsa-x-509");
1131 MECHNAME(CKM_MD5_RSA_PKCS, "md5-rsa-pkcs");
1132 MECHNAME(CKM_SHA1_RSA_PKCS, "sha1-rsa-pkcs");
1133 MECHNAME(CKM_SHA256_RSA_PKCS, "sha256-rsa-pkcs");
1134 MECHNAME(CKM_SHA384_RSA_PKCS, "sha384-rsa-pkcs");
1135 MECHNAME(CKM_SHA512_RSA_PKCS, "sha512-rsa-pkcs");
1136 MECHNAME(CKM_RIPEMD160_RSA_PKCS, "ripemd160-rsa-pkcs");
1137 MECHNAME(CKM_RSA_PKCS_OAEP, "rsa-pkcs-oaep");
1138 MECHNAME(CKM_SHA512_HMAC, "sha512-hmac");
1139 MECHNAME(CKM_SHA512, "sha512");
1140 MECHNAME(CKM_SHA384_HMAC, "sha384-hmac");
1141 MECHNAME(CKM_SHA384, "sha384");
1142 MECHNAME(CKM_SHA256_HMAC, "sha256-hmac");
1143 MECHNAME(CKM_SHA256, "sha256");
1144 MECHNAME(CKM_SHA_1, "sha1");
1145 MECHNAME(CKM_MD5, "md5");
1146 MECHNAME(CKM_MD2, "md2");
1147 MECHNAME(CKM_RIPEMD160, "ripemd-160");
1148 MECHNAME(CKM_DES_ECB, "des-ecb");
1149 MECHNAME(CKM_DES_CBC, "des-cbc");
1150 MECHNAME(CKM_AES_ECB, "aes-ecb");
1151 MECHNAME(CKM_AES_CBC, "aes-cbc");
1152 MECHNAME(CKM_DH_PKCS_PARAMETER_GEN, "dh-pkcs-parameter-gen");
1153 default:
1154 snprintf(unknownname, sizeof(unknownname),
1155 "unknown-mech-%lu",
1156 (unsigned long)s->mechs.list[j]);
1157 mechname = unknownname;
1158 break;
1160 #undef MECHNAME
1161 unparse_flags(s->mechs.infos[j]->flags, mechflags,
1162 flags, sizeof(flags));
1164 _hx509_pi_printf(func, ctx, " %s: %s", mechname, flags);
1168 return 0;
1171 static struct hx509_keyset_ops keyset_pkcs11 = {
1172 "PKCS11",
1174 p11_init,
1175 NULL,
1176 p11_free,
1177 NULL,
1178 NULL,
1179 p11_iter_start,
1180 p11_iter,
1181 p11_iter_end,
1182 p11_printinfo
1185 #endif /* HAVE_DLOPEN */
1187 void
1188 _hx509_ks_pkcs11_register(hx509_context context)
1190 #ifdef HAVE_DLOPEN
1191 _hx509_ks_register(context, &keyset_pkcs11);
1192 #endif