]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/shared/pkcs11-util.c
license: LGPL-2.1+ -> LGPL-2.1-or-later
[thirdparty/systemd.git] / src / shared / pkcs11-util.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
839fddbe
LP
2
3#include <fcntl.h>
4
5#include "ask-password-api.h"
6#include "escape.h"
7#include "fd-util.h"
8#include "io-util.h"
9#include "memory-util.h"
10#if HAVE_OPENSSL
11#include "openssl-util.h"
12#endif
13#include "pkcs11-util.h"
14#include "random-util.h"
15#include "string-util.h"
16#include "strv.h"
17
18bool pkcs11_uri_valid(const char *uri) {
19 const char *p;
20
21 /* A very superficial checker for RFC7512 PKCS#11 URI syntax */
22
23 if (isempty(uri))
24 return false;
25
26 p = startswith(uri, "pkcs11:");
27 if (!p)
28 return false;
29
30 if (isempty(p))
31 return false;
32
33 if (!in_charset(p, ALPHANUMERICAL "-_?;&%="))
34 return false;
35
36 return true;
37}
38
39#if HAVE_P11KIT
40
41int uri_from_string(const char *p, P11KitUri **ret) {
42 _cleanup_(p11_kit_uri_freep) P11KitUri *uri = NULL;
43
44 assert(p);
45 assert(ret);
46
47 uri = p11_kit_uri_new();
48 if (!uri)
49 return -ENOMEM;
50
51 if (p11_kit_uri_parse(p, P11_KIT_URI_FOR_ANY, uri) != P11_KIT_URI_OK)
52 return -EINVAL;
53
54 *ret = TAKE_PTR(uri);
55 return 0;
56}
57
58P11KitUri *uri_from_module_info(const CK_INFO *info) {
59 P11KitUri *uri;
60
61 assert(info);
62
63 uri = p11_kit_uri_new();
64 if (!uri)
65 return NULL;
66
67 *p11_kit_uri_get_module_info(uri) = *info;
68 return uri;
69}
70
71P11KitUri *uri_from_slot_info(const CK_SLOT_INFO *slot_info) {
72 P11KitUri *uri;
73
74 assert(slot_info);
75
76 uri = p11_kit_uri_new();
77 if (!uri)
78 return NULL;
79
80 *p11_kit_uri_get_slot_info(uri) = *slot_info;
81 return uri;
82}
83
84P11KitUri *uri_from_token_info(const CK_TOKEN_INFO *token_info) {
85 P11KitUri *uri;
86
87 assert(token_info);
88
89 uri = p11_kit_uri_new();
90 if (!uri)
91 return NULL;
92
93 *p11_kit_uri_get_token_info(uri) = *token_info;
94 return uri;
95}
96
97CK_RV pkcs11_get_slot_list_malloc(
98 CK_FUNCTION_LIST *m,
99 CK_SLOT_ID **ret_slotids,
100 CK_ULONG *ret_n_slotids) {
101
102 CK_RV rv;
103
104 assert(m);
105 assert(ret_slotids);
106 assert(ret_n_slotids);
107
108 for (unsigned tries = 0; tries < 16; tries++) {
109 _cleanup_free_ CK_SLOT_ID *slotids = NULL;
110 CK_ULONG n_slotids = 0;
111
112 rv = m->C_GetSlotList(0, NULL, &n_slotids);
113 if (rv != CKR_OK)
114 return rv;
115 if (n_slotids == 0) {
116 *ret_slotids = NULL;
117 *ret_n_slotids = 0;
118 return CKR_OK;
119 }
120
121 slotids = new(CK_SLOT_ID, n_slotids);
122 if (!slotids)
123 return CKR_HOST_MEMORY;
124
125 rv = m->C_GetSlotList(0, slotids, &n_slotids);
126 if (rv == CKR_OK) {
127 *ret_slotids = TAKE_PTR(slotids);
128 *ret_n_slotids = n_slotids;
129 return CKR_OK;
130 }
131
132 if (rv != CKR_BUFFER_TOO_SMALL)
133 return rv;
134
135 /* Hu? Maybe somebody plugged something in and things changed? Let's try again */
136 }
137
138 return CKR_BUFFER_TOO_SMALL;
139}
140
141char *pkcs11_token_label(const CK_TOKEN_INFO *token_info) {
142 char *t;
143
144 /* The label is not NUL terminated and likely padded with spaces, let's make a copy here, so that we
145 * can strip that. */
146 t = strndup((char*) token_info->label, sizeof(token_info->label));
147 if (!t)
148 return NULL;
149
150 strstrip(t);
151 return t;
152}
153
0eb3be46
LP
154char *pkcs11_token_manufacturer_id(const CK_TOKEN_INFO *token_info) {
155 char *t;
156
157 t = strndup((char*) token_info->manufacturerID, sizeof(token_info->manufacturerID));
158 if (!t)
159 return NULL;
160
161 strstrip(t);
162 return t;
163}
164
165char *pkcs11_token_model(const CK_TOKEN_INFO *token_info) {
166 char *t;
167
168 t = strndup((char*) token_info->model, sizeof(token_info->model));
169 if (!t)
170 return NULL;
171
172 strstrip(t);
173 return t;
174}
175
839fddbe
LP
176int pkcs11_token_login(
177 CK_FUNCTION_LIST *m,
178 CK_SESSION_HANDLE session,
179 CK_SLOT_ID slotid,
180 const CK_TOKEN_INFO *token_info,
181 const char *friendly_name,
182 const char *icon_name,
183 const char *keyname,
184 usec_t until,
185 char **ret_used_pin) {
186
187 _cleanup_free_ char *token_uri_string = NULL, *token_uri_escaped = NULL, *id = NULL, *token_label = NULL;
188 _cleanup_(p11_kit_uri_freep) P11KitUri *token_uri = NULL;
189 CK_TOKEN_INFO updated_token_info;
0eb3be46 190 int uri_result, r;
839fddbe 191 CK_RV rv;
839fddbe
LP
192
193 assert(m);
194 assert(token_info);
195
196 token_label = pkcs11_token_label(token_info);
197 if (!token_label)
198 return log_oom();
199
200 token_uri = uri_from_token_info(token_info);
201 if (!token_uri)
202 return log_oom();
203
204 uri_result = p11_kit_uri_format(token_uri, P11_KIT_URI_FOR_ANY, &token_uri_string);
205 if (uri_result != P11_KIT_URI_OK)
206 return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN), "Failed to format slot URI: %s", p11_kit_uri_message(uri_result));
207
208 if (FLAGS_SET(token_info->flags, CKF_PROTECTED_AUTHENTICATION_PATH)) {
209 rv = m->C_Login(session, CKU_USER, NULL, 0);
210 if (rv != CKR_OK)
211 return log_error_errno(SYNTHETIC_ERRNO(EIO),
212 "Failed to log into security token '%s': %s", token_label, p11_kit_strerror(rv));
213
162392b7 214 log_info("Successfully logged into security token '%s' via protected authentication path.", token_label);
664ad0f6
MS
215 if (ret_used_pin)
216 *ret_used_pin = NULL;
839fddbe
LP
217 return 0;
218 }
219
220 if (!FLAGS_SET(token_info->flags, CKF_LOGIN_REQUIRED)) {
221 log_info("No login into security token '%s' required.", token_label);
664ad0f6
MS
222 if (ret_used_pin)
223 *ret_used_pin = NULL;
839fddbe
LP
224 return 0;
225 }
226
227 token_uri_escaped = cescape(token_uri_string);
228 if (!token_uri_escaped)
229 return log_oom();
230
231 id = strjoin("pkcs11:", token_uri_escaped);
232 if (!id)
233 return log_oom();
234
235 for (unsigned tries = 0; tries < 3; tries++) {
236 _cleanup_strv_free_erase_ char **passwords = NULL;
839fddbe
LP
237 char **i, *e;
238
839fddbe
LP
239 e = getenv("PIN");
240 if (e) {
241 passwords = strv_new(e);
242 if (!passwords)
243 return log_oom();
244
245 string_erase(e);
246 if (unsetenv("PIN") < 0)
247 return log_error_errno(errno, "Failed to unset $PIN: %m");
248 } else {
c63ec11b
LP
249 _cleanup_free_ char *text = NULL;
250
251 if (FLAGS_SET(token_info->flags, CKF_USER_PIN_FINAL_TRY))
252 r = asprintf(&text,
253 "Please enter correct PIN for security token '%s' in order to unlock %s (final try):",
254 token_label, friendly_name);
255 else if (FLAGS_SET(token_info->flags, CKF_USER_PIN_COUNT_LOW))
256 r = asprintf(&text,
257 "PIN has been entered incorrectly previously, please enter correct PIN for security token '%s' in order to unlock %s:",
258 token_label, friendly_name);
259 else if (tries == 0)
260 r = asprintf(&text,
261 "Please enter PIN for security token '%s' in order to unlock %s:",
262 token_label, friendly_name);
263 else
264 r = asprintf(&text,
265 "Please enter PIN for security token '%s' in order to unlock %s (try #%u):",
266 token_label, friendly_name, tries+1);
267 if (r < 0)
268 return log_oom();
269
839fddbe
LP
270 /* We never cache PINs, simply because it's fatal if we use wrong PINs, since usually there are only 3 tries */
271 r = ask_password_auto(text, icon_name, id, keyname, until, 0, &passwords);
272 if (r < 0)
273 return log_error_errno(r, "Failed to query PIN for security token '%s': %m", token_label);
274 }
275
276 STRV_FOREACH(i, passwords) {
277 rv = m->C_Login(session, CKU_USER, (CK_UTF8CHAR*) *i, strlen(*i));
278 if (rv == CKR_OK) {
279
280 if (ret_used_pin) {
281 char *c;
282
283 c = strdup(*i);
284 if (!c)
285 return log_oom();
286
287 *ret_used_pin = c;
288 }
289
290 log_info("Successfully logged into security token '%s'.", token_label);
291 return 0;
292 }
293 if (rv == CKR_PIN_LOCKED)
294 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
295 "PIN has been locked, please reset PIN of security token '%s'.", token_label);
296 if (!IN_SET(rv, CKR_PIN_INCORRECT, CKR_PIN_LEN_RANGE))
297 return log_error_errno(SYNTHETIC_ERRNO(EIO),
298 "Failed to log into security token '%s': %s", token_label, p11_kit_strerror(rv));
299
300 /* Referesh the token info, so that we can prompt knowing the new flags if they changed. */
301 rv = m->C_GetTokenInfo(slotid, &updated_token_info);
302 if (rv != CKR_OK)
303 return log_error_errno(SYNTHETIC_ERRNO(EIO),
304 "Failed to acquire updated security token information for slot %lu: %s",
305 slotid, p11_kit_strerror(rv));
306
307 token_info = &updated_token_info;
308 log_notice("PIN for token '%s' is incorrect, please try again.", token_label);
309 }
310 }
311
312 return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Too many attempts to log into token '%s'.", token_label);
313}
314
315int pkcs11_token_find_x509_certificate(
316 CK_FUNCTION_LIST *m,
317 CK_SESSION_HANDLE session,
318 P11KitUri *search_uri,
319 CK_OBJECT_HANDLE *ret_object) {
320
321 bool found_class = false, found_certificate_type = false;
322 _cleanup_free_ CK_ATTRIBUTE *attributes_buffer = NULL;
323 CK_ULONG n_attributes, a, n_objects;
324 CK_ATTRIBUTE *attributes = NULL;
325 CK_OBJECT_HANDLE objects[2];
326 CK_RV rv, rv2;
327
328 assert(m);
329 assert(search_uri);
330 assert(ret_object);
331
332 attributes = p11_kit_uri_get_attributes(search_uri, &n_attributes);
333 for (a = 0; a < n_attributes; a++) {
334
335 /* We use the URI's included match attributes, but make them more strict. This allows users
336 * to specify a token URL instead of an object URL and the right thing should happen if
337 * there's only one suitable key on the token. */
338
339 switch (attributes[a].type) {
340
341 case CKA_CLASS: {
342 CK_OBJECT_CLASS c;
343
344 if (attributes[a].ulValueLen != sizeof(c))
345 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid PKCS#11 CKA_CLASS attribute size.");
346
347 memcpy(&c, attributes[a].pValue, sizeof(c));
348 if (c != CKO_CERTIFICATE)
349 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Selected PKCS#11 object is not an X.509 certificate, refusing.");
350
351 found_class = true;
352 break;
353 }
354
355 case CKA_CERTIFICATE_TYPE: {
356 CK_CERTIFICATE_TYPE t;
357
358 if (attributes[a].ulValueLen != sizeof(t))
359 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid PKCS#11 CKA_CERTIFICATE_TYPE attribute size.");
360
361 memcpy(&t, attributes[a].pValue, sizeof(t));
362 if (t != CKC_X_509)
363 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Selected PKCS#11 object is not an X.509 certificate, refusing.");
364
365 found_certificate_type = true;
366 break;
367 }}
368 }
369
370 if (!found_class || !found_certificate_type) {
371 /* Hmm, let's slightly extend the attribute list we search for */
372
373 attributes_buffer = new(CK_ATTRIBUTE, n_attributes + !found_class + !found_certificate_type);
374 if (!attributes_buffer)
375 return log_oom();
376
377 memcpy(attributes_buffer, attributes, sizeof(CK_ATTRIBUTE) * n_attributes);
378
379 if (!found_class) {
380 static const CK_OBJECT_CLASS class = CKO_CERTIFICATE;
381
382 attributes_buffer[n_attributes++] = (CK_ATTRIBUTE) {
383 .type = CKA_CLASS,
384 .pValue = (CK_OBJECT_CLASS*) &class,
385 .ulValueLen = sizeof(class),
386 };
387 }
388
389 if (!found_certificate_type) {
390 static const CK_CERTIFICATE_TYPE type = CKC_X_509;
391
392 attributes_buffer[n_attributes++] = (CK_ATTRIBUTE) {
393 .type = CKA_CERTIFICATE_TYPE,
394 .pValue = (CK_CERTIFICATE_TYPE*) &type,
395 .ulValueLen = sizeof(type),
396 };
397 }
398
399 attributes = attributes_buffer;
400 }
401
402 rv = m->C_FindObjectsInit(session, attributes, n_attributes);
403 if (rv != CKR_OK)
404 return log_error_errno(SYNTHETIC_ERRNO(EIO),
405 "Failed to initialize object find call: %s", p11_kit_strerror(rv));
406
407 rv = m->C_FindObjects(session, objects, ELEMENTSOF(objects), &n_objects);
408 rv2 = m->C_FindObjectsFinal(session);
409 if (rv != CKR_OK)
410 return log_error_errno(SYNTHETIC_ERRNO(EIO),
411 "Failed to find objects: %s", p11_kit_strerror(rv));
412 if (rv2 != CKR_OK)
413 return log_error_errno(SYNTHETIC_ERRNO(EIO),
414 "Failed to finalize object find call: %s", p11_kit_strerror(rv));
415 if (n_objects == 0)
416 return log_error_errno(SYNTHETIC_ERRNO(ENOENT),
417 "Failed to find selected X509 certificate on token.");
418 if (n_objects > 1)
419 return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ),
420 "Configured URI matches multiple certificates, refusing.");
421
422 *ret_object = objects[0];
423 return 0;
424}
425
426#if HAVE_OPENSSL
427int pkcs11_token_read_x509_certificate(
428 CK_FUNCTION_LIST *m,
429 CK_SESSION_HANDLE session,
430 CK_OBJECT_HANDLE object,
431 X509 **ret_cert) {
432
433 _cleanup_free_ void *buffer = NULL;
434 _cleanup_free_ char *t = NULL;
435 CK_ATTRIBUTE attribute = {
436 .type = CKA_VALUE
437 };
438 CK_RV rv;
439 _cleanup_(X509_freep) X509 *x509 = NULL;
440 X509_NAME *name = NULL;
441 const unsigned char *p;
442
443 rv = m->C_GetAttributeValue(session, object, &attribute, 1);
444 if (rv != CKR_OK)
445 return log_error_errno(SYNTHETIC_ERRNO(EIO),
446 "Failed to read X.509 certificate size off token: %s", p11_kit_strerror(rv));
447
448 buffer = malloc(attribute.ulValueLen);
449 if (!buffer)
450 return log_oom();
451
452 attribute.pValue = buffer;
453
454 rv = m->C_GetAttributeValue(session, object, &attribute, 1);
455 if (rv != CKR_OK)
456 return log_error_errno(SYNTHETIC_ERRNO(EIO),
457 "Failed to read X.509 certificate data off token: %s", p11_kit_strerror(rv));
458
459 p = attribute.pValue;
460 x509 = d2i_X509(NULL, &p, attribute.ulValueLen);
461 if (!x509)
462 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Failed parse X.509 certificate.");
463
464 name = X509_get_subject_name(x509);
465 if (!name)
466 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Failed to acquire X.509 subject name.");
467
468 t = X509_NAME_oneline(name, NULL, 0);
469 if (!t)
470 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to format X.509 subject name as string.");
471
472 log_debug("Using X.509 certificate issued for '%s'.", t);
473
474 *ret_cert = TAKE_PTR(x509);
475 return 0;
476}
477#endif
478
479int pkcs11_token_find_private_key(
480 CK_FUNCTION_LIST *m,
481 CK_SESSION_HANDLE session,
482 P11KitUri *search_uri,
483 CK_OBJECT_HANDLE *ret_object) {
484
485 bool found_decrypt = false, found_class = false, found_key_type = false;
486 _cleanup_free_ CK_ATTRIBUTE *attributes_buffer = NULL;
487 CK_ULONG n_attributes, a, n_objects;
488 CK_ATTRIBUTE *attributes = NULL;
489 CK_OBJECT_HANDLE objects[2];
490 CK_RV rv, rv2;
491
492 assert(m);
493 assert(search_uri);
494 assert(ret_object);
495
496 attributes = p11_kit_uri_get_attributes(search_uri, &n_attributes);
497 for (a = 0; a < n_attributes; a++) {
498
499 /* We use the URI's included match attributes, but make them more strict. This allows users
500 * to specify a token URL instead of an object URL and the right thing should happen if
501 * there's only one suitable key on the token. */
502
503 switch (attributes[a].type) {
504
505 case CKA_CLASS: {
506 CK_OBJECT_CLASS c;
507
508 if (attributes[a].ulValueLen != sizeof(c))
509 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid PKCS#11 CKA_CLASS attribute size.");
510
511 memcpy(&c, attributes[a].pValue, sizeof(c));
512 if (c != CKO_PRIVATE_KEY)
513 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
514 "Selected PKCS#11 object is not a private key, refusing.");
515
516 found_class = true;
517 break;
518 }
519
520 case CKA_DECRYPT: {
521 CK_BBOOL b;
522
523 if (attributes[a].ulValueLen != sizeof(b))
524 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid PKCS#11 CKA_DECRYPT attribute size.");
525
526 memcpy(&b, attributes[a].pValue, sizeof(b));
527 if (!b)
528 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
529 "Selected PKCS#11 object is not suitable for decryption, refusing.");
530
531 found_decrypt = true;
532 break;
533 }
534
535 case CKA_KEY_TYPE: {
536 CK_KEY_TYPE t;
537
538 if (attributes[a].ulValueLen != sizeof(t))
539 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid PKCS#11 CKA_KEY_TYPE attribute size.");
540
541 memcpy(&t, attributes[a].pValue, sizeof(t));
542 if (t != CKK_RSA)
543 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Selected PKCS#11 object is not an RSA key, refusing.");
544
545 found_key_type = true;
546 break;
547 }}
548 }
549
550 if (!found_decrypt || !found_class || !found_key_type) {
551 /* Hmm, let's slightly extend the attribute list we search for */
552
553 attributes_buffer = new(CK_ATTRIBUTE, n_attributes + !found_decrypt + !found_class + !found_key_type);
554 if (!attributes_buffer)
555 return log_oom();
556
557 memcpy(attributes_buffer, attributes, sizeof(CK_ATTRIBUTE) * n_attributes);
558
559 if (!found_decrypt) {
560 static const CK_BBOOL yes = true;
561
562 attributes_buffer[n_attributes++] = (CK_ATTRIBUTE) {
563 .type = CKA_DECRYPT,
564 .pValue = (CK_BBOOL*) &yes,
565 .ulValueLen = sizeof(yes),
566 };
567 }
568
569 if (!found_class) {
570 static const CK_OBJECT_CLASS class = CKO_PRIVATE_KEY;
571
572 attributes_buffer[n_attributes++] = (CK_ATTRIBUTE) {
573 .type = CKA_CLASS,
574 .pValue = (CK_OBJECT_CLASS*) &class,
575 .ulValueLen = sizeof(class),
576 };
577 }
578
579 if (!found_key_type) {
580 static const CK_KEY_TYPE type = CKK_RSA;
581
582 attributes_buffer[n_attributes++] = (CK_ATTRIBUTE) {
583 .type = CKA_KEY_TYPE,
584 .pValue = (CK_KEY_TYPE*) &type,
585 .ulValueLen = sizeof(type),
586 };
587 }
588
589 attributes = attributes_buffer;
590 }
591
592 rv = m->C_FindObjectsInit(session, attributes, n_attributes);
593 if (rv != CKR_OK)
594 return log_error_errno(SYNTHETIC_ERRNO(EIO),
595 "Failed to initialize object find call: %s", p11_kit_strerror(rv));
596
597 rv = m->C_FindObjects(session, objects, ELEMENTSOF(objects), &n_objects);
598 rv2 = m->C_FindObjectsFinal(session);
599 if (rv != CKR_OK)
600 return log_error_errno(SYNTHETIC_ERRNO(EIO),
601 "Failed to find objects: %s", p11_kit_strerror(rv));
602 if (rv2 != CKR_OK)
603 return log_error_errno(SYNTHETIC_ERRNO(EIO),
604 "Failed to finalize object find call: %s", p11_kit_strerror(rv));
605 if (n_objects == 0)
606 return log_error_errno(SYNTHETIC_ERRNO(ENOENT),
607 "Failed to find selected private key suitable for decryption on token.");
608 if (n_objects > 1)
609 return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ),
610 "Configured private key URI matches multiple keys, refusing.");
611
612 *ret_object = objects[0];
613 return 0;
614}
615
616int pkcs11_token_decrypt_data(
617 CK_FUNCTION_LIST *m,
618 CK_SESSION_HANDLE session,
619 CK_OBJECT_HANDLE object,
620 const void *encrypted_data,
621 size_t encrypted_data_size,
622 void **ret_decrypted_data,
623 size_t *ret_decrypted_data_size) {
624
625 static const CK_MECHANISM mechanism = {
626 .mechanism = CKM_RSA_PKCS
627 };
628 _cleanup_(erase_and_freep) CK_BYTE *dbuffer = NULL;
629 CK_ULONG dbuffer_size = 0;
630 CK_RV rv;
631
632 assert(m);
633 assert(encrypted_data);
634 assert(encrypted_data_size > 0);
635 assert(ret_decrypted_data);
636 assert(ret_decrypted_data_size);
637
638 rv = m->C_DecryptInit(session, (CK_MECHANISM*) &mechanism, object);
639 if (rv != CKR_OK)
640 return log_error_errno(SYNTHETIC_ERRNO(EIO),
641 "Failed to initialize decryption on security token: %s", p11_kit_strerror(rv));
642
643 dbuffer_size = encrypted_data_size; /* Start with something reasonable */
644 dbuffer = malloc(dbuffer_size);
645 if (!dbuffer)
646 return log_oom();
647
648 rv = m->C_Decrypt(session, (CK_BYTE*) encrypted_data, encrypted_data_size, dbuffer, &dbuffer_size);
649 if (rv == CKR_BUFFER_TOO_SMALL) {
650 erase_and_free(dbuffer);
651
652 dbuffer = malloc(dbuffer_size);
653 if (!dbuffer)
654 return log_oom();
655
656 rv = m->C_Decrypt(session, (CK_BYTE*) encrypted_data, encrypted_data_size, dbuffer, &dbuffer_size);
657 }
658 if (rv != CKR_OK)
659 return log_error_errno(SYNTHETIC_ERRNO(EIO),
660 "Failed to decrypt key on security token: %s", p11_kit_strerror(rv));
661
662 log_info("Successfully decrypted key with security token.");
663
664 *ret_decrypted_data = TAKE_PTR(dbuffer);
665 *ret_decrypted_data_size = dbuffer_size;
666 return 0;
667}
668
669int pkcs11_token_acquire_rng(
670 CK_FUNCTION_LIST *m,
671 CK_SESSION_HANDLE session) {
672
673 _cleanup_free_ void *buffer = NULL;
674 _cleanup_close_ int fd = -1;
675 size_t rps;
676 CK_RV rv;
677 int r;
678
679 assert(m);
680
681 /* While we are at it, let's read some RNG data from the PKCS#11 token and pass it to the kernel
682 * random pool. This should be cheap if we are talking to the device already. Note that we don't
683 * credit any entropy, since we don't know about the quality of the pkcs#11 token's RNG. Why bother
684 * at all? There are two sides to the argument whether to generate private keys on tokens or on the
685 * host. By crediting some data from the token RNG to the host's pool we at least can say that any
686 * key generated from it is at least as good as both sources individually. */
687
688 rps = random_pool_size();
689
690 buffer = malloc(rps);
691 if (!buffer)
692 return log_oom();
693
694 rv = m->C_GenerateRandom(session, buffer, rps);
695 if (rv != CKR_OK)
696 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
697 "Failed to generate RNG data on security token: %s", p11_kit_strerror(rv));
698
699 fd = open("/dev/urandom", O_WRONLY|O_CLOEXEC|O_NOCTTY);
700 if (fd < 0)
701 return log_debug_errno(errno, "Failed to open /dev/urandom for writing: %m");
702
703 r = loop_write(fd, buffer, rps, false);
704 if (r < 0)
705 return log_debug_errno(r, "Failed to write PKCS#11 acquired random data to /dev/urandom: %m");
706
707 log_debug("Successfully written %zu bytes random data acquired via PKCS#11 to kernel random pool.", rps);
708
709 return 0;
710}
711
712static int token_process(
713 CK_FUNCTION_LIST *m,
714 CK_SLOT_ID slotid,
715 const CK_SLOT_INFO *slot_info,
716 const CK_TOKEN_INFO *token_info,
717 P11KitUri *search_uri,
718 pkcs11_find_token_callback_t callback,
719 void *userdata) {
720
721 _cleanup_free_ char *token_label = NULL;
722 CK_SESSION_HANDLE session;
723 CK_RV rv;
724 int r;
725
726 assert(m);
727 assert(slot_info);
728 assert(token_info);
839fddbe
LP
729
730 token_label = pkcs11_token_label(token_info);
731 if (!token_label)
732 return log_oom();
733
734 rv = m->C_OpenSession(slotid, CKF_SERIAL_SESSION, NULL, NULL, &session);
735 if (rv != CKR_OK)
736 return log_error_errno(SYNTHETIC_ERRNO(EIO),
737 "Failed to create session for security token '%s': %s", token_label, p11_kit_strerror(rv));
738
739 if (callback)
740 r = callback(m, session, slotid, slot_info, token_info, search_uri, userdata);
741 else
742 r = 1; /* if not callback was specified, just say we found what we were looking for */
743
744 rv = m->C_CloseSession(session);
745 if (rv != CKR_OK)
746 log_warning("Failed to close session on PKCS#11 token, ignoring: %s", p11_kit_strerror(rv));
747
748 return r;
749}
750
751static int slot_process(
752 CK_FUNCTION_LIST *m,
753 CK_SLOT_ID slotid,
754 P11KitUri *search_uri,
755 pkcs11_find_token_callback_t callback,
756 void *userdata) {
757
758 _cleanup_(p11_kit_uri_freep) P11KitUri* slot_uri = NULL, *token_uri = NULL;
759 _cleanup_free_ char *token_uri_string = NULL;
760 CK_TOKEN_INFO token_info;
761 CK_SLOT_INFO slot_info;
762 int uri_result;
763 CK_RV rv;
764
765 assert(m);
839fddbe
LP
766
767 /* We return -EAGAIN for all failures we can attribute to a specific slot in some way, so that the
768 * caller might try other slots before giving up. */
769
770 rv = m->C_GetSlotInfo(slotid, &slot_info);
771 if (rv != CKR_OK) {
772 log_warning("Failed to acquire slot info for slot %lu, ignoring slot: %s", slotid, p11_kit_strerror(rv));
773 return -EAGAIN;
774 }
775
776 slot_uri = uri_from_slot_info(&slot_info);
777 if (!slot_uri)
778 return log_oom();
779
780 if (DEBUG_LOGGING) {
781 _cleanup_free_ char *slot_uri_string = NULL;
782
783 uri_result = p11_kit_uri_format(slot_uri, P11_KIT_URI_FOR_ANY, &slot_uri_string);
784 if (uri_result != P11_KIT_URI_OK) {
785 log_warning("Failed to format slot URI, ignoring slot: %s", p11_kit_uri_message(uri_result));
786 return -EAGAIN;
787 }
788
789 log_debug("Found slot with URI %s", slot_uri_string);
790 }
791
792 rv = m->C_GetTokenInfo(slotid, &token_info);
793 if (rv == CKR_TOKEN_NOT_PRESENT) {
d7a0f1f4
FS
794 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
795 "Token not present in slot, ignoring.");
839fddbe
LP
796 } else if (rv != CKR_OK) {
797 log_warning("Failed to acquire token info for slot %lu, ignoring slot: %s", slotid, p11_kit_strerror(rv));
798 return -EAGAIN;
799 }
800
801 token_uri = uri_from_token_info(&token_info);
802 if (!token_uri)
803 return log_oom();
804
805 uri_result = p11_kit_uri_format(token_uri, P11_KIT_URI_FOR_ANY, &token_uri_string);
806 if (uri_result != P11_KIT_URI_OK) {
807 log_warning("Failed to format slot URI: %s", p11_kit_uri_message(uri_result));
808 return -EAGAIN;
809 }
810
d7a0f1f4
FS
811 if (search_uri && !p11_kit_uri_match_token_info(search_uri, &token_info))
812 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
813 "Found non-matching token with URI %s.",
814 token_uri_string);
839fddbe
LP
815
816 log_debug("Found matching token with URI %s.", token_uri_string);
817
818 return token_process(
819 m,
820 slotid,
821 &slot_info,
822 &token_info,
823 search_uri,
824 callback,
825 userdata);
826}
827
828static int module_process(
829 CK_FUNCTION_LIST *m,
830 P11KitUri *search_uri,
831 pkcs11_find_token_callback_t callback,
832 void *userdata) {
833
834 _cleanup_free_ char *name = NULL, *module_uri_string = NULL;
835 _cleanup_(p11_kit_uri_freep) P11KitUri* module_uri = NULL;
836 _cleanup_free_ CK_SLOT_ID *slotids = NULL;
837 CK_ULONG n_slotids = 0;
838 int uri_result;
839 CK_INFO info;
840 size_t k;
841 CK_RV rv;
842 int r;
843
844 assert(m);
839fddbe
LP
845
846 /* We ignore most errors from modules here, in order to skip over faulty modules: one faulty module
847 * should not have the effect that we don't try the others anymore. We indicate such per-module
848 * failures with -EAGAIN, which let's the caller try the next module. */
849
850 name = p11_kit_module_get_name(m);
851 if (!name)
852 return log_oom();
853
854 log_debug("Trying PKCS#11 module %s.", name);
855
856 rv = m->C_GetInfo(&info);
857 if (rv != CKR_OK) {
858 log_warning("Failed to get info on PKCS#11 module, ignoring module: %s", p11_kit_strerror(rv));
859 return -EAGAIN;
860 }
861
862 module_uri = uri_from_module_info(&info);
863 if (!module_uri)
864 return log_oom();
865
866 uri_result = p11_kit_uri_format(module_uri, P11_KIT_URI_FOR_ANY, &module_uri_string);
867 if (uri_result != P11_KIT_URI_OK) {
868 log_warning("Failed to format module URI, ignoring module: %s", p11_kit_uri_message(uri_result));
869 return -EAGAIN;
870 }
871
872 log_debug("Found module with URI %s", module_uri_string);
873
874 rv = pkcs11_get_slot_list_malloc(m, &slotids, &n_slotids);
875 if (rv != CKR_OK) {
876 log_warning("Failed to get slot list, ignoring module: %s", p11_kit_strerror(rv));
877 return -EAGAIN;
878 }
d7a0f1f4
FS
879 if (n_slotids == 0)
880 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
881 "This module has no slots? Ignoring module.");
839fddbe
LP
882
883 for (k = 0; k < n_slotids; k++) {
884 r = slot_process(
885 m,
886 slotids[k],
887 search_uri,
888 callback,
889 userdata);
890 if (r != -EAGAIN)
891 return r;
892 }
893
894 return -EAGAIN;
895}
896
897int pkcs11_find_token(
898 const char *pkcs11_uri,
899 pkcs11_find_token_callback_t callback,
900 void *userdata) {
901
902 _cleanup_(p11_kit_modules_finalize_and_releasep) CK_FUNCTION_LIST **modules = NULL;
903 _cleanup_(p11_kit_uri_freep) P11KitUri *search_uri = NULL;
904 int r;
905
839fddbe
LP
906 /* Execute the specified callback for each matching token found. If nothing is found returns
907 * -EAGAIN. Logs about all errors, except for EAGAIN, which the caller has to log about. */
908
0eb3be46
LP
909 if (pkcs11_uri) {
910 r = uri_from_string(pkcs11_uri, &search_uri);
911 if (r < 0)
912 return log_error_errno(r, "Failed to parse PKCS#11 URI '%s': %m", pkcs11_uri);
913 }
839fddbe
LP
914
915 modules = p11_kit_modules_load_and_initialize(0);
916 if (!modules)
917 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to initialize pkcs11 modules");
918
919 for (CK_FUNCTION_LIST **i = modules; *i; i++) {
920 r = module_process(
921 *i,
922 search_uri,
923 callback,
924 userdata);
925 if (r != -EAGAIN)
926 return r;
927 }
928
929 return -EAGAIN;
930}
931
932#endif