1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
5 #include "ask-password-api.h"
8 #include "format-table.h"
10 #include "memory-util.h"
12 #include "openssl-util.h"
14 #include "pkcs11-util.h"
15 #include "random-util.h"
16 #include "string-util.h"
19 bool pkcs11_uri_valid(const char *uri
) {
22 /* A very superficial checker for RFC7512 PKCS#11 URI syntax */
27 p
= startswith(uri
, "pkcs11:");
34 if (!in_charset(p
, ALPHANUMERICAL
".~/-_?;&%="))
42 int uri_from_string(const char *p
, P11KitUri
**ret
) {
43 _cleanup_(p11_kit_uri_freep
) P11KitUri
*uri
= NULL
;
48 uri
= p11_kit_uri_new();
52 if (p11_kit_uri_parse(p
, P11_KIT_URI_FOR_ANY
, uri
) != P11_KIT_URI_OK
)
59 P11KitUri
*uri_from_module_info(const CK_INFO
*info
) {
64 uri
= p11_kit_uri_new();
68 *p11_kit_uri_get_module_info(uri
) = *info
;
72 P11KitUri
*uri_from_slot_info(const CK_SLOT_INFO
*slot_info
) {
77 uri
= p11_kit_uri_new();
81 *p11_kit_uri_get_slot_info(uri
) = *slot_info
;
85 P11KitUri
*uri_from_token_info(const CK_TOKEN_INFO
*token_info
) {
90 uri
= p11_kit_uri_new();
94 *p11_kit_uri_get_token_info(uri
) = *token_info
;
98 CK_RV
pkcs11_get_slot_list_malloc(
100 CK_SLOT_ID
**ret_slotids
,
101 CK_ULONG
*ret_n_slotids
) {
107 assert(ret_n_slotids
);
109 for (unsigned tries
= 0; tries
< 16; tries
++) {
110 _cleanup_free_ CK_SLOT_ID
*slotids
= NULL
;
111 CK_ULONG n_slotids
= 0;
113 rv
= m
->C_GetSlotList(0, NULL
, &n_slotids
);
116 if (n_slotids
== 0) {
122 slotids
= new(CK_SLOT_ID
, n_slotids
);
124 return CKR_HOST_MEMORY
;
126 rv
= m
->C_GetSlotList(0, slotids
, &n_slotids
);
128 *ret_slotids
= TAKE_PTR(slotids
);
129 *ret_n_slotids
= n_slotids
;
133 if (rv
!= CKR_BUFFER_TOO_SMALL
)
136 /* Hu? Maybe somebody plugged something in and things changed? Let's try again */
139 return CKR_BUFFER_TOO_SMALL
;
142 char *pkcs11_token_label(const CK_TOKEN_INFO
*token_info
) {
145 /* The label is not NUL terminated and likely padded with spaces, let's make a copy here, so that we
147 t
= strndup((char*) token_info
->label
, sizeof(token_info
->label
));
155 char *pkcs11_token_manufacturer_id(const CK_TOKEN_INFO
*token_info
) {
158 t
= strndup((char*) token_info
->manufacturerID
, sizeof(token_info
->manufacturerID
));
166 char *pkcs11_token_model(const CK_TOKEN_INFO
*token_info
) {
169 t
= strndup((char*) token_info
->model
, sizeof(token_info
->model
));
177 int pkcs11_token_login(
179 CK_SESSION_HANDLE session
,
181 const CK_TOKEN_INFO
*token_info
,
182 const char *friendly_name
,
183 const char *icon_name
,
184 const char *key_name
,
185 const char *credential_name
,
187 char **ret_used_pin
) {
189 _cleanup_free_
char *token_uri_string
= NULL
, *token_uri_escaped
= NULL
, *id
= NULL
, *token_label
= NULL
;
190 _cleanup_(p11_kit_uri_freep
) P11KitUri
*token_uri
= NULL
;
191 CK_TOKEN_INFO updated_token_info
;
198 token_label
= pkcs11_token_label(token_info
);
202 token_uri
= uri_from_token_info(token_info
);
206 uri_result
= p11_kit_uri_format(token_uri
, P11_KIT_URI_FOR_ANY
, &token_uri_string
);
207 if (uri_result
!= P11_KIT_URI_OK
)
208 return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN
), "Failed to format slot URI: %s", p11_kit_uri_message(uri_result
));
210 if (FLAGS_SET(token_info
->flags
, CKF_PROTECTED_AUTHENTICATION_PATH
)) {
211 rv
= m
->C_Login(session
, CKU_USER
, NULL
, 0);
213 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
214 "Failed to log into security token '%s': %s", token_label
, p11_kit_strerror(rv
));
216 log_info("Successfully logged into security token '%s' via protected authentication path.", token_label
);
218 *ret_used_pin
= NULL
;
222 if (!FLAGS_SET(token_info
->flags
, CKF_LOGIN_REQUIRED
)) {
223 log_info("No login into security token '%s' required.", token_label
);
225 *ret_used_pin
= NULL
;
229 token_uri_escaped
= cescape(token_uri_string
);
230 if (!token_uri_escaped
)
233 id
= strjoin("pkcs11:", token_uri_escaped
);
237 for (unsigned tries
= 0; tries
< 3; tries
++) {
238 _cleanup_strv_free_erase_
char **passwords
= NULL
;
243 passwords
= strv_new(e
);
248 if (unsetenv("PIN") < 0)
249 return log_error_errno(errno
, "Failed to unset $PIN: %m");
251 _cleanup_free_
char *text
= NULL
;
253 if (FLAGS_SET(token_info
->flags
, CKF_USER_PIN_FINAL_TRY
))
255 "Please enter correct PIN for security token '%s' in order to unlock %s (final try):",
256 token_label
, friendly_name
);
257 else if (FLAGS_SET(token_info
->flags
, CKF_USER_PIN_COUNT_LOW
))
259 "PIN has been entered incorrectly previously, please enter correct PIN for security token '%s' in order to unlock %s:",
260 token_label
, friendly_name
);
263 "Please enter PIN for security token '%s' in order to unlock %s:",
264 token_label
, friendly_name
);
267 "Please enter PIN for security token '%s' in order to unlock %s (try #%u):",
268 token_label
, friendly_name
, tries
+1);
272 /* We never cache PINs, simply because it's fatal if we use wrong PINs, since usually there are only 3 tries */
273 r
= ask_password_auto(text
, icon_name
, id
, key_name
, credential_name
, until
, 0, &passwords
);
275 return log_error_errno(r
, "Failed to query PIN for security token '%s': %m", token_label
);
278 STRV_FOREACH(i
, passwords
) {
279 rv
= m
->C_Login(session
, CKU_USER
, (CK_UTF8CHAR
*) *i
, strlen(*i
));
292 log_info("Successfully logged into security token '%s'.", token_label
);
295 if (rv
== CKR_PIN_LOCKED
)
296 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
297 "PIN has been locked, please reset PIN of security token '%s'.", token_label
);
298 if (!IN_SET(rv
, CKR_PIN_INCORRECT
, CKR_PIN_LEN_RANGE
))
299 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
300 "Failed to log into security token '%s': %s", token_label
, p11_kit_strerror(rv
));
302 /* Referesh the token info, so that we can prompt knowing the new flags if they changed. */
303 rv
= m
->C_GetTokenInfo(slotid
, &updated_token_info
);
305 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
306 "Failed to acquire updated security token information for slot %lu: %s",
307 slotid
, p11_kit_strerror(rv
));
309 token_info
= &updated_token_info
;
310 log_notice("PIN for token '%s' is incorrect, please try again.", token_label
);
314 return log_error_errno(SYNTHETIC_ERRNO(EPERM
), "Too many attempts to log into token '%s'.", token_label
);
317 int pkcs11_token_find_x509_certificate(
319 CK_SESSION_HANDLE session
,
320 P11KitUri
*search_uri
,
321 CK_OBJECT_HANDLE
*ret_object
) {
323 bool found_class
= false, found_certificate_type
= false;
324 _cleanup_free_ CK_ATTRIBUTE
*attributes_buffer
= NULL
;
325 CK_ULONG n_attributes
, a
, n_objects
;
326 CK_ATTRIBUTE
*attributes
= NULL
;
327 CK_OBJECT_HANDLE objects
[2];
334 attributes
= p11_kit_uri_get_attributes(search_uri
, &n_attributes
);
335 for (a
= 0; a
< n_attributes
; a
++) {
337 /* We use the URI's included match attributes, but make them more strict. This allows users
338 * to specify a token URL instead of an object URL and the right thing should happen if
339 * there's only one suitable key on the token. */
341 switch (attributes
[a
].type
) {
346 if (attributes
[a
].ulValueLen
!= sizeof(c
))
347 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid PKCS#11 CKA_CLASS attribute size.");
349 memcpy(&c
, attributes
[a
].pValue
, sizeof(c
));
350 if (c
!= CKO_CERTIFICATE
)
351 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Selected PKCS#11 object is not an X.509 certificate, refusing.");
357 case CKA_CERTIFICATE_TYPE
: {
358 CK_CERTIFICATE_TYPE t
;
360 if (attributes
[a
].ulValueLen
!= sizeof(t
))
361 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid PKCS#11 CKA_CERTIFICATE_TYPE attribute size.");
363 memcpy(&t
, attributes
[a
].pValue
, sizeof(t
));
365 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Selected PKCS#11 object is not an X.509 certificate, refusing.");
367 found_certificate_type
= true;
372 if (!found_class
|| !found_certificate_type
) {
373 /* Hmm, let's slightly extend the attribute list we search for */
375 attributes_buffer
= new(CK_ATTRIBUTE
, n_attributes
+ !found_class
+ !found_certificate_type
);
376 if (!attributes_buffer
)
379 memcpy(attributes_buffer
, attributes
, sizeof(CK_ATTRIBUTE
) * n_attributes
);
382 static const CK_OBJECT_CLASS
class = CKO_CERTIFICATE
;
384 attributes_buffer
[n_attributes
++] = (CK_ATTRIBUTE
) {
386 .pValue
= (CK_OBJECT_CLASS
*) &class,
387 .ulValueLen
= sizeof(class),
391 if (!found_certificate_type
) {
392 static const CK_CERTIFICATE_TYPE type
= CKC_X_509
;
394 attributes_buffer
[n_attributes
++] = (CK_ATTRIBUTE
) {
395 .type
= CKA_CERTIFICATE_TYPE
,
396 .pValue
= (CK_CERTIFICATE_TYPE
*) &type
,
397 .ulValueLen
= sizeof(type
),
401 attributes
= attributes_buffer
;
404 rv
= m
->C_FindObjectsInit(session
, attributes
, n_attributes
);
406 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
407 "Failed to initialize object find call: %s", p11_kit_strerror(rv
));
409 rv
= m
->C_FindObjects(session
, objects
, ELEMENTSOF(objects
), &n_objects
);
410 rv2
= m
->C_FindObjectsFinal(session
);
412 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
413 "Failed to find objects: %s", p11_kit_strerror(rv
));
415 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
416 "Failed to finalize object find call: %s", p11_kit_strerror(rv
));
418 return log_error_errno(SYNTHETIC_ERRNO(ENOENT
),
419 "Failed to find selected X509 certificate on token.");
421 return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ
),
422 "Configured URI matches multiple certificates, refusing.");
424 *ret_object
= objects
[0];
429 int pkcs11_token_read_x509_certificate(
431 CK_SESSION_HANDLE session
,
432 CK_OBJECT_HANDLE object
,
435 _cleanup_free_
void *buffer
= NULL
;
436 _cleanup_free_
char *t
= NULL
;
437 CK_ATTRIBUTE attribute
= {
441 _cleanup_(X509_freep
) X509
*x509
= NULL
;
442 X509_NAME
*name
= NULL
;
443 const unsigned char *p
;
445 rv
= m
->C_GetAttributeValue(session
, object
, &attribute
, 1);
447 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
448 "Failed to read X.509 certificate size off token: %s", p11_kit_strerror(rv
));
450 buffer
= malloc(attribute
.ulValueLen
);
454 attribute
.pValue
= buffer
;
456 rv
= m
->C_GetAttributeValue(session
, object
, &attribute
, 1);
458 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
459 "Failed to read X.509 certificate data off token: %s", p11_kit_strerror(rv
));
461 p
= attribute
.pValue
;
462 x509
= d2i_X509(NULL
, &p
, attribute
.ulValueLen
);
464 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Failed parse X.509 certificate.");
466 name
= X509_get_subject_name(x509
);
468 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Failed to acquire X.509 subject name.");
470 t
= X509_NAME_oneline(name
, NULL
, 0);
472 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to format X.509 subject name as string.");
474 log_debug("Using X.509 certificate issued for '%s'.", t
);
476 *ret_cert
= TAKE_PTR(x509
);
481 int pkcs11_token_find_private_key(
483 CK_SESSION_HANDLE session
,
484 P11KitUri
*search_uri
,
485 CK_OBJECT_HANDLE
*ret_object
) {
487 bool found_decrypt
= false, found_class
= false, found_key_type
= false;
488 _cleanup_free_ CK_ATTRIBUTE
*attributes_buffer
= NULL
;
489 CK_ULONG n_attributes
, a
, n_objects
;
490 CK_ATTRIBUTE
*attributes
= NULL
;
491 CK_OBJECT_HANDLE objects
[2];
498 attributes
= p11_kit_uri_get_attributes(search_uri
, &n_attributes
);
499 for (a
= 0; a
< n_attributes
; a
++) {
501 /* We use the URI's included match attributes, but make them more strict. This allows users
502 * to specify a token URL instead of an object URL and the right thing should happen if
503 * there's only one suitable key on the token. */
505 switch (attributes
[a
].type
) {
510 if (attributes
[a
].ulValueLen
!= sizeof(c
))
511 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid PKCS#11 CKA_CLASS attribute size.");
513 memcpy(&c
, attributes
[a
].pValue
, sizeof(c
));
514 if (c
!= CKO_PRIVATE_KEY
)
515 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
516 "Selected PKCS#11 object is not a private key, refusing.");
525 if (attributes
[a
].ulValueLen
!= sizeof(b
))
526 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid PKCS#11 CKA_DECRYPT attribute size.");
528 memcpy(&b
, attributes
[a
].pValue
, sizeof(b
));
530 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
531 "Selected PKCS#11 object is not suitable for decryption, refusing.");
533 found_decrypt
= true;
540 if (attributes
[a
].ulValueLen
!= sizeof(t
))
541 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid PKCS#11 CKA_KEY_TYPE attribute size.");
543 memcpy(&t
, attributes
[a
].pValue
, sizeof(t
));
545 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Selected PKCS#11 object is not an RSA key, refusing.");
547 found_key_type
= true;
552 if (!found_decrypt
|| !found_class
|| !found_key_type
) {
553 /* Hmm, let's slightly extend the attribute list we search for */
555 attributes_buffer
= new(CK_ATTRIBUTE
, n_attributes
+ !found_decrypt
+ !found_class
+ !found_key_type
);
556 if (!attributes_buffer
)
559 memcpy(attributes_buffer
, attributes
, sizeof(CK_ATTRIBUTE
) * n_attributes
);
561 if (!found_decrypt
) {
562 static const CK_BBOOL yes
= true;
564 attributes_buffer
[n_attributes
++] = (CK_ATTRIBUTE
) {
566 .pValue
= (CK_BBOOL
*) &yes
,
567 .ulValueLen
= sizeof(yes
),
572 static const CK_OBJECT_CLASS
class = CKO_PRIVATE_KEY
;
574 attributes_buffer
[n_attributes
++] = (CK_ATTRIBUTE
) {
576 .pValue
= (CK_OBJECT_CLASS
*) &class,
577 .ulValueLen
= sizeof(class),
581 if (!found_key_type
) {
582 static const CK_KEY_TYPE type
= CKK_RSA
;
584 attributes_buffer
[n_attributes
++] = (CK_ATTRIBUTE
) {
585 .type
= CKA_KEY_TYPE
,
586 .pValue
= (CK_KEY_TYPE
*) &type
,
587 .ulValueLen
= sizeof(type
),
591 attributes
= attributes_buffer
;
594 rv
= m
->C_FindObjectsInit(session
, attributes
, n_attributes
);
596 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
597 "Failed to initialize object find call: %s", p11_kit_strerror(rv
));
599 rv
= m
->C_FindObjects(session
, objects
, ELEMENTSOF(objects
), &n_objects
);
600 rv2
= m
->C_FindObjectsFinal(session
);
602 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
603 "Failed to find objects: %s", p11_kit_strerror(rv
));
605 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
606 "Failed to finalize object find call: %s", p11_kit_strerror(rv
));
608 return log_error_errno(SYNTHETIC_ERRNO(ENOENT
),
609 "Failed to find selected private key suitable for decryption on token.");
611 return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ
),
612 "Configured private key URI matches multiple keys, refusing.");
614 *ret_object
= objects
[0];
618 int pkcs11_token_decrypt_data(
620 CK_SESSION_HANDLE session
,
621 CK_OBJECT_HANDLE object
,
622 const void *encrypted_data
,
623 size_t encrypted_data_size
,
624 void **ret_decrypted_data
,
625 size_t *ret_decrypted_data_size
) {
627 static const CK_MECHANISM mechanism
= {
628 .mechanism
= CKM_RSA_PKCS
630 _cleanup_(erase_and_freep
) CK_BYTE
*dbuffer
= NULL
;
631 CK_ULONG dbuffer_size
= 0;
635 assert(encrypted_data
);
636 assert(encrypted_data_size
> 0);
637 assert(ret_decrypted_data
);
638 assert(ret_decrypted_data_size
);
640 rv
= m
->C_DecryptInit(session
, (CK_MECHANISM
*) &mechanism
, object
);
642 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
643 "Failed to initialize decryption on security token: %s", p11_kit_strerror(rv
));
645 dbuffer_size
= encrypted_data_size
; /* Start with something reasonable */
646 dbuffer
= malloc(dbuffer_size
);
650 rv
= m
->C_Decrypt(session
, (CK_BYTE
*) encrypted_data
, encrypted_data_size
, dbuffer
, &dbuffer_size
);
651 if (rv
== CKR_BUFFER_TOO_SMALL
) {
652 erase_and_free(dbuffer
);
654 dbuffer
= malloc(dbuffer_size
);
658 rv
= m
->C_Decrypt(session
, (CK_BYTE
*) encrypted_data
, encrypted_data_size
, dbuffer
, &dbuffer_size
);
661 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
662 "Failed to decrypt key on security token: %s", p11_kit_strerror(rv
));
664 log_info("Successfully decrypted key with security token.");
666 *ret_decrypted_data
= TAKE_PTR(dbuffer
);
667 *ret_decrypted_data_size
= dbuffer_size
;
671 int pkcs11_token_acquire_rng(
673 CK_SESSION_HANDLE session
) {
675 _cleanup_free_
void *buffer
= NULL
;
682 /* While we are at it, let's read some RNG data from the PKCS#11 token and pass it to the kernel
683 * random pool. This should be cheap if we are talking to the device already. Note that we don't
684 * credit any entropy, since we don't know about the quality of the pkcs#11 token's RNG. Why bother
685 * at all? There are two sides to the argument whether to generate private keys on tokens or on the
686 * host. By crediting some data from the token RNG to the host's pool we at least can say that any
687 * key generated from it is at least as good as both sources individually. */
689 rps
= random_pool_size();
691 buffer
= malloc(rps
);
695 rv
= m
->C_GenerateRandom(session
, buffer
, rps
);
697 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
698 "Failed to generate RNG data on security token: %s", p11_kit_strerror(rv
));
700 r
= random_write_entropy(-1, buffer
, rps
, false);
702 return log_debug_errno(r
, "Failed to write PKCS#11 acquired random data to /dev/urandom: %m");
704 log_debug("Successfully written %zu bytes random data acquired via PKCS#11 to kernel random pool.", rps
);
709 static int token_process(
712 const CK_SLOT_INFO
*slot_info
,
713 const CK_TOKEN_INFO
*token_info
,
714 P11KitUri
*search_uri
,
715 pkcs11_find_token_callback_t callback
,
718 _cleanup_free_
char *token_label
= NULL
;
719 CK_SESSION_HANDLE session
;
727 token_label
= pkcs11_token_label(token_info
);
731 rv
= m
->C_OpenSession(slotid
, CKF_SERIAL_SESSION
, NULL
, NULL
, &session
);
733 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
734 "Failed to create session for security token '%s': %s", token_label
, p11_kit_strerror(rv
));
737 r
= callback(m
, session
, slotid
, slot_info
, token_info
, search_uri
, userdata
);
739 r
= 1; /* if not callback was specified, just say we found what we were looking for */
741 rv
= m
->C_CloseSession(session
);
743 log_warning("Failed to close session on PKCS#11 token, ignoring: %s", p11_kit_strerror(rv
));
748 static int slot_process(
751 P11KitUri
*search_uri
,
752 pkcs11_find_token_callback_t callback
,
755 _cleanup_(p11_kit_uri_freep
) P11KitUri
* slot_uri
= NULL
, *token_uri
= NULL
;
756 _cleanup_free_
char *token_uri_string
= NULL
;
757 CK_TOKEN_INFO token_info
;
758 CK_SLOT_INFO slot_info
;
764 /* We return -EAGAIN for all failures we can attribute to a specific slot in some way, so that the
765 * caller might try other slots before giving up. */
767 rv
= m
->C_GetSlotInfo(slotid
, &slot_info
);
769 log_warning("Failed to acquire slot info for slot %lu, ignoring slot: %s", slotid
, p11_kit_strerror(rv
));
773 slot_uri
= uri_from_slot_info(&slot_info
);
778 _cleanup_free_
char *slot_uri_string
= NULL
;
780 uri_result
= p11_kit_uri_format(slot_uri
, P11_KIT_URI_FOR_ANY
, &slot_uri_string
);
781 if (uri_result
!= P11_KIT_URI_OK
) {
782 log_warning("Failed to format slot URI, ignoring slot: %s", p11_kit_uri_message(uri_result
));
786 log_debug("Found slot with URI %s", slot_uri_string
);
789 rv
= m
->C_GetTokenInfo(slotid
, &token_info
);
790 if (rv
== CKR_TOKEN_NOT_PRESENT
) {
791 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN
),
792 "Token not present in slot, ignoring.");
793 } else if (rv
!= CKR_OK
) {
794 log_warning("Failed to acquire token info for slot %lu, ignoring slot: %s", slotid
, p11_kit_strerror(rv
));
798 token_uri
= uri_from_token_info(&token_info
);
802 uri_result
= p11_kit_uri_format(token_uri
, P11_KIT_URI_FOR_ANY
, &token_uri_string
);
803 if (uri_result
!= P11_KIT_URI_OK
) {
804 log_warning("Failed to format slot URI: %s", p11_kit_uri_message(uri_result
));
808 if (search_uri
&& !p11_kit_uri_match_token_info(search_uri
, &token_info
))
809 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN
),
810 "Found non-matching token with URI %s.",
813 log_debug("Found matching token with URI %s.", token_uri_string
);
815 return token_process(
825 static int module_process(
827 P11KitUri
*search_uri
,
828 pkcs11_find_token_callback_t callback
,
831 _cleanup_free_
char *name
= NULL
, *module_uri_string
= NULL
;
832 _cleanup_(p11_kit_uri_freep
) P11KitUri
* module_uri
= NULL
;
833 _cleanup_free_ CK_SLOT_ID
*slotids
= NULL
;
834 CK_ULONG n_slotids
= 0;
843 /* We ignore most errors from modules here, in order to skip over faulty modules: one faulty module
844 * should not have the effect that we don't try the others anymore. We indicate such per-module
845 * failures with -EAGAIN, which let's the caller try the next module. */
847 name
= p11_kit_module_get_name(m
);
851 log_debug("Trying PKCS#11 module %s.", name
);
853 rv
= m
->C_GetInfo(&info
);
855 log_warning("Failed to get info on PKCS#11 module, ignoring module: %s", p11_kit_strerror(rv
));
859 module_uri
= uri_from_module_info(&info
);
863 uri_result
= p11_kit_uri_format(module_uri
, P11_KIT_URI_FOR_ANY
, &module_uri_string
);
864 if (uri_result
!= P11_KIT_URI_OK
) {
865 log_warning("Failed to format module URI, ignoring module: %s", p11_kit_uri_message(uri_result
));
869 log_debug("Found module with URI %s", module_uri_string
);
871 rv
= pkcs11_get_slot_list_malloc(m
, &slotids
, &n_slotids
);
873 log_warning("Failed to get slot list, ignoring module: %s", p11_kit_strerror(rv
));
877 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN
),
878 "This module has no slots? Ignoring module.");
880 for (k
= 0; k
< n_slotids
; k
++) {
894 int pkcs11_find_token(
895 const char *pkcs11_uri
,
896 pkcs11_find_token_callback_t callback
,
899 _cleanup_(p11_kit_modules_finalize_and_releasep
) CK_FUNCTION_LIST
**modules
= NULL
;
900 _cleanup_(p11_kit_uri_freep
) P11KitUri
*search_uri
= NULL
;
903 /* Execute the specified callback for each matching token found. If nothing is found returns
904 * -EAGAIN. Logs about all errors, except for EAGAIN, which the caller has to log about. */
907 r
= uri_from_string(pkcs11_uri
, &search_uri
);
909 return log_error_errno(r
, "Failed to parse PKCS#11 URI '%s': %m", pkcs11_uri
);
912 modules
= p11_kit_modules_load_and_initialize(0);
914 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to initialize pkcs11 modules");
916 for (CK_FUNCTION_LIST
**i
= modules
; *i
; i
++) {
930 struct pkcs11_acquire_certificate_callback_data
{
933 const char *askpw_friendly_name
, *askpw_icon_name
;
936 static void pkcs11_acquire_certificate_callback_data_release(struct pkcs11_acquire_certificate_callback_data
*data
) {
937 erase_and_free(data
->pin_used
);
938 X509_free(data
->cert
);
941 static int pkcs11_acquire_certificate_callback(
943 CK_SESSION_HANDLE session
,
945 const CK_SLOT_INFO
*slot_info
,
946 const CK_TOKEN_INFO
*token_info
,
950 _cleanup_(erase_and_freep
) char *pin_used
= NULL
;
951 struct pkcs11_acquire_certificate_callback_data
*data
= userdata
;
952 CK_OBJECT_HANDLE object
;
961 /* Called for every token matching our URI */
963 r
= pkcs11_token_login(m
, session
, slot_id
, token_info
, data
->askpw_friendly_name
, data
->askpw_icon_name
, "pkcs11-pin", "pkcs11-pin", UINT64_MAX
, &pin_used
);
967 r
= pkcs11_token_find_x509_certificate(m
, session
, uri
, &object
);
971 r
= pkcs11_token_read_x509_certificate(m
, session
, object
, &data
->cert
);
975 /* Let's read some random data off the token and write it to the kernel pool before we generate our
976 * random key from it. This way we can claim the quality of the RNG is at least as good as the
977 * kernel's and the token's pool */
978 (void) pkcs11_token_acquire_rng(m
, session
);
980 data
->pin_used
= TAKE_PTR(pin_used
);
984 int pkcs11_acquire_certificate(
986 const char *askpw_friendly_name
,
987 const char *askpw_icon_name
,
989 char **ret_pin_used
) {
991 _cleanup_(pkcs11_acquire_certificate_callback_data_release
) struct pkcs11_acquire_certificate_callback_data data
= {
992 .askpw_friendly_name
= askpw_friendly_name
,
993 .askpw_icon_name
= askpw_icon_name
,
1000 r
= pkcs11_find_token(uri
, pkcs11_acquire_certificate_callback
, &data
);
1001 if (r
== -EAGAIN
) /* pkcs11_find_token() doesn't log about this error, but all others */
1002 return log_error_errno(SYNTHETIC_ERRNO(ENXIO
),
1003 "Specified PKCS#11 token with URI '%s' not found.",
1008 *ret_cert
= TAKE_PTR(data
.cert
);
1011 *ret_pin_used
= TAKE_PTR(data
.pin_used
);
1017 static int list_callback(
1018 CK_FUNCTION_LIST
*m
,
1019 CK_SESSION_HANDLE session
,
1021 const CK_SLOT_INFO
*slot_info
,
1022 const CK_TOKEN_INFO
*token_info
,
1026 _cleanup_free_
char *token_uri_string
= NULL
, *token_label
= NULL
, *token_manufacturer_id
= NULL
, *token_model
= NULL
;
1027 _cleanup_(p11_kit_uri_freep
) P11KitUri
*token_uri
= NULL
;
1028 Table
*t
= userdata
;
1034 /* We only care about hardware devices here with a token inserted. Let's filter everything else
1035 * out. (Note that the user can explicitly specify non-hardware tokens if they like, but during
1036 * enumeration we'll filter those, since software tokens are typically the system certificate store
1037 * and such, and it's typically not what people want to bind their home directories to.) */
1038 if (!FLAGS_SET(token_info
->flags
, CKF_HW_SLOT
|CKF_TOKEN_PRESENT
))
1041 token_label
= pkcs11_token_label(token_info
);
1045 token_manufacturer_id
= pkcs11_token_manufacturer_id(token_info
);
1046 if (!token_manufacturer_id
)
1049 token_model
= pkcs11_token_model(token_info
);
1053 token_uri
= uri_from_token_info(token_info
);
1057 uri_result
= p11_kit_uri_format(token_uri
, P11_KIT_URI_FOR_ANY
, &token_uri_string
);
1058 if (uri_result
!= P11_KIT_URI_OK
)
1059 return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN
), "Failed to format slot URI: %s", p11_kit_uri_message(uri_result
));
1063 TABLE_STRING
, token_uri_string
,
1064 TABLE_STRING
, token_label
,
1065 TABLE_STRING
, token_manufacturer_id
,
1066 TABLE_STRING
, token_model
);
1068 return table_log_add_error(r
);
1070 return -EAGAIN
; /* keep scanning */
1074 int pkcs11_list_tokens(void) {
1076 _cleanup_(table_unrefp
) Table
*t
= NULL
;
1079 t
= table_new("uri", "label", "manufacturer", "model");
1083 r
= pkcs11_find_token(NULL
, list_callback
, t
);
1084 if (r
< 0 && r
!= -EAGAIN
)
1087 if (table_get_rows(t
) <= 1) {
1088 log_info("No suitable PKCS#11 tokens found.");
1092 r
= table_print(t
, stdout
);
1094 return log_error_errno(r
, "Failed to show device table: %m");
1098 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
1099 "PKCS#11 tokens not supported on this build.");
1104 static int auto_callback(
1105 CK_FUNCTION_LIST
*m
,
1106 CK_SESSION_HANDLE session
,
1108 const CK_SLOT_INFO
*slot_info
,
1109 const CK_TOKEN_INFO
*token_info
,
1113 _cleanup_(p11_kit_uri_freep
) P11KitUri
*token_uri
= NULL
;
1114 char **t
= userdata
;
1120 if (!FLAGS_SET(token_info
->flags
, CKF_HW_SLOT
|CKF_TOKEN_PRESENT
))
1124 return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ
),
1125 "More than one suitable PKCS#11 token found.");
1127 token_uri
= uri_from_token_info(token_info
);
1131 uri_result
= p11_kit_uri_format(token_uri
, P11_KIT_URI_FOR_ANY
, t
);
1132 if (uri_result
!= P11_KIT_URI_OK
)
1133 return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN
), "Failed to format slot URI: %s", p11_kit_uri_message(uri_result
));
1139 int pkcs11_find_token_auto(char **ret
) {
1143 r
= pkcs11_find_token(NULL
, auto_callback
, ret
);
1145 return log_error_errno(SYNTHETIC_ERRNO(ENODEV
), "No suitable PKCS#11 tokens found.");
1151 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
1152 "PKCS#11 tokens not supported on this build.");