Debian Codegraph @

src/shared/pkcs11-util.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #if HAVE_OPENSSL
4 # include <openssl/core_names.h>
5 #endif
6
7 #include "sd-dlopen.h"
8
9 #include "alloc-util.h"
10 #include "ask-password-api.h"
11 #include "crypto-util.h"
12 #include "dlfcn-util.h"
13 #include "env-util.h"
14 #include "escape.h"
15 #include "format-table.h"
16 #include "log.h"
17 #include "memory-util.h"
18 #include "pkcs11-util.h"
19 #include "random-util.h"
20 #include "string-table.h"
21 #include "string-util.h"
22 #include "strv.h"
23
24 bool pkcs11_uri_valid(const char *uri) {
25 const char *p;
26
27 /* A very superficial checker for RFC7512 PKCS#11 URI syntax */
28
29 if (isempty(uri))
30 return false;
31
32 p = startswith(uri, "pkcs11:");
33 if (!p)
34 return false;
35
36 if (isempty(p))
37 return false;
38
39 if (!in_charset(p, ALPHANUMERICAL ".~/-_?;&%="))
40 return false;
41
42 return true;
43 }
44
45 static const char* const pkcs11_rsa_padding_table[_PKCS11_RSA_PADDING_MAX] = {
46 [PKCS11_RSA_PADDING_PKCS1V15] = "pkcs1",
47 [PKCS11_RSA_PADDING_OAEP_SHA1] = "oaep-sha1",
48 [PKCS11_RSA_PADDING_OAEP_SHA256] = "oaep-sha256",
49 };
50
51 DEFINE_STRING_TABLE_LOOKUP(pkcs11_rsa_padding, Pkcs11RsaPadding);
52
53 #if HAVE_P11KIT
54
55 DLSYM_PROTOTYPE(p11_kit_module_get_name) = NULL;
56 DLSYM_PROTOTYPE(p11_kit_modules_finalize_and_release) = NULL;
57 DLSYM_PROTOTYPE(p11_kit_modules_load_and_initialize) = NULL;
58 DLSYM_PROTOTYPE(p11_kit_strerror) = NULL;
59 DLSYM_PROTOTYPE(p11_kit_uri_format) = NULL;
60 DLSYM_PROTOTYPE(p11_kit_uri_free) = NULL;
61 DLSYM_PROTOTYPE(p11_kit_uri_get_attributes) = NULL;
62 DLSYM_PROTOTYPE(p11_kit_uri_get_attribute) = NULL;
63 DLSYM_PROTOTYPE(p11_kit_uri_set_attribute) = NULL;
64 DLSYM_PROTOTYPE(p11_kit_uri_get_module_info) = NULL;
65 DLSYM_PROTOTYPE(p11_kit_uri_get_slot_info) = NULL;
66 DLSYM_PROTOTYPE(p11_kit_uri_get_token_info) = NULL;
67 DLSYM_PROTOTYPE(p11_kit_uri_match_token_info) = NULL;
68 DLSYM_PROTOTYPE(p11_kit_uri_message) = NULL;
69 DLSYM_PROTOTYPE(p11_kit_uri_new) = NULL;
70 DLSYM_PROTOTYPE(p11_kit_uri_parse) = NULL;
71
72 int uri_from_string(const char *p, P11KitUri **ret) {
73 _cleanup_(p11_kit_uri_freep) P11KitUri *uri = NULL;
74 int r;
75
76 assert(p);
77 assert(ret);
78
79 r = dlopen_p11kit(LOG_DEBUG);
80 if (r < 0)
81 return r;
82
83 uri = sym_p11_kit_uri_new();
84 if (!uri)
85 return -ENOMEM;
86
87 if (sym_p11_kit_uri_parse(p, P11_KIT_URI_FOR_ANY, uri) != P11_KIT_URI_OK)
88 return -EINVAL;
89
90 *ret = TAKE_PTR(uri);
91 return 0;
92 }
93
94 P11KitUri *uri_from_module_info(const CK_INFO *info) {
95 P11KitUri *uri;
96
97 assert(info);
98
99 if (dlopen_p11kit(LOG_DEBUG) < 0)
100 return NULL;
101
102 uri = sym_p11_kit_uri_new();
103 if (!uri)
104 return NULL;
105
106 *sym_p11_kit_uri_get_module_info(uri) = *info;
107 return uri;
108 }
109
110 P11KitUri *uri_from_slot_info(const CK_SLOT_INFO *slot_info) {
111 P11KitUri *uri;
112
113 assert(slot_info);
114
115 if (dlopen_p11kit(LOG_DEBUG) < 0)
116 return NULL;
117
118 uri = sym_p11_kit_uri_new();
119 if (!uri)
120 return NULL;
121
122 *sym_p11_kit_uri_get_slot_info(uri) = *slot_info;
123 return uri;
124 }
125
126 P11KitUri *uri_from_token_info(const CK_TOKEN_INFO *token_info) {
127 P11KitUri *uri;
128
129 assert(token_info);
130
131 if (dlopen_p11kit(LOG_DEBUG) < 0)
132 return NULL;
133
134 uri = sym_p11_kit_uri_new();
135 if (!uri)
136 return NULL;
137
138 *sym_p11_kit_uri_get_token_info(uri) = *token_info;
139 return uri;
140 }
141
142 CK_RV pkcs11_get_slot_list_malloc(
143 CK_FUNCTION_LIST *m,
144 CK_SLOT_ID **ret_slotids,
145 CK_ULONG *ret_n_slotids) {
146
147 CK_RV rv;
148
149 assert(m);
150 assert(ret_slotids);
151 assert(ret_n_slotids);
152
153 for (unsigned tries = 0; tries < 16; tries++) {
154 _cleanup_free_ CK_SLOT_ID *slotids = NULL;
155 CK_ULONG n_slotids = 0;
156
157 rv = m->C_GetSlotList(0, NULL, &n_slotids);
158 if (rv != CKR_OK)
159 return rv;
160 if (n_slotids == 0) {
161 *ret_slotids = NULL;
162 *ret_n_slotids = 0;
163 return CKR_OK;
164 }
165
166 slotids = new(CK_SLOT_ID, n_slotids);
167 if (!slotids)
168 return CKR_HOST_MEMORY;
169
170 rv = m->C_GetSlotList(0, slotids, &n_slotids);
171 if (rv == CKR_OK) {
172 *ret_slotids = TAKE_PTR(slotids);
173 *ret_n_slotids = n_slotids;
174 return CKR_OK;
175 }
176
177 if (rv != CKR_BUFFER_TOO_SMALL)
178 return rv;
179
180 /* Hu? Maybe somebody plugged something in and things changed? Let's try again */
181 }
182
183 return CKR_BUFFER_TOO_SMALL;
184 }
185
186 char* pkcs11_token_label(const CK_TOKEN_INFO *token_info) {
187 char *t;
188
189 /* The label is not NUL terminated and likely padded with spaces, let's make a copy here, so that we
190 * can strip that. */
191 t = strndup((char*) token_info->label, sizeof(token_info->label));
192 if (!t)
193 return NULL;
194
195 strstrip(t);
196 return t;
197 }
198
199 char* pkcs11_token_manufacturer_id(const CK_TOKEN_INFO *token_info) {
200 char *t;
201
202 t = strndup((char*) token_info->manufacturerID, sizeof(token_info->manufacturerID));
203 if (!t)
204 return NULL;
205
206 strstrip(t);
207 return t;
208 }
209
210 char* pkcs11_token_model(const CK_TOKEN_INFO *token_info) {
211 char *t;
212
213 t = strndup((char*) token_info->model, sizeof(token_info->model));
214 if (!t)
215 return NULL;
216
217 strstrip(t);
218 return t;
219 }
220
221 int pkcs11_token_login_by_pin(
222 CK_FUNCTION_LIST *m,
223 CK_SESSION_HANDLE session,
224 const CK_TOKEN_INFO *token_info,
225 const char *token_label,
226 const void *pin,
227 size_t pin_size) {
228
229 CK_RV rv;
230 int r;
231
232 assert(m);
233 assert(token_info);
234
235 r = dlopen_p11kit(LOG_DEBUG);
236 if (r < 0)
237 return r;
238
239 if (FLAGS_SET(token_info->flags, CKF_PROTECTED_AUTHENTICATION_PATH)) {
240 rv = m->C_Login(session, CKU_USER, NULL, 0);
241 if (rv != CKR_OK)
242 return log_error_errno(SYNTHETIC_ERRNO(EIO),
243 "Failed to log into security token '%s': %s", token_label, sym_p11_kit_strerror(rv));
244
245 log_info("Successfully logged into security token '%s' via protected authentication path.", token_label);
246 return 0;
247 }
248
249 if (!FLAGS_SET(token_info->flags, CKF_LOGIN_REQUIRED)) {
250 log_info("No login into security token '%s' required.", token_label);
251 return 0;
252 }
253
254 if (!pin)
255 return -ENOANO;
256
257 rv = m->C_Login(session, CKU_USER, (CK_UTF8CHAR*) pin, pin_size);
258 if (rv == CKR_OK) {
259 log_info("Successfully logged into security token '%s'.", token_label);
260 return 0;
261 }
262
263 if (rv == CKR_PIN_LOCKED)
264 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
265 "PIN has been locked, please reset PIN of security token '%s'.", token_label);
266 if (!IN_SET(rv, CKR_PIN_INCORRECT, CKR_PIN_LEN_RANGE))
267 return log_error_errno(SYNTHETIC_ERRNO(EIO),
268 "Failed to log into security token '%s': %s", token_label, sym_p11_kit_strerror(rv));
269
270 return log_notice_errno(SYNTHETIC_ERRNO(ENOLCK),
271 "PIN for token '%s' is incorrect, please try again.",
272 token_label);
273 }
274
275 int pkcs11_token_login(
276 CK_FUNCTION_LIST *m,
277 CK_SESSION_HANDLE session,
278 CK_SLOT_ID slotid,
279 const CK_TOKEN_INFO *token_info,
280 const char *friendly_name,
281 const char *ask_password_icon,
282 const char *ask_password_keyring,
283 const char *ask_password_credential,
284 usec_t until,
285 AskPasswordFlags ask_password_flags,
286 char **ret_used_pin) {
287
288 _cleanup_free_ char *token_uri_string = NULL, *token_uri_escaped = NULL, *id = NULL, *token_label = NULL;
289 _cleanup_(p11_kit_uri_freep) P11KitUri *token_uri = NULL;
290 CK_TOKEN_INFO updated_token_info;
291 int uri_result, r;
292 CK_RV rv;
293
294 assert(m);
295 assert(token_info);
296
297 r = dlopen_p11kit(LOG_DEBUG);
298 if (r < 0)
299 return r;
300
301 token_label = pkcs11_token_label(token_info);
302 if (!token_label)
303 return log_oom();
304
305 token_uri = uri_from_token_info(token_info);
306 if (!token_uri)
307 return log_oom();
308
309 uri_result = sym_p11_kit_uri_format(token_uri, P11_KIT_URI_FOR_ANY, &token_uri_string);
310 if (uri_result != P11_KIT_URI_OK)
311 return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN), "Failed to format slot URI: %s", sym_p11_kit_uri_message(uri_result));
312
313 r = pkcs11_token_login_by_pin(m, session, token_info, token_label, /* pin= */ NULL, 0);
314 if (r == 0 && ret_used_pin)
315 *ret_used_pin = NULL;
316
317 if (r != -ENOANO) /* pin required */
318 return r;
319
320 token_uri_escaped = cescape(token_uri_string);
321 if (!token_uri_escaped)
322 return log_oom();
323
324 id = strjoin("pkcs11:", token_uri_escaped);
325 if (!id)
326 return log_oom();
327
328 for (unsigned tries = 0; tries < 3; tries++) {
329 _cleanup_strv_free_erase_ char **passwords = NULL;
330 _cleanup_(erase_and_freep) char *envpin = NULL;
331
332 r = getenv_steal_erase("PIN", &envpin);
333 if (r < 0)
334 return log_error_errno(r, "Failed to acquire PIN from environment: %m");
335 if (r > 0) {
336 passwords = strv_new(envpin);
337 if (!passwords)
338 return log_oom();
339
340 } else if (FLAGS_SET(ask_password_flags, ASK_PASSWORD_HEADLESS))
341 return log_error_errno(SYNTHETIC_ERRNO(ENOPKG), "PIN querying disabled via 'headless' option. Use the 'PIN' environment variable.");
342 else {
343 _cleanup_free_ char *text = NULL;
344
345 if (FLAGS_SET(token_info->flags, CKF_USER_PIN_FINAL_TRY))
346 r = asprintf(&text,
347 "Please enter correct PIN for security token '%s' in order to unlock %s (final try):",
348 token_label, friendly_name);
349 else if (FLAGS_SET(token_info->flags, CKF_USER_PIN_COUNT_LOW))
350 r = asprintf(&text,
351 "PIN has been entered incorrectly previously, please enter correct PIN for security token '%s' in order to unlock %s:",
352 token_label, friendly_name);
353 else if (tries == 0)
354 r = asprintf(&text,
355 "Please enter PIN for security token '%s' in order to unlock %s:",
356 token_label, friendly_name);
357 else
358 r = asprintf(&text,
359 "Please enter PIN for security token '%s' in order to unlock %s (try #%u):",
360 token_label, friendly_name, tries+1);
361 if (r < 0)
362 return log_oom();
363
364 AskPasswordRequest req = {
365 .tty_fd = -EBADF,
366 .message = text,
367 .icon = ask_password_icon,
368 .id = id,
369 .keyring = ask_password_keyring,
370 .credential = ask_password_credential,
371 .until = until,
372 .hup_fd = -EBADF,
373 };
374
375 /* We never cache PINs, simply because it's fatal if we use wrong PINs, since usually there are only 3 tries */
376 r = ask_password_auto(&req, ask_password_flags, &passwords);
377 if (r < 0)
378 return log_error_errno(r, "Failed to query PIN for security token '%s': %m", token_label);
379 }
380
381 STRV_FOREACH(i, passwords) {
382 r = pkcs11_token_login_by_pin(m, session, token_info, token_label, *i, strlen(*i));
383 if (r == 0 && ret_used_pin) {
384 char *c;
385
386 c = strdup(*i);
387 if (!c)
388 return log_oom();
389
390 *ret_used_pin = c;
391 }
392
393 if (r != -ENOLCK)
394 return r;
395
396 /* Refresh the token info, so that we can prompt knowing the new flags if they changed. */
397 rv = m->C_GetTokenInfo(slotid, &updated_token_info);
398 if (rv != CKR_OK)
399 return log_error_errno(SYNTHETIC_ERRNO(EIO),
400 "Failed to acquire updated security token information for slot %lu: %s",
401 slotid, sym_p11_kit_strerror(rv));
402
403 token_info = &updated_token_info;
404 }
405 }
406
407 return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Too many attempts to log into token '%s'.", token_label);
408 }
409
410 #if HAVE_OPENSSL
411 static int read_public_key_info(
412 CK_FUNCTION_LIST *m,
413 CK_SESSION_HANDLE session,
414 CK_OBJECT_HANDLE object,
415 EVP_PKEY **ret_pkey) {
416
417 assert(ret_pkey);
418
419 CK_ATTRIBUTE attribute = { CKA_PUBLIC_KEY_INFO, NULL_PTR, 0 };
420 _cleanup_(EVP_PKEY_freep) EVP_PKEY *pkey = NULL;
421 CK_RV rv;
422
423 rv = m->C_GetAttributeValue(session, object, &attribute, 1);
424 if (rv != CKR_OK)
425 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
426 "Failed to get size of CKA_PUBLIC_KEY_INFO: %s", sym_p11_kit_strerror(rv));
427
428 if (attribute.ulValueLen == 0)
429 return log_debug_errno(SYNTHETIC_ERRNO(ENOENT), "CKA_PUBLIC_KEY_INFO is empty");
430
431 _cleanup_free_ void *buffer = malloc(attribute.ulValueLen);
432 if (!buffer)
433 return log_oom_debug();
434
435 attribute.pValue = buffer;
436
437 rv = m->C_GetAttributeValue(session, object, &attribute, 1);
438 if (rv != CKR_OK)
439 return log_debug_errno(SYNTHETIC_ERRNO(EIO),
440 "Failed to read CKA_PUBLIC_KEY_INFO: %s", sym_p11_kit_strerror(rv));
441
442 const unsigned char *value = attribute.pValue;
443 pkey = sym_d2i_PUBKEY(NULL, &value, attribute.ulValueLen);
444 if (!pkey)
445 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "Failed to parse CKA_PUBLIC_KEY_INFO");
446
447 *ret_pkey = TAKE_PTR(pkey);
448 return 0;
449 }
450
451 int pkcs11_token_read_public_key(
452 CK_FUNCTION_LIST *m,
453 CK_SESSION_HANDLE session,
454 CK_OBJECT_HANDLE object,
455 EVP_PKEY **ret_pkey) {
456
457 _cleanup_(EVP_PKEY_freep) EVP_PKEY *pkey = NULL;
458 CK_RV rv;
459 int r;
460
461 assert(ret_pkey);
462
463 r = dlopen_libcrypto(LOG_DEBUG);
464 if (r < 0)
465 return r;
466
467 r = read_public_key_info(m, session, object, &pkey);
468 if (r >= 0) {
469 *ret_pkey = TAKE_PTR(pkey);
470 return 0;
471 }
472
473 CK_KEY_TYPE key_type;
474 CK_ATTRIBUTE attribute = { CKA_KEY_TYPE, &key_type, sizeof(key_type) };
475
476 rv = m->C_GetAttributeValue(session, object, &attribute, 1);
477 if (rv != CKR_OK)
478 return log_debug_errno(SYNTHETIC_ERRNO(EIO),
479 "Failed to get CKA_KEY_TYPE of a public key: %s", sym_p11_kit_strerror(rv));
480
481 switch (key_type) {
482 case CKK_RSA: {
483 CK_ATTRIBUTE rsa_attributes[] = {
484 { CKA_MODULUS, NULL_PTR, 0 },
485 { CKA_PUBLIC_EXPONENT, NULL_PTR, 0 },
486 };
487
488 rv = m->C_GetAttributeValue(session, object, rsa_attributes, ELEMENTSOF(rsa_attributes));
489 if (rv != CKR_OK)
490 return log_debug_errno(SYNTHETIC_ERRNO(EIO),
491 "Failed to get size of attributes of an RSA public key: %s", sym_p11_kit_strerror(rv));
492
493 if (rsa_attributes[0].ulValueLen == 0)
494 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "An RSA public key has empty CKA_MODULUS.");
495
496 _cleanup_free_ void *modulus = malloc(rsa_attributes[0].ulValueLen);
497 if (!modulus)
498 return log_oom_debug();
499
500 rsa_attributes[0].pValue = modulus;
501
502 if (rsa_attributes[1].ulValueLen == 0)
503 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "An RSA public key has empty CKA_PUBLIC_EXPONENT.");
504
505 _cleanup_free_ void *public_exponent = malloc(rsa_attributes[1].ulValueLen);
506 if (!public_exponent)
507 return log_oom_debug();
508
509 rsa_attributes[1].pValue = public_exponent;
510
511 rv = m->C_GetAttributeValue(session, object, rsa_attributes, ELEMENTSOF(rsa_attributes));
512 if (rv != CKR_OK)
513 return log_debug_errno(SYNTHETIC_ERRNO(EIO),
514 "Failed to get attributes of an RSA public key: %s", sym_p11_kit_strerror(rv));
515
516 size_t n_size = rsa_attributes[0].ulValueLen, e_size = rsa_attributes[1].ulValueLen;
517 r = rsa_pkey_from_n_e(rsa_attributes[0].pValue, n_size, rsa_attributes[1].pValue, e_size, &pkey);
518 if (r < 0)
519 return log_debug_errno(r, "Failed to create an EVP_PKEY from RSA parameters.");
520
521 break;
522 }
523 case CKK_EC: {
524 CK_ATTRIBUTE ec_attributes[] = {
525 { CKA_EC_PARAMS, NULL_PTR, 0 },
526 { CKA_EC_POINT, NULL_PTR, 0 },
527 };
528
529 rv = m->C_GetAttributeValue(session, object, ec_attributes, ELEMENTSOF(ec_attributes));
530 if (rv != CKR_OK)
531 return log_debug_errno(SYNTHETIC_ERRNO(EIO),
532 "Failed to get size of attributes of an EC public key: %s", sym_p11_kit_strerror(rv));
533
534 if (ec_attributes[0].ulValueLen == 0)
535 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "An EC public key has empty CKA_EC_PARAMS.");
536
537 _cleanup_free_ void *ec_group = malloc(ec_attributes[0].ulValueLen);
538 if (!ec_group)
539 return log_oom_debug();
540
541 ec_attributes[0].pValue = ec_group;
542
543 if (ec_attributes[1].ulValueLen == 0)
544 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "An EC public key has empty CKA_EC_POINT.");
545
546 _cleanup_free_ void *ec_point = malloc(ec_attributes[1].ulValueLen);
547 if (!ec_point)
548 return log_oom_debug();
549
550 ec_attributes[1].pValue = ec_point;
551
552 rv = m->C_GetAttributeValue(session, object, ec_attributes, ELEMENTSOF(ec_attributes));
553 if (rv != CKR_OK)
554 return log_debug_errno(SYNTHETIC_ERRNO(EIO),
555 "Failed to get attributes of an EC public key: %s", sym_p11_kit_strerror(rv));
556
557 _cleanup_(EC_GROUP_freep) EC_GROUP *group = NULL;
558 _cleanup_(ASN1_OCTET_STRING_freep) ASN1_OCTET_STRING *os = NULL;
559
560 const unsigned char *ec_params_value = ec_attributes[0].pValue;
561 group = sym_d2i_ECPKParameters(NULL, &ec_params_value, ec_attributes[0].ulValueLen);
562 if (!group)
563 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Unable to decode CKA_EC_PARAMS.");
564
565 const unsigned char *ec_point_value = ec_attributes[1].pValue;
566 os = sym_d2i_ASN1_OCTET_STRING(NULL, &ec_point_value, ec_attributes[1].ulValueLen);
567 if (!os)
568 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Unable to decode CKA_EC_POINT.");
569
570 _cleanup_(EVP_PKEY_CTX_freep) EVP_PKEY_CTX *ctx = sym_EVP_PKEY_CTX_new_from_name(NULL, "EC", NULL);
571 if (!ctx)
572 return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Failed to create an EVP_PKEY_CTX for EC.");
573
574 if (sym_EVP_PKEY_fromdata_init(ctx) != 1)
575 return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Failed to init an EVP_PKEY_CTX for EC.");
576
577 OSSL_PARAM ec_params[8] = {
578 /* We need to drop the const from the data param, because ec_params is
579 * modified below. But we'll not modify ec_params[0]. */
580 OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_PUB_KEY,
581 (unsigned char *) sym_ASN1_STRING_get0_data(os),
582 sym_ASN1_STRING_length(os)),
583 };
584
585 _cleanup_free_ void *order = NULL, *p = NULL, *a = NULL, *b = NULL, *generator = NULL;
586 size_t order_size, p_size, a_size, b_size, generator_size;
587
588 int nid = sym_EC_GROUP_get_curve_name(group);
589 if (nid != NID_undef) {
590 const char* name = sym_OSSL_EC_curve_nid2name(nid);
591 ec_params[1] = sym_OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME, (char*)name, strlen(name));
592 ec_params[2] = sym_OSSL_PARAM_construct_end();
593 } else {
594 const char *field_type = sym_EC_GROUP_get_field_type(group) == NID_X9_62_prime_field ?
595 "prime-field" : "characteristic-two-field";
596
597 const BIGNUM *bn_order = sym_EC_GROUP_get0_order(group);
598
599 _cleanup_(BN_CTX_freep) BN_CTX *bnctx = sym_BN_CTX_new();
600 if (!bnctx)
601 return log_oom_debug();
602
603 _cleanup_(BN_freep) BIGNUM *bn_p = sym_BN_new();
604 if (!bn_p)
605 return log_oom_debug();
606
607 _cleanup_(BN_freep) BIGNUM *bn_a = sym_BN_new();
608 if (!bn_a)
609 return log_oom_debug();
610
611 _cleanup_(BN_freep) BIGNUM *bn_b = sym_BN_new();
612 if (!bn_b)
613 return log_oom_debug();
614
615 if (sym_EC_GROUP_get_curve(group, bn_p, bn_a, bn_b, bnctx) != 1)
616 return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Failed to extract EC parameters from EC_GROUP.");
617
618 order_size = sym_BN_num_bytes(bn_order);
619 p_size = sym_BN_num_bytes(bn_p);
620 a_size = sym_BN_num_bytes(bn_a);
621 b_size = sym_BN_num_bytes(bn_b);
622
623 order = malloc(order_size);
624 if (!order)
625 return log_oom_debug();
626
627 p = malloc(p_size);
628 if (!p)
629 return log_oom_debug();
630
631 a = malloc(a_size);
632 if (!a)
633 return log_oom_debug();
634
635 b = malloc(b_size);
636 if (!b)
637 return log_oom_debug();
638
639 if (sym_BN_bn2nativepad(bn_order, order, order_size) <= 0 ||
640 sym_BN_bn2nativepad(bn_p, p, p_size) <= 0 ||
641 sym_BN_bn2nativepad(bn_a, a, a_size) <= 0 ||
642 sym_BN_bn2nativepad(bn_b, b, b_size) <= 0 )
643 return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Failed to store EC parameters in native byte order.");
644
645 const EC_POINT *point_gen = sym_EC_GROUP_get0_generator(group);
646 generator_size = sym_EC_POINT_point2oct(group, point_gen, POINT_CONVERSION_UNCOMPRESSED, NULL, 0, bnctx);
647 if (generator_size == 0)
648 return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Failed to determine size of a EC generator.");
649
650 generator = malloc(generator_size);
651 if (!generator)
652 return log_oom_debug();
653
654 generator_size = sym_EC_POINT_point2oct(group, point_gen, POINT_CONVERSION_UNCOMPRESSED, generator, generator_size, bnctx);
655 if (generator_size == 0)
656 return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Failed to convert a EC generator to octet string.");
657
658 ec_params[1] = sym_OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_EC_FIELD_TYPE, (char*)field_type, strlen(field_type));
659 ec_params[2] = sym_OSSL_PARAM_construct_octet_string(OSSL_PKEY_PARAM_EC_GENERATOR, generator, generator_size);
660 ec_params[3] = sym_OSSL_PARAM_construct_BN(OSSL_PKEY_PARAM_EC_ORDER, order, order_size);
661 ec_params[4] = sym_OSSL_PARAM_construct_BN(OSSL_PKEY_PARAM_EC_P, p, p_size);
662 ec_params[5] = sym_OSSL_PARAM_construct_BN(OSSL_PKEY_PARAM_EC_A, a, a_size);
663 ec_params[6] = sym_OSSL_PARAM_construct_BN(OSSL_PKEY_PARAM_EC_B, b, b_size);
664 ec_params[7] = sym_OSSL_PARAM_construct_end();
665 }
666
667 if (sym_EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_PUBLIC_KEY, ec_params) != 1)
668 return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Failed to create EVP_PKEY from EC parameters.");
669 break;
670 }
671 default:
672 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Unsupported type of public key: %lu", key_type);
673 }
674
675 *ret_pkey = TAKE_PTR(pkey);
676 return 0;
677 }
678
679 int pkcs11_token_read_x509_certificate(
680 CK_FUNCTION_LIST *m,
681 CK_SESSION_HANDLE session,
682 CK_OBJECT_HANDLE object,
683 X509 **ret_cert) {
684
685 CK_ATTRIBUTE attribute = {
686 .type = CKA_VALUE
687 };
688 CK_RV rv;
689 int r;
690
691 assert(ret_cert);
692
693 r = dlopen_p11kit(LOG_DEBUG);
694 if (r < 0)
695 return r;
696
697 rv = m->C_GetAttributeValue(session, object, &attribute, 1);
698 if (rv != CKR_OK)
699 return log_debug_errno(SYNTHETIC_ERRNO(EIO),
700 "Failed to read X.509 certificate size off token: %s", sym_p11_kit_strerror(rv));
701
702 _cleanup_free_ void *buffer = malloc(attribute.ulValueLen);
703 if (!buffer)
704 return log_oom_debug();
705
706 attribute.pValue = buffer;
707
708 rv = m->C_GetAttributeValue(session, object, &attribute, 1);
709 if (rv != CKR_OK)
710 return log_debug_errno(SYNTHETIC_ERRNO(EIO),
711 "Failed to read X.509 certificate data off token: %s", sym_p11_kit_strerror(rv));
712
713 r = dlopen_libcrypto(LOG_DEBUG);
714 if (r < 0)
715 return r;
716
717 const unsigned char *p = attribute.pValue;
718 _cleanup_(X509_freep) X509 *x509 = sym_d2i_X509(NULL, &p, attribute.ulValueLen);
719 if (!x509)
720 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "Failed to parse X.509 certificate.");
721
722 const X509_NAME *name = sym_X509_get_subject_name(x509);
723 if (!name)
724 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "Failed to acquire X.509 subject name.");
725
726 _cleanup_free_ char *t = sym_X509_NAME_oneline(name, NULL, 0);
727 if (!t)
728 return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Failed to format X.509 subject name as string.");
729
730 log_debug("Using X.509 certificate issued for '%s'.", t);
731
732 *ret_cert = TAKE_PTR(x509);
733 return 0;
734 }
735 #endif
736
737 int pkcs11_token_find_private_key(
738 CK_FUNCTION_LIST *m,
739 CK_SESSION_HANDLE session,
740 P11KitUri *search_uri,
741 CK_OBJECT_HANDLE *ret_object) {
742
743 bool found_class = false;
744 _cleanup_free_ CK_ATTRIBUTE *attributes_buffer = NULL;
745 CK_KEY_TYPE key_type;
746 CK_BBOOL decrypt_value, derive_value;
747 CK_ATTRIBUTE optional_attributes[] = {
748 { CKA_KEY_TYPE, &key_type, sizeof(key_type) },
749 { CKA_DECRYPT, &decrypt_value, sizeof(decrypt_value) },
750 { CKA_DERIVE, &derive_value, sizeof(derive_value) },
751 };
752 uint8_t n_private_keys = 0;
753 CK_OBJECT_HANDLE private_key = CK_INVALID_HANDLE;
754 CK_RV rv;
755
756 assert(m);
757 assert(search_uri);
758 assert(ret_object);
759
760 CK_ULONG n_attributes;
761 CK_ATTRIBUTE *attributes = sym_p11_kit_uri_get_attributes(search_uri, &n_attributes);
762 for (CK_ULONG i = 0; i < n_attributes; i++) {
763
764 /* We use the URI's included match attributes, but make them more strict. This allows users
765 * to specify a token URL instead of an object URL and the right thing should happen if
766 * there's only one suitable key on the token. */
767
768 switch (attributes[i].type) {
769 case CKA_CLASS: {
770 if (attributes[i].ulValueLen != sizeof(CK_OBJECT_CLASS))
771 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid PKCS#11 CKA_CLASS attribute size.");
772
773 CK_OBJECT_CLASS *class = (CK_OBJECT_CLASS*) attributes[i].pValue;
774 if (*class != CKO_PRIVATE_KEY)
775 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
776 "Selected PKCS#11 object is not a private key, refusing.");
777
778 found_class = true;
779 break;
780 }}
781 }
782
783 if (!found_class) {
784 /* Hmm, let's slightly extend the attribute list we search for */
785 static const CK_OBJECT_CLASS required_class = CKO_PRIVATE_KEY;
786
787 attributes_buffer = new(CK_ATTRIBUTE, n_attributes + 1);
788 if (!attributes_buffer)
789 return log_oom();
790
791 memcpy(attributes_buffer, attributes, sizeof(CK_ATTRIBUTE) * n_attributes);
792
793 attributes_buffer[n_attributes++] = (CK_ATTRIBUTE) {
794 .type = CKA_CLASS,
795 .pValue = (CK_OBJECT_CLASS*) &required_class,
796 .ulValueLen = sizeof(required_class),
797 };
798
799 attributes = attributes_buffer;
800 }
801
802 rv = m->C_FindObjectsInit(session, attributes, n_attributes);
803 if (rv != CKR_OK)
804 return log_error_errno(SYNTHETIC_ERRNO(EIO),
805 "Failed to initialize object find call: %s", sym_p11_kit_strerror(rv));
806
807 for (;;) {
808 CK_ULONG b;
809 CK_OBJECT_HANDLE candidate;
810 rv = m->C_FindObjects(session, &candidate, 1, &b);
811 if (rv != CKR_OK)
812 return log_error_errno(SYNTHETIC_ERRNO(EIO),
813 "Failed to find objects: %s", sym_p11_kit_strerror(rv));
814
815 if (b == 0)
816 break;
817
818 optional_attributes[0].ulValueLen = sizeof(key_type);
819 optional_attributes[1].ulValueLen = sizeof(decrypt_value);
820 optional_attributes[2].ulValueLen = sizeof(derive_value);
821
822 rv = m->C_GetAttributeValue(session, candidate, optional_attributes, ELEMENTSOF(optional_attributes));
823 if (!IN_SET(rv, CKR_OK, CKR_ATTRIBUTE_TYPE_INVALID))
824 return log_error_errno(SYNTHETIC_ERRNO(EIO),
825 "Failed to get attributes of a found private key: %s", sym_p11_kit_strerror(rv));
826
827 if (optional_attributes[0].ulValueLen == CK_UNAVAILABLE_INFORMATION) {
828 log_debug("A found private key does not have CKA_KEY_TYPE, rejecting the key.");
829 continue;
830 }
831
832 if (key_type == CKK_RSA)
833 if (optional_attributes[1].ulValueLen == CK_UNAVAILABLE_INFORMATION || decrypt_value == CK_FALSE) {
834 log_debug("A found private RSA key can't decrypt, rejecting the key.");
835 continue;
836 }
837
838 if (key_type == CKK_EC)
839 if (optional_attributes[2].ulValueLen == CK_UNAVAILABLE_INFORMATION || derive_value == CK_FALSE) {
840 log_debug("A found private EC key can't derive, rejecting the key.");
841 continue;
842 }
843
844 n_private_keys++;
845 if (n_private_keys > 1)
846 break;
847 private_key = candidate;
848 }
849
850 rv = m->C_FindObjectsFinal(session);
851 if (rv != CKR_OK)
852 return log_error_errno(SYNTHETIC_ERRNO(EIO),
853 "Failed to finalize object find call: %s", sym_p11_kit_strerror(rv));
854
855 if (n_private_keys == 0)
856 return log_error_errno(SYNTHETIC_ERRNO(ENOENT),
857 "Failed to find selected private key suitable for decryption or derivation on token.");
858
859 if (n_private_keys > 1)
860 return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ),
861 "Configured private key URI matches multiple keys, refusing.");
862
863 *ret_object = private_key;
864 return 0;
865 }
866
867 static const char* object_class_to_string(CK_OBJECT_CLASS class) {
868 switch (class) {
869 case CKO_CERTIFICATE:
870 return "CKO_CERTIFICATE";
871 case CKO_PUBLIC_KEY:
872 return "CKO_PUBLIC_KEY";
873 case CKO_PRIVATE_KEY:
874 return "CKO_PRIVATE_KEY";
875 case CKO_SECRET_KEY:
876 return "CKO_SECRET_KEY";
877 default:
878 return NULL;
879 }
880 }
881
882 /* Returns an object with the given class and the same CKA_ID or CKA_LABEL as prototype */
883 int pkcs11_token_find_related_object(
884 CK_FUNCTION_LIST *m,
885 CK_SESSION_HANDLE session,
886 CK_OBJECT_HANDLE prototype,
887 CK_OBJECT_CLASS class,
888 CK_OBJECT_HANDLE *ret_object ) {
889
890 _cleanup_free_ void *buffer = NULL;
891 CK_ATTRIBUTE attributes[] = {
892 { CKA_ID, NULL_PTR, 0 },
893 { CKA_LABEL, NULL_PTR, 0 }
894 };
895 CK_OBJECT_CLASS search_class = class;
896 CK_ATTRIBUTE search_attributes[2] = {
897 { CKA_CLASS, &search_class, sizeof(search_class) }
898 };
899 CK_ULONG n_objects;
900 CK_OBJECT_HANDLE objects[2];
901 CK_RV rv;
902
903 assert(ret_object);
904
905 rv = m->C_GetAttributeValue(session, prototype, attributes, ELEMENTSOF(attributes));
906 if (!IN_SET(rv, CKR_OK, CKR_ATTRIBUTE_TYPE_INVALID))
907 return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Failed to retrieve length of attributes: %s", sym_p11_kit_strerror(rv));
908
909 if (attributes[0].ulValueLen != CK_UNAVAILABLE_INFORMATION) {
910 buffer = malloc(attributes[0].ulValueLen);
911 if (!buffer)
912 return log_oom();
913
914 attributes[0].pValue = buffer;
915 rv = m->C_GetAttributeValue(session, prototype, &attributes[0], 1);
916 if (rv != CKR_OK)
917 return log_debug_errno(SYNTHETIC_ERRNO(EIO),
918 "Failed to retrieve CKA_ID: %s", sym_p11_kit_strerror(rv));
919
920 search_attributes[1] = attributes[0];
921
922 } else if (attributes[1].ulValueLen != CK_UNAVAILABLE_INFORMATION) {
923 buffer = malloc(attributes[1].ulValueLen);
924 if (!buffer)
925 return log_oom();
926
927 attributes[1].pValue = buffer;
928 rv = m->C_GetAttributeValue(session, prototype, &attributes[1], 1);
929 if (rv != CKR_OK)
930 return log_debug_errno(SYNTHETIC_ERRNO(EIO),
931 "Failed to retrieve CKA_LABEL: %s", sym_p11_kit_strerror(rv));
932
933 search_attributes[1] = attributes[1];
934
935 } else
936 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "The prototype does not have CKA_ID or CKA_LABEL");
937
938 rv = m->C_FindObjectsInit(session, search_attributes, 2);
939 if (rv != CKR_OK)
940 return log_debug_errno(SYNTHETIC_ERRNO(EIO),
941 "Failed to initialize object find call: %s", sym_p11_kit_strerror(rv));
942
943 rv = m->C_FindObjects(session, objects, 2, &n_objects);
944 if (rv != CKR_OK)
945 return log_debug_errno(SYNTHETIC_ERRNO(EIO),
946 "Failed to find objects: %s", sym_p11_kit_strerror(rv));
947
948 rv = m->C_FindObjectsFinal(session);
949 if (rv != CKR_OK)
950 return log_debug_errno(SYNTHETIC_ERRNO(EIO),
951 "Failed to finalize object find call: %s", sym_p11_kit_strerror(rv));
952
953 if (n_objects == 0)
954 return log_debug_errno(SYNTHETIC_ERRNO(ENOENT),
955 "Failed to find a related object with class %s", object_class_to_string(class));
956
957 if (n_objects > 1)
958 log_warning("Found multiple related objects with class %s, using the first object.",
959 object_class_to_string(class));
960
961 *ret_object = objects[0];
962 return 0;
963 }
964
965 #if HAVE_OPENSSL
966 static int ecc_convert_to_compressed(
967 CK_FUNCTION_LIST *m,
968 CK_SESSION_HANDLE session,
969 CK_OBJECT_HANDLE object,
970 const void *uncompressed_point,
971 size_t uncompressed_point_size,
972 void **ret_compressed_point,
973 size_t *ret_compressed_point_size) {
974
975 _cleanup_free_ void *ec_params_buffer = NULL;
976 CK_ATTRIBUTE ec_params_attr = { CKA_EC_PARAMS, NULL_PTR, 0 };
977 CK_RV rv;
978 int r;
979
980 assert(ret_compressed_point);
981 assert(ret_compressed_point_size);
982
983 rv = m->C_GetAttributeValue(session, object, &ec_params_attr, 1);
984 if (!IN_SET(rv, CKR_OK, CKR_ATTRIBUTE_TYPE_INVALID))
985 return log_error_errno(SYNTHETIC_ERRNO(EIO),
986 "Failed to retrieve length of CKA_EC_PARAMS: %s", sym_p11_kit_strerror(rv));
987
988 if (ec_params_attr.ulValueLen != CK_UNAVAILABLE_INFORMATION) {
989 ec_params_buffer = malloc(ec_params_attr.ulValueLen);
990 if (!ec_params_buffer)
991 return log_oom();
992
993 ec_params_attr.pValue = ec_params_buffer;
994 rv = m->C_GetAttributeValue(session, object, &ec_params_attr, 1);
995 if (rv != CKR_OK)
996 return log_error_errno(SYNTHETIC_ERRNO(EIO),
997 "Failed to retrieve CKA_EC_PARAMS from a private key: %s", sym_p11_kit_strerror(rv));
998 } else {
999 CK_OBJECT_HANDLE public_key;
1000 r = pkcs11_token_find_related_object(m, session, object, CKO_PUBLIC_KEY, &public_key);
1001 if (r < 0)
1002 return log_error_errno(r, "Failed to find a public key for compressing a EC point");
1003
1004 ec_params_attr.ulValueLen = 0;
1005 rv = m->C_GetAttributeValue(session, public_key, &ec_params_attr, 1);
1006 if (!IN_SET(rv, CKR_OK, CKR_ATTRIBUTE_TYPE_INVALID))
1007 return log_error_errno(SYNTHETIC_ERRNO(EIO),
1008 "Failed to retrieve length of CKA_EC_PARAMS: %s", sym_p11_kit_strerror(rv));
1009
1010 if (ec_params_attr.ulValueLen == CK_UNAVAILABLE_INFORMATION)
1011 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1012 "The public key does not have CKA_EC_PARAMS");
1013
1014 ec_params_buffer = malloc(ec_params_attr.ulValueLen);
1015 if (!ec_params_buffer)
1016 return log_oom();
1017
1018 ec_params_attr.pValue = ec_params_buffer;
1019 rv = m->C_GetAttributeValue(session, public_key, &ec_params_attr, 1);
1020 if (rv != CKR_OK)
1021 return log_error_errno(SYNTHETIC_ERRNO(EIO),
1022 "Failed to retrieve CKA_EC_PARAMS from a public key: %s", sym_p11_kit_strerror(rv));
1023 }
1024
1025 _cleanup_(EC_GROUP_freep) EC_GROUP *group = NULL;
1026 _cleanup_(EC_POINT_freep) EC_POINT *point = NULL;
1027 _cleanup_(BN_CTX_freep) BN_CTX *bnctx = NULL;
1028 _cleanup_free_ void *compressed_point = NULL;
1029 size_t compressed_point_size;
1030
1031 r = dlopen_libcrypto(LOG_DEBUG);
1032 if (r < 0)
1033 return r;
1034
1035 const unsigned char *ec_params_value = ec_params_attr.pValue;
1036 group = sym_d2i_ECPKParameters(NULL, &ec_params_value, ec_params_attr.ulValueLen);
1037 if (!group)
1038 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unable to decode CKA_EC_PARAMS");
1039
1040 point = sym_EC_POINT_new(group);
1041 if (!point)
1042 return log_oom();
1043
1044 bnctx = sym_BN_CTX_new();
1045 if (!bnctx)
1046 return log_oom();
1047
1048 if (sym_EC_POINT_oct2point(group, point, uncompressed_point, uncompressed_point_size, bnctx) != 1)
1049 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unable to decode an uncompressed EC point");
1050
1051 compressed_point_size = sym_EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, NULL, 0, bnctx);
1052 if (compressed_point_size == 0)
1053 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to determine size of a compressed EC point");
1054
1055 compressed_point = malloc(compressed_point_size);
1056 if (!compressed_point)
1057 return log_oom();
1058
1059 compressed_point_size = sym_EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, compressed_point, compressed_point_size, bnctx);
1060 if (compressed_point_size == 0)
1061 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to convert a EC point to compressed format");
1062
1063 *ret_compressed_point = TAKE_PTR(compressed_point);
1064 *ret_compressed_point_size = compressed_point_size;
1065 return 0;
1066 }
1067 #endif
1068
1069 /* Since EC keys doesn't support encryption directly, we use ECDH protocol to derive shared secret here.
1070 * We use PKCS#11 C_DeriveKey function to derive a shared secret with a private key stored in the token and
1071 * a public key saved on enrollment. */
1072 static int pkcs11_token_decrypt_data_ecc(
1073 CK_FUNCTION_LIST *m,
1074 CK_SESSION_HANDLE session,
1075 CK_OBJECT_HANDLE object,
1076 const void *encrypted_data,
1077 size_t encrypted_data_size,
1078 void **ret_decrypted_data,
1079 size_t *ret_decrypted_data_size) {
1080
1081 static const CK_BBOOL yes = CK_TRUE, no = CK_FALSE;
1082 static const CK_OBJECT_CLASS shared_secret_class = CKO_SECRET_KEY;
1083 static const CK_KEY_TYPE shared_secret_type = CKK_GENERIC_SECRET;
1084 static const CK_ATTRIBUTE shared_secret_template[] = {
1085 { CKA_TOKEN, (void*) &no, sizeof(no) },
1086 { CKA_CLASS, (void*) &shared_secret_class, sizeof(shared_secret_class) },
1087 { CKA_KEY_TYPE, (void*) &shared_secret_type, sizeof(shared_secret_type) },
1088 { CKA_SENSITIVE, (void*) &no, sizeof(no) },
1089 { CKA_EXTRACTABLE, (void*) &yes, sizeof(yes) }
1090 };
1091 CK_ECDH1_DERIVE_PARAMS params = {
1092 .kdf = CKD_NULL,
1093 .pPublicData = (void*) encrypted_data,
1094 .ulPublicDataLen = encrypted_data_size
1095 };
1096 CK_MECHANISM mechanism = {
1097 .mechanism = CKM_ECDH1_DERIVE,
1098 .pParameter = &params,
1099 .ulParameterLen = sizeof(params)
1100 };
1101 CK_OBJECT_HANDLE shared_secret_handle;
1102 CK_SESSION_INFO session_info;
1103 CK_MECHANISM_INFO mechanism_info;
1104 CK_RV rv, rv2;
1105 #if HAVE_OPENSSL
1106 _cleanup_free_ void *compressed_point = NULL;
1107 int r;
1108 #endif
1109
1110 assert(ret_decrypted_data);
1111 assert(ret_decrypted_data_size);
1112
1113 rv = m->C_GetSessionInfo(session, &session_info);
1114 if (rv != CKR_OK)
1115 return log_error_errno(SYNTHETIC_ERRNO(EIO),
1116 "Failed to get information about the PKCS#11 session: %s", sym_p11_kit_strerror(rv));
1117
1118 rv = m->C_GetMechanismInfo(session_info.slotID, CKM_ECDH1_DERIVE, &mechanism_info);
1119 if (rv != CKR_OK)
1120 return log_error_errno(SYNTHETIC_ERRNO(EIO),
1121 "Failed to get information about CKM_ECDH1_DERIVE: %s", sym_p11_kit_strerror(rv));
1122
1123 if (!(mechanism_info.flags & CKF_EC_UNCOMPRESS)) {
1124 if (mechanism_info.flags & CKF_EC_COMPRESS) {
1125 #if HAVE_OPENSSL
1126 log_debug("CKM_ECDH1_DERIVE accepts compressed EC points only, trying to convert.");
1127 size_t compressed_point_size = 0; /* Explicit initialization to appease gcc */
1128 r = ecc_convert_to_compressed(m, session, object, encrypted_data, encrypted_data_size, &compressed_point, &compressed_point_size);
1129 if (r < 0)
1130 return r;
1131
1132 params.pPublicData = compressed_point;
1133 params.ulPublicDataLen = compressed_point_size;
1134 #else
1135 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1136 "CKM_ECDH1_DERIVE does not support uncompressed format of EC points");
1137 #endif
1138 } else
1139 log_debug("Both CKF_EC_UNCOMPRESS and CKF_EC_COMPRESS are false for CKM_ECDH1_DERIVE, ignoring.");
1140 }
1141
1142 rv = m->C_DeriveKey(session, &mechanism, object, (CK_ATTRIBUTE*) shared_secret_template, ELEMENTSOF(shared_secret_template), &shared_secret_handle);
1143 if (rv != CKR_OK)
1144 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to derive a shared secret: %s", sym_p11_kit_strerror(rv));
1145
1146 CK_ATTRIBUTE shared_secret_attr = { CKA_VALUE, NULL_PTR, 0};
1147
1148 rv = m->C_GetAttributeValue(session, shared_secret_handle, &shared_secret_attr, 1);
1149 if (rv != CKR_OK) {
1150 rv2 = m->C_DestroyObject(session, shared_secret_handle);
1151 if (rv2 != CKR_OK)
1152 log_warning("Failed to destroy a shared secret, ignoring: %s", sym_p11_kit_strerror(rv2));
1153 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to retrieve shared secret length: %s", sym_p11_kit_strerror(rv));
1154 }
1155
1156 shared_secret_attr.pValue = malloc(shared_secret_attr.ulValueLen);
1157 if (!shared_secret_attr.pValue)
1158 return log_oom();
1159
1160 rv = m->C_GetAttributeValue(session, shared_secret_handle, &shared_secret_attr, 1);
1161 rv2 = m->C_DestroyObject(session, shared_secret_handle);
1162 if (rv2 != CKR_OK)
1163 log_warning("Failed to destroy a shared secret, ignoring: %s", sym_p11_kit_strerror(rv2));
1164
1165 if (rv != CKR_OK) {
1166 erase_and_free(shared_secret_attr.pValue);
1167 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to retrieve a shared secret: %s", sym_p11_kit_strerror(rv));
1168 }
1169
1170 log_info("Successfully derived key with security token.");
1171
1172 *ret_decrypted_data = shared_secret_attr.pValue;
1173 *ret_decrypted_data_size = shared_secret_attr.ulValueLen;
1174 return 0;
1175 }
1176
1177 static int pkcs11_token_decrypt_data_rsa(
1178 CK_FUNCTION_LIST *m,
1179 CK_SESSION_HANDLE session,
1180 CK_OBJECT_HANDLE object,
1181 const void *encrypted_data,
1182 size_t encrypted_data_size,
1183 Pkcs11RsaPadding rsa_padding,
1184 void **ret_decrypted_data,
1185 size_t *ret_decrypted_data_size) {
1186
1187 /* For RSA-OAEP we use SHA-256 or SHA-1 with the matching MGF1 and an empty (zero-length) label.
1188 * SHA-256 is preferred when the token supports it, but for example SoftHSM doesn't support it. */
1189 CK_RSA_PKCS_OAEP_PARAMS oaep_params_sha1 = {
1190 .hashAlg = CKM_SHA_1,
1191 .mgf = CKG_MGF1_SHA1,
1192 .source = CKZ_DATA_SPECIFIED,
1193 };
1194 CK_RSA_PKCS_OAEP_PARAMS oaep_params_sha256 = {
1195 .hashAlg = CKM_SHA256,
1196 .mgf = CKG_MGF1_SHA256,
1197 .source = CKZ_DATA_SPECIFIED,
1198 };
1199 CK_MECHANISM mechanism;
1200 _cleanup_(erase_and_freep) CK_BYTE *dbuffer = NULL;
1201 CK_ULONG dbuffer_size = 0;
1202 CK_RV rv;
1203
1204 assert(ret_decrypted_data);
1205 assert(ret_decrypted_data_size);
1206
1207 switch (rsa_padding) {
1208
1209 case PKCS11_RSA_PADDING_PKCS1V15:
1210 mechanism = (CK_MECHANISM) {
1211 .mechanism = CKM_RSA_PKCS,
1212 };
1213 break;
1214
1215 case PKCS11_RSA_PADDING_OAEP_SHA1:
1216 mechanism = (CK_MECHANISM) {
1217 .mechanism = CKM_RSA_PKCS_OAEP,
1218 .pParameter = &oaep_params_sha1,
1219 .ulParameterLen = sizeof(oaep_params_sha1),
1220 };
1221 break;
1222
1223 case PKCS11_RSA_PADDING_OAEP_SHA256:
1224 mechanism = (CK_MECHANISM) {
1225 .mechanism = CKM_RSA_PKCS_OAEP,
1226 .pParameter = &oaep_params_sha256,
1227 .ulParameterLen = sizeof(oaep_params_sha256),
1228 };
1229 break;
1230
1231 default:
1232 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1233 "Unknown RSA padding scheme requested for PKCS#11 decryption.");
1234 }
1235
1236 rv = m->C_DecryptInit(session, &mechanism, object);
1237 if (rv != CKR_OK)
1238 return log_error_errno(SYNTHETIC_ERRNO(EIO),
1239 "Failed to initialize decryption on security token: %s", sym_p11_kit_strerror(rv));
1240
1241 dbuffer_size = encrypted_data_size; /* Start with something reasonable */
1242 dbuffer = malloc(dbuffer_size);
1243 if (!dbuffer)
1244 return log_oom();
1245
1246 rv = m->C_Decrypt(session, (CK_BYTE*) encrypted_data, encrypted_data_size, dbuffer, &dbuffer_size);
1247 if (rv == CKR_BUFFER_TOO_SMALL) {
1248 erase_and_free(dbuffer);
1249
1250 dbuffer = malloc(dbuffer_size);
1251 if (!dbuffer)
1252 return log_oom();
1253
1254 rv = m->C_Decrypt(session, (CK_BYTE*) encrypted_data, encrypted_data_size, dbuffer, &dbuffer_size);
1255 }
1256 if (rv != CKR_OK)
1257 return log_error_errno(SYNTHETIC_ERRNO(EIO),
1258 "Failed to decrypt key on security token: %s", sym_p11_kit_strerror(rv));
1259
1260 log_info("Successfully decrypted key with security token (%s padding).",
1261 pkcs11_rsa_padding_to_string(rsa_padding));
1262
1263 *ret_decrypted_data = TAKE_PTR(dbuffer);
1264 *ret_decrypted_data_size = dbuffer_size;
1265 return 0;
1266 }
1267
1268 int pkcs11_token_decrypt_data(
1269 CK_FUNCTION_LIST *m,
1270 CK_SESSION_HANDLE session,
1271 CK_OBJECT_HANDLE object,
1272 const void *encrypted_data,
1273 size_t encrypted_data_size,
1274 Pkcs11RsaPadding rsa_padding,
1275 void **ret_decrypted_data,
1276 size_t *ret_decrypted_data_size) {
1277
1278 CK_KEY_TYPE key_type;
1279 CK_ATTRIBUTE key_type_template = { CKA_KEY_TYPE, &key_type, sizeof(key_type) };
1280 CK_RV rv;
1281
1282 assert(m);
1283 assert(encrypted_data);
1284 assert(encrypted_data_size > 0);
1285 assert(ret_decrypted_data);
1286 assert(ret_decrypted_data_size);
1287
1288 rv = m->C_GetAttributeValue(session, object, &key_type_template, 1);
1289 if (rv != CKR_OK)
1290 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to retrieve private key type");
1291
1292 switch (key_type) {
1293
1294 case CKK_RSA:
1295 return pkcs11_token_decrypt_data_rsa(m, session, object, encrypted_data, encrypted_data_size, rsa_padding, ret_decrypted_data, ret_decrypted_data_size);
1296
1297 case CKK_EC:
1298 return pkcs11_token_decrypt_data_ecc(m, session, object, encrypted_data, encrypted_data_size, ret_decrypted_data, ret_decrypted_data_size);
1299
1300 default:
1301 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Unsupported private key type: %lu", key_type);
1302 }
1303 }
1304
1305 int pkcs11_token_acquire_rng(
1306 CK_FUNCTION_LIST *m,
1307 CK_SESSION_HANDLE session) {
1308
1309 _cleanup_free_ void *buffer = NULL;
1310 size_t rps;
1311 CK_RV rv;
1312 int r;
1313
1314 assert(m);
1315
1316 r = dlopen_p11kit(LOG_DEBUG);
1317 if (r < 0)
1318 return r;
1319
1320 /* While we are at it, let's read some RNG data from the PKCS#11 token and pass it to the kernel
1321 * random pool. This should be cheap if we are talking to the device already. Note that we don't
1322 * credit any entropy, since we don't know about the quality of the pkcs#11 token's RNG. Why bother
1323 * at all? There are two sides to the argument whether to generate private keys on tokens or on the
1324 * host. By crediting some data from the token RNG to the host's pool we at least can say that any
1325 * key generated from it is at least as good as both sources individually. */
1326
1327 rps = random_pool_size();
1328
1329 buffer = malloc(rps);
1330 if (!buffer)
1331 return log_oom();
1332
1333 rv = m->C_GenerateRandom(session, buffer, rps);
1334 if (rv != CKR_OK)
1335 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1336 "Failed to generate RNG data on security token: %s", sym_p11_kit_strerror(rv));
1337
1338 r = random_write_entropy(-1, buffer, rps, false);
1339 if (r < 0)
1340 return log_debug_errno(r, "Failed to write PKCS#11 acquired random data to /dev/urandom: %m");
1341
1342 log_debug("Successfully written %zu bytes random data acquired via PKCS#11 to kernel random pool.", rps);
1343
1344 return 0;
1345 }
1346
1347 static int token_process(
1348 CK_FUNCTION_LIST *m,
1349 CK_SLOT_ID slotid,
1350 const CK_SLOT_INFO *slot_info,
1351 const CK_TOKEN_INFO *token_info,
1352 P11KitUri *search_uri,
1353 pkcs11_find_token_callback_t callback,
1354 void *userdata) {
1355
1356 _cleanup_free_ char *token_label = NULL;
1357 CK_SESSION_HANDLE session;
1358 CK_RV rv;
1359 int r;
1360
1361 assert(m);
1362 assert(slot_info);
1363 assert(token_info);
1364
1365 token_label = pkcs11_token_label(token_info);
1366 if (!token_label)
1367 return log_oom();
1368
1369 rv = m->C_OpenSession(slotid, CKF_SERIAL_SESSION, NULL, NULL, &session);
1370 if (rv != CKR_OK)
1371 return log_error_errno(SYNTHETIC_ERRNO(EIO),
1372 "Failed to create session for security token '%s': %s", token_label, sym_p11_kit_strerror(rv));
1373
1374 if (callback)
1375 r = callback(m, session, slotid, slot_info, token_info, search_uri, userdata);
1376 else
1377 r = 1; /* if not callback was specified, just say we found what we were looking for */
1378
1379 rv = m->C_CloseSession(session);
1380 if (rv != CKR_OK)
1381 log_warning("Failed to close session on PKCS#11 token, ignoring: %s", sym_p11_kit_strerror(rv));
1382
1383 return r;
1384 }
1385
1386 static int slot_process(
1387 CK_FUNCTION_LIST *m,
1388 CK_SLOT_ID slotid,
1389 P11KitUri *search_uri,
1390 pkcs11_find_token_callback_t callback,
1391 void *userdata) {
1392
1393 _cleanup_(p11_kit_uri_freep) P11KitUri* slot_uri = NULL, *token_uri = NULL;
1394 _cleanup_free_ char *token_uri_string = NULL;
1395 CK_TOKEN_INFO token_info;
1396 CK_SLOT_INFO slot_info;
1397 int uri_result, r;
1398 CK_RV rv;
1399
1400 assert(m);
1401
1402 r = dlopen_p11kit(LOG_DEBUG);
1403 if (r < 0)
1404 return r;
1405
1406 /* We return -EAGAIN for all failures we can attribute to a specific slot in some way, so that the
1407 * caller might try other slots before giving up. */
1408
1409 rv = m->C_GetSlotInfo(slotid, &slot_info);
1410 if (rv != CKR_OK) {
1411 log_warning("Failed to acquire slot info for slot %lu, ignoring slot: %s", slotid, sym_p11_kit_strerror(rv));
1412 return -EAGAIN;
1413 }
1414
1415 slot_uri = uri_from_slot_info(&slot_info);
1416 if (!slot_uri)
1417 return log_oom();
1418
1419 if (DEBUG_LOGGING) {
1420 _cleanup_free_ char *slot_uri_string = NULL;
1421
1422 uri_result = sym_p11_kit_uri_format(slot_uri, P11_KIT_URI_FOR_ANY, &slot_uri_string);
1423 if (uri_result != P11_KIT_URI_OK) {
1424 log_warning("Failed to format slot URI, ignoring slot: %s", sym_p11_kit_uri_message(uri_result));
1425 return -EAGAIN;
1426 }
1427
1428 log_debug("Found slot with URI %s", slot_uri_string);
1429 }
1430
1431 rv = m->C_GetTokenInfo(slotid, &token_info);
1432 if (rv == CKR_TOKEN_NOT_PRESENT) {
1433 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
1434 "Token not present in slot, ignoring.");
1435 } else if (rv != CKR_OK) {
1436 log_warning("Failed to acquire token info for slot %lu, ignoring slot: %s", slotid, sym_p11_kit_strerror(rv));
1437 return -EAGAIN;
1438 }
1439
1440 token_uri = uri_from_token_info(&token_info);
1441 if (!token_uri)
1442 return log_oom();
1443
1444 uri_result = sym_p11_kit_uri_format(token_uri, P11_KIT_URI_FOR_ANY, &token_uri_string);
1445 if (uri_result != P11_KIT_URI_OK) {
1446 log_warning("Failed to format slot URI: %s", sym_p11_kit_uri_message(uri_result));
1447 return -EAGAIN;
1448 }
1449
1450 if (search_uri && !sym_p11_kit_uri_match_token_info(search_uri, &token_info))
1451 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
1452 "Found non-matching token with URI %s.",
1453 token_uri_string);
1454
1455 log_debug("Found matching token with URI %s.", token_uri_string);
1456
1457 return token_process(
1458 m,
1459 slotid,
1460 &slot_info,
1461 &token_info,
1462 search_uri,
1463 callback,
1464 userdata);
1465 }
1466
1467 static int module_process(
1468 CK_FUNCTION_LIST *m,
1469 P11KitUri *search_uri,
1470 pkcs11_find_token_callback_t callback,
1471 void *userdata) {
1472
1473 _cleanup_(p11_kit_uri_freep) P11KitUri* module_uri = NULL;
1474 _cleanup_free_ char *name = NULL, *module_uri_string = NULL;
1475 _cleanup_free_ CK_SLOT_ID *slotids = NULL;
1476 CK_ULONG n_slotids = 0;
1477 int uri_result;
1478 CK_INFO info;
1479 size_t k;
1480 CK_RV rv;
1481 int r;
1482
1483 assert(m);
1484
1485 r = dlopen_p11kit(LOG_DEBUG);
1486 if (r < 0)
1487 return r;
1488
1489 /* We ignore most errors from modules here, in order to skip over faulty modules: one faulty module
1490 * should not have the effect that we don't try the others anymore. We indicate such per-module
1491 * failures with -EAGAIN, which let's the caller try the next module. */
1492
1493 name = sym_p11_kit_module_get_name(m);
1494 if (!name)
1495 return log_oom();
1496
1497 log_debug("Trying PKCS#11 module %s.", name);
1498
1499 rv = m->C_GetInfo(&info);
1500 if (rv != CKR_OK) {
1501 log_warning("Failed to get info on PKCS#11 module, ignoring module: %s", sym_p11_kit_strerror(rv));
1502 return -EAGAIN;
1503 }
1504
1505 module_uri = uri_from_module_info(&info);
1506 if (!module_uri)
1507 return log_oom();
1508
1509 uri_result = sym_p11_kit_uri_format(module_uri, P11_KIT_URI_FOR_ANY, &module_uri_string);
1510 if (uri_result != P11_KIT_URI_OK) {
1511 log_warning("Failed to format module URI, ignoring module: %s", sym_p11_kit_uri_message(uri_result));
1512 return -EAGAIN;
1513 }
1514
1515 log_debug("Found module with URI %s", module_uri_string);
1516
1517 rv = pkcs11_get_slot_list_malloc(m, &slotids, &n_slotids);
1518 if (rv != CKR_OK) {
1519 log_warning("Failed to get slot list, ignoring module: %s", sym_p11_kit_strerror(rv));
1520 return -EAGAIN;
1521 }
1522 if (n_slotids == 0)
1523 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN),
1524 "This module has no slots? Ignoring module.");
1525
1526 for (k = 0; k < n_slotids; k++) {
1527 r = slot_process(
1528 m,
1529 slotids[k],
1530 search_uri,
1531 callback,
1532 userdata);
1533 if (r != -EAGAIN)
1534 return r;
1535 }
1536
1537 return -EAGAIN;
1538 }
1539
1540 int pkcs11_find_token(
1541 const char *pkcs11_uri,
1542 pkcs11_find_token_callback_t callback,
1543 void *userdata) {
1544
1545 _cleanup_(p11_kit_modules_finalize_and_releasep) CK_FUNCTION_LIST **modules = NULL;
1546 _cleanup_(p11_kit_uri_freep) P11KitUri *search_uri = NULL;
1547 int r;
1548
1549 r = dlopen_p11kit(LOG_DEBUG);
1550 if (r < 0)
1551 return r;
1552
1553 /* Execute the specified callback for each matching token found. If nothing is found returns
1554 * -EAGAIN. Logs about all errors, except for EAGAIN, which the caller has to log about. */
1555
1556 if (pkcs11_uri) {
1557 r = uri_from_string(pkcs11_uri, &search_uri);
1558 if (r < 0)
1559 return log_error_errno(r, "Failed to parse PKCS#11 URI '%s': %m", pkcs11_uri);
1560 }
1561
1562 modules = sym_p11_kit_modules_load_and_initialize(0);
1563 if (!modules)
1564 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to initialize pkcs11 modules");
1565
1566 for (CK_FUNCTION_LIST **i = modules; *i; i++) {
1567 r = module_process(
1568 *i,
1569 search_uri,
1570 callback,
1571 userdata);
1572 if (r != -EAGAIN)
1573 return r;
1574 }
1575
1576 return -EAGAIN;
1577 }
1578
1579 #if HAVE_OPENSSL
1580 struct pkcs11_acquire_public_key_callback_data {
1581 char *pin_used;
1582 EVP_PKEY *pkey;
1583 Pkcs11RsaPadding rsa_padding;
1584 const char *askpw_friendly_name, *askpw_icon, *askpw_credential;
1585 AskPasswordFlags askpw_flags;
1586 };
1587
1588 static void pkcs11_acquire_public_key_callback_data_release(struct pkcs11_acquire_public_key_callback_data *data) {
1589 erase_and_free(data->pin_used);
1590 if (data->pkey)
1591 sym_EVP_PKEY_free(data->pkey);
1592 }
1593
1594 static int pkcs11_token_try_oaep_mechanism(
1595 CK_FUNCTION_LIST *m,
1596 CK_SESSION_HANDLE session,
1597 CK_OBJECT_HANDLE private_key,
1598 CK_MECHANISM_TYPE hash_alg,
1599 CK_RSA_PKCS_MGF_TYPE mgf) {
1600
1601 CK_RSA_PKCS_OAEP_PARAMS params = {
1602 .hashAlg = hash_alg,
1603 .mgf = mgf,
1604 .source = CKZ_DATA_SPECIFIED,
1605 };
1606 CK_MECHANISM mechanism = {
1607 .mechanism = CKM_RSA_PKCS_OAEP,
1608 .pParameter = &params,
1609 .ulParameterLen = sizeof(params),
1610 };
1611 CK_RV rv;
1612
1613 rv = m->C_DecryptInit(session, &mechanism, private_key);
1614 if (rv != CKR_OK)
1615 return -EIO;
1616
1617 /* Accepted: terminate the operation. Per PKCS#11 spec section 5.2 any cryptographic function
1618 * returning an error other than CKR_BUFFER_TOO_SMALL terminates the active operation, so feed
1619 * deliberately invalid (too-short) ciphertext to C_Decrypt to trigger a cancellation that's
1620 * likely to be portable across token implementations. */
1621 CK_BYTE in[1] = {};
1622 CK_BYTE out[1];
1623 CK_ULONG out_len = sizeof(out);
1624 (void) m->C_Decrypt(session, in, sizeof(in), out, &out_len);
1625
1626 return 0;
1627 }
1628
1629 static int pkcs11_token_probe_rsa_oaep_padding(
1630 CK_FUNCTION_LIST *m,
1631 CK_SESSION_HANDLE session,
1632 CK_OBJECT_HANDLE private_key,
1633 Pkcs11RsaPadding *ret) {
1634
1635 CK_KEY_TYPE key_type;
1636 CK_ATTRIBUTE key_type_template = { CKA_KEY_TYPE, &key_type, sizeof(key_type) };
1637 CK_RV rv;
1638 int r;
1639
1640 assert(m);
1641 assert(ret);
1642
1643 /* Probes whether the token will accept the OAEP-SHA256 or OAEP-SHA1 mechanism for decryption with
1644 * the given private key. On any failure (wrong key type, related-object lookup ambiguity yielded
1645 * an EC private key, both mechanisms rejected, etc.) we bail out, this can only be best-effort. */
1646 rv = m->C_GetAttributeValue(session, private_key, &key_type_template, /* ulCount= */ 1);
1647 if (rv != CKR_OK)
1648 return log_debug_errno(SYNTHETIC_ERRNO(EIO),
1649 "Failed to retrieve private key type: %s", sym_p11_kit_strerror(rv));
1650 if (key_type != CKK_RSA)
1651 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1652 "Located private key is not RSA, skipping OAEP padding probe.");
1653
1654 /* For RSA-OAEP we use SHA-256 or SHA-1 with the matching MGF1 and an empty (zero-length) label.
1655 * SHA-256 is preferred when the token supports it, but for example SoftHSM doesn't support it, so
1656 * fall back to SHA-1 if it gets rejected. */
1657 r = pkcs11_token_try_oaep_mechanism(m, session, private_key, CKM_SHA256, CKG_MGF1_SHA256);
1658 if (r >= 0) {
1659 *ret = PKCS11_RSA_PADDING_OAEP_SHA256;
1660 log_debug("Token accepts OAEP-SHA256 for decryption.");
1661 return 0;
1662 }
1663
1664 r = pkcs11_token_try_oaep_mechanism(m, session, private_key, CKM_SHA_1, CKG_MGF1_SHA1);
1665 if (r >= 0) {
1666 *ret = PKCS11_RSA_PADDING_OAEP_SHA1;
1667 log_debug("Token accepts OAEP-SHA1 for decryption.");
1668 return 0;
1669 }
1670
1671 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Token rejected both OAEP-SHA256 and OAEP-SHA1.");
1672 }
1673
1674 static int pkcs11_acquire_public_key_callback(
1675 CK_FUNCTION_LIST *m,
1676 CK_SESSION_HANDLE session,
1677 CK_SLOT_ID slot_id,
1678 const CK_SLOT_INFO *slot_info,
1679 const CK_TOKEN_INFO *token_info,
1680 P11KitUri *uri,
1681 void *userdata) {
1682
1683 _cleanup_(erase_and_freep) char *pin_used = NULL;
1684 _cleanup_(EVP_PKEY_freep) EVP_PKEY *pkey = NULL;
1685 CK_OBJECT_CLASS class;
1686 CK_CERTIFICATE_TYPE type;
1687 CK_ATTRIBUTE candidate_attributes[] = {
1688 { CKA_CLASS, &class, sizeof(class) },
1689 { CKA_CERTIFICATE_TYPE, &type, sizeof(type) },
1690 };
1691 CK_OBJECT_HANDLE candidate, public_key = CK_INVALID_HANDLE, certificate = CK_INVALID_HANDLE;
1692 uint8_t n_public_keys = 0, n_certificates = 0;
1693 CK_RV rv;
1694 int r;
1695
1696 assert(m);
1697 assert(slot_info);
1698 assert(token_info);
1699 assert(uri);
1700
1701 struct pkcs11_acquire_public_key_callback_data *data = ASSERT_PTR(userdata);
1702
1703 /* Called for every token matching our URI */
1704
1705 r = pkcs11_token_login(
1706 m,
1707 session,
1708 slot_id,
1709 token_info,
1710 data->askpw_friendly_name,
1711 data->askpw_icon,
1712 "pkcs11-pin",
1713 data->askpw_credential,
1714 UINT64_MAX,
1715 data->askpw_flags,
1716 &pin_used);
1717 if (r < 0)
1718 return r;
1719
1720 CK_ULONG n_attributes;
1721 CK_ATTRIBUTE *attributes = sym_p11_kit_uri_get_attributes(uri, &n_attributes);
1722 for (CK_ULONG i = 0; i < n_attributes; i++) {
1723 switch (attributes[i].type) {
1724 case CKA_CLASS: {
1725 CK_OBJECT_CLASS requested_class = *((CK_OBJECT_CLASS*) attributes[i].pValue);
1726 if (!IN_SET(requested_class, CKO_PUBLIC_KEY, CKO_CERTIFICATE))
1727 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1728 "Selected PKCS#11 object is not a public key or certificate, refusing.");
1729 break;
1730 }
1731
1732 case CKA_CERTIFICATE_TYPE: {
1733 CK_CERTIFICATE_TYPE requested_type = *((CK_CERTIFICATE_TYPE*) attributes[i].pValue);
1734 if (requested_type != CKC_X_509)
1735 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Selected PKCS#11 object is not an X.509 certificate, refusing.");
1736 break;
1737 }}
1738 }
1739
1740 rv = m->C_FindObjectsInit(session, attributes, n_attributes);
1741 if (rv != CKR_OK)
1742 return log_error_errno(SYNTHETIC_ERRNO(EIO),
1743 "Failed to initialize object find call: %s", sym_p11_kit_strerror(rv));
1744
1745 for (;;) {
1746 CK_ULONG n;
1747 rv = m->C_FindObjects(session, &candidate, 1, &n);
1748 if (rv != CKR_OK)
1749 return log_error_errno(SYNTHETIC_ERRNO(EIO),
1750 "Failed to find objects: %s", sym_p11_kit_strerror(rv));
1751
1752 if (n == 0)
1753 break;
1754
1755 candidate_attributes[0].ulValueLen = sizeof(class);
1756 candidate_attributes[1].ulValueLen = sizeof(type);
1757 rv = m->C_GetAttributeValue(session, candidate, candidate_attributes, ELEMENTSOF(candidate_attributes));
1758 if (!IN_SET(rv, CKR_OK, CKR_ATTRIBUTE_TYPE_INVALID))
1759 return log_error_errno(SYNTHETIC_ERRNO(EIO),
1760 "Failed to get attributes of a selected candidate: %s", sym_p11_kit_strerror(rv));
1761
1762 if (candidate_attributes[0].ulValueLen == CK_UNAVAILABLE_INFORMATION) {
1763 log_debug("Failed to get CKA_CLASS of a selected candidate");
1764 continue;
1765 }
1766
1767 if (class == CKO_PUBLIC_KEY) {
1768 n_public_keys++;
1769 if (n_public_keys > 1)
1770 break;
1771 public_key = candidate;
1772 continue;
1773 }
1774
1775 if (class == CKO_CERTIFICATE) {
1776 if (candidate_attributes[1].ulValueLen == CK_UNAVAILABLE_INFORMATION) {
1777 log_debug("Failed to get CKA_CERTIFICATE_TYPE of a selected candidate");
1778 continue;
1779 }
1780 if (type != CKC_X_509)
1781 continue;
1782 n_certificates++;
1783 if (n_certificates > 1)
1784 break;
1785 certificate = candidate;
1786 continue;
1787 }
1788 }
1789
1790 rv = m->C_FindObjectsFinal(session);
1791 if (rv != CKR_OK)
1792 return log_error_errno(SYNTHETIC_ERRNO(EIO),
1793 "Failed to finalize object find call: %s", sym_p11_kit_strerror(rv));
1794
1795 if (n_public_keys == 0 && n_certificates == 0)
1796 return log_error_errno(SYNTHETIC_ERRNO(ENOENT),
1797 "Failed to find selected public key or X.509 certificate.");
1798
1799 if (n_public_keys > 1)
1800 return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ),
1801 "Provided URI matches multiple public keys, refusing.");
1802
1803 if (n_certificates > 1)
1804 return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ),
1805 "Provided URI matches multiple certificates, refusing.");
1806
1807 if (n_public_keys != 0) {
1808 r = pkcs11_token_read_public_key(m, session, public_key, &pkey);
1809 if (r >= 0)
1810 goto success;
1811 }
1812
1813 if (n_certificates == 0)
1814 return log_error_errno(r, "Failed to read a found public key.");
1815
1816 {
1817 _cleanup_(X509_freep) X509 *cert = NULL;
1818
1819 r = pkcs11_token_read_x509_certificate(m, session, certificate, &cert);
1820 if (r < 0)
1821 return log_error_errno(r, "Failed to read a found X.509 certificate.");
1822
1823 r = dlopen_libcrypto(LOG_DEBUG);
1824 if (r < 0)
1825 return r;
1826
1827 pkey = sym_X509_get_pubkey(cert);
1828 if (!pkey)
1829 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to extract public key from X.509 certificate.");
1830 }
1831 success:
1832 /* Let's read some random data off the token and write it to the kernel pool before we generate our
1833 * random key from it. This way we can claim the quality of the RNG is at least as good as the
1834 * kernel's and the token's pool */
1835 (void) pkcs11_token_acquire_rng(m, session);
1836
1837 /* Decide whether the enrolled key needs RSA padding metadata at all based on the public key we
1838 * extracted (RSA vs EC). For RSA, default to OAEP-SHA1 which works on all known tokens (e.g.
1839 * SoftHSM only accepts SHA-1), then try to upgrade to OAEP-SHA256 by probing the matching private
1840 * key on the token. The probe is best-effort: if we cannot find the private key (e.g. token holds
1841 * only the certificate, or the related-object lookup is ambiguous because CKA_ID is missing or
1842 * doesn't match) we keep the OAEP-SHA1 default. For non-RSA keys (EC) we leave rsa_padding as
1843 * _INVALID, so no padding tag is recorded and the decrypt path uses ECDH instead. */
1844 data->rsa_padding = _PKCS11_RSA_PADDING_INVALID;
1845
1846 if (sym_EVP_PKEY_get_base_id(pkey) == EVP_PKEY_RSA) {
1847 CK_OBJECT_HANDLE prototype = public_key != CK_INVALID_HANDLE ? public_key : certificate;
1848 CK_OBJECT_HANDLE private_key = CK_INVALID_HANDLE;
1849 Pkcs11RsaPadding padding = PKCS11_RSA_PADDING_OAEP_SHA1; /* default to SHA1 unless we can do better */
1850
1851 if (pkcs11_token_find_related_object(m, session, prototype, CKO_PRIVATE_KEY, &private_key) >= 0) {
1852 r = pkcs11_token_probe_rsa_oaep_padding(m, session, private_key, &padding);
1853 if (r < 0)
1854 log_info_errno(r, "Token rejected both OAEP-SHA256 and OAEP-SHA1, defaulting RSA enrollment to OAEP-SHA1.");
1855 } else
1856 log_info("No matching PKCS#11 private key found, OAEP padding probe skipped, defaulting RSA enrollment to OAEP-SHA1.");
1857
1858 data->rsa_padding = padding;
1859 }
1860
1861 data->pin_used = TAKE_PTR(pin_used);
1862 data->pkey = TAKE_PTR(pkey);
1863 return 0;
1864 }
1865
1866 int pkcs11_acquire_public_key(
1867 const char *uri,
1868 const char *askpw_friendly_name,
1869 const char *askpw_icon,
1870 const char *askpw_credential,
1871 AskPasswordFlags askpw_flags,
1872 EVP_PKEY **ret_pkey,
1873 Pkcs11RsaPadding *ret_rsa_padding,
1874 char **ret_pin_used) {
1875
1876 _cleanup_(pkcs11_acquire_public_key_callback_data_release) struct pkcs11_acquire_public_key_callback_data data = {
1877 .askpw_friendly_name = askpw_friendly_name,
1878 .askpw_icon = askpw_icon,
1879 .askpw_credential = askpw_credential,
1880 .askpw_flags = askpw_flags,
1881 .rsa_padding = _PKCS11_RSA_PADDING_INVALID,
1882 };
1883 int r;
1884
1885 assert(uri);
1886 assert(ret_pkey);
1887
1888 r = pkcs11_find_token(uri, pkcs11_acquire_public_key_callback, &data);
1889 if (r == -EAGAIN) /* pkcs11_find_token() doesn't log about this error, but all others */
1890 return log_error_errno(SYNTHETIC_ERRNO(ENXIO),
1891 "Specified PKCS#11 token with URI '%s' not found.",
1892 uri);
1893 if (r < 0)
1894 return r;
1895
1896 *ret_pkey = TAKE_PTR(data.pkey);
1897 if (ret_rsa_padding)
1898 *ret_rsa_padding = data.rsa_padding;
1899 if (ret_pin_used)
1900 *ret_pin_used = TAKE_PTR(data.pin_used);
1901 return 0;
1902 }
1903 #endif
1904
1905 static int list_callback(
1906 CK_FUNCTION_LIST *m,
1907 CK_SESSION_HANDLE session,
1908 CK_SLOT_ID slot_id,
1909 const CK_SLOT_INFO *slot_info,
1910 const CK_TOKEN_INFO *token_info,
1911 P11KitUri *uri,
1912 void *userdata) {
1913
1914 _cleanup_free_ char *token_uri_string = NULL, *token_label = NULL, *token_manufacturer_id = NULL, *token_model = NULL;
1915 _cleanup_(p11_kit_uri_freep) P11KitUri *token_uri = NULL;
1916 Table *t = userdata;
1917 int uri_result, r;
1918
1919 assert(slot_info);
1920 assert(token_info);
1921
1922 r = dlopen_p11kit(LOG_DEBUG);
1923 if (r < 0)
1924 return r;
1925
1926 /* We only care about hardware devices here with a token inserted. Let's filter everything else
1927 * out. (Note that the user can explicitly specify non-hardware tokens if they like, but during
1928 * enumeration we'll filter those, since software tokens are typically the system certificate store
1929 * and such, and it's typically not what people want to bind their home directories to.) */
1930 if (!FLAGS_SET(slot_info->flags, CKF_HW_SLOT|CKF_TOKEN_PRESENT))
1931 return -EAGAIN;
1932
1933 token_label = pkcs11_token_label(token_info);
1934 if (!token_label)
1935 return log_oom();
1936
1937 token_manufacturer_id = pkcs11_token_manufacturer_id(token_info);
1938 if (!token_manufacturer_id)
1939 return log_oom();
1940
1941 token_model = pkcs11_token_model(token_info);
1942 if (!token_model)
1943 return log_oom();
1944
1945 token_uri = uri_from_token_info(token_info);
1946 if (!token_uri)
1947 return log_oom();
1948
1949 uri_result = sym_p11_kit_uri_format(token_uri, P11_KIT_URI_FOR_ANY, &token_uri_string);
1950 if (uri_result != P11_KIT_URI_OK)
1951 return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN), "Failed to format slot URI: %s", sym_p11_kit_uri_message(uri_result));
1952
1953 r = table_add_many(
1954 t,
1955 TABLE_STRING, token_uri_string,
1956 TABLE_STRING, token_label,
1957 TABLE_STRING, token_manufacturer_id,
1958 TABLE_STRING, token_model);
1959 if (r < 0)
1960 return table_log_add_error(r);
1961
1962 return -EAGAIN; /* keep scanning */
1963 }
1964 #endif
1965
1966 int dlopen_p11kit(int log_level) {
1967 #if HAVE_P11KIT
1968 static void *p11kit_dl = NULL;
1969
1970 SD_ELF_NOTE_DLOPEN(
1971 "p11-kit",
1972 "Support for PKCS11 hardware tokens",
1973 SD_ELF_NOTE_DLOPEN_PRIORITY_SUGGESTED,
1974 "libp11-kit.so.0");
1975
1976 return dlopen_many_sym_or_warn(
1977 &p11kit_dl,
1978 "libp11-kit.so.0", log_level,
1979 DLSYM_ARG(p11_kit_module_get_name),
1980 DLSYM_ARG(p11_kit_modules_finalize_and_release),
1981 DLSYM_ARG(p11_kit_modules_load_and_initialize),
1982 DLSYM_ARG(p11_kit_strerror),
1983 DLSYM_ARG(p11_kit_uri_format),
1984 DLSYM_ARG(p11_kit_uri_free),
1985 DLSYM_ARG(p11_kit_uri_get_attributes),
1986 DLSYM_ARG(p11_kit_uri_get_attribute),
1987 DLSYM_ARG(p11_kit_uri_set_attribute),
1988 DLSYM_ARG(p11_kit_uri_get_module_info),
1989 DLSYM_ARG(p11_kit_uri_get_slot_info),
1990 DLSYM_ARG(p11_kit_uri_get_token_info),
1991 DLSYM_ARG(p11_kit_uri_match_token_info),
1992 DLSYM_ARG(p11_kit_uri_message),
1993 DLSYM_ARG(p11_kit_uri_new),
1994 DLSYM_ARG(p11_kit_uri_parse));
1995 #else
1996 return log_full_errno(log_level, SYNTHETIC_ERRNO(EOPNOTSUPP),
1997 "libp11-kit support is not compiled in.");
1998 #endif
1999 }
2000
2001 int pkcs11_list_tokens(void) {
2002 #if HAVE_P11KIT
2003 _cleanup_(table_unrefp) Table *t = NULL;
2004 int r;
2005
2006 t = table_new("uri", "label", "manufacturer", "model");
2007 if (!t)
2008 return log_oom();
2009
2010 r = pkcs11_find_token(NULL, list_callback, t);
2011 if (r < 0 && r != -EAGAIN)
2012 return r;
2013
2014 if (table_isempty(t)) {
2015 log_info("No suitable PKCS#11 tokens found.");
2016 return 0;
2017 }
2018
2019 return table_print_or_warn(t);
2020 #else
2021 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2022 "PKCS#11 tokens not supported on this build.");
2023 #endif
2024 }
2025
2026 #if HAVE_P11KIT
2027 static int auto_callback(
2028 CK_FUNCTION_LIST *m,
2029 CK_SESSION_HANDLE session,
2030 CK_SLOT_ID slot_id,
2031 const CK_SLOT_INFO *slot_info,
2032 const CK_TOKEN_INFO *token_info,
2033 P11KitUri *uri,
2034 void *userdata) {
2035
2036 _cleanup_(p11_kit_uri_freep) P11KitUri *token_uri = NULL;
2037 char **t = userdata;
2038 int uri_result, r;
2039
2040 assert(slot_info);
2041 assert(token_info);
2042
2043 r = dlopen_p11kit(LOG_DEBUG);
2044 if (r < 0)
2045 return r;
2046
2047 if (!FLAGS_SET(token_info->flags, CKF_HW_SLOT|CKF_TOKEN_PRESENT))
2048 return -EAGAIN;
2049
2050 if (*t)
2051 return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ),
2052 "More than one suitable PKCS#11 token found.");
2053
2054 token_uri = uri_from_token_info(token_info);
2055 if (!token_uri)
2056 return log_oom();
2057
2058 uri_result = sym_p11_kit_uri_format(token_uri, P11_KIT_URI_FOR_ANY, t);
2059 if (uri_result != P11_KIT_URI_OK)
2060 return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN), "Failed to format slot URI: %s", sym_p11_kit_uri_message(uri_result));
2061
2062 return 0;
2063 }
2064 #endif
2065
2066 int pkcs11_find_token_auto(char **ret) {
2067 #if HAVE_P11KIT
2068 int r;
2069
2070 r = pkcs11_find_token(NULL, auto_callback, ret);
2071 if (r == -EAGAIN)
2072 return log_error_errno(SYNTHETIC_ERRNO(ENODEV), "No suitable PKCS#11 tokens found.");
2073 if (r < 0)
2074 return r;
2075
2076 return 0;
2077 #else
2078 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2079 "PKCS#11 tokens not supported on this build.");
2080 #endif
2081 }
2082
2083 #if HAVE_P11KIT
2084 void pkcs11_crypt_device_callback_data_release(pkcs11_crypt_device_callback_data *data) {
2085 erase_and_free(data->decrypted_key);
2086
2087 if (data->free_encrypted_key)
2088 free(data->encrypted_key);
2089 }
2090
2091 int pkcs11_crypt_device_callback(
2092 CK_FUNCTION_LIST *m,
2093 CK_SESSION_HANDLE session,
2094 CK_SLOT_ID slot_id,
2095 const CK_SLOT_INFO *slot_info,
2096 const CK_TOKEN_INFO *token_info,
2097 P11KitUri *uri,
2098 void *userdata) {
2099
2100 pkcs11_crypt_device_callback_data *data = ASSERT_PTR(userdata);
2101 CK_OBJECT_HANDLE object;
2102 int r;
2103
2104 assert(m);
2105 assert(slot_info);
2106 assert(token_info);
2107 assert(uri);
2108
2109 /* Called for every token matching our URI */
2110
2111 r = pkcs11_token_login(
2112 m,
2113 session,
2114 slot_id,
2115 token_info,
2116 data->friendly_name,
2117 "drive-harddisk",
2118 "pkcs11-pin",
2119 data->askpw_credential,
2120 data->until,
2121 data->askpw_flags,
2122 NULL);
2123 if (r < 0)
2124 return r;
2125
2126 /* We are likely called during early boot, where entropy is scarce. Mix some data from the PKCS#11
2127 * token, if it supports that. It should be cheap, given that we already are talking to it anyway and
2128 * shouldn't hurt. */
2129 (void) pkcs11_token_acquire_rng(m, session);
2130
2131 r = pkcs11_token_find_private_key(m, session, uri, &object);
2132 if (r < 0)
2133 return r;
2134
2135 r = pkcs11_token_decrypt_data(
2136 m,
2137 session,
2138 object,
2139 data->encrypted_key,
2140 data->encrypted_key_size,
2141 data->rsa_padding,
2142 &data->decrypted_key,
2143 &data->decrypted_key_size);
2144 if (r < 0)
2145 return r;
2146
2147 return 0;
2148 }
2149 #endif