1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 #include "errno-util.h"
4 #include "format-table.h"
6 #include "homectl-pkcs11.h"
7 #include "libcrypt-util.h"
8 #include "memory-util.h"
9 #include "openssl-util.h"
10 #include "pkcs11-util.h"
11 #include "random-util.h"
14 struct pkcs11_callback_data
{
20 static void pkcs11_callback_data_release(struct pkcs11_callback_data
*data
) {
21 erase_and_free(data
->pin_used
);
22 X509_free(data
->cert
);
25 static int pkcs11_callback(
27 CK_SESSION_HANDLE session
,
29 const CK_SLOT_INFO
*slot_info
,
30 const CK_TOKEN_INFO
*token_info
,
34 _cleanup_(erase_and_freep
) char *pin_used
= NULL
;
35 struct pkcs11_callback_data
*data
= userdata
;
36 CK_OBJECT_HANDLE object
;
45 /* Called for every token matching our URI */
47 r
= pkcs11_token_login(m
, session
, slot_id
, token_info
, "home directory operation", "user-home", "pkcs11-pin", UINT64_MAX
, &pin_used
);
51 r
= pkcs11_token_find_x509_certificate(m
, session
, uri
, &object
);
55 r
= pkcs11_token_read_x509_certificate(m
, session
, object
, &data
->cert
);
59 /* Let's read some random data off the token and write it to the kernel pool before we generate our
60 * random key from it. This way we can claim the quality of the RNG is at least as good as the
61 * kernel's and the token's pool */
62 (void) pkcs11_token_acquire_rng(m
, session
);
64 data
->pin_used
= TAKE_PTR(pin_used
);
69 static int acquire_pkcs11_certificate(
72 char **ret_pin_used
) {
75 _cleanup_(pkcs11_callback_data_release
) struct pkcs11_callback_data data
= {};
78 r
= pkcs11_find_token(uri
, pkcs11_callback
, &data
);
79 if (r
== -EAGAIN
) /* pkcs11_find_token() doesn't log about this error, but all others */
80 return log_error_errno(ENXIO
, "Specified PKCS#11 token with URI '%s' not found.", uri
);
84 *ret_cert
= TAKE_PTR(data
.cert
);
85 *ret_pin_used
= TAKE_PTR(data
.pin_used
);
89 return log_error_errno(EOPNOTSUPP
, "PKCS#11 tokens not supported on this build.");
93 static int encrypt_bytes(
95 const void *decrypted_key
,
96 size_t decrypted_key_size
,
97 void **ret_encrypt_key
,
98 size_t *ret_encrypt_key_size
) {
100 _cleanup_(EVP_PKEY_CTX_freep
) EVP_PKEY_CTX
*ctx
= NULL
;
101 _cleanup_free_
void *b
= NULL
;
104 ctx
= EVP_PKEY_CTX_new(pkey
, NULL
);
106 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to allocate public key context");
108 if (EVP_PKEY_encrypt_init(ctx
) <= 0)
109 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to initialize public key context");
111 if (EVP_PKEY_CTX_set_rsa_padding(ctx
, RSA_PKCS1_PADDING
) <= 0)
112 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to configure PKCS#1 padding");
114 if (EVP_PKEY_encrypt(ctx
, NULL
, &l
, decrypted_key
, decrypted_key_size
) <= 0)
115 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to determine encrypted key size");
121 if (EVP_PKEY_encrypt(ctx
, b
, &l
, decrypted_key
, decrypted_key_size
) <= 0)
122 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to determine encrypted key size");
124 *ret_encrypt_key
= TAKE_PTR(b
);
125 *ret_encrypt_key_size
= l
;
130 static int add_pkcs11_encrypted_key(
133 const void *encrypted_key
, size_t encrypted_key_size
,
134 const void *decrypted_key
, size_t decrypted_key_size
) {
136 _cleanup_(json_variant_unrefp
) JsonVariant
*l
= NULL
, *w
= NULL
, *e
= NULL
;
137 _cleanup_(erase_and_freep
) char *base64_encoded
= NULL
;
138 _cleanup_free_
char *salt
= NULL
;
139 struct crypt_data cd
= {};
145 assert(encrypted_key
);
146 assert(encrypted_key_size
> 0);
147 assert(decrypted_key
);
148 assert(decrypted_key_size
> 0);
150 r
= make_salt(&salt
);
152 return log_error_errno(r
, "Failed to generate salt: %m");
154 /* Before using UNIX hashing on the supplied key we base64 encode it, since crypt_r() and friends
155 * expect a NUL terminated string, and we use a binary key */
156 r
= base64mem(decrypted_key
, decrypted_key_size
, &base64_encoded
);
158 return log_error_errno(r
, "Failed to base64 encode secret key: %m");
161 k
= crypt_r(base64_encoded
, salt
, &cd
);
163 return log_error_errno(errno_or_else(EINVAL
), "Failed to UNIX hash secret key: %m");
165 r
= json_build(&e
, JSON_BUILD_OBJECT(
166 JSON_BUILD_PAIR("uri", JSON_BUILD_STRING(uri
)),
167 JSON_BUILD_PAIR("data", JSON_BUILD_BASE64(encrypted_key
, encrypted_key_size
)),
168 JSON_BUILD_PAIR("hashedPassword", JSON_BUILD_STRING(k
))));
170 return log_error_errno(r
, "Failed to build encrypted JSON key object: %m");
172 w
= json_variant_ref(json_variant_by_key(*v
, "privileged"));
173 l
= json_variant_ref(json_variant_by_key(w
, "pkcs11EncryptedKey"));
175 r
= json_variant_append_array(&l
, e
);
177 return log_error_errno(r
, "Failed append PKCS#11 encrypted key: %m");
179 r
= json_variant_set_field(&w
, "pkcs11EncryptedKey", l
);
181 return log_error_errno(r
, "Failed to set PKCS#11 encrypted key: %m");
183 r
= json_variant_set_field(v
, "privileged", w
);
185 return log_error_errno(r
, "Failed to update privileged field: %m");
190 static int add_pkcs11_token_uri(JsonVariant
**v
, const char *uri
) {
191 _cleanup_(json_variant_unrefp
) JsonVariant
*w
= NULL
;
192 _cleanup_strv_free_
char **l
= NULL
;
198 w
= json_variant_ref(json_variant_by_key(*v
, "pkcs11TokenUri"));
200 r
= json_variant_strv(w
, &l
);
202 return log_error_errno(r
, "Failed to parse PKCS#11 token list: %m");
204 if (strv_contains(l
, uri
))
208 r
= strv_extend(&l
, uri
);
212 w
= json_variant_unref(w
);
213 r
= json_variant_new_array_strv(&w
, l
);
215 return log_error_errno(r
, "Failed to create PKCS#11 token URI JSON: %m");
217 r
= json_variant_set_field(v
, "pkcs11TokenUri", w
);
219 return log_error_errno(r
, "Failed to update PKCS#11 token URI list: %m");
224 int identity_add_token_pin(JsonVariant
**v
, const char *pin
) {
225 _cleanup_(json_variant_unrefp
) JsonVariant
*w
= NULL
, *l
= NULL
;
226 _cleanup_(strv_free_erasep
) char **pins
= NULL
;
234 w
= json_variant_ref(json_variant_by_key(*v
, "secret"));
235 l
= json_variant_ref(json_variant_by_key(w
, "tokenPin"));
237 r
= json_variant_strv(l
, &pins
);
239 return log_error_errno(r
, "Failed to convert PIN array: %m");
241 if (strv_find(pins
, pin
))
244 r
= strv_extend(&pins
, pin
);
250 l
= json_variant_unref(l
);
252 r
= json_variant_new_array_strv(&l
, pins
);
254 return log_error_errno(r
, "Failed to allocate new PIN array JSON: %m");
256 json_variant_sensitive(l
);
258 r
= json_variant_set_field(&w
, "tokenPin", l
);
260 return log_error_errno(r
, "Failed to update PIN field: %m");
262 r
= json_variant_set_field(v
, "secret", w
);
264 return log_error_errno(r
, "Failed to update secret object: %m");
269 int identity_add_pkcs11_key_data(JsonVariant
**v
, const char *uri
) {
270 _cleanup_(erase_and_freep
) void *decrypted_key
= NULL
, *encrypted_key
= NULL
;
271 _cleanup_(erase_and_freep
) char *pin
= NULL
;
272 size_t decrypted_key_size
, encrypted_key_size
;
273 _cleanup_(X509_freep
) X509
*cert
= NULL
;
281 r
= acquire_pkcs11_certificate(uri
, &cert
, &pin
);
285 pkey
= X509_get0_pubkey(cert
);
287 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to extract public key from X.509 certificate.");
289 if (EVP_PKEY_base_id(pkey
) != EVP_PKEY_RSA
)
290 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
), "X.509 certificate does not refer to RSA key.");
292 rsa
= EVP_PKEY_get0_RSA(pkey
);
294 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to acquire RSA public key from X.509 certificate.");
296 bits
= RSA_bits(rsa
);
297 log_debug("Bits in RSA key: %i", bits
);
299 /* We use PKCS#1 padding for the RSA cleartext, hence let's leave some extra space for it, hence only
300 * generate a random key half the size of the RSA length */
301 decrypted_key_size
= bits
/ 8 / 2;
303 if (decrypted_key_size
< 1)
304 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Uh, RSA key size too short?");
306 log_debug("Generating %zu bytes random key.", decrypted_key_size
);
308 decrypted_key
= malloc(decrypted_key_size
);
312 r
= genuine_random_bytes(decrypted_key
, decrypted_key_size
, RANDOM_BLOCK
);
314 return log_error_errno(r
, "Failed to generate random key: %m");
316 r
= encrypt_bytes(pkey
, decrypted_key
, decrypted_key_size
, &encrypted_key
, &encrypted_key_size
);
318 return log_error_errno(r
, "Failed to encrypt key: %m");
320 /* Add the token URI to the public part of the record. */
321 r
= add_pkcs11_token_uri(v
, uri
);
325 /* Include the encrypted version of the random key we just generated in the privileged part of the record */
326 r
= add_pkcs11_encrypted_key(
329 encrypted_key
, encrypted_key_size
,
330 decrypted_key
, decrypted_key_size
);
334 /* If we acquired the PIN also include it in the secret section of the record, so that systemd-homed
335 * can use it if it needs to, given that it likely needs to decrypt the key again to pass to LUKS or
337 r
= identity_add_token_pin(v
, pin
);
345 static int list_callback(
347 CK_SESSION_HANDLE session
,
349 const CK_SLOT_INFO
*slot_info
,
350 const CK_TOKEN_INFO
*token_info
,
354 _cleanup_free_
char *token_uri_string
= NULL
, *token_label
= NULL
, *token_manufacturer_id
= NULL
, *token_model
= NULL
;
355 _cleanup_(p11_kit_uri_freep
) P11KitUri
*token_uri
= NULL
;
362 /* We only care about hardware devices here with a token inserted. Let's filter everything else
363 * out. (Note that the user can explicitly specify non-hardware tokens if they like, but during
364 * enumeration we'll filter those, since software tokens are typically the system certificate store
365 * and such, and it's typically not what people want to bind their home directories to.) */
366 if (!FLAGS_SET(token_info
->flags
, CKF_HW_SLOT
|CKF_TOKEN_PRESENT
))
369 token_label
= pkcs11_token_label(token_info
);
373 token_manufacturer_id
= pkcs11_token_manufacturer_id(token_info
);
374 if (!token_manufacturer_id
)
377 token_model
= pkcs11_token_model(token_info
);
381 token_uri
= uri_from_token_info(token_info
);
385 uri_result
= p11_kit_uri_format(token_uri
, P11_KIT_URI_FOR_ANY
, &token_uri_string
);
386 if (uri_result
!= P11_KIT_URI_OK
)
387 return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN
), "Failed to format slot URI: %s", p11_kit_uri_message(uri_result
));
391 TABLE_STRING
, token_uri_string
,
392 TABLE_STRING
, token_label
,
393 TABLE_STRING
, token_manufacturer_id
,
394 TABLE_STRING
, token_model
);
396 return table_log_add_error(r
);
398 return -EAGAIN
; /* keep scanning */
402 int list_pkcs11_tokens(void) {
404 _cleanup_(table_unrefp
) Table
*t
= NULL
;
407 t
= table_new("uri", "label", "manufacturer", "model");
411 r
= pkcs11_find_token(NULL
, list_callback
, t
);
412 if (r
< 0 && r
!= -EAGAIN
)
415 if (table_get_rows(t
) <= 1) {
416 log_info("No suitable PKCS#11 tokens found.");
420 r
= table_print(t
, stdout
);
422 return log_error_errno(r
, "Failed to show device table: %m");
426 return log_error_errno(EOPNOTSUPP
, "PKCS#11 tokens not supported on this build.");
431 static int auto_callback(
433 CK_SESSION_HANDLE session
,
435 const CK_SLOT_INFO
*slot_info
,
436 const CK_TOKEN_INFO
*token_info
,
440 _cleanup_(p11_kit_uri_freep
) P11KitUri
*token_uri
= NULL
;
447 if (!FLAGS_SET(token_info
->flags
, CKF_HW_SLOT
|CKF_TOKEN_PRESENT
))
451 return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ
),
452 "More than one suitable PKCS#11 token found.");
454 token_uri
= uri_from_token_info(token_info
);
458 uri_result
= p11_kit_uri_format(token_uri
, P11_KIT_URI_FOR_ANY
, t
);
459 if (uri_result
!= P11_KIT_URI_OK
)
460 return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN
), "Failed to format slot URI: %s", p11_kit_uri_message(uri_result
));
466 int find_pkcs11_token_auto(char **ret
) {
470 r
= pkcs11_find_token(NULL
, auto_callback
, ret
);
472 return log_error_errno(SYNTHETIC_ERRNO(ENODEV
), "No suitable PKCS#11 tokens found.");
478 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
479 "PKCS#11 tokens not supported on this build.");