Add ability to specifiy PKCS#11 slot number when using hx509
[heimdal.git] / lib / hx509 / ks_p11.c
blob12037e6aa83063257fd1ae2566db4c5e1e43c625
1 /*
2 * Copyright (c) 2004 - 2008 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 #ifdef HAVE_DLFCN_H
36 #include <dlfcn.h>
37 #endif
39 #ifdef HAVE_DLOPEN
41 #include "pkcs11.h"
43 struct p11_slot {
44 int flags;
45 #define P11_SESSION 1
46 #define P11_SESSION_IN_USE 2
47 #define P11_LOGIN_REQ 4
48 #define P11_LOGIN_DONE 8
49 #define P11_TOKEN_PRESENT 16
50 CK_SESSION_HANDLE session;
51 CK_SLOT_ID id;
52 CK_BBOOL token;
53 char *name;
54 hx509_certs certs;
55 char *pin;
56 struct {
57 CK_MECHANISM_TYPE_PTR list;
58 CK_ULONG num;
59 CK_MECHANISM_INFO_PTR *infos;
60 } mechs;
63 struct p11_module {
64 void *dl_handle;
65 CK_FUNCTION_LIST_PTR funcs;
66 CK_ULONG num_slots;
67 unsigned int ref;
68 unsigned int selected_slot;
69 struct p11_slot *slot;
72 #define P11FUNC(module,f,args) (*(module)->funcs->C_##f)args
74 static int p11_get_session(hx509_context,
75 struct p11_module *,
76 struct p11_slot *,
77 hx509_lock,
78 CK_SESSION_HANDLE *);
79 static int p11_put_session(struct p11_module *,
80 struct p11_slot *,
81 CK_SESSION_HANDLE);
82 static void p11_release_module(struct p11_module *);
84 static int p11_list_keys(hx509_context,
85 struct p11_module *,
86 struct p11_slot *,
87 CK_SESSION_HANDLE,
88 hx509_lock,
89 hx509_certs *);
95 struct p11_rsa {
96 struct p11_module *p;
97 struct p11_slot *slot;
98 CK_OBJECT_HANDLE private_key;
99 CK_OBJECT_HANDLE public_key;
102 static int
103 p11_rsa_public_encrypt(int flen,
104 const unsigned char *from,
105 unsigned char *to,
106 RSA *rsa,
107 int padding)
109 return -1;
112 static int
113 p11_rsa_public_decrypt(int flen,
114 const unsigned char *from,
115 unsigned char *to,
116 RSA *rsa,
117 int padding)
119 return -1;
123 static int
124 p11_rsa_private_encrypt(int flen,
125 const unsigned char *from,
126 unsigned char *to,
127 RSA *rsa,
128 int padding)
130 struct p11_rsa *p11rsa = RSA_get_app_data(rsa);
131 CK_OBJECT_HANDLE key = p11rsa->private_key;
132 CK_SESSION_HANDLE session;
133 CK_MECHANISM mechanism;
134 CK_ULONG ck_sigsize;
135 int ret;
137 if (padding != RSA_PKCS1_PADDING)
138 return -1;
140 memset(&mechanism, 0, sizeof(mechanism));
141 mechanism.mechanism = CKM_RSA_PKCS;
143 ck_sigsize = RSA_size(rsa);
145 ret = p11_get_session(NULL, p11rsa->p, p11rsa->slot, NULL, &session);
146 if (ret)
147 return -1;
149 ret = P11FUNC(p11rsa->p, SignInit, (session, &mechanism, key));
150 if (ret != CKR_OK) {
151 p11_put_session(p11rsa->p, p11rsa->slot, session);
152 return -1;
155 ret = P11FUNC(p11rsa->p, Sign,
156 (session, (CK_BYTE *)(intptr_t)from, flen, to, &ck_sigsize));
157 p11_put_session(p11rsa->p, p11rsa->slot, session);
158 if (ret != CKR_OK)
159 return -1;
161 return ck_sigsize;
164 static int
165 p11_rsa_private_decrypt(int flen, const unsigned char *from, unsigned char *to,
166 RSA * rsa, int padding)
168 struct p11_rsa *p11rsa = RSA_get_app_data(rsa);
169 CK_OBJECT_HANDLE key = p11rsa->private_key;
170 CK_SESSION_HANDLE session;
171 CK_MECHANISM mechanism;
172 CK_ULONG ck_sigsize;
173 int ret;
175 if (padding != RSA_PKCS1_PADDING)
176 return -1;
178 memset(&mechanism, 0, sizeof(mechanism));
179 mechanism.mechanism = CKM_RSA_PKCS;
181 ck_sigsize = RSA_size(rsa);
183 ret = p11_get_session(NULL, p11rsa->p, p11rsa->slot, NULL, &session);
184 if (ret)
185 return -1;
187 ret = P11FUNC(p11rsa->p, DecryptInit, (session, &mechanism, key));
188 if (ret != CKR_OK) {
189 p11_put_session(p11rsa->p, p11rsa->slot, session);
190 return -1;
193 ret = P11FUNC(p11rsa->p, Decrypt,
194 (session, (CK_BYTE *)(intptr_t)from, flen, to, &ck_sigsize));
195 p11_put_session(p11rsa->p, p11rsa->slot, session);
196 if (ret != CKR_OK)
197 return -1;
199 return ck_sigsize;
202 static int
203 p11_rsa_init(RSA *rsa)
205 return 1;
208 static int
209 p11_rsa_finish(RSA *rsa)
211 struct p11_rsa *p11rsa = RSA_get_app_data(rsa);
212 p11_release_module(p11rsa->p);
213 free(p11rsa);
214 return 1;
217 static const RSA_METHOD p11_rsa_pkcs1_method = {
218 "hx509 PKCS11 PKCS#1 RSA",
219 p11_rsa_public_encrypt,
220 p11_rsa_public_decrypt,
221 p11_rsa_private_encrypt,
222 p11_rsa_private_decrypt,
223 NULL,
224 NULL,
225 p11_rsa_init,
226 p11_rsa_finish,
228 NULL,
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 size_t i;
314 int ret;
316 slot->certs = NULL;
317 slot->id = id;
319 ret = P11FUNC(p, GetSlotInfo, (slot->id, &slot_info));
320 if (ret) {
321 hx509_set_error_string(context, 0, HX509_PKCS11_TOKEN_CONFUSED,
322 "Failed to init PKCS11 slot %d",
323 num);
324 return HX509_PKCS11_TOKEN_CONFUSED;
327 for (i = sizeof(slot_info.slotDescription) - 1; i > 0; i--) {
328 char c = slot_info.slotDescription[i];
329 if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\0')
330 continue;
331 i++;
332 break;
335 ret = asprintf(&slot->name, "%.*s", (int)i,
336 slot_info.slotDescription);
337 if (ret == -1)
338 return ENOMEM;
340 if ((slot_info.flags & CKF_TOKEN_PRESENT) == 0)
341 return 0;
343 ret = P11FUNC(p, GetTokenInfo, (slot->id, &token_info));
344 if (ret) {
345 hx509_set_error_string(context, 0, HX509_PKCS11_NO_TOKEN,
346 "Failed to init PKCS11 slot %d "
347 "with error 0x%08x",
348 num, ret);
349 return HX509_PKCS11_NO_TOKEN;
351 slot->flags |= P11_TOKEN_PRESENT;
353 if (token_info.flags & CKF_LOGIN_REQUIRED)
354 slot->flags |= P11_LOGIN_REQ;
356 ret = p11_get_session(context, p, slot, lock, &session);
357 if (ret)
358 return ret;
360 ret = p11_mech_info(context, p, slot, num);
361 if (ret)
362 goto out;
364 ret = p11_list_keys(context, p, slot, session, lock, &slot->certs);
365 out:
366 p11_put_session(p, slot, session);
368 return ret;
371 static int
372 p11_get_session(hx509_context context,
373 struct p11_module *p,
374 struct p11_slot *slot,
375 hx509_lock lock,
376 CK_SESSION_HANDLE *psession)
378 CK_RV ret;
380 if (slot->flags & P11_SESSION_IN_USE)
381 _hx509_abort("slot already in session");
383 if (slot->flags & P11_SESSION) {
384 slot->flags |= P11_SESSION_IN_USE;
385 *psession = slot->session;
386 return 0;
389 ret = P11FUNC(p, OpenSession, (slot->id,
390 CKF_SERIAL_SESSION,
391 NULL,
392 NULL,
393 &slot->session));
394 if (ret != CKR_OK) {
395 if (context)
396 hx509_set_error_string(context, 0, HX509_PKCS11_OPEN_SESSION,
397 "Failed to OpenSession for slot id %d "
398 "with error: 0x%08x",
399 (int)slot->id, ret);
400 return HX509_PKCS11_OPEN_SESSION;
403 slot->flags |= P11_SESSION;
406 * If we have have to login, and haven't tried before and have a
407 * prompter or known to work pin code.
409 * This code is very conversative and only uses the prompter in
410 * the hx509_lock, the reason is that it's bad to try many
411 * passwords on a pkcs11 token, it might lock up and have to be
412 * unlocked by a administrator.
414 * XXX try harder to not use pin several times on the same card.
417 if ( (slot->flags & P11_LOGIN_REQ)
418 && (slot->flags & P11_LOGIN_DONE) == 0
419 && (lock || slot->pin))
421 hx509_prompt prompt;
422 char pin[20];
423 char *str;
425 if (slot->pin == NULL) {
427 memset(&prompt, 0, sizeof(prompt));
429 ret = asprintf(&str, "PIN code for %s: ", slot->name);
430 if (ret == -1 || str == NULL) {
431 if (context)
432 hx509_set_error_string(context, 0, ENOMEM, "out of memory");
433 return ENOMEM;
435 prompt.prompt = str;
436 prompt.type = HX509_PROMPT_TYPE_PASSWORD;
437 prompt.reply.data = pin;
438 prompt.reply.length = sizeof(pin);
440 ret = hx509_lock_prompt(lock, &prompt);
441 if (ret) {
442 free(str);
443 if (context)
444 hx509_set_error_string(context, 0, ret,
445 "Failed to get pin code for slot "
446 "id %d with error: %d",
447 (int)slot->id, ret);
448 return ret;
450 free(str);
451 } else {
452 strlcpy(pin, slot->pin, sizeof(pin));
455 ret = P11FUNC(p, Login, (slot->session, CKU_USER,
456 (unsigned char*)pin, strlen(pin)));
457 if (ret != CKR_OK) {
458 if (context)
459 hx509_set_error_string(context, 0, HX509_PKCS11_LOGIN,
460 "Failed to login on slot id %d "
461 "with error: 0x%08x",
462 (int)slot->id, ret);
463 switch(ret) {
464 case CKR_PIN_LOCKED:
465 return HX509_PKCS11_PIN_LOCKED;
466 case CKR_PIN_EXPIRED:
467 return HX509_PKCS11_PIN_EXPIRED;
468 case CKR_PIN_INCORRECT:
469 return HX509_PKCS11_PIN_INCORRECT;
470 case CKR_USER_PIN_NOT_INITIALIZED:
471 return HX509_PKCS11_PIN_NOT_INITIALIZED;
472 default:
473 return HX509_PKCS11_LOGIN;
475 } else
476 slot->flags |= P11_LOGIN_DONE;
478 if (slot->pin == NULL) {
479 slot->pin = strdup(pin);
480 if (slot->pin == NULL) {
481 if (context)
482 hx509_set_error_string(context, 0, ENOMEM,
483 "out of memory");
484 return ENOMEM;
487 } else
488 slot->flags |= P11_LOGIN_DONE;
490 slot->flags |= P11_SESSION_IN_USE;
492 *psession = slot->session;
494 return 0;
497 static int
498 p11_put_session(struct p11_module *p,
499 struct p11_slot *slot,
500 CK_SESSION_HANDLE session)
502 if ((slot->flags & P11_SESSION_IN_USE) == 0)
503 _hx509_abort("slot not in session");
504 slot->flags &= ~P11_SESSION_IN_USE;
506 return 0;
509 static int
510 iterate_entries(hx509_context context,
511 struct p11_module *p, struct p11_slot *slot,
512 CK_SESSION_HANDLE session,
513 CK_ATTRIBUTE *search_data, int num_search_data,
514 CK_ATTRIBUTE *query, int num_query,
515 int (*func)(hx509_context,
516 struct p11_module *, struct p11_slot *,
517 CK_SESSION_HANDLE session,
518 CK_OBJECT_HANDLE object,
519 void *, CK_ATTRIBUTE *, int), void *ptr)
521 CK_OBJECT_HANDLE object;
522 CK_ULONG object_count;
523 int ret, ret2, i;
525 ret = P11FUNC(p, FindObjectsInit, (session, search_data, num_search_data));
526 if (ret != CKR_OK) {
527 return -1;
529 while (1) {
530 ret = P11FUNC(p, FindObjects, (session, &object, 1, &object_count));
531 if (ret != CKR_OK) {
532 return -1;
534 if (object_count == 0)
535 break;
537 for (i = 0; i < num_query; i++)
538 query[i].pValue = NULL;
540 ret = P11FUNC(p, GetAttributeValue,
541 (session, object, query, num_query));
542 if (ret != CKR_OK) {
543 return -1;
545 for (i = 0; i < num_query; i++) {
546 query[i].pValue = malloc(query[i].ulValueLen);
547 if (query[i].pValue == NULL) {
548 ret = ENOMEM;
549 goto out;
552 ret = P11FUNC(p, GetAttributeValue,
553 (session, object, query, num_query));
554 if (ret != CKR_OK) {
555 ret = -1;
556 goto out;
559 ret = (*func)(context, p, slot, session, object, ptr, query, num_query);
560 if (ret)
561 goto out;
563 for (i = 0; i < num_query; i++) {
564 if (query[i].pValue)
565 free(query[i].pValue);
566 query[i].pValue = NULL;
569 out:
571 for (i = 0; i < num_query; i++) {
572 if (query[i].pValue)
573 free(query[i].pValue);
574 query[i].pValue = NULL;
577 ret2 = P11FUNC(p, FindObjectsFinal, (session));
578 if (ret2 != CKR_OK) {
579 return ret2;
582 return ret;
585 static BIGNUM *
586 getattr_bn(struct p11_module *p,
587 struct p11_slot *slot,
588 CK_SESSION_HANDLE session,
589 CK_OBJECT_HANDLE object,
590 unsigned int type)
592 CK_ATTRIBUTE query;
593 BIGNUM *bn;
594 int ret;
596 query.type = type;
597 query.pValue = NULL;
598 query.ulValueLen = 0;
600 ret = P11FUNC(p, GetAttributeValue,
601 (session, object, &query, 1));
602 if (ret != CKR_OK)
603 return NULL;
605 query.pValue = malloc(query.ulValueLen);
607 ret = P11FUNC(p, GetAttributeValue,
608 (session, object, &query, 1));
609 if (ret != CKR_OK) {
610 free(query.pValue);
611 return NULL;
613 bn = BN_bin2bn(query.pValue, query.ulValueLen, NULL);
614 free(query.pValue);
616 return bn;
619 static int
620 collect_private_key(hx509_context context,
621 struct p11_module *p, struct p11_slot *slot,
622 CK_SESSION_HANDLE session,
623 CK_OBJECT_HANDLE object,
624 void *ptr, CK_ATTRIBUTE *query, int num_query)
626 struct hx509_collector *collector = ptr;
627 hx509_private_key key;
628 heim_octet_string localKeyId;
629 int ret;
630 RSA *rsa;
631 struct p11_rsa *p11rsa;
633 localKeyId.data = query[0].pValue;
634 localKeyId.length = query[0].ulValueLen;
636 ret = hx509_private_key_init(&key, NULL, NULL);
637 if (ret)
638 return ret;
640 rsa = RSA_new();
641 if (rsa == NULL)
642 _hx509_abort("out of memory");
645 * The exponent and modulus should always be present according to
646 * the pkcs11 specification, but some smartcards leaves it out,
647 * let ignore any failure to fetch it.
649 rsa->n = getattr_bn(p, slot, session, object, CKA_MODULUS);
650 rsa->e = getattr_bn(p, slot, session, object, CKA_PUBLIC_EXPONENT);
652 p11rsa = calloc(1, sizeof(*p11rsa));
653 if (p11rsa == NULL)
654 _hx509_abort("out of memory");
656 p11rsa->p = p;
657 p11rsa->slot = slot;
658 p11rsa->private_key = object;
660 if (p->ref == 0)
661 _hx509_abort("pkcs11 ref == 0 on alloc");
662 p->ref++;
663 if (p->ref == UINT_MAX)
664 _hx509_abort("pkcs11 ref == UINT_MAX on alloc");
666 RSA_set_method(rsa, &p11_rsa_pkcs1_method);
667 ret = RSA_set_app_data(rsa, p11rsa);
668 if (ret != 1)
669 _hx509_abort("RSA_set_app_data");
671 hx509_private_key_assign_rsa(key, rsa);
673 ret = _hx509_collector_private_key_add(context,
674 collector,
675 hx509_signature_rsa(),
676 key,
677 NULL,
678 &localKeyId);
680 if (ret) {
681 hx509_private_key_free(&key);
682 return ret;
684 return 0;
687 static void
688 p11_cert_release(hx509_cert cert, void *ctx)
690 struct p11_module *p = ctx;
691 p11_release_module(p);
695 static int
696 collect_cert(hx509_context context,
697 struct p11_module *p, struct p11_slot *slot,
698 CK_SESSION_HANDLE session,
699 CK_OBJECT_HANDLE object,
700 void *ptr, CK_ATTRIBUTE *query, int num_query)
702 struct hx509_collector *collector = ptr;
703 heim_error_t error = NULL;
704 hx509_cert cert;
705 int ret;
707 if ((CK_LONG)query[0].ulValueLen == -1 ||
708 (CK_LONG)query[1].ulValueLen == -1)
710 return 0;
713 cert = hx509_cert_init_data(context, query[1].pValue,
714 query[1].ulValueLen, &error);
715 if (cert == NULL) {
716 ret = heim_error_get_code(error);
717 heim_release(error);
718 return ret;
721 if (p->ref == 0)
722 _hx509_abort("pkcs11 ref == 0 on alloc");
723 p->ref++;
724 if (p->ref == UINT_MAX)
725 _hx509_abort("pkcs11 ref to high");
727 _hx509_cert_set_release(cert, p11_cert_release, p);
730 heim_octet_string data;
732 data.data = query[0].pValue;
733 data.length = query[0].ulValueLen;
735 _hx509_set_cert_attribute(context,
736 cert,
737 &asn1_oid_id_pkcs_9_at_localKeyId,
738 &data);
741 if ((CK_LONG)query[2].ulValueLen != -1) {
742 char *str;
744 ret = asprintf(&str, "%.*s",
745 (int)query[2].ulValueLen, (char *)query[2].pValue);
746 if (ret != -1 && str) {
747 hx509_cert_set_friendly_name(cert, str);
748 free(str);
752 ret = _hx509_collector_certs_add(context, collector, cert);
753 hx509_cert_free(cert);
755 return ret;
759 static int
760 p11_list_keys(hx509_context context,
761 struct p11_module *p,
762 struct p11_slot *slot,
763 CK_SESSION_HANDLE session,
764 hx509_lock lock,
765 hx509_certs *certs)
767 struct hx509_collector *collector;
768 CK_OBJECT_CLASS key_class;
769 CK_ATTRIBUTE search_data[] = {
770 {CKA_CLASS, NULL, 0},
772 CK_ATTRIBUTE query_data[3] = {
773 {CKA_ID, NULL, 0},
774 {CKA_VALUE, NULL, 0},
775 {CKA_LABEL, NULL, 0}
777 int ret;
779 search_data[0].pValue = &key_class;
780 search_data[0].ulValueLen = sizeof(key_class);
782 if (lock == NULL)
783 lock = _hx509_empty_lock;
785 ret = _hx509_collector_alloc(context, lock, &collector);
786 if (ret)
787 return ret;
789 key_class = CKO_PRIVATE_KEY;
790 ret = iterate_entries(context, p, slot, session,
791 search_data, 1,
792 query_data, 1,
793 collect_private_key, collector);
794 if (ret)
795 goto out;
797 key_class = CKO_CERTIFICATE;
798 ret = iterate_entries(context, p, slot, session,
799 search_data, 1,
800 query_data, 3,
801 collect_cert, collector);
802 if (ret)
803 goto out;
805 ret = _hx509_collector_collect_certs(context, collector, &slot->certs);
807 out:
808 _hx509_collector_free(collector);
810 return ret;
814 static int
815 p11_init(hx509_context context,
816 hx509_certs certs, void **data, int flags,
817 const char *residue, hx509_lock lock)
819 CK_C_GetFunctionList getFuncs;
820 struct p11_module *p;
821 char *list, *str;
822 int ret;
824 *data = NULL;
826 list = strdup(residue);
827 if (list == NULL)
828 return ENOMEM;
830 p = calloc(1, sizeof(*p));
831 if (p == NULL) {
832 free(list);
833 return ENOMEM;
836 p->ref = 1;
837 p->selected_slot = 0;
839 str = strchr(list, ',');
840 if (str)
841 *str++ = '\0';
842 while (str) {
843 char *strnext;
844 strnext = strchr(str, ',');
845 if (strnext)
846 *strnext++ = '\0';
847 if (strncasecmp(str, "slot=", 5) == 0)
848 p->selected_slot = atoi(str + 5);
849 str = strnext;
852 p->dl_handle = dlopen(list, RTLD_NOW);
853 if (p->dl_handle == NULL) {
854 ret = HX509_PKCS11_LOAD;
855 hx509_set_error_string(context, 0, ret,
856 "Failed to open %s: %s", list, dlerror());
857 goto out;
860 getFuncs = (CK_C_GetFunctionList) dlsym(p->dl_handle, "C_GetFunctionList");
861 if (getFuncs == NULL) {
862 ret = HX509_PKCS11_LOAD;
863 hx509_set_error_string(context, 0, ret,
864 "C_GetFunctionList missing in %s: %s",
865 list, dlerror());
866 goto out;
869 ret = (*getFuncs)(&p->funcs);
870 if (ret) {
871 ret = HX509_PKCS11_LOAD;
872 hx509_set_error_string(context, 0, ret,
873 "C_GetFunctionList failed in %s", list);
874 goto out;
877 ret = P11FUNC(p, Initialize, (NULL_PTR));
878 if (ret != CKR_OK) {
879 ret = HX509_PKCS11_TOKEN_CONFUSED;
880 hx509_set_error_string(context, 0, ret,
881 "Failed initialize the PKCS11 module");
882 goto out;
885 ret = P11FUNC(p, GetSlotList, (FALSE, NULL, &p->num_slots));
886 if (ret) {
887 ret = HX509_PKCS11_TOKEN_CONFUSED;
888 hx509_set_error_string(context, 0, ret,
889 "Failed to get number of PKCS11 slots");
890 goto out;
893 if (p->num_slots == 0) {
894 ret = HX509_PKCS11_NO_SLOT;
895 hx509_set_error_string(context, 0, ret,
896 "Selected PKCS11 module have no slots");
897 goto out;
902 CK_SLOT_ID_PTR slot_ids;
903 int num_tokens = 0;
904 size_t i;
906 slot_ids = malloc(p->num_slots * sizeof(*slot_ids));
907 if (slot_ids == NULL) {
908 hx509_clear_error_string(context);
909 ret = ENOMEM;
910 goto out;
913 ret = P11FUNC(p, GetSlotList, (FALSE, slot_ids, &p->num_slots));
914 if (ret) {
915 free(slot_ids);
916 hx509_set_error_string(context, 0, HX509_PKCS11_TOKEN_CONFUSED,
917 "Failed getting slot-list from "
918 "PKCS11 module");
919 ret = HX509_PKCS11_TOKEN_CONFUSED;
920 goto out;
923 p->slot = calloc(p->num_slots, sizeof(p->slot[0]));
924 if (p->slot == NULL) {
925 free(slot_ids);
926 hx509_set_error_string(context, 0, ENOMEM,
927 "Failed to get memory for slot-list");
928 ret = ENOMEM;
929 goto out;
932 for (i = 0; i < p->num_slots; i++) {
933 if ((p->selected_slot != 0) && (slot_ids[i] != (p->selected_slot - 1)))
934 continue;
935 ret = p11_init_slot(context, p, lock, slot_ids[i], i, &p->slot[i]);
936 if (!ret) {
937 if (p->slot[i].flags & P11_TOKEN_PRESENT)
938 num_tokens++;
941 free(slot_ids);
942 if (ret)
943 goto out;
944 if (num_tokens == 0) {
945 ret = HX509_PKCS11_NO_TOKEN;
946 goto out;
950 free(list);
952 *data = p;
954 return 0;
955 out:
956 if (list)
957 free(list);
958 p11_release_module(p);
959 return ret;
962 static void
963 p11_release_module(struct p11_module *p)
965 size_t i;
967 if (p->ref == 0)
968 _hx509_abort("pkcs11 ref to low");
969 if (--p->ref > 0)
970 return;
972 for (i = 0; i < p->num_slots; i++) {
973 if (p->slot[i].flags & P11_SESSION_IN_USE)
974 _hx509_abort("pkcs11 module release while session in use");
975 if (p->slot[i].flags & P11_SESSION) {
976 P11FUNC(p, CloseSession, (p->slot[i].session));
979 if (p->slot[i].name)
980 free(p->slot[i].name);
981 if (p->slot[i].pin) {
982 memset(p->slot[i].pin, 0, strlen(p->slot[i].pin));
983 free(p->slot[i].pin);
985 if (p->slot[i].mechs.num) {
986 free(p->slot[i].mechs.list);
988 if (p->slot[i].mechs.infos) {
989 size_t j;
991 for (j = 0 ; j < p->slot[i].mechs.num ; j++)
992 free(p->slot[i].mechs.infos[j]);
993 free(p->slot[i].mechs.infos);
997 free(p->slot);
999 if (p->funcs)
1000 P11FUNC(p, Finalize, (NULL));
1002 if (p->dl_handle)
1003 dlclose(p->dl_handle);
1005 memset(p, 0, sizeof(*p));
1006 free(p);
1009 static int
1010 p11_free(hx509_certs certs, void *data)
1012 struct p11_module *p = data;
1013 size_t i;
1015 for (i = 0; i < p->num_slots; i++) {
1016 if (p->slot[i].certs)
1017 hx509_certs_free(&p->slot[i].certs);
1019 p11_release_module(p);
1020 return 0;
1023 struct p11_cursor {
1024 hx509_certs certs;
1025 void *cursor;
1028 static int
1029 p11_iter_start(hx509_context context,
1030 hx509_certs certs, void *data, void **cursor)
1032 struct p11_module *p = data;
1033 struct p11_cursor *c;
1034 int ret;
1035 size_t i;
1037 c = malloc(sizeof(*c));
1038 if (c == NULL) {
1039 hx509_clear_error_string(context);
1040 return ENOMEM;
1042 ret = hx509_certs_init(context, "MEMORY:pkcs11-iter", 0, NULL, &c->certs);
1043 if (ret) {
1044 free(c);
1045 return ret;
1048 for (i = 0 ; i < p->num_slots; i++) {
1049 if (p->slot[i].certs == NULL)
1050 continue;
1051 ret = hx509_certs_merge(context, c->certs, p->slot[i].certs);
1052 if (ret) {
1053 hx509_certs_free(&c->certs);
1054 free(c);
1055 return ret;
1059 ret = hx509_certs_start_seq(context, c->certs, &c->cursor);
1060 if (ret) {
1061 hx509_certs_free(&c->certs);
1062 free(c);
1063 return 0;
1065 *cursor = c;
1067 return 0;
1070 static int
1071 p11_iter(hx509_context context,
1072 hx509_certs certs, void *data, void *cursor, hx509_cert *cert)
1074 struct p11_cursor *c = cursor;
1075 return hx509_certs_next_cert(context, c->certs, c->cursor, cert);
1078 static int
1079 p11_iter_end(hx509_context context,
1080 hx509_certs certs, void *data, void *cursor)
1082 struct p11_cursor *c = cursor;
1083 int ret;
1084 ret = hx509_certs_end_seq(context, c->certs, c->cursor);
1085 hx509_certs_free(&c->certs);
1086 free(c);
1087 return ret;
1090 #define MECHFLAG(x) { "unknown-flag-" #x, x }
1091 static struct units mechflags[] = {
1092 MECHFLAG(0x80000000),
1093 MECHFLAG(0x40000000),
1094 MECHFLAG(0x20000000),
1095 MECHFLAG(0x10000000),
1096 MECHFLAG(0x08000000),
1097 MECHFLAG(0x04000000),
1098 {"ec-compress", 0x2000000 },
1099 {"ec-uncompress", 0x1000000 },
1100 {"ec-namedcurve", 0x0800000 },
1101 {"ec-ecparameters", 0x0400000 },
1102 {"ec-f-2m", 0x0200000 },
1103 {"ec-f-p", 0x0100000 },
1104 {"derive", 0x0080000 },
1105 {"unwrap", 0x0040000 },
1106 {"wrap", 0x0020000 },
1107 {"genereate-key-pair", 0x0010000 },
1108 {"generate", 0x0008000 },
1109 {"verify-recover", 0x0004000 },
1110 {"verify", 0x0002000 },
1111 {"sign-recover", 0x0001000 },
1112 {"sign", 0x0000800 },
1113 {"digest", 0x0000400 },
1114 {"decrypt", 0x0000200 },
1115 {"encrypt", 0x0000100 },
1116 MECHFLAG(0x00080),
1117 MECHFLAG(0x00040),
1118 MECHFLAG(0x00020),
1119 MECHFLAG(0x00010),
1120 MECHFLAG(0x00008),
1121 MECHFLAG(0x00004),
1122 MECHFLAG(0x00002),
1123 {"hw", 0x0000001 },
1124 { NULL, 0x0000000 }
1126 #undef MECHFLAG
1128 static int
1129 p11_printinfo(hx509_context context,
1130 hx509_certs certs,
1131 void *data,
1132 int (*func)(void *, const char *),
1133 void *ctx)
1135 struct p11_module *p = data;
1136 size_t i, j;
1138 _hx509_pi_printf(func, ctx, "pkcs11 driver with %d slot%s",
1139 p->num_slots, p->num_slots > 1 ? "s" : "");
1141 for (i = 0; i < p->num_slots; i++) {
1142 struct p11_slot *s = &p->slot[i];
1144 _hx509_pi_printf(func, ctx, "slot %d: id: %d name: %s flags: %08x",
1145 i, (int)s->id, s->name, s->flags);
1147 _hx509_pi_printf(func, ctx, "number of supported mechanisms: %lu",
1148 (unsigned long)s->mechs.num);
1149 for (j = 0; j < s->mechs.num; j++) {
1150 const char *mechname = "unknown";
1151 char flags[256], unknownname[40];
1152 #define MECHNAME(s,n) case s: mechname = n; break
1153 switch(s->mechs.list[j]) {
1154 MECHNAME(CKM_RSA_PKCS_KEY_PAIR_GEN, "rsa-pkcs-key-pair-gen");
1155 MECHNAME(CKM_RSA_PKCS, "rsa-pkcs");
1156 MECHNAME(CKM_RSA_X_509, "rsa-x-509");
1157 MECHNAME(CKM_MD5_RSA_PKCS, "md5-rsa-pkcs");
1158 MECHNAME(CKM_SHA1_RSA_PKCS, "sha1-rsa-pkcs");
1159 MECHNAME(CKM_SHA256_RSA_PKCS, "sha256-rsa-pkcs");
1160 MECHNAME(CKM_SHA384_RSA_PKCS, "sha384-rsa-pkcs");
1161 MECHNAME(CKM_SHA512_RSA_PKCS, "sha512-rsa-pkcs");
1162 MECHNAME(CKM_RIPEMD160_RSA_PKCS, "ripemd160-rsa-pkcs");
1163 MECHNAME(CKM_RSA_PKCS_OAEP, "rsa-pkcs-oaep");
1164 MECHNAME(CKM_SHA512_HMAC, "sha512-hmac");
1165 MECHNAME(CKM_SHA512, "sha512");
1166 MECHNAME(CKM_SHA384_HMAC, "sha384-hmac");
1167 MECHNAME(CKM_SHA384, "sha384");
1168 MECHNAME(CKM_SHA256_HMAC, "sha256-hmac");
1169 MECHNAME(CKM_SHA256, "sha256");
1170 MECHNAME(CKM_SHA_1, "sha1");
1171 MECHNAME(CKM_MD5, "md5");
1172 MECHNAME(CKM_RIPEMD160, "ripemd-160");
1173 MECHNAME(CKM_DES_ECB, "des-ecb");
1174 MECHNAME(CKM_DES_CBC, "des-cbc");
1175 MECHNAME(CKM_AES_ECB, "aes-ecb");
1176 MECHNAME(CKM_AES_CBC, "aes-cbc");
1177 MECHNAME(CKM_DH_PKCS_PARAMETER_GEN, "dh-pkcs-parameter-gen");
1178 default:
1179 snprintf(unknownname, sizeof(unknownname),
1180 "unknown-mech-%lu",
1181 (unsigned long)s->mechs.list[j]);
1182 mechname = unknownname;
1183 break;
1185 #undef MECHNAME
1186 unparse_flags(s->mechs.infos[j]->flags, mechflags,
1187 flags, sizeof(flags));
1189 _hx509_pi_printf(func, ctx, " %s: %s", mechname, flags);
1193 return 0;
1196 static struct hx509_keyset_ops keyset_pkcs11 = {
1197 "PKCS11",
1199 p11_init,
1200 NULL,
1201 p11_free,
1202 NULL,
1203 NULL,
1204 p11_iter_start,
1205 p11_iter,
1206 p11_iter_end,
1207 p11_printinfo,
1208 NULL,
1209 NULL
1212 #endif /* HAVE_DLOPEN */
1214 void
1215 _hx509_ks_pkcs11_register(hx509_context context)
1217 #ifdef HAVE_DLOPEN
1218 _hx509_ks_register(context, &keyset_pkcs11);
1219 #endif