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
,
186 char **ret_used_pin
) {
188 _cleanup_free_
char *token_uri_string
= NULL
, *token_uri_escaped
= NULL
, *id
= NULL
, *token_label
= NULL
;
189 _cleanup_(p11_kit_uri_freep
) P11KitUri
*token_uri
= NULL
;
190 CK_TOKEN_INFO updated_token_info
;
197 token_label
= pkcs11_token_label(token_info
);
201 token_uri
= uri_from_token_info(token_info
);
205 uri_result
= p11_kit_uri_format(token_uri
, P11_KIT_URI_FOR_ANY
, &token_uri_string
);
206 if (uri_result
!= P11_KIT_URI_OK
)
207 return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN
), "Failed to format slot URI: %s", p11_kit_uri_message(uri_result
));
209 if (FLAGS_SET(token_info
->flags
, CKF_PROTECTED_AUTHENTICATION_PATH
)) {
210 rv
= m
->C_Login(session
, CKU_USER
, NULL
, 0);
212 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
213 "Failed to log into security token '%s': %s", token_label
, p11_kit_strerror(rv
));
215 log_info("Successfully logged into security token '%s' via protected authentication path.", token_label
);
217 *ret_used_pin
= NULL
;
221 if (!FLAGS_SET(token_info
->flags
, CKF_LOGIN_REQUIRED
)) {
222 log_info("No login into security token '%s' required.", token_label
);
224 *ret_used_pin
= NULL
;
228 token_uri_escaped
= cescape(token_uri_string
);
229 if (!token_uri_escaped
)
232 id
= strjoin("pkcs11:", token_uri_escaped
);
236 for (unsigned tries
= 0; tries
< 3; tries
++) {
237 _cleanup_strv_free_erase_
char **passwords
= NULL
;
242 passwords
= strv_new(e
);
247 if (unsetenv("PIN") < 0)
248 return log_error_errno(errno
, "Failed to unset $PIN: %m");
250 _cleanup_free_
char *text
= NULL
;
252 if (FLAGS_SET(token_info
->flags
, CKF_USER_PIN_FINAL_TRY
))
254 "Please enter correct PIN for security token '%s' in order to unlock %s (final try):",
255 token_label
, friendly_name
);
256 else if (FLAGS_SET(token_info
->flags
, CKF_USER_PIN_COUNT_LOW
))
258 "PIN has been entered incorrectly previously, please enter correct PIN for security token '%s' in order to unlock %s:",
259 token_label
, friendly_name
);
262 "Please enter PIN for security token '%s' in order to unlock %s:",
263 token_label
, friendly_name
);
266 "Please enter PIN for security token '%s' in order to unlock %s (try #%u):",
267 token_label
, friendly_name
, tries
+1);
271 /* We never cache PINs, simply because it's fatal if we use wrong PINs, since usually there are only 3 tries */
272 r
= ask_password_auto(text
, icon_name
, id
, keyname
, until
, 0, &passwords
);
274 return log_error_errno(r
, "Failed to query PIN for security token '%s': %m", token_label
);
277 STRV_FOREACH(i
, passwords
) {
278 rv
= m
->C_Login(session
, CKU_USER
, (CK_UTF8CHAR
*) *i
, strlen(*i
));
291 log_info("Successfully logged into security token '%s'.", token_label
);
294 if (rv
== CKR_PIN_LOCKED
)
295 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
296 "PIN has been locked, please reset PIN of security token '%s'.", token_label
);
297 if (!IN_SET(rv
, CKR_PIN_INCORRECT
, CKR_PIN_LEN_RANGE
))
298 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
299 "Failed to log into security token '%s': %s", token_label
, p11_kit_strerror(rv
));
301 /* Referesh the token info, so that we can prompt knowing the new flags if they changed. */
302 rv
= m
->C_GetTokenInfo(slotid
, &updated_token_info
);
304 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
305 "Failed to acquire updated security token information for slot %lu: %s",
306 slotid
, p11_kit_strerror(rv
));
308 token_info
= &updated_token_info
;
309 log_notice("PIN for token '%s' is incorrect, please try again.", token_label
);
313 return log_error_errno(SYNTHETIC_ERRNO(EPERM
), "Too many attempts to log into token '%s'.", token_label
);
316 int pkcs11_token_find_x509_certificate(
318 CK_SESSION_HANDLE session
,
319 P11KitUri
*search_uri
,
320 CK_OBJECT_HANDLE
*ret_object
) {
322 bool found_class
= false, found_certificate_type
= false;
323 _cleanup_free_ CK_ATTRIBUTE
*attributes_buffer
= NULL
;
324 CK_ULONG n_attributes
, a
, n_objects
;
325 CK_ATTRIBUTE
*attributes
= NULL
;
326 CK_OBJECT_HANDLE objects
[2];
333 attributes
= p11_kit_uri_get_attributes(search_uri
, &n_attributes
);
334 for (a
= 0; a
< n_attributes
; a
++) {
336 /* We use the URI's included match attributes, but make them more strict. This allows users
337 * to specify a token URL instead of an object URL and the right thing should happen if
338 * there's only one suitable key on the token. */
340 switch (attributes
[a
].type
) {
345 if (attributes
[a
].ulValueLen
!= sizeof(c
))
346 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid PKCS#11 CKA_CLASS attribute size.");
348 memcpy(&c
, attributes
[a
].pValue
, sizeof(c
));
349 if (c
!= CKO_CERTIFICATE
)
350 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Selected PKCS#11 object is not an X.509 certificate, refusing.");
356 case CKA_CERTIFICATE_TYPE
: {
357 CK_CERTIFICATE_TYPE t
;
359 if (attributes
[a
].ulValueLen
!= sizeof(t
))
360 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid PKCS#11 CKA_CERTIFICATE_TYPE attribute size.");
362 memcpy(&t
, attributes
[a
].pValue
, sizeof(t
));
364 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Selected PKCS#11 object is not an X.509 certificate, refusing.");
366 found_certificate_type
= true;
371 if (!found_class
|| !found_certificate_type
) {
372 /* Hmm, let's slightly extend the attribute list we search for */
374 attributes_buffer
= new(CK_ATTRIBUTE
, n_attributes
+ !found_class
+ !found_certificate_type
);
375 if (!attributes_buffer
)
378 memcpy(attributes_buffer
, attributes
, sizeof(CK_ATTRIBUTE
) * n_attributes
);
381 static const CK_OBJECT_CLASS
class = CKO_CERTIFICATE
;
383 attributes_buffer
[n_attributes
++] = (CK_ATTRIBUTE
) {
385 .pValue
= (CK_OBJECT_CLASS
*) &class,
386 .ulValueLen
= sizeof(class),
390 if (!found_certificate_type
) {
391 static const CK_CERTIFICATE_TYPE type
= CKC_X_509
;
393 attributes_buffer
[n_attributes
++] = (CK_ATTRIBUTE
) {
394 .type
= CKA_CERTIFICATE_TYPE
,
395 .pValue
= (CK_CERTIFICATE_TYPE
*) &type
,
396 .ulValueLen
= sizeof(type
),
400 attributes
= attributes_buffer
;
403 rv
= m
->C_FindObjectsInit(session
, attributes
, n_attributes
);
405 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
406 "Failed to initialize object find call: %s", p11_kit_strerror(rv
));
408 rv
= m
->C_FindObjects(session
, objects
, ELEMENTSOF(objects
), &n_objects
);
409 rv2
= m
->C_FindObjectsFinal(session
);
411 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
412 "Failed to find objects: %s", p11_kit_strerror(rv
));
414 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
415 "Failed to finalize object find call: %s", p11_kit_strerror(rv
));
417 return log_error_errno(SYNTHETIC_ERRNO(ENOENT
),
418 "Failed to find selected X509 certificate on token.");
420 return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ
),
421 "Configured URI matches multiple certificates, refusing.");
423 *ret_object
= objects
[0];
428 int pkcs11_token_read_x509_certificate(
430 CK_SESSION_HANDLE session
,
431 CK_OBJECT_HANDLE object
,
434 _cleanup_free_
void *buffer
= NULL
;
435 _cleanup_free_
char *t
= NULL
;
436 CK_ATTRIBUTE attribute
= {
440 _cleanup_(X509_freep
) X509
*x509
= NULL
;
441 X509_NAME
*name
= NULL
;
442 const unsigned char *p
;
444 rv
= m
->C_GetAttributeValue(session
, object
, &attribute
, 1);
446 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
447 "Failed to read X.509 certificate size off token: %s", p11_kit_strerror(rv
));
449 buffer
= malloc(attribute
.ulValueLen
);
453 attribute
.pValue
= buffer
;
455 rv
= m
->C_GetAttributeValue(session
, object
, &attribute
, 1);
457 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
458 "Failed to read X.509 certificate data off token: %s", p11_kit_strerror(rv
));
460 p
= attribute
.pValue
;
461 x509
= d2i_X509(NULL
, &p
, attribute
.ulValueLen
);
463 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Failed parse X.509 certificate.");
465 name
= X509_get_subject_name(x509
);
467 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "Failed to acquire X.509 subject name.");
469 t
= X509_NAME_oneline(name
, NULL
, 0);
471 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to format X.509 subject name as string.");
473 log_debug("Using X.509 certificate issued for '%s'.", t
);
475 *ret_cert
= TAKE_PTR(x509
);
480 int pkcs11_token_find_private_key(
482 CK_SESSION_HANDLE session
,
483 P11KitUri
*search_uri
,
484 CK_OBJECT_HANDLE
*ret_object
) {
486 bool found_decrypt
= false, found_class
= false, found_key_type
= false;
487 _cleanup_free_ CK_ATTRIBUTE
*attributes_buffer
= NULL
;
488 CK_ULONG n_attributes
, a
, n_objects
;
489 CK_ATTRIBUTE
*attributes
= NULL
;
490 CK_OBJECT_HANDLE objects
[2];
497 attributes
= p11_kit_uri_get_attributes(search_uri
, &n_attributes
);
498 for (a
= 0; a
< n_attributes
; a
++) {
500 /* We use the URI's included match attributes, but make them more strict. This allows users
501 * to specify a token URL instead of an object URL and the right thing should happen if
502 * there's only one suitable key on the token. */
504 switch (attributes
[a
].type
) {
509 if (attributes
[a
].ulValueLen
!= sizeof(c
))
510 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid PKCS#11 CKA_CLASS attribute size.");
512 memcpy(&c
, attributes
[a
].pValue
, sizeof(c
));
513 if (c
!= CKO_PRIVATE_KEY
)
514 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
515 "Selected PKCS#11 object is not a private key, refusing.");
524 if (attributes
[a
].ulValueLen
!= sizeof(b
))
525 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid PKCS#11 CKA_DECRYPT attribute size.");
527 memcpy(&b
, attributes
[a
].pValue
, sizeof(b
));
529 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
530 "Selected PKCS#11 object is not suitable for decryption, refusing.");
532 found_decrypt
= true;
539 if (attributes
[a
].ulValueLen
!= sizeof(t
))
540 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid PKCS#11 CKA_KEY_TYPE attribute size.");
542 memcpy(&t
, attributes
[a
].pValue
, sizeof(t
));
544 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Selected PKCS#11 object is not an RSA key, refusing.");
546 found_key_type
= true;
551 if (!found_decrypt
|| !found_class
|| !found_key_type
) {
552 /* Hmm, let's slightly extend the attribute list we search for */
554 attributes_buffer
= new(CK_ATTRIBUTE
, n_attributes
+ !found_decrypt
+ !found_class
+ !found_key_type
);
555 if (!attributes_buffer
)
558 memcpy(attributes_buffer
, attributes
, sizeof(CK_ATTRIBUTE
) * n_attributes
);
560 if (!found_decrypt
) {
561 static const CK_BBOOL yes
= true;
563 attributes_buffer
[n_attributes
++] = (CK_ATTRIBUTE
) {
565 .pValue
= (CK_BBOOL
*) &yes
,
566 .ulValueLen
= sizeof(yes
),
571 static const CK_OBJECT_CLASS
class = CKO_PRIVATE_KEY
;
573 attributes_buffer
[n_attributes
++] = (CK_ATTRIBUTE
) {
575 .pValue
= (CK_OBJECT_CLASS
*) &class,
576 .ulValueLen
= sizeof(class),
580 if (!found_key_type
) {
581 static const CK_KEY_TYPE type
= CKK_RSA
;
583 attributes_buffer
[n_attributes
++] = (CK_ATTRIBUTE
) {
584 .type
= CKA_KEY_TYPE
,
585 .pValue
= (CK_KEY_TYPE
*) &type
,
586 .ulValueLen
= sizeof(type
),
590 attributes
= attributes_buffer
;
593 rv
= m
->C_FindObjectsInit(session
, attributes
, n_attributes
);
595 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
596 "Failed to initialize object find call: %s", p11_kit_strerror(rv
));
598 rv
= m
->C_FindObjects(session
, objects
, ELEMENTSOF(objects
), &n_objects
);
599 rv2
= m
->C_FindObjectsFinal(session
);
601 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
602 "Failed to find objects: %s", p11_kit_strerror(rv
));
604 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
605 "Failed to finalize object find call: %s", p11_kit_strerror(rv
));
607 return log_error_errno(SYNTHETIC_ERRNO(ENOENT
),
608 "Failed to find selected private key suitable for decryption on token.");
610 return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ
),
611 "Configured private key URI matches multiple keys, refusing.");
613 *ret_object
= objects
[0];
617 int pkcs11_token_decrypt_data(
619 CK_SESSION_HANDLE session
,
620 CK_OBJECT_HANDLE object
,
621 const void *encrypted_data
,
622 size_t encrypted_data_size
,
623 void **ret_decrypted_data
,
624 size_t *ret_decrypted_data_size
) {
626 static const CK_MECHANISM mechanism
= {
627 .mechanism
= CKM_RSA_PKCS
629 _cleanup_(erase_and_freep
) CK_BYTE
*dbuffer
= NULL
;
630 CK_ULONG dbuffer_size
= 0;
634 assert(encrypted_data
);
635 assert(encrypted_data_size
> 0);
636 assert(ret_decrypted_data
);
637 assert(ret_decrypted_data_size
);
639 rv
= m
->C_DecryptInit(session
, (CK_MECHANISM
*) &mechanism
, object
);
641 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
642 "Failed to initialize decryption on security token: %s", p11_kit_strerror(rv
));
644 dbuffer_size
= encrypted_data_size
; /* Start with something reasonable */
645 dbuffer
= malloc(dbuffer_size
);
649 rv
= m
->C_Decrypt(session
, (CK_BYTE
*) encrypted_data
, encrypted_data_size
, dbuffer
, &dbuffer_size
);
650 if (rv
== CKR_BUFFER_TOO_SMALL
) {
651 erase_and_free(dbuffer
);
653 dbuffer
= malloc(dbuffer_size
);
657 rv
= m
->C_Decrypt(session
, (CK_BYTE
*) encrypted_data
, encrypted_data_size
, dbuffer
, &dbuffer_size
);
660 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
661 "Failed to decrypt key on security token: %s", p11_kit_strerror(rv
));
663 log_info("Successfully decrypted key with security token.");
665 *ret_decrypted_data
= TAKE_PTR(dbuffer
);
666 *ret_decrypted_data_size
= dbuffer_size
;
670 int pkcs11_token_acquire_rng(
672 CK_SESSION_HANDLE session
) {
674 _cleanup_free_
void *buffer
= NULL
;
681 /* While we are at it, let's read some RNG data from the PKCS#11 token and pass it to the kernel
682 * random pool. This should be cheap if we are talking to the device already. Note that we don't
683 * credit any entropy, since we don't know about the quality of the pkcs#11 token's RNG. Why bother
684 * at all? There are two sides to the argument whether to generate private keys on tokens or on the
685 * host. By crediting some data from the token RNG to the host's pool we at least can say that any
686 * key generated from it is at least as good as both sources individually. */
688 rps
= random_pool_size();
690 buffer
= malloc(rps
);
694 rv
= m
->C_GenerateRandom(session
, buffer
, rps
);
696 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
697 "Failed to generate RNG data on security token: %s", p11_kit_strerror(rv
));
699 r
= random_write_entropy(-1, buffer
, rps
, false);
701 return log_debug_errno(r
, "Failed to write PKCS#11 acquired random data to /dev/urandom: %m");
703 log_debug("Successfully written %zu bytes random data acquired via PKCS#11 to kernel random pool.", rps
);
708 static int token_process(
711 const CK_SLOT_INFO
*slot_info
,
712 const CK_TOKEN_INFO
*token_info
,
713 P11KitUri
*search_uri
,
714 pkcs11_find_token_callback_t callback
,
717 _cleanup_free_
char *token_label
= NULL
;
718 CK_SESSION_HANDLE session
;
726 token_label
= pkcs11_token_label(token_info
);
730 rv
= m
->C_OpenSession(slotid
, CKF_SERIAL_SESSION
, NULL
, NULL
, &session
);
732 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
733 "Failed to create session for security token '%s': %s", token_label
, p11_kit_strerror(rv
));
736 r
= callback(m
, session
, slotid
, slot_info
, token_info
, search_uri
, userdata
);
738 r
= 1; /* if not callback was specified, just say we found what we were looking for */
740 rv
= m
->C_CloseSession(session
);
742 log_warning("Failed to close session on PKCS#11 token, ignoring: %s", p11_kit_strerror(rv
));
747 static int slot_process(
750 P11KitUri
*search_uri
,
751 pkcs11_find_token_callback_t callback
,
754 _cleanup_(p11_kit_uri_freep
) P11KitUri
* slot_uri
= NULL
, *token_uri
= NULL
;
755 _cleanup_free_
char *token_uri_string
= NULL
;
756 CK_TOKEN_INFO token_info
;
757 CK_SLOT_INFO slot_info
;
763 /* We return -EAGAIN for all failures we can attribute to a specific slot in some way, so that the
764 * caller might try other slots before giving up. */
766 rv
= m
->C_GetSlotInfo(slotid
, &slot_info
);
768 log_warning("Failed to acquire slot info for slot %lu, ignoring slot: %s", slotid
, p11_kit_strerror(rv
));
772 slot_uri
= uri_from_slot_info(&slot_info
);
777 _cleanup_free_
char *slot_uri_string
= NULL
;
779 uri_result
= p11_kit_uri_format(slot_uri
, P11_KIT_URI_FOR_ANY
, &slot_uri_string
);
780 if (uri_result
!= P11_KIT_URI_OK
) {
781 log_warning("Failed to format slot URI, ignoring slot: %s", p11_kit_uri_message(uri_result
));
785 log_debug("Found slot with URI %s", slot_uri_string
);
788 rv
= m
->C_GetTokenInfo(slotid
, &token_info
);
789 if (rv
== CKR_TOKEN_NOT_PRESENT
) {
790 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN
),
791 "Token not present in slot, ignoring.");
792 } else if (rv
!= CKR_OK
) {
793 log_warning("Failed to acquire token info for slot %lu, ignoring slot: %s", slotid
, p11_kit_strerror(rv
));
797 token_uri
= uri_from_token_info(&token_info
);
801 uri_result
= p11_kit_uri_format(token_uri
, P11_KIT_URI_FOR_ANY
, &token_uri_string
);
802 if (uri_result
!= P11_KIT_URI_OK
) {
803 log_warning("Failed to format slot URI: %s", p11_kit_uri_message(uri_result
));
807 if (search_uri
&& !p11_kit_uri_match_token_info(search_uri
, &token_info
))
808 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN
),
809 "Found non-matching token with URI %s.",
812 log_debug("Found matching token with URI %s.", token_uri_string
);
814 return token_process(
824 static int module_process(
826 P11KitUri
*search_uri
,
827 pkcs11_find_token_callback_t callback
,
830 _cleanup_free_
char *name
= NULL
, *module_uri_string
= NULL
;
831 _cleanup_(p11_kit_uri_freep
) P11KitUri
* module_uri
= NULL
;
832 _cleanup_free_ CK_SLOT_ID
*slotids
= NULL
;
833 CK_ULONG n_slotids
= 0;
842 /* We ignore most errors from modules here, in order to skip over faulty modules: one faulty module
843 * should not have the effect that we don't try the others anymore. We indicate such per-module
844 * failures with -EAGAIN, which let's the caller try the next module. */
846 name
= p11_kit_module_get_name(m
);
850 log_debug("Trying PKCS#11 module %s.", name
);
852 rv
= m
->C_GetInfo(&info
);
854 log_warning("Failed to get info on PKCS#11 module, ignoring module: %s", p11_kit_strerror(rv
));
858 module_uri
= uri_from_module_info(&info
);
862 uri_result
= p11_kit_uri_format(module_uri
, P11_KIT_URI_FOR_ANY
, &module_uri_string
);
863 if (uri_result
!= P11_KIT_URI_OK
) {
864 log_warning("Failed to format module URI, ignoring module: %s", p11_kit_uri_message(uri_result
));
868 log_debug("Found module with URI %s", module_uri_string
);
870 rv
= pkcs11_get_slot_list_malloc(m
, &slotids
, &n_slotids
);
872 log_warning("Failed to get slot list, ignoring module: %s", p11_kit_strerror(rv
));
876 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN
),
877 "This module has no slots? Ignoring module.");
879 for (k
= 0; k
< n_slotids
; k
++) {
893 int pkcs11_find_token(
894 const char *pkcs11_uri
,
895 pkcs11_find_token_callback_t callback
,
898 _cleanup_(p11_kit_modules_finalize_and_releasep
) CK_FUNCTION_LIST
**modules
= NULL
;
899 _cleanup_(p11_kit_uri_freep
) P11KitUri
*search_uri
= NULL
;
902 /* Execute the specified callback for each matching token found. If nothing is found returns
903 * -EAGAIN. Logs about all errors, except for EAGAIN, which the caller has to log about. */
906 r
= uri_from_string(pkcs11_uri
, &search_uri
);
908 return log_error_errno(r
, "Failed to parse PKCS#11 URI '%s': %m", pkcs11_uri
);
911 modules
= p11_kit_modules_load_and_initialize(0);
913 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to initialize pkcs11 modules");
915 for (CK_FUNCTION_LIST
**i
= modules
; *i
; i
++) {
929 struct pkcs11_acquire_certificate_callback_data
{
932 const char *askpw_friendly_name
, *askpw_icon_name
;
935 static void pkcs11_acquire_certificate_callback_data_release(struct pkcs11_acquire_certificate_callback_data
*data
) {
936 erase_and_free(data
->pin_used
);
937 X509_free(data
->cert
);
940 static int pkcs11_acquire_certificate_callback(
942 CK_SESSION_HANDLE session
,
944 const CK_SLOT_INFO
*slot_info
,
945 const CK_TOKEN_INFO
*token_info
,
949 _cleanup_(erase_and_freep
) char *pin_used
= NULL
;
950 struct pkcs11_acquire_certificate_callback_data
*data
= userdata
;
951 CK_OBJECT_HANDLE object
;
960 /* Called for every token matching our URI */
962 r
= pkcs11_token_login(m
, session
, slot_id
, token_info
, data
->askpw_friendly_name
, data
->askpw_icon_name
, "pkcs11-pin", UINT64_MAX
, &pin_used
);
966 r
= pkcs11_token_find_x509_certificate(m
, session
, uri
, &object
);
970 r
= pkcs11_token_read_x509_certificate(m
, session
, object
, &data
->cert
);
974 /* Let's read some random data off the token and write it to the kernel pool before we generate our
975 * random key from it. This way we can claim the quality of the RNG is at least as good as the
976 * kernel's and the token's pool */
977 (void) pkcs11_token_acquire_rng(m
, session
);
979 data
->pin_used
= TAKE_PTR(pin_used
);
983 int pkcs11_acquire_certificate(
985 const char *askpw_friendly_name
,
986 const char *askpw_icon_name
,
988 char **ret_pin_used
) {
990 _cleanup_(pkcs11_acquire_certificate_callback_data_release
) struct pkcs11_acquire_certificate_callback_data data
= {
991 .askpw_friendly_name
= askpw_friendly_name
,
992 .askpw_icon_name
= askpw_icon_name
,
999 r
= pkcs11_find_token(uri
, pkcs11_acquire_certificate_callback
, &data
);
1000 if (r
== -EAGAIN
) /* pkcs11_find_token() doesn't log about this error, but all others */
1001 return log_error_errno(SYNTHETIC_ERRNO(ENXIO
),
1002 "Specified PKCS#11 token with URI '%s' not found.",
1007 *ret_cert
= TAKE_PTR(data
.cert
);
1010 *ret_pin_used
= TAKE_PTR(data
.pin_used
);
1016 static int list_callback(
1017 CK_FUNCTION_LIST
*m
,
1018 CK_SESSION_HANDLE session
,
1020 const CK_SLOT_INFO
*slot_info
,
1021 const CK_TOKEN_INFO
*token_info
,
1025 _cleanup_free_
char *token_uri_string
= NULL
, *token_label
= NULL
, *token_manufacturer_id
= NULL
, *token_model
= NULL
;
1026 _cleanup_(p11_kit_uri_freep
) P11KitUri
*token_uri
= NULL
;
1027 Table
*t
= userdata
;
1033 /* We only care about hardware devices here with a token inserted. Let's filter everything else
1034 * out. (Note that the user can explicitly specify non-hardware tokens if they like, but during
1035 * enumeration we'll filter those, since software tokens are typically the system certificate store
1036 * and such, and it's typically not what people want to bind their home directories to.) */
1037 if (!FLAGS_SET(token_info
->flags
, CKF_HW_SLOT
|CKF_TOKEN_PRESENT
))
1040 token_label
= pkcs11_token_label(token_info
);
1044 token_manufacturer_id
= pkcs11_token_manufacturer_id(token_info
);
1045 if (!token_manufacturer_id
)
1048 token_model
= pkcs11_token_model(token_info
);
1052 token_uri
= uri_from_token_info(token_info
);
1056 uri_result
= p11_kit_uri_format(token_uri
, P11_KIT_URI_FOR_ANY
, &token_uri_string
);
1057 if (uri_result
!= P11_KIT_URI_OK
)
1058 return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN
), "Failed to format slot URI: %s", p11_kit_uri_message(uri_result
));
1062 TABLE_STRING
, token_uri_string
,
1063 TABLE_STRING
, token_label
,
1064 TABLE_STRING
, token_manufacturer_id
,
1065 TABLE_STRING
, token_model
);
1067 return table_log_add_error(r
);
1069 return -EAGAIN
; /* keep scanning */
1073 int pkcs11_list_tokens(void) {
1075 _cleanup_(table_unrefp
) Table
*t
= NULL
;
1078 t
= table_new("uri", "label", "manufacturer", "model");
1082 r
= pkcs11_find_token(NULL
, list_callback
, t
);
1083 if (r
< 0 && r
!= -EAGAIN
)
1086 if (table_get_rows(t
) <= 1) {
1087 log_info("No suitable PKCS#11 tokens found.");
1091 r
= table_print(t
, stdout
);
1093 return log_error_errno(r
, "Failed to show device table: %m");
1097 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
1098 "PKCS#11 tokens not supported on this build.");
1103 static int auto_callback(
1104 CK_FUNCTION_LIST
*m
,
1105 CK_SESSION_HANDLE session
,
1107 const CK_SLOT_INFO
*slot_info
,
1108 const CK_TOKEN_INFO
*token_info
,
1112 _cleanup_(p11_kit_uri_freep
) P11KitUri
*token_uri
= NULL
;
1113 char **t
= userdata
;
1119 if (!FLAGS_SET(token_info
->flags
, CKF_HW_SLOT
|CKF_TOKEN_PRESENT
))
1123 return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ
),
1124 "More than one suitable PKCS#11 token found.");
1126 token_uri
= uri_from_token_info(token_info
);
1130 uri_result
= p11_kit_uri_format(token_uri
, P11_KIT_URI_FOR_ANY
, t
);
1131 if (uri_result
!= P11_KIT_URI_OK
)
1132 return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN
), "Failed to format slot URI: %s", p11_kit_uri_message(uri_result
));
1138 int pkcs11_find_token_auto(char **ret
) {
1142 r
= pkcs11_find_token(NULL
, auto_callback
, ret
);
1144 return log_error_errno(SYNTHETIC_ERRNO(ENODEV
), "No suitable PKCS#11 tokens found.");
1150 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
1151 "PKCS#11 tokens not supported on this build.");