]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/pkcs11-util.c
Merge pull request #20776 from medhefgo/boot-timeout
[thirdparty/systemd.git] / src / shared / pkcs11-util.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <fcntl.h>
4
5 #include "ask-password-api.h"
6 #include "env-util.h"
7 #include "escape.h"
8 #include "fd-util.h"
9 #include "format-table.h"
10 #include "io-util.h"
11 #include "memory-util.h"
12 #if HAVE_OPENSSL
13 #include "openssl-util.h"
14 #endif
15 #include "pkcs11-util.h"
16 #include "random-util.h"
17 #include "string-util.h"
18 #include "strv.h"
19
20 bool pkcs11_uri_valid(const char *uri) {
21 const char *p;
22
23 /* A very superficial checker for RFC7512 PKCS#11 URI syntax */
24
25 if (isempty(uri))
26 return false;
27
28 p = startswith(uri, "pkcs11:");
29 if (!p)
30 return false;
31
32 if (isempty(p))
33 return false;
34
35 if (!in_charset(p, ALPHANUMERICAL ".~/-_?;&%="))
36 return false;
37
38 return true;
39 }
40
41 #if HAVE_P11KIT
42
43 int uri_from_string(const char *p, P11KitUri **ret) {
44 _cleanup_(p11_kit_uri_freep) P11KitUri *uri = NULL;
45
46 assert(p);
47 assert(ret);
48
49 uri = p11_kit_uri_new();
50 if (!uri)
51 return -ENOMEM;
52
53 if (p11_kit_uri_parse(p, P11_KIT_URI_FOR_ANY, uri) != P11_KIT_URI_OK)
54 return -EINVAL;
55
56 *ret = TAKE_PTR(uri);
57 return 0;
58 }
59
60 P11KitUri *uri_from_module_info(const CK_INFO *info) {
61 P11KitUri *uri;
62
63 assert(info);
64
65 uri = p11_kit_uri_new();
66 if (!uri)
67 return NULL;
68
69 *p11_kit_uri_get_module_info(uri) = *info;
70 return uri;
71 }
72
73 P11KitUri *uri_from_slot_info(const CK_SLOT_INFO *slot_info) {
74 P11KitUri *uri;
75
76 assert(slot_info);
77
78 uri = p11_kit_uri_new();
79 if (!uri)
80 return NULL;
81
82 *p11_kit_uri_get_slot_info(uri) = *slot_info;
83 return uri;
84 }
85
86 P11KitUri *uri_from_token_info(const CK_TOKEN_INFO *token_info) {
87 P11KitUri *uri;
88
89 assert(token_info);
90
91 uri = p11_kit_uri_new();
92 if (!uri)
93 return NULL;
94
95 *p11_kit_uri_get_token_info(uri) = *token_info;
96 return uri;
97 }
98
99 CK_RV pkcs11_get_slot_list_malloc(
100 CK_FUNCTION_LIST *m,
101 CK_SLOT_ID **ret_slotids,
102 CK_ULONG *ret_n_slotids) {
103
104 CK_RV rv;
105
106 assert(m);
107 assert(ret_slotids);
108 assert(ret_n_slotids);
109
110 for (unsigned tries = 0; tries < 16; tries++) {
111 _cleanup_free_ CK_SLOT_ID *slotids = NULL;
112 CK_ULONG n_slotids = 0;
113
114 rv = m->C_GetSlotList(0, NULL, &n_slotids);
115 if (rv != CKR_OK)
116 return rv;
117 if (n_slotids == 0) {
118 *ret_slotids = NULL;
119 *ret_n_slotids = 0;
120 return CKR_OK;
121 }
122
123 slotids = new(CK_SLOT_ID, n_slotids);
124 if (!slotids)
125 return CKR_HOST_MEMORY;
126
127 rv = m->C_GetSlotList(0, slotids, &n_slotids);
128 if (rv == CKR_OK) {
129 *ret_slotids = TAKE_PTR(slotids);
130 *ret_n_slotids = n_slotids;
131 return CKR_OK;
132 }
133
134 if (rv != CKR_BUFFER_TOO_SMALL)
135 return rv;
136
137 /* Hu? Maybe somebody plugged something in and things changed? Let's try again */
138 }
139
140 return CKR_BUFFER_TOO_SMALL;
141 }
142
143 char *pkcs11_token_label(const CK_TOKEN_INFO *token_info) {
144 char *t;
145
146 /* The label is not NUL terminated and likely padded with spaces, let's make a copy here, so that we
147 * can strip that. */
148 t = strndup((char*) token_info->label, sizeof(token_info->label));
149 if (!t)
150 return NULL;
151
152 strstrip(t);
153 return t;
154 }
155
156 char *pkcs11_token_manufacturer_id(const CK_TOKEN_INFO *token_info) {
157 char *t;
158
159 t = strndup((char*) token_info->manufacturerID, sizeof(token_info->manufacturerID));
160 if (!t)
161 return NULL;
162
163 strstrip(t);
164 return t;
165 }
166
167 char *pkcs11_token_model(const CK_TOKEN_INFO *token_info) {
168 char *t;
169
170 t = strndup((char*) token_info->model, sizeof(token_info->model));
171 if (!t)
172 return NULL;
173
174 strstrip(t);
175 return t;
176 }
177
178 int pkcs11_token_login_by_pin(
179 CK_FUNCTION_LIST *m,
180 CK_SESSION_HANDLE session,
181 const CK_TOKEN_INFO *token_info,
182 const char *token_label,
183 const void *pin,
184 size_t pin_size) {
185
186 CK_RV rv;
187
188 assert(m);
189 assert(token_info);
190
191 if (FLAGS_SET(token_info->flags, CKF_PROTECTED_AUTHENTICATION_PATH)) {
192 rv = m->C_Login(session, CKU_USER, NULL, 0);
193 if (rv != CKR_OK)
194 return log_error_errno(SYNTHETIC_ERRNO(EIO),
195 "Failed to log into security token '%s': %s", token_label, p11_kit_strerror(rv));
196
197 log_info("Successfully logged into security token '%s' via protected authentication path.", token_label);
198 return 0;
199 }
200
201 if (!FLAGS_SET(token_info->flags, CKF_LOGIN_REQUIRED)) {
202 log_info("No login into security token '%s' required.", token_label);
203 return 0;
204 }
205
206 if (!pin)
207 return -ENOANO;
208
209 rv = m->C_Login(session, CKU_USER, (CK_UTF8CHAR*) pin, pin_size);
210 if (rv == CKR_OK) {
211 log_info("Successfully logged into security token '%s'.", token_label);
212 return 0;
213 }
214
215 if (rv == CKR_PIN_LOCKED)
216 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
217 "PIN has been locked, please reset PIN of security token '%s'.", token_label);
218 if (!IN_SET(rv, CKR_PIN_INCORRECT, CKR_PIN_LEN_RANGE))
219 return log_error_errno(SYNTHETIC_ERRNO(EIO),
220 "Failed to log into security token '%s': %s", token_label, p11_kit_strerror(rv));
221
222 return log_notice_errno(SYNTHETIC_ERRNO(ENOLCK),
223 "PIN for token '%s' is incorrect, please try again.",
224 token_label);
225 }
226
227 int pkcs11_token_login(
228 CK_FUNCTION_LIST *m,
229 CK_SESSION_HANDLE session,
230 CK_SLOT_ID slotid,
231 const CK_TOKEN_INFO *token_info,
232 const char *friendly_name,
233 const char *icon_name,
234 const char *key_name,
235 const char *credential_name,
236 usec_t until,
237 bool headless,
238 char **ret_used_pin) {
239
240 _cleanup_free_ char *token_uri_string = NULL, *token_uri_escaped = NULL, *id = NULL, *token_label = NULL;
241 _cleanup_(p11_kit_uri_freep) P11KitUri *token_uri = NULL;
242 CK_TOKEN_INFO updated_token_info;
243 int uri_result, r;
244 CK_RV rv;
245
246 assert(m);
247 assert(token_info);
248
249 token_label = pkcs11_token_label(token_info);
250 if (!token_label)
251 return log_oom();
252
253 token_uri = uri_from_token_info(token_info);
254 if (!token_uri)
255 return log_oom();
256
257 uri_result = p11_kit_uri_format(token_uri, P11_KIT_URI_FOR_ANY, &token_uri_string);
258 if (uri_result != P11_KIT_URI_OK)
259 return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN), "Failed to format slot URI: %s", p11_kit_uri_message(uri_result));
260
261 r = pkcs11_token_login_by_pin(m, session, token_info, token_label, /* pin= */ NULL, 0);
262 if (r == 0 && ret_used_pin)
263 *ret_used_pin = NULL;
264
265 if (r != -ENOANO) /* pin required */
266 return r;
267
268 token_uri_escaped = cescape(token_uri_string);
269 if (!token_uri_escaped)
270 return log_oom();
271
272 id = strjoin("pkcs11:", token_uri_escaped);
273 if (!id)
274 return log_oom();
275
276 for (unsigned tries = 0; tries < 3; tries++) {
277 _cleanup_strv_free_erase_ char **passwords = NULL;
278 char **i, *e;
279
280 e = getenv("PIN");
281 if (e) {
282 passwords = strv_new(e);
283 if (!passwords)
284 return log_oom();
285
286 assert_se(unsetenv_erase("PIN") >= 0);
287 } else if (headless)
288 return log_error_errno(SYNTHETIC_ERRNO(ENOPKG), "PIN querying disabled via 'headless' option. Use the 'PIN' environment variable.");
289 else {
290 _cleanup_free_ char *text = NULL;
291
292 if (FLAGS_SET(token_info->flags, CKF_USER_PIN_FINAL_TRY))
293 r = asprintf(&text,
294 "Please enter correct PIN for security token '%s' in order to unlock %s (final try):",
295 token_label, friendly_name);
296 else if (FLAGS_SET(token_info->flags, CKF_USER_PIN_COUNT_LOW))
297 r = asprintf(&text,
298 "PIN has been entered incorrectly previously, please enter correct PIN for security token '%s' in order to unlock %s:",
299 token_label, friendly_name);
300 else if (tries == 0)
301 r = asprintf(&text,
302 "Please enter PIN for security token '%s' in order to unlock %s:",
303 token_label, friendly_name);
304 else
305 r = asprintf(&text,
306 "Please enter PIN for security token '%s' in order to unlock %s (try #%u):",
307 token_label, friendly_name, tries+1);
308 if (r < 0)
309 return log_oom();
310
311 /* We never cache PINs, simply because it's fatal if we use wrong PINs, since usually there are only 3 tries */
312 r = ask_password_auto(text, icon_name, id, key_name, credential_name, until, 0, &passwords);
313 if (r < 0)
314 return log_error_errno(r, "Failed to query PIN for security token '%s': %m", token_label);
315 }
316
317 STRV_FOREACH(i, passwords) {
318 r = pkcs11_token_login_by_pin(m, session, token_info, token_label, *i, strlen(*i));
319 if (r == 0 && ret_used_pin) {
320 char *c;
321
322 c = strdup(*i);
323 if (!c)
324 return log_oom();
325
326 *ret_used_pin = c;
327 }
328
329 if (r != -ENOLCK)
330 return r;
331
332 /* Referesh the token info, so that we can prompt knowing the new flags if they changed. */
333 rv = m->C_GetTokenInfo(slotid, &updated_token_info);
334 if (rv != CKR_OK)
335 return log_error_errno(SYNTHETIC_ERRNO(EIO),
336 "Failed to acquire updated security token information for slot %lu: %s",
337 slotid, p11_kit_strerror(rv));
338
339 token_info = &updated_token_info;
340 }
341 }
342
343 return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Too many attempts to log into token '%s'.", token_label);
344 }
345
346 int pkcs11_token_find_x509_certificate(
347 CK_FUNCTION_LIST *m,
348 CK_SESSION_HANDLE session,
349 P11KitUri *search_uri,
350 CK_OBJECT_HANDLE *ret_object) {
351
352 bool found_class = false, found_certificate_type = false;
353 _cleanup_free_ CK_ATTRIBUTE *attributes_buffer = NULL;
354 CK_ULONG n_attributes, a, n_objects;
355 CK_ATTRIBUTE *attributes = NULL;
356 CK_OBJECT_HANDLE objects[2];
357 CK_RV rv, rv2;
358
359 assert(m);
360 assert(search_uri);
361 assert(ret_object);
362
363 attributes = p11_kit_uri_get_attributes(search_uri, &n_attributes);
364 for (a = 0; a < n_attributes; a++) {
365
366 /* We use the URI's included match attributes, but make them more strict. This allows users
367 * to specify a token URL instead of an object URL and the right thing should happen if
368 * there's only one suitable key on the token. */
369
370 switch (attributes[a].type) {
371
372 case CKA_CLASS: {
373 CK_OBJECT_CLASS c;
374
375 if (attributes[a].ulValueLen != sizeof(c))
376 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid PKCS#11 CKA_CLASS attribute size.");
377
378 memcpy(&c, attributes[a].pValue, sizeof(c));
379 if (c != CKO_CERTIFICATE)
380 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Selected PKCS#11 object is not an X.509 certificate, refusing.");
381
382 found_class = true;
383 break;
384 }
385
386 case CKA_CERTIFICATE_TYPE: {
387 CK_CERTIFICATE_TYPE t;
388
389 if (attributes[a].ulValueLen != sizeof(t))
390 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid PKCS#11 CKA_CERTIFICATE_TYPE attribute size.");
391
392 memcpy(&t, attributes[a].pValue, sizeof(t));
393 if (t != CKC_X_509)
394 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Selected PKCS#11 object is not an X.509 certificate, refusing.");
395
396 found_certificate_type = true;
397 break;
398 }}
399 }
400
401 if (!found_class || !found_certificate_type) {
402 /* Hmm, let's slightly extend the attribute list we search for */
403
404 attributes_buffer = new(CK_ATTRIBUTE, n_attributes + !found_class + !found_certificate_type);
405 if (!attributes_buffer)
406 return log_oom();
407
408 memcpy(attributes_buffer, attributes, sizeof(CK_ATTRIBUTE) * n_attributes);
409
410 if (!found_class) {
411 static const CK_OBJECT_CLASS class = CKO_CERTIFICATE;
412
413 attributes_buffer[n_attributes++] = (CK_ATTRIBUTE) {
414 .type = CKA_CLASS,
415 .pValue = (CK_OBJECT_CLASS*) &class,
416 .ulValueLen = sizeof(class),
417 };
418 }
419
420 if (!found_certificate_type) {
421 static const CK_CERTIFICATE_TYPE type = CKC_X_509;
422
423 attributes_buffer[n_attributes++] = (CK_ATTRIBUTE) {
424 .type = CKA_CERTIFICATE_TYPE,
425 .pValue = (CK_CERTIFICATE_TYPE*) &type,
426 .ulValueLen = sizeof(type),
427 };
428 }
429
430 attributes = attributes_buffer;
431 }
432
433 rv = m->C_FindObjectsInit(session, attributes, n_attributes);
434 if (rv != CKR_OK)
435 return log_error_errno(SYNTHETIC_ERRNO(EIO),
436 "Failed to initialize object find call: %s", p11_kit_strerror(rv));
437
438 rv = m->C_FindObjects(session, objects, ELEMENTSOF(objects), &n_objects);
439 rv2 = m->C_FindObjectsFinal(session);
440 if (rv != CKR_OK)
441 return log_error_errno(SYNTHETIC_ERRNO(EIO),
442 "Failed to find objects: %s", p11_kit_strerror(rv));
443 if (rv2 != CKR_OK)
444 return log_error_errno(SYNTHETIC_ERRNO(EIO),
445 "Failed to finalize object find call: %s", p11_kit_strerror(rv));
446 if (n_objects == 0)
447 return log_error_errno(SYNTHETIC_ERRNO(ENOENT),
448 "Failed to find selected X509 certificate on token.");
449 if (n_objects > 1)
450 return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ),
451 "Configured URI matches multiple certificates, refusing.");
452
453 *ret_object = objects[0];
454 return 0;
455 }
456
457 #if HAVE_OPENSSL
458 int pkcs11_token_read_x509_certificate(
459 CK_FUNCTION_LIST *m,
460 CK_SESSION_HANDLE session,
461 CK_OBJECT_HANDLE object,
462 X509 **ret_cert) {
463
464 _cleanup_free_ void *buffer = NULL;
465 _cleanup_free_ char *t = NULL;
466 CK_ATTRIBUTE attribute = {
467 .type = CKA_VALUE
468 };
469 CK_RV rv;
470 _cleanup_(X509_freep) X509 *x509 = NULL;
471 X509_NAME *name = NULL;
472 const unsigned char *p;
473
474 rv = m->C_GetAttributeValue(session, object, &attribute, 1);
475 if (rv != CKR_OK)
476 return log_error_errno(SYNTHETIC_ERRNO(EIO),
477 "Failed to read X.509 certificate size off token: %s", p11_kit_strerror(rv));
478
479 buffer = malloc(attribute.ulValueLen);
480 if (!buffer)
481 return log_oom();
482
483 attribute.pValue = buffer;
484
485 rv = m->C_GetAttributeValue(session, object, &attribute, 1);
486 if (rv != CKR_OK)
487 return log_error_errno(SYNTHETIC_ERRNO(EIO),
488 "Failed to read X.509 certificate data off token: %s", p11_kit_strerror(rv));
489
490 p = attribute.pValue;
491 x509 = d2i_X509(NULL, &p, attribute.ulValueLen);
492 if (!x509)
493 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Failed parse X.509 certificate.");
494
495 name = X509_get_subject_name(x509);
496 if (!name)
497 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Failed to acquire X.509 subject name.");
498
499 t = X509_NAME_oneline(name, NULL, 0);
500 if (!t)
501 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to format X.509 subject name as string.");
502
503 log_debug("Using X.509 certificate issued for '%s'.", t);
504
505 *ret_cert = TAKE_PTR(x509);
506 return 0;
507 }
508 #endif
509
510 int pkcs11_token_find_private_key(
511 CK_FUNCTION_LIST *m,
512 CK_SESSION_HANDLE session,
513 P11KitUri *search_uri,
514 CK_OBJECT_HANDLE *ret_object) {
515
516 bool found_decrypt = false, found_class = false, found_key_type = false;
517 _cleanup_free_ CK_ATTRIBUTE *attributes_buffer = NULL;
518 CK_ULONG n_attributes, a, n_objects;
519 CK_ATTRIBUTE *attributes = NULL;
520 CK_OBJECT_HANDLE objects[2];
521 CK_RV rv, rv2;
522
523 assert(m);
524 assert(search_uri);
525 assert(ret_object);
526
527 attributes = p11_kit_uri_get_attributes(search_uri, &n_attributes);
528 for (a = 0; a < n_attributes; a++) {
529
530 /* We use the URI's included match attributes, but make them more strict. This allows users
531 * to specify a token URL instead of an object URL and the right thing should happen if
532 * there's only one suitable key on the token. */
533
534 switch (attributes[a].type) {
535
536 case CKA_CLASS: {
537 CK_OBJECT_CLASS c;
538
539 if (attributes[a].ulValueLen != sizeof(c))
540 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid PKCS#11 CKA_CLASS attribute size.");
541
542 memcpy(&c, attributes[a].pValue, sizeof(c));
543 if (c != CKO_PRIVATE_KEY)
544 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
545 "Selected PKCS#11 object is not a private key, refusing.");
546
547 found_class = true;
548 break;
549 }
550
551 case CKA_DECRYPT: {
552 CK_BBOOL b;
553
554 if (attributes[a].ulValueLen != sizeof(b))
555 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid PKCS#11 CKA_DECRYPT attribute size.");
556
557 memcpy(&b, attributes[a].pValue, sizeof(b));
558 if (!b)
559 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
560 "Selected PKCS#11 object is not suitable for decryption, refusing.");
561
562 found_decrypt = true;
563 break;
564 }
565
566 case CKA_KEY_TYPE: {
567 CK_KEY_TYPE t;
568
569 if (attributes[a].ulValueLen != sizeof(t))
570 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid PKCS#11 CKA_KEY_TYPE attribute size.");
571
572 memcpy(&t, attributes[a].pValue, sizeof(t));
573 if (t != CKK_RSA)
574 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Selected PKCS#11 object is not an RSA key, refusing.");
575
576 found_key_type = true;
577 break;
578 }}
579 }
580
581 if (!found_decrypt || !found_class || !found_key_type) {
582 /* Hmm, let's slightly extend the attribute list we search for */
583
584 attributes_buffer = new(CK_ATTRIBUTE, n_attributes + !found_decrypt + !found_class + !found_key_type);
585 if (!attributes_buffer)
586 return log_oom();
587
588 memcpy(attributes_buffer, attributes, sizeof(CK_ATTRIBUTE) * n_attributes);
589
590 if (!found_decrypt) {
591 static const CK_BBOOL yes = true;
592
593 attributes_buffer[n_attributes++] = (CK_ATTRIBUTE) {
594 .type = CKA_DECRYPT,
595 .pValue = (CK_BBOOL*) &yes,
596 .ulValueLen = sizeof(yes),
597 };
598 }
599
600 if (!found_class) {
601 static const CK_OBJECT_CLASS class = CKO_PRIVATE_KEY;
602
603 attributes_buffer[n_attributes++] = (CK_ATTRIBUTE) {
604 .type = CKA_CLASS,
605 .pValue = (CK_OBJECT_CLASS*) &class,
606 .ulValueLen = sizeof(class),
607 };
608 }
609
610 if (!found_key_type) {
611 static const CK_KEY_TYPE type = CKK_RSA;
612
613 attributes_buffer[n_attributes++] = (CK_ATTRIBUTE) {
614 .type = CKA_KEY_TYPE,
615 .pValue = (CK_KEY_TYPE*) &type,
616 .ulValueLen = sizeof(type),
617 };
618 }
619
620 attributes = attributes_buffer;
621 }
622
623 rv = m->C_FindObjectsInit(session, attributes, n_attributes);
624 if (rv != CKR_OK)
625 return log_error_errno(SYNTHETIC_ERRNO(EIO),
626 "Failed to initialize object find call: %s", p11_kit_strerror(rv));
627
628 rv = m->C_FindObjects(session, objects, ELEMENTSOF(objects), &n_objects);
629 rv2 = m->C_FindObjectsFinal(session);
630 if (rv != CKR_OK)
631 return log_error_errno(SYNTHETIC_ERRNO(EIO),
632 "Failed to find objects: %s", p11_kit_strerror(rv));
633 if (rv2 != CKR_OK)
634 return log_error_errno(SYNTHETIC_ERRNO(EIO),
635 "Failed to finalize object find call: %s", p11_kit_strerror(rv));
636 if (n_objects == 0)
637 return log_error_errno(SYNTHETIC_ERRNO(ENOENT),
638 "Failed to find selected private key suitable for decryption on token.");
639 if (n_objects > 1)
640 return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ),
641 "Configured private key URI matches multiple keys, refusing.");
642
643 *ret_object = objects[0];
644 return 0;
645 }
646
647 int pkcs11_token_decrypt_data(
648 CK_FUNCTION_LIST *m,
649 CK_SESSION_HANDLE session,
650 CK_OBJECT_HANDLE object,
651 const void *encrypted_data,
652 size_t encrypted_data_size,
653 void **ret_decrypted_data,
654 size_t *ret_decrypted_data_size) {
655
656 static const CK_MECHANISM mechanism = {
657 .mechanism = CKM_RSA_PKCS
658 };
659 _cleanup_(erase_and_freep) CK_BYTE *dbuffer = NULL;
660 CK_ULONG dbuffer_size = 0;
661 CK_RV rv;
662
663 assert(m);
664 assert(encrypted_data);
665 assert(encrypted_data_size > 0);
666 assert(ret_decrypted_data);
667 assert(ret_decrypted_data_size);
668
669 rv = m->C_DecryptInit(session, (CK_MECHANISM*) &mechanism, object);
670 if (rv != CKR_OK)
671 return log_error_errno(SYNTHETIC_ERRNO(EIO),
672 "Failed to initialize decryption on security token: %s", p11_kit_strerror(rv));
673
674 dbuffer_size = encrypted_data_size; /* Start with something reasonable */
675 dbuffer = malloc(dbuffer_size);
676 if (!dbuffer)
677 return log_oom();
678
679 rv = m->C_Decrypt(session, (CK_BYTE*) encrypted_data, encrypted_data_size, dbuffer, &dbuffer_size);
680 if (rv == CKR_BUFFER_TOO_SMALL) {
681 erase_and_free(dbuffer);
682
683 dbuffer = malloc(dbuffer_size);
684 if (!dbuffer)
685 return log_oom();
686
687 rv = m->C_Decrypt(session, (CK_BYTE*) encrypted_data, encrypted_data_size, dbuffer, &dbuffer_size);
688 }
689 if (rv != CKR_OK)
690 return log_error_errno(SYNTHETIC_ERRNO(EIO),
691 "Failed to decrypt key on security token: %s", p11_kit_strerror(rv));
692
693 log_info("Successfully decrypted key with security token.");
694
695 *ret_decrypted_data = TAKE_PTR(dbuffer);
696 *ret_decrypted_data_size = dbuffer_size;
697 return 0;
698 }
699
700 int pkcs11_token_acquire_rng(
701 CK_FUNCTION_LIST *m,
702 CK_SESSION_HANDLE session) {
703
704 _cleanup_free_ void *buffer = NULL;
705 size_t rps;
706 CK_RV rv;
707 int r;
708
709 assert(m);
710
711 /* While we are at it, let's read some RNG data from the PKCS#11 token and pass it to the kernel
712 * random pool. This should be cheap if we are talking to the device already. Note that we don't
713 * credit any entropy, since we don't know about the quality of the pkcs#11 token's RNG. Why bother
714 * at all? There are two sides to the argument whether to generate private keys on tokens or on the
715 * host. By crediting some data from the token RNG to the host's pool we at least can say that any
716 * key generated from it is at least as good as both sources individually. */
717
718 rps = random_pool_size();
719
720 buffer = malloc(rps);
721 if (!buffer)
722 return log_oom();
723
724 rv = m->C_GenerateRandom(session, buffer, rps);
725 if (rv != CKR_OK)
726 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
727 "Failed to generate RNG data on security token: %s", p11_kit_strerror(rv));
728
729 r = random_write_entropy(-1, buffer, rps, false);
730 if (r < 0)
731 return log_debug_errno(r, "Failed to write PKCS#11 acquired random data to /dev/urandom: %m");
732
733 log_debug("Successfully written %zu bytes random data acquired via PKCS#11 to kernel random pool.", rps);
734
735 return 0;
736 }
737
738 static int token_process(
739 CK_FUNCTION_LIST *m,
740 CK_SLOT_ID slotid,
741 const CK_SLOT_INFO *slot_info,
742 const CK_TOKEN_INFO *token_info,
743 P11KitUri *search_uri,
744 pkcs11_find_token_callback_t callback,
745 void *userdata) {
746
747 _cleanup_free_ char *token_label = NULL;
748 CK_SESSION_HANDLE session;
749 CK_RV rv;
750 int r;
751
752 assert(m);
753 assert(slot_info);
754 assert(token_info);
755
756 token_label = pkcs11_token_label(token_info);
757 if (!token_label)
758 return log_oom();
759
760 rv = m->C_OpenSession(slotid, CKF_SERIAL_SESSION, NULL, NULL, &session);
761 if (rv != CKR_OK)
762 return log_error_errno(SYNTHETIC_ERRNO(EIO),
763 "Failed to create session for security token '%s': %s", token_label, p11_kit_strerror(rv));
764
765 if (callback)
766 r = callback(m, session, slotid, slot_info, token_info, search_uri, userdata);
767 else
768 r = 1; /* if not callback was specified, just say we found what we were looking for */
769
770 rv = m->C_CloseSession(session);
771 if (rv != CKR_OK)
772 log_warning("Failed to close session on PKCS#11 token, ignoring: %s", p11_kit_strerror(rv));
773
774 return r;
775 }
776
777 static int slot_process(
778 CK_FUNCTION_LIST *m,
779 CK_SLOT_ID slotid,
780 P11KitUri *search_uri,
781 pkcs11_find_token_callback_t callback,
782 void *userdata) {
783
784 _cleanup_(p11_kit_uri_freep) P11KitUri* slot_uri = NULL, *token_uri = NULL;
785 _cleanup_free_ char *token_uri_string = NULL;
786 CK_TOKEN_INFO token_info;
787 CK_SLOT_INFO slot_info;
788 int uri_result;
789 CK_RV rv;
790
791 assert(m);
792
793 /* We return -EAGAIN for all failures we can attribute to a specific slot in some way, so that the
794 * caller might try other slots before giving up. */
795
796 rv = m->C_GetSlotInfo(slotid, &slot_info);
797 if (rv != CKR_OK) {
798 log_warning("Failed to acquire slot info for slot %lu, ignoring slot: %s", slotid, p11_kit_strerror(rv));
799 return -EAGAIN;
800 }
801
802 slot_uri = uri_from_slot_info(&slot_info);
803 if (!slot_uri)
804 return log_oom();
805
806 if (DEBUG_LOGGING) {
807 _cleanup_free_ char *slot_uri_string = NULL;
808
809 uri_result = p11_kit_uri_format(slot_uri, P11_KIT_URI_FOR_ANY, &slot_uri_string);
810 if (uri_result != P11_KIT_URI_OK) {
811 log_warning("Failed to format slot URI, ignoring slot: %s", p11_kit_uri_message(uri_result));
812 return -EAGAIN;
813 }
814
815 log_debug("Found slot with URI %s", slot_uri_string);
816 }
817
818 rv = m->C_GetTokenInfo(slotid, &token_info);
819 if (rv == CKR_TOKEN_NOT_PRESENT) {
820 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
821 "Token not present in slot, ignoring.");
822 } else if (rv != CKR_OK) {
823 log_warning("Failed to acquire token info for slot %lu, ignoring slot: %s", slotid, p11_kit_strerror(rv));
824 return -EAGAIN;
825 }
826
827 token_uri = uri_from_token_info(&token_info);
828 if (!token_uri)
829 return log_oom();
830
831 uri_result = p11_kit_uri_format(token_uri, P11_KIT_URI_FOR_ANY, &token_uri_string);
832 if (uri_result != P11_KIT_URI_OK) {
833 log_warning("Failed to format slot URI: %s", p11_kit_uri_message(uri_result));
834 return -EAGAIN;
835 }
836
837 if (search_uri && !p11_kit_uri_match_token_info(search_uri, &token_info))
838 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
839 "Found non-matching token with URI %s.",
840 token_uri_string);
841
842 log_debug("Found matching token with URI %s.", token_uri_string);
843
844 return token_process(
845 m,
846 slotid,
847 &slot_info,
848 &token_info,
849 search_uri,
850 callback,
851 userdata);
852 }
853
854 static int module_process(
855 CK_FUNCTION_LIST *m,
856 P11KitUri *search_uri,
857 pkcs11_find_token_callback_t callback,
858 void *userdata) {
859
860 _cleanup_free_ char *name = NULL, *module_uri_string = NULL;
861 _cleanup_(p11_kit_uri_freep) P11KitUri* module_uri = NULL;
862 _cleanup_free_ CK_SLOT_ID *slotids = NULL;
863 CK_ULONG n_slotids = 0;
864 int uri_result;
865 CK_INFO info;
866 size_t k;
867 CK_RV rv;
868 int r;
869
870 assert(m);
871
872 /* We ignore most errors from modules here, in order to skip over faulty modules: one faulty module
873 * should not have the effect that we don't try the others anymore. We indicate such per-module
874 * failures with -EAGAIN, which let's the caller try the next module. */
875
876 name = p11_kit_module_get_name(m);
877 if (!name)
878 return log_oom();
879
880 log_debug("Trying PKCS#11 module %s.", name);
881
882 rv = m->C_GetInfo(&info);
883 if (rv != CKR_OK) {
884 log_warning("Failed to get info on PKCS#11 module, ignoring module: %s", p11_kit_strerror(rv));
885 return -EAGAIN;
886 }
887
888 module_uri = uri_from_module_info(&info);
889 if (!module_uri)
890 return log_oom();
891
892 uri_result = p11_kit_uri_format(module_uri, P11_KIT_URI_FOR_ANY, &module_uri_string);
893 if (uri_result != P11_KIT_URI_OK) {
894 log_warning("Failed to format module URI, ignoring module: %s", p11_kit_uri_message(uri_result));
895 return -EAGAIN;
896 }
897
898 log_debug("Found module with URI %s", module_uri_string);
899
900 rv = pkcs11_get_slot_list_malloc(m, &slotids, &n_slotids);
901 if (rv != CKR_OK) {
902 log_warning("Failed to get slot list, ignoring module: %s", p11_kit_strerror(rv));
903 return -EAGAIN;
904 }
905 if (n_slotids == 0)
906 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
907 "This module has no slots? Ignoring module.");
908
909 for (k = 0; k < n_slotids; k++) {
910 r = slot_process(
911 m,
912 slotids[k],
913 search_uri,
914 callback,
915 userdata);
916 if (r != -EAGAIN)
917 return r;
918 }
919
920 return -EAGAIN;
921 }
922
923 int pkcs11_find_token(
924 const char *pkcs11_uri,
925 pkcs11_find_token_callback_t callback,
926 void *userdata) {
927
928 _cleanup_(p11_kit_modules_finalize_and_releasep) CK_FUNCTION_LIST **modules = NULL;
929 _cleanup_(p11_kit_uri_freep) P11KitUri *search_uri = NULL;
930 int r;
931
932 /* Execute the specified callback for each matching token found. If nothing is found returns
933 * -EAGAIN. Logs about all errors, except for EAGAIN, which the caller has to log about. */
934
935 if (pkcs11_uri) {
936 r = uri_from_string(pkcs11_uri, &search_uri);
937 if (r < 0)
938 return log_error_errno(r, "Failed to parse PKCS#11 URI '%s': %m", pkcs11_uri);
939 }
940
941 modules = p11_kit_modules_load_and_initialize(0);
942 if (!modules)
943 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to initialize pkcs11 modules");
944
945 for (CK_FUNCTION_LIST **i = modules; *i; i++) {
946 r = module_process(
947 *i,
948 search_uri,
949 callback,
950 userdata);
951 if (r != -EAGAIN)
952 return r;
953 }
954
955 return -EAGAIN;
956 }
957
958 #if HAVE_OPENSSL
959 struct pkcs11_acquire_certificate_callback_data {
960 char *pin_used;
961 X509 *cert;
962 const char *askpw_friendly_name, *askpw_icon_name;
963 };
964
965 static void pkcs11_acquire_certificate_callback_data_release(struct pkcs11_acquire_certificate_callback_data *data) {
966 erase_and_free(data->pin_used);
967 X509_free(data->cert);
968 }
969
970 static int pkcs11_acquire_certificate_callback(
971 CK_FUNCTION_LIST *m,
972 CK_SESSION_HANDLE session,
973 CK_SLOT_ID slot_id,
974 const CK_SLOT_INFO *slot_info,
975 const CK_TOKEN_INFO *token_info,
976 P11KitUri *uri,
977 void *userdata) {
978
979 _cleanup_(erase_and_freep) char *pin_used = NULL;
980 struct pkcs11_acquire_certificate_callback_data *data = userdata;
981 CK_OBJECT_HANDLE object;
982 int r;
983
984 assert(m);
985 assert(slot_info);
986 assert(token_info);
987 assert(uri);
988 assert(data);
989
990 /* Called for every token matching our URI */
991
992 r = pkcs11_token_login(m, session, slot_id, token_info, data->askpw_friendly_name, data->askpw_icon_name, "pkcs11-pin", "pkcs11-pin", UINT64_MAX, false, &pin_used);
993 if (r < 0)
994 return r;
995
996 r = pkcs11_token_find_x509_certificate(m, session, uri, &object);
997 if (r < 0)
998 return r;
999
1000 r = pkcs11_token_read_x509_certificate(m, session, object, &data->cert);
1001 if (r < 0)
1002 return r;
1003
1004 /* Let's read some random data off the token and write it to the kernel pool before we generate our
1005 * random key from it. This way we can claim the quality of the RNG is at least as good as the
1006 * kernel's and the token's pool */
1007 (void) pkcs11_token_acquire_rng(m, session);
1008
1009 data->pin_used = TAKE_PTR(pin_used);
1010 return 1;
1011 }
1012
1013 int pkcs11_acquire_certificate(
1014 const char *uri,
1015 const char *askpw_friendly_name,
1016 const char *askpw_icon_name,
1017 X509 **ret_cert,
1018 char **ret_pin_used) {
1019
1020 _cleanup_(pkcs11_acquire_certificate_callback_data_release) struct pkcs11_acquire_certificate_callback_data data = {
1021 .askpw_friendly_name = askpw_friendly_name,
1022 .askpw_icon_name = askpw_icon_name,
1023 };
1024 int r;
1025
1026 assert(uri);
1027 assert(ret_cert);
1028
1029 r = pkcs11_find_token(uri, pkcs11_acquire_certificate_callback, &data);
1030 if (r == -EAGAIN) /* pkcs11_find_token() doesn't log about this error, but all others */
1031 return log_error_errno(SYNTHETIC_ERRNO(ENXIO),
1032 "Specified PKCS#11 token with URI '%s' not found.",
1033 uri);
1034 if (r < 0)
1035 return r;
1036
1037 *ret_cert = TAKE_PTR(data.cert);
1038
1039 if (ret_pin_used)
1040 *ret_pin_used = TAKE_PTR(data.pin_used);
1041
1042 return 0;
1043 }
1044 #endif
1045
1046 static int list_callback(
1047 CK_FUNCTION_LIST *m,
1048 CK_SESSION_HANDLE session,
1049 CK_SLOT_ID slot_id,
1050 const CK_SLOT_INFO *slot_info,
1051 const CK_TOKEN_INFO *token_info,
1052 P11KitUri *uri,
1053 void *userdata) {
1054
1055 _cleanup_free_ char *token_uri_string = NULL, *token_label = NULL, *token_manufacturer_id = NULL, *token_model = NULL;
1056 _cleanup_(p11_kit_uri_freep) P11KitUri *token_uri = NULL;
1057 Table *t = userdata;
1058 int uri_result, r;
1059
1060 assert(slot_info);
1061 assert(token_info);
1062
1063 /* We only care about hardware devices here with a token inserted. Let's filter everything else
1064 * out. (Note that the user can explicitly specify non-hardware tokens if they like, but during
1065 * enumeration we'll filter those, since software tokens are typically the system certificate store
1066 * and such, and it's typically not what people want to bind their home directories to.) */
1067 if (!FLAGS_SET(token_info->flags, CKF_HW_SLOT|CKF_TOKEN_PRESENT))
1068 return -EAGAIN;
1069
1070 token_label = pkcs11_token_label(token_info);
1071 if (!token_label)
1072 return log_oom();
1073
1074 token_manufacturer_id = pkcs11_token_manufacturer_id(token_info);
1075 if (!token_manufacturer_id)
1076 return log_oom();
1077
1078 token_model = pkcs11_token_model(token_info);
1079 if (!token_model)
1080 return log_oom();
1081
1082 token_uri = uri_from_token_info(token_info);
1083 if (!token_uri)
1084 return log_oom();
1085
1086 uri_result = p11_kit_uri_format(token_uri, P11_KIT_URI_FOR_ANY, &token_uri_string);
1087 if (uri_result != P11_KIT_URI_OK)
1088 return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN), "Failed to format slot URI: %s", p11_kit_uri_message(uri_result));
1089
1090 r = table_add_many(
1091 t,
1092 TABLE_STRING, token_uri_string,
1093 TABLE_STRING, token_label,
1094 TABLE_STRING, token_manufacturer_id,
1095 TABLE_STRING, token_model);
1096 if (r < 0)
1097 return table_log_add_error(r);
1098
1099 return -EAGAIN; /* keep scanning */
1100 }
1101 #endif
1102
1103 int pkcs11_list_tokens(void) {
1104 #if HAVE_P11KIT
1105 _cleanup_(table_unrefp) Table *t = NULL;
1106 int r;
1107
1108 t = table_new("uri", "label", "manufacturer", "model");
1109 if (!t)
1110 return log_oom();
1111
1112 r = pkcs11_find_token(NULL, list_callback, t);
1113 if (r < 0 && r != -EAGAIN)
1114 return r;
1115
1116 if (table_get_rows(t) <= 1) {
1117 log_info("No suitable PKCS#11 tokens found.");
1118 return 0;
1119 }
1120
1121 r = table_print(t, stdout);
1122 if (r < 0)
1123 return log_error_errno(r, "Failed to show device table: %m");
1124
1125 return 0;
1126 #else
1127 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1128 "PKCS#11 tokens not supported on this build.");
1129 #endif
1130 }
1131
1132 #if HAVE_P11KIT
1133 static int auto_callback(
1134 CK_FUNCTION_LIST *m,
1135 CK_SESSION_HANDLE session,
1136 CK_SLOT_ID slot_id,
1137 const CK_SLOT_INFO *slot_info,
1138 const CK_TOKEN_INFO *token_info,
1139 P11KitUri *uri,
1140 void *userdata) {
1141
1142 _cleanup_(p11_kit_uri_freep) P11KitUri *token_uri = NULL;
1143 char **t = userdata;
1144 int uri_result;
1145
1146 assert(slot_info);
1147 assert(token_info);
1148
1149 if (!FLAGS_SET(token_info->flags, CKF_HW_SLOT|CKF_TOKEN_PRESENT))
1150 return -EAGAIN;
1151
1152 if (*t)
1153 return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ),
1154 "More than one suitable PKCS#11 token found.");
1155
1156 token_uri = uri_from_token_info(token_info);
1157 if (!token_uri)
1158 return log_oom();
1159
1160 uri_result = p11_kit_uri_format(token_uri, P11_KIT_URI_FOR_ANY, t);
1161 if (uri_result != P11_KIT_URI_OK)
1162 return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN), "Failed to format slot URI: %s", p11_kit_uri_message(uri_result));
1163
1164 return 0;
1165 }
1166 #endif
1167
1168 int pkcs11_find_token_auto(char **ret) {
1169 #if HAVE_P11KIT
1170 int r;
1171
1172 r = pkcs11_find_token(NULL, auto_callback, ret);
1173 if (r == -EAGAIN)
1174 return log_error_errno(SYNTHETIC_ERRNO(ENODEV), "No suitable PKCS#11 tokens found.");
1175 if (r < 0)
1176 return r;
1177
1178 return 0;
1179 #else
1180 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1181 "PKCS#11 tokens not supported on this build.");
1182 #endif
1183 }
1184
1185 #if HAVE_P11KIT
1186 void pkcs11_crypt_device_callback_data_release(pkcs11_crypt_device_callback_data *data) {
1187 erase_and_free(data->decrypted_key);
1188
1189 if (data->free_encrypted_key)
1190 free(data->encrypted_key);
1191 }
1192
1193 int pkcs11_crypt_device_callback(
1194 CK_FUNCTION_LIST *m,
1195 CK_SESSION_HANDLE session,
1196 CK_SLOT_ID slot_id,
1197 const CK_SLOT_INFO *slot_info,
1198 const CK_TOKEN_INFO *token_info,
1199 P11KitUri *uri,
1200 void *userdata) {
1201
1202 pkcs11_crypt_device_callback_data *data = userdata;
1203 CK_OBJECT_HANDLE object;
1204 int r;
1205
1206 assert(m);
1207 assert(slot_info);
1208 assert(token_info);
1209 assert(uri);
1210 assert(data);
1211
1212 /* Called for every token matching our URI */
1213
1214 r = pkcs11_token_login(
1215 m,
1216 session,
1217 slot_id,
1218 token_info,
1219 data->friendly_name,
1220 "drive-harddisk",
1221 "pkcs11-pin",
1222 "cryptsetup.pkcs11-pin",
1223 data->until,
1224 data->headless,
1225 NULL);
1226 if (r < 0)
1227 return r;
1228
1229 /* We are likely called during early boot, where entropy is scarce. Mix some data from the PKCS#11
1230 * token, if it supports that. It should be cheap, given that we already are talking to it anyway and
1231 * shouldn't hurt. */
1232 (void) pkcs11_token_acquire_rng(m, session);
1233
1234 r = pkcs11_token_find_private_key(m, session, uri, &object);
1235 if (r < 0)
1236 return r;
1237
1238 r = pkcs11_token_decrypt_data(
1239 m,
1240 session,
1241 object,
1242 data->encrypted_key,
1243 data->encrypted_key_size,
1244 &data->decrypted_key,
1245 &data->decrypted_key_size);
1246 if (r < 0)
1247 return r;
1248
1249 return 0;
1250 }
1251 #endif