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