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