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