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