Fix typo
[heimdal.git] / lib / hx509 / ks_p11.c
blob67222091a3a5adc84948201541c95482e5fce97f
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 struct p11_slot *slot;
71 #define P11FUNC(module,f,args) (*(module)->funcs->C_##f)args
73 static int p11_get_session(hx509_context,
74 struct p11_module *,
75 struct p11_slot *,
76 hx509_lock,
77 CK_SESSION_HANDLE *);
78 static int p11_put_session(struct p11_module *,
79 struct p11_slot *,
80 CK_SESSION_HANDLE);
81 static void p11_release_module(struct p11_module *);
83 static int p11_list_keys(hx509_context,
84 struct p11_module *,
85 struct p11_slot *,
86 CK_SESSION_HANDLE,
87 hx509_lock,
88 hx509_certs *);
94 struct p11_rsa {
95 struct p11_module *p;
96 struct p11_slot *slot;
97 CK_OBJECT_HANDLE private_key;
98 CK_OBJECT_HANDLE public_key;
101 static int
102 p11_rsa_public_encrypt(int flen,
103 const unsigned char *from,
104 unsigned char *to,
105 RSA *rsa,
106 int padding)
108 return -1;
111 static int
112 p11_rsa_public_decrypt(int flen,
113 const unsigned char *from,
114 unsigned char *to,
115 RSA *rsa,
116 int padding)
118 return -1;
122 static int
123 p11_rsa_private_encrypt(int flen,
124 const unsigned char *from,
125 unsigned char *to,
126 RSA *rsa,
127 int padding)
129 struct p11_rsa *p11rsa = RSA_get_app_data(rsa);
130 CK_OBJECT_HANDLE key = p11rsa->private_key;
131 CK_SESSION_HANDLE session;
132 CK_MECHANISM mechanism;
133 CK_ULONG ck_sigsize;
134 int ret;
136 if (padding != RSA_PKCS1_PADDING)
137 return -1;
139 memset(&mechanism, 0, sizeof(mechanism));
140 mechanism.mechanism = CKM_RSA_PKCS;
142 ck_sigsize = RSA_size(rsa);
144 ret = p11_get_session(NULL, p11rsa->p, p11rsa->slot, NULL, &session);
145 if (ret)
146 return -1;
148 ret = P11FUNC(p11rsa->p, SignInit, (session, &mechanism, key));
149 if (ret != CKR_OK) {
150 p11_put_session(p11rsa->p, p11rsa->slot, session);
151 return -1;
154 ret = P11FUNC(p11rsa->p, Sign,
155 (session, (CK_BYTE *)(intptr_t)from, flen, to, &ck_sigsize));
156 p11_put_session(p11rsa->p, p11rsa->slot, session);
157 if (ret != CKR_OK)
158 return -1;
160 return ck_sigsize;
163 static int
164 p11_rsa_private_decrypt(int flen, const unsigned char *from, unsigned char *to,
165 RSA * rsa, int padding)
167 struct p11_rsa *p11rsa = RSA_get_app_data(rsa);
168 CK_OBJECT_HANDLE key = p11rsa->private_key;
169 CK_SESSION_HANDLE session;
170 CK_MECHANISM mechanism;
171 CK_ULONG ck_sigsize;
172 int ret;
174 if (padding != RSA_PKCS1_PADDING)
175 return -1;
177 memset(&mechanism, 0, sizeof(mechanism));
178 mechanism.mechanism = CKM_RSA_PKCS;
180 ck_sigsize = RSA_size(rsa);
182 ret = p11_get_session(NULL, p11rsa->p, p11rsa->slot, NULL, &session);
183 if (ret)
184 return -1;
186 ret = P11FUNC(p11rsa->p, DecryptInit, (session, &mechanism, key));
187 if (ret != CKR_OK) {
188 p11_put_session(p11rsa->p, p11rsa->slot, session);
189 return -1;
192 ret = P11FUNC(p11rsa->p, Decrypt,
193 (session, (CK_BYTE *)(intptr_t)from, flen, to, &ck_sigsize));
194 p11_put_session(p11rsa->p, p11rsa->slot, session);
195 if (ret != CKR_OK)
196 return -1;
198 return ck_sigsize;
201 static int
202 p11_rsa_init(RSA *rsa)
204 return 1;
207 static int
208 p11_rsa_finish(RSA *rsa)
210 struct p11_rsa *p11rsa = RSA_get_app_data(rsa);
211 p11_release_module(p11rsa->p);
212 free(p11rsa);
213 return 1;
216 static const RSA_METHOD p11_rsa_pkcs1_method = {
217 "hx509 PKCS11 PKCS#1 RSA",
218 p11_rsa_public_encrypt,
219 p11_rsa_public_decrypt,
220 p11_rsa_private_encrypt,
221 p11_rsa_private_decrypt,
222 NULL,
223 NULL,
224 p11_rsa_init,
225 p11_rsa_finish,
227 NULL,
228 NULL,
229 NULL,
230 NULL
237 static int
238 p11_mech_info(hx509_context context,
239 struct p11_module *p,
240 struct p11_slot *slot,
241 int num)
243 CK_ULONG i;
244 int ret;
246 ret = P11FUNC(p, GetMechanismList, (slot->id, NULL_PTR, &i));
247 if (ret) {
248 hx509_set_error_string(context, 0, HX509_PKCS11_NO_MECH,
249 "Failed to get mech list count for slot %d",
250 num);
251 return HX509_PKCS11_NO_MECH;
253 if (i == 0) {
254 hx509_set_error_string(context, 0, HX509_PKCS11_NO_MECH,
255 "no mech supported for slot %d", num);
256 return HX509_PKCS11_NO_MECH;
258 slot->mechs.list = calloc(i, sizeof(slot->mechs.list[0]));
259 if (slot->mechs.list == NULL) {
260 hx509_set_error_string(context, 0, ENOMEM,
261 "out of memory");
262 return ENOMEM;
264 slot->mechs.num = i;
265 ret = P11FUNC(p, GetMechanismList, (slot->id, slot->mechs.list, &i));
266 if (ret) {
267 hx509_set_error_string(context, 0, HX509_PKCS11_NO_MECH,
268 "Failed to get mech list for slot %d",
269 num);
270 return HX509_PKCS11_NO_MECH;
272 assert(i == slot->mechs.num);
274 slot->mechs.infos = calloc(i, sizeof(*slot->mechs.infos));
275 if (slot->mechs.list == NULL) {
276 hx509_set_error_string(context, 0, ENOMEM,
277 "out of memory");
278 return ENOMEM;
281 for (i = 0; i < slot->mechs.num; i++) {
282 slot->mechs.infos[i] = calloc(1, sizeof(*(slot->mechs.infos[0])));
283 if (slot->mechs.infos[i] == NULL) {
284 hx509_set_error_string(context, 0, ENOMEM,
285 "out of memory");
286 return ENOMEM;
288 ret = P11FUNC(p, GetMechanismInfo, (slot->id, slot->mechs.list[i],
289 slot->mechs.infos[i]));
290 if (ret) {
291 hx509_set_error_string(context, 0, HX509_PKCS11_NO_MECH,
292 "Failed to get mech info for slot %d",
293 num);
294 return HX509_PKCS11_NO_MECH;
298 return 0;
301 static int
302 p11_init_slot(hx509_context context,
303 struct p11_module *p,
304 hx509_lock lock,
305 CK_SLOT_ID id,
306 int num,
307 struct p11_slot *slot)
309 CK_SESSION_HANDLE session;
310 CK_SLOT_INFO slot_info;
311 CK_TOKEN_INFO token_info;
312 size_t i;
313 int ret;
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 ret = asprintf(&slot->name, "%.*s", (int)i,
335 slot_info.slotDescription);
336 if (ret == -1)
337 return ENOMEM;
339 if ((slot_info.flags & CKF_TOKEN_PRESENT) == 0)
340 return 0;
342 ret = P11FUNC(p, GetTokenInfo, (slot->id, &token_info));
343 if (ret) {
344 hx509_set_error_string(context, 0, HX509_PKCS11_NO_TOKEN,
345 "Failed to init PKCS11 slot %d "
346 "with error 0x%08x",
347 num, ret);
348 return HX509_PKCS11_NO_TOKEN;
350 slot->flags |= P11_TOKEN_PRESENT;
352 if (token_info.flags & CKF_LOGIN_REQUIRED)
353 slot->flags |= P11_LOGIN_REQ;
355 ret = p11_get_session(context, p, slot, lock, &session);
356 if (ret)
357 return ret;
359 ret = p11_mech_info(context, p, slot, num);
360 if (ret)
361 goto out;
363 ret = p11_list_keys(context, p, slot, session, lock, &slot->certs);
364 out:
365 p11_put_session(p, slot, session);
367 return ret;
370 static int
371 p11_get_session(hx509_context context,
372 struct p11_module *p,
373 struct p11_slot *slot,
374 hx509_lock lock,
375 CK_SESSION_HANDLE *psession)
377 CK_RV ret;
379 if (slot->flags & P11_SESSION_IN_USE)
380 _hx509_abort("slot already in session");
382 if (slot->flags & P11_SESSION) {
383 slot->flags |= P11_SESSION_IN_USE;
384 *psession = slot->session;
385 return 0;
388 ret = P11FUNC(p, OpenSession, (slot->id,
389 CKF_SERIAL_SESSION,
390 NULL,
391 NULL,
392 &slot->session));
393 if (ret != CKR_OK) {
394 if (context)
395 hx509_set_error_string(context, 0, HX509_PKCS11_OPEN_SESSION,
396 "Failed to OpenSession for slot id %d "
397 "with error: 0x%08x",
398 (int)slot->id, ret);
399 return HX509_PKCS11_OPEN_SESSION;
402 slot->flags |= P11_SESSION;
405 * If we have have to login, and haven't tried before and have a
406 * prompter or known to work pin code.
408 * This code is very conversative and only uses the prompter in
409 * the hx509_lock, the reason is that it's bad to try many
410 * passwords on a pkcs11 token, it might lock up and have to be
411 * unlocked by a administrator.
413 * XXX try harder to not use pin several times on the same card.
416 if ( (slot->flags & P11_LOGIN_REQ)
417 && (slot->flags & P11_LOGIN_DONE) == 0
418 && (lock || slot->pin))
420 hx509_prompt prompt;
421 char pin[20];
422 char *str;
424 if (slot->pin == NULL) {
426 memset(&prompt, 0, sizeof(prompt));
428 ret = asprintf(&str, "PIN code for %s: ", slot->name);
429 if (ret == -1 || str == NULL) {
430 if (context)
431 hx509_set_error_string(context, 0, ENOMEM, "out of memory");
432 return ENOMEM;
434 prompt.prompt = str;
435 prompt.type = HX509_PROMPT_TYPE_PASSWORD;
436 prompt.reply.data = pin;
437 prompt.reply.length = sizeof(pin);
439 ret = hx509_lock_prompt(lock, &prompt);
440 if (ret) {
441 free(str);
442 if (context)
443 hx509_set_error_string(context, 0, ret,
444 "Failed to get pin code for slot "
445 "id %d with error: %d",
446 (int)slot->id, ret);
447 return ret;
449 free(str);
450 } else {
451 strlcpy(pin, slot->pin, sizeof(pin));
454 ret = P11FUNC(p, Login, (slot->session, CKU_USER,
455 (unsigned char*)pin, strlen(pin)));
456 if (ret != CKR_OK) {
457 if (context)
458 hx509_set_error_string(context, 0, HX509_PKCS11_LOGIN,
459 "Failed to login on slot id %d "
460 "with error: 0x%08x",
461 (int)slot->id, ret);
462 return HX509_PKCS11_LOGIN;
463 } else
464 slot->flags |= P11_LOGIN_DONE;
466 if (slot->pin == NULL) {
467 slot->pin = strdup(pin);
468 if (slot->pin == NULL) {
469 if (context)
470 hx509_set_error_string(context, 0, ENOMEM,
471 "out of memory");
472 return ENOMEM;
475 } else
476 slot->flags |= P11_LOGIN_DONE;
478 slot->flags |= P11_SESSION_IN_USE;
480 *psession = slot->session;
482 return 0;
485 static int
486 p11_put_session(struct p11_module *p,
487 struct p11_slot *slot,
488 CK_SESSION_HANDLE session)
490 if ((slot->flags & P11_SESSION_IN_USE) == 0)
491 _hx509_abort("slot not in session");
492 slot->flags &= ~P11_SESSION_IN_USE;
494 return 0;
497 static int
498 iterate_entries(hx509_context context,
499 struct p11_module *p, struct p11_slot *slot,
500 CK_SESSION_HANDLE session,
501 CK_ATTRIBUTE *search_data, int num_search_data,
502 CK_ATTRIBUTE *query, int num_query,
503 int (*func)(hx509_context,
504 struct p11_module *, struct p11_slot *,
505 CK_SESSION_HANDLE session,
506 CK_OBJECT_HANDLE object,
507 void *, CK_ATTRIBUTE *, int), void *ptr)
509 CK_OBJECT_HANDLE object;
510 CK_ULONG object_count;
511 int ret, ret2, i;
513 ret = P11FUNC(p, FindObjectsInit, (session, search_data, num_search_data));
514 if (ret != CKR_OK) {
515 return -1;
517 while (1) {
518 ret = P11FUNC(p, FindObjects, (session, &object, 1, &object_count));
519 if (ret != CKR_OK) {
520 return -1;
522 if (object_count == 0)
523 break;
525 for (i = 0; i < num_query; i++)
526 query[i].pValue = NULL;
528 ret = P11FUNC(p, GetAttributeValue,
529 (session, object, query, num_query));
530 if (ret != CKR_OK) {
531 return -1;
533 for (i = 0; i < num_query; i++) {
534 query[i].pValue = malloc(query[i].ulValueLen);
535 if (query[i].pValue == NULL) {
536 ret = ENOMEM;
537 goto out;
540 ret = P11FUNC(p, GetAttributeValue,
541 (session, object, query, num_query));
542 if (ret != CKR_OK) {
543 ret = -1;
544 goto out;
547 ret = (*func)(context, p, slot, session, object, ptr, query, num_query);
548 if (ret)
549 goto out;
551 for (i = 0; i < num_query; i++) {
552 if (query[i].pValue)
553 free(query[i].pValue);
554 query[i].pValue = NULL;
557 out:
559 for (i = 0; i < num_query; i++) {
560 if (query[i].pValue)
561 free(query[i].pValue);
562 query[i].pValue = NULL;
565 ret2 = P11FUNC(p, FindObjectsFinal, (session));
566 if (ret2 != CKR_OK) {
567 return ret2;
570 return ret;
573 static BIGNUM *
574 getattr_bn(struct p11_module *p,
575 struct p11_slot *slot,
576 CK_SESSION_HANDLE session,
577 CK_OBJECT_HANDLE object,
578 unsigned int type)
580 CK_ATTRIBUTE query;
581 BIGNUM *bn;
582 int ret;
584 query.type = type;
585 query.pValue = NULL;
586 query.ulValueLen = 0;
588 ret = P11FUNC(p, GetAttributeValue,
589 (session, object, &query, 1));
590 if (ret != CKR_OK)
591 return NULL;
593 query.pValue = malloc(query.ulValueLen);
595 ret = P11FUNC(p, GetAttributeValue,
596 (session, object, &query, 1));
597 if (ret != CKR_OK) {
598 free(query.pValue);
599 return NULL;
601 bn = BN_bin2bn(query.pValue, query.ulValueLen, NULL);
602 free(query.pValue);
604 return bn;
607 static int
608 collect_private_key(hx509_context context,
609 struct p11_module *p, struct p11_slot *slot,
610 CK_SESSION_HANDLE session,
611 CK_OBJECT_HANDLE object,
612 void *ptr, CK_ATTRIBUTE *query, int num_query)
614 struct hx509_collector *collector = ptr;
615 hx509_private_key key;
616 heim_octet_string localKeyId;
617 int ret;
618 RSA *rsa;
619 struct p11_rsa *p11rsa;
621 localKeyId.data = query[0].pValue;
622 localKeyId.length = query[0].ulValueLen;
624 ret = hx509_private_key_init(&key, NULL, NULL);
625 if (ret)
626 return ret;
628 rsa = RSA_new();
629 if (rsa == NULL)
630 _hx509_abort("out of memory");
633 * The exponent and modulus should always be present according to
634 * the pkcs11 specification, but some smartcards leaves it out,
635 * let ignore any failure to fetch it.
637 rsa->n = getattr_bn(p, slot, session, object, CKA_MODULUS);
638 rsa->e = getattr_bn(p, slot, session, object, CKA_PUBLIC_EXPONENT);
640 p11rsa = calloc(1, sizeof(*p11rsa));
641 if (p11rsa == NULL)
642 _hx509_abort("out of memory");
644 p11rsa->p = p;
645 p11rsa->slot = slot;
646 p11rsa->private_key = object;
648 if (p->ref == 0)
649 _hx509_abort("pkcs11 ref == 0 on alloc");
650 p->ref++;
651 if (p->ref == UINT_MAX)
652 _hx509_abort("pkcs11 ref == UINT_MAX on alloc");
654 RSA_set_method(rsa, &p11_rsa_pkcs1_method);
655 ret = RSA_set_app_data(rsa, p11rsa);
656 if (ret != 1)
657 _hx509_abort("RSA_set_app_data");
659 hx509_private_key_assign_rsa(key, rsa);
661 ret = _hx509_collector_private_key_add(context,
662 collector,
663 hx509_signature_rsa(),
664 key,
665 NULL,
666 &localKeyId);
668 if (ret) {
669 hx509_private_key_free(&key);
670 return ret;
672 return 0;
675 static void
676 p11_cert_release(hx509_cert cert, void *ctx)
678 struct p11_module *p = ctx;
679 p11_release_module(p);
683 static int
684 collect_cert(hx509_context context,
685 struct p11_module *p, struct p11_slot *slot,
686 CK_SESSION_HANDLE session,
687 CK_OBJECT_HANDLE object,
688 void *ptr, CK_ATTRIBUTE *query, int num_query)
690 struct hx509_collector *collector = ptr;
691 heim_error_t error = NULL;
692 hx509_cert cert;
693 int ret;
695 if ((CK_LONG)query[0].ulValueLen == -1 ||
696 (CK_LONG)query[1].ulValueLen == -1)
698 return 0;
701 cert = hx509_cert_init_data(context, query[1].pValue,
702 query[1].ulValueLen, &error);
703 if (cert == NULL) {
704 ret = heim_error_get_code(error);
705 heim_release(error);
706 return ret;
709 if (p->ref == 0)
710 _hx509_abort("pkcs11 ref == 0 on alloc");
711 p->ref++;
712 if (p->ref == UINT_MAX)
713 _hx509_abort("pkcs11 ref to high");
715 _hx509_cert_set_release(cert, p11_cert_release, p);
718 heim_octet_string data;
720 data.data = query[0].pValue;
721 data.length = query[0].ulValueLen;
723 _hx509_set_cert_attribute(context,
724 cert,
725 &asn1_oid_id_pkcs_9_at_localKeyId,
726 &data);
729 if ((CK_LONG)query[2].ulValueLen != -1) {
730 char *str;
732 ret = asprintf(&str, "%.*s",
733 (int)query[2].ulValueLen, (char *)query[2].pValue);
734 if (ret != -1 && str) {
735 hx509_cert_set_friendly_name(cert, str);
736 free(str);
740 ret = _hx509_collector_certs_add(context, collector, cert);
741 hx509_cert_free(cert);
743 return ret;
747 static int
748 p11_list_keys(hx509_context context,
749 struct p11_module *p,
750 struct p11_slot *slot,
751 CK_SESSION_HANDLE session,
752 hx509_lock lock,
753 hx509_certs *certs)
755 struct hx509_collector *collector;
756 CK_OBJECT_CLASS key_class;
757 CK_ATTRIBUTE search_data[] = {
758 {CKA_CLASS, NULL, 0},
760 CK_ATTRIBUTE query_data[3] = {
761 {CKA_ID, NULL, 0},
762 {CKA_VALUE, NULL, 0},
763 {CKA_LABEL, NULL, 0}
765 int ret;
767 search_data[0].pValue = &key_class;
768 search_data[0].ulValueLen = sizeof(key_class);
770 if (lock == NULL)
771 lock = _hx509_empty_lock;
773 ret = _hx509_collector_alloc(context, lock, &collector);
774 if (ret)
775 return ret;
777 key_class = CKO_PRIVATE_KEY;
778 ret = iterate_entries(context, p, slot, session,
779 search_data, 1,
780 query_data, 1,
781 collect_private_key, collector);
782 if (ret)
783 goto out;
785 key_class = CKO_CERTIFICATE;
786 ret = iterate_entries(context, p, slot, session,
787 search_data, 1,
788 query_data, 3,
789 collect_cert, collector);
790 if (ret)
791 goto out;
793 ret = _hx509_collector_collect_certs(context, collector, &slot->certs);
795 out:
796 _hx509_collector_free(collector);
798 return ret;
802 static int
803 p11_init(hx509_context context,
804 hx509_certs certs, void **data, int flags,
805 const char *residue, hx509_lock lock)
807 CK_C_GetFunctionList getFuncs;
808 struct p11_module *p;
809 char *list, *str;
810 int ret;
812 *data = NULL;
814 list = strdup(residue);
815 if (list == NULL)
816 return ENOMEM;
818 p = calloc(1, sizeof(*p));
819 if (p == NULL) {
820 free(list);
821 return ENOMEM;
824 p->ref = 1;
826 str = strchr(list, ',');
827 if (str)
828 *str++ = '\0';
829 while (str) {
830 char *strnext;
831 strnext = strchr(str, ',');
832 if (strnext)
833 *strnext++ = '\0';
834 #if 0
835 if (strncasecmp(str, "slot=", 5) == 0)
836 p->selected_slot = atoi(str + 5);
837 #endif
838 str = strnext;
841 p->dl_handle = dlopen(list, RTLD_NOW);
842 if (p->dl_handle == NULL) {
843 ret = HX509_PKCS11_LOAD;
844 hx509_set_error_string(context, 0, ret,
845 "Failed to open %s: %s", list, dlerror());
846 goto out;
849 getFuncs = (CK_C_GetFunctionList) dlsym(p->dl_handle, "C_GetFunctionList");
850 if (getFuncs == NULL) {
851 ret = HX509_PKCS11_LOAD;
852 hx509_set_error_string(context, 0, ret,
853 "C_GetFunctionList missing in %s: %s",
854 list, dlerror());
855 goto out;
858 ret = (*getFuncs)(&p->funcs);
859 if (ret) {
860 ret = HX509_PKCS11_LOAD;
861 hx509_set_error_string(context, 0, ret,
862 "C_GetFunctionList failed in %s", list);
863 goto out;
866 ret = P11FUNC(p, Initialize, (NULL_PTR));
867 if (ret != CKR_OK) {
868 ret = HX509_PKCS11_TOKEN_CONFUSED;
869 hx509_set_error_string(context, 0, ret,
870 "Failed initialize the PKCS11 module");
871 goto out;
874 ret = P11FUNC(p, GetSlotList, (FALSE, NULL, &p->num_slots));
875 if (ret) {
876 ret = HX509_PKCS11_TOKEN_CONFUSED;
877 hx509_set_error_string(context, 0, ret,
878 "Failed to get number of PKCS11 slots");
879 goto out;
882 if (p->num_slots == 0) {
883 ret = HX509_PKCS11_NO_SLOT;
884 hx509_set_error_string(context, 0, ret,
885 "Selected PKCS11 module have no slots");
886 goto out;
891 CK_SLOT_ID_PTR slot_ids;
892 int num_tokens = 0;
893 size_t i;
895 slot_ids = malloc(p->num_slots * sizeof(*slot_ids));
896 if (slot_ids == NULL) {
897 hx509_clear_error_string(context);
898 ret = ENOMEM;
899 goto out;
902 ret = P11FUNC(p, GetSlotList, (FALSE, slot_ids, &p->num_slots));
903 if (ret) {
904 free(slot_ids);
905 hx509_set_error_string(context, 0, HX509_PKCS11_TOKEN_CONFUSED,
906 "Failed getting slot-list from "
907 "PKCS11 module");
908 ret = HX509_PKCS11_TOKEN_CONFUSED;
909 goto out;
912 p->slot = calloc(p->num_slots, sizeof(p->slot[0]));
913 if (p->slot == NULL) {
914 free(slot_ids);
915 hx509_set_error_string(context, 0, ENOMEM,
916 "Failed to get memory for slot-list");
917 ret = ENOMEM;
918 goto out;
921 for (i = 0; i < p->num_slots; i++) {
922 ret = p11_init_slot(context, p, lock, slot_ids[i], i, &p->slot[i]);
923 if (ret)
924 break;
925 if (p->slot[i].flags & P11_TOKEN_PRESENT)
926 num_tokens++;
928 free(slot_ids);
929 if (ret)
930 goto out;
931 if (num_tokens == 0) {
932 ret = HX509_PKCS11_NO_TOKEN;
933 goto out;
937 free(list);
939 *data = p;
941 return 0;
942 out:
943 if (list)
944 free(list);
945 p11_release_module(p);
946 return ret;
949 static void
950 p11_release_module(struct p11_module *p)
952 size_t i;
954 if (p->ref == 0)
955 _hx509_abort("pkcs11 ref to low");
956 if (--p->ref > 0)
957 return;
959 for (i = 0; i < p->num_slots; i++) {
960 if (p->slot[i].flags & P11_SESSION_IN_USE)
961 _hx509_abort("pkcs11 module release while session in use");
962 if (p->slot[i].flags & P11_SESSION) {
963 P11FUNC(p, CloseSession, (p->slot[i].session));
966 if (p->slot[i].name)
967 free(p->slot[i].name);
968 if (p->slot[i].pin) {
969 memset(p->slot[i].pin, 0, strlen(p->slot[i].pin));
970 free(p->slot[i].pin);
972 if (p->slot[i].mechs.num) {
973 free(p->slot[i].mechs.list);
975 if (p->slot[i].mechs.infos) {
976 size_t j;
978 for (j = 0 ; j < p->slot[i].mechs.num ; j++)
979 free(p->slot[i].mechs.infos[j]);
980 free(p->slot[i].mechs.infos);
984 free(p->slot);
986 if (p->funcs)
987 P11FUNC(p, Finalize, (NULL));
989 if (p->dl_handle)
990 dlclose(p->dl_handle);
992 memset(p, 0, sizeof(*p));
993 free(p);
996 static int
997 p11_free(hx509_certs certs, void *data)
999 struct p11_module *p = data;
1000 size_t i;
1002 for (i = 0; i < p->num_slots; i++) {
1003 if (p->slot[i].certs)
1004 hx509_certs_free(&p->slot[i].certs);
1006 p11_release_module(p);
1007 return 0;
1010 struct p11_cursor {
1011 hx509_certs certs;
1012 void *cursor;
1015 static int
1016 p11_iter_start(hx509_context context,
1017 hx509_certs certs, void *data, void **cursor)
1019 struct p11_module *p = data;
1020 struct p11_cursor *c;
1021 int ret;
1022 size_t i;
1024 c = malloc(sizeof(*c));
1025 if (c == NULL) {
1026 hx509_clear_error_string(context);
1027 return ENOMEM;
1029 ret = hx509_certs_init(context, "MEMORY:pkcs11-iter", 0, NULL, &c->certs);
1030 if (ret) {
1031 free(c);
1032 return ret;
1035 for (i = 0 ; i < p->num_slots; i++) {
1036 if (p->slot[i].certs == NULL)
1037 continue;
1038 ret = hx509_certs_merge(context, c->certs, p->slot[i].certs);
1039 if (ret) {
1040 hx509_certs_free(&c->certs);
1041 free(c);
1042 return ret;
1046 ret = hx509_certs_start_seq(context, c->certs, &c->cursor);
1047 if (ret) {
1048 hx509_certs_free(&c->certs);
1049 free(c);
1050 return 0;
1052 *cursor = c;
1054 return 0;
1057 static int
1058 p11_iter(hx509_context context,
1059 hx509_certs certs, void *data, void *cursor, hx509_cert *cert)
1061 struct p11_cursor *c = cursor;
1062 return hx509_certs_next_cert(context, c->certs, c->cursor, cert);
1065 static int
1066 p11_iter_end(hx509_context context,
1067 hx509_certs certs, void *data, void *cursor)
1069 struct p11_cursor *c = cursor;
1070 int ret;
1071 ret = hx509_certs_end_seq(context, c->certs, c->cursor);
1072 hx509_certs_free(&c->certs);
1073 free(c);
1074 return ret;
1077 #define MECHFLAG(x) { "unknown-flag-" #x, x }
1078 static struct units mechflags[] = {
1079 MECHFLAG(0x80000000),
1080 MECHFLAG(0x40000000),
1081 MECHFLAG(0x20000000),
1082 MECHFLAG(0x10000000),
1083 MECHFLAG(0x08000000),
1084 MECHFLAG(0x04000000),
1085 {"ec-compress", 0x2000000 },
1086 {"ec-uncompress", 0x1000000 },
1087 {"ec-namedcurve", 0x0800000 },
1088 {"ec-ecparameters", 0x0400000 },
1089 {"ec-f-2m", 0x0200000 },
1090 {"ec-f-p", 0x0100000 },
1091 {"derive", 0x0080000 },
1092 {"unwrap", 0x0040000 },
1093 {"wrap", 0x0020000 },
1094 {"genereate-key-pair", 0x0010000 },
1095 {"generate", 0x0008000 },
1096 {"verify-recover", 0x0004000 },
1097 {"verify", 0x0002000 },
1098 {"sign-recover", 0x0001000 },
1099 {"sign", 0x0000800 },
1100 {"digest", 0x0000400 },
1101 {"decrypt", 0x0000200 },
1102 {"encrypt", 0x0000100 },
1103 MECHFLAG(0x00080),
1104 MECHFLAG(0x00040),
1105 MECHFLAG(0x00020),
1106 MECHFLAG(0x00010),
1107 MECHFLAG(0x00008),
1108 MECHFLAG(0x00004),
1109 MECHFLAG(0x00002),
1110 {"hw", 0x0000001 },
1111 { NULL, 0x0000000 }
1113 #undef MECHFLAG
1115 static int
1116 p11_printinfo(hx509_context context,
1117 hx509_certs certs,
1118 void *data,
1119 int (*func)(void *, const char *),
1120 void *ctx)
1122 struct p11_module *p = data;
1123 size_t i, j;
1125 _hx509_pi_printf(func, ctx, "pkcs11 driver with %d slot%s",
1126 p->num_slots, p->num_slots > 1 ? "s" : "");
1128 for (i = 0; i < p->num_slots; i++) {
1129 struct p11_slot *s = &p->slot[i];
1131 _hx509_pi_printf(func, ctx, "slot %d: id: %d name: %s flags: %08x",
1132 i, (int)s->id, s->name, s->flags);
1134 _hx509_pi_printf(func, ctx, "number of supported mechanisms: %lu",
1135 (unsigned long)s->mechs.num);
1136 for (j = 0; j < s->mechs.num; j++) {
1137 const char *mechname = "unknown";
1138 char flags[256], unknownname[40];
1139 #define MECHNAME(s,n) case s: mechname = n; break
1140 switch(s->mechs.list[j]) {
1141 MECHNAME(CKM_RSA_PKCS_KEY_PAIR_GEN, "rsa-pkcs-key-pair-gen");
1142 MECHNAME(CKM_RSA_PKCS, "rsa-pkcs");
1143 MECHNAME(CKM_RSA_X_509, "rsa-x-509");
1144 MECHNAME(CKM_MD5_RSA_PKCS, "md5-rsa-pkcs");
1145 MECHNAME(CKM_SHA1_RSA_PKCS, "sha1-rsa-pkcs");
1146 MECHNAME(CKM_SHA256_RSA_PKCS, "sha256-rsa-pkcs");
1147 MECHNAME(CKM_SHA384_RSA_PKCS, "sha384-rsa-pkcs");
1148 MECHNAME(CKM_SHA512_RSA_PKCS, "sha512-rsa-pkcs");
1149 MECHNAME(CKM_RIPEMD160_RSA_PKCS, "ripemd160-rsa-pkcs");
1150 MECHNAME(CKM_RSA_PKCS_OAEP, "rsa-pkcs-oaep");
1151 MECHNAME(CKM_SHA512_HMAC, "sha512-hmac");
1152 MECHNAME(CKM_SHA512, "sha512");
1153 MECHNAME(CKM_SHA384_HMAC, "sha384-hmac");
1154 MECHNAME(CKM_SHA384, "sha384");
1155 MECHNAME(CKM_SHA256_HMAC, "sha256-hmac");
1156 MECHNAME(CKM_SHA256, "sha256");
1157 MECHNAME(CKM_SHA_1, "sha1");
1158 MECHNAME(CKM_MD5, "md5");
1159 MECHNAME(CKM_RIPEMD160, "ripemd-160");
1160 MECHNAME(CKM_DES_ECB, "des-ecb");
1161 MECHNAME(CKM_DES_CBC, "des-cbc");
1162 MECHNAME(CKM_AES_ECB, "aes-ecb");
1163 MECHNAME(CKM_AES_CBC, "aes-cbc");
1164 MECHNAME(CKM_DH_PKCS_PARAMETER_GEN, "dh-pkcs-parameter-gen");
1165 default:
1166 snprintf(unknownname, sizeof(unknownname),
1167 "unknown-mech-%lu",
1168 (unsigned long)s->mechs.list[j]);
1169 mechname = unknownname;
1170 break;
1172 #undef MECHNAME
1173 unparse_flags(s->mechs.infos[j]->flags, mechflags,
1174 flags, sizeof(flags));
1176 _hx509_pi_printf(func, ctx, " %s: %s", mechname, flags);
1180 return 0;
1183 static struct hx509_keyset_ops keyset_pkcs11 = {
1184 "PKCS11",
1186 p11_init,
1187 NULL,
1188 p11_free,
1189 NULL,
1190 NULL,
1191 p11_iter_start,
1192 p11_iter,
1193 p11_iter_end,
1194 p11_printinfo,
1195 NULL,
1196 NULL
1199 #endif /* HAVE_DLOPEN */
1201 void
1202 _hx509_ks_pkcs11_register(hx509_context context)
1204 #ifdef HAVE_DLOPEN
1205 _hx509_ks_register(context, &keyset_pkcs11);
1206 #endif