]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/home/homectl-pkcs11.c
Merge pull request #17493 from Villemoes/va-arg-simplifications
[thirdparty/systemd.git] / src / home / homectl-pkcs11.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include "errno-util.h"
4 #include "format-table.h"
5 #include "hexdecoct.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"
12 #include "strv.h"
13
14 struct pkcs11_callback_data {
15 char *pin_used;
16 X509 *cert;
17 };
18
19 #if HAVE_P11KIT
20 static void pkcs11_callback_data_release(struct pkcs11_callback_data *data) {
21 erase_and_free(data->pin_used);
22 X509_free(data->cert);
23 }
24
25 static int pkcs11_callback(
26 CK_FUNCTION_LIST *m,
27 CK_SESSION_HANDLE session,
28 CK_SLOT_ID slot_id,
29 const CK_SLOT_INFO *slot_info,
30 const CK_TOKEN_INFO *token_info,
31 P11KitUri *uri,
32 void *userdata) {
33
34 _cleanup_(erase_and_freep) char *pin_used = NULL;
35 struct pkcs11_callback_data *data = userdata;
36 CK_OBJECT_HANDLE object;
37 int r;
38
39 assert(m);
40 assert(slot_info);
41 assert(token_info);
42 assert(uri);
43 assert(data);
44
45 /* Called for every token matching our URI */
46
47 r = pkcs11_token_login(m, session, slot_id, token_info, "home directory operation", "user-home", "pkcs11-pin", UINT64_MAX, &pin_used);
48 if (r < 0)
49 return r;
50
51 r = pkcs11_token_find_x509_certificate(m, session, uri, &object);
52 if (r < 0)
53 return r;
54
55 r = pkcs11_token_read_x509_certificate(m, session, object, &data->cert);
56 if (r < 0)
57 return r;
58
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);
63
64 data->pin_used = TAKE_PTR(pin_used);
65 return 1;
66 }
67 #endif
68
69 static int acquire_pkcs11_certificate(
70 const char *uri,
71 X509 **ret_cert,
72 char **ret_pin_used) {
73
74 #if HAVE_P11KIT
75 _cleanup_(pkcs11_callback_data_release) struct pkcs11_callback_data data = {};
76 int r;
77
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(SYNTHETIC_ERRNO(ENXIO),
81 "Specified PKCS#11 token with URI '%s' not found.",
82 uri);
83 if (r < 0)
84 return r;
85
86 *ret_cert = TAKE_PTR(data.cert);
87 *ret_pin_used = TAKE_PTR(data.pin_used);
88
89 return 0;
90 #else
91 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
92 "PKCS#11 tokens not supported on this build.");
93 #endif
94 }
95
96 static int encrypt_bytes(
97 EVP_PKEY *pkey,
98 const void *decrypted_key,
99 size_t decrypted_key_size,
100 void **ret_encrypt_key,
101 size_t *ret_encrypt_key_size) {
102
103 _cleanup_(EVP_PKEY_CTX_freep) EVP_PKEY_CTX *ctx = NULL;
104 _cleanup_free_ void *b = NULL;
105 size_t l;
106
107 ctx = EVP_PKEY_CTX_new(pkey, NULL);
108 if (!ctx)
109 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to allocate public key context");
110
111 if (EVP_PKEY_encrypt_init(ctx) <= 0)
112 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to initialize public key context");
113
114 if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PADDING) <= 0)
115 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to configure PKCS#1 padding");
116
117 if (EVP_PKEY_encrypt(ctx, NULL, &l, decrypted_key, decrypted_key_size) <= 0)
118 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to determine encrypted key size");
119
120 b = malloc(l);
121 if (!b)
122 return log_oom();
123
124 if (EVP_PKEY_encrypt(ctx, b, &l, decrypted_key, decrypted_key_size) <= 0)
125 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to determine encrypted key size");
126
127 *ret_encrypt_key = TAKE_PTR(b);
128 *ret_encrypt_key_size = l;
129
130 return 0;
131 }
132
133 static int add_pkcs11_encrypted_key(
134 JsonVariant **v,
135 const char *uri,
136 const void *encrypted_key, size_t encrypted_key_size,
137 const void *decrypted_key, size_t decrypted_key_size) {
138
139 _cleanup_(json_variant_unrefp) JsonVariant *l = NULL, *w = NULL, *e = NULL;
140 _cleanup_(erase_and_freep) char *base64_encoded = NULL, *hashed = NULL;
141 int r;
142
143 assert(v);
144 assert(uri);
145 assert(encrypted_key);
146 assert(encrypted_key_size > 0);
147 assert(decrypted_key);
148 assert(decrypted_key_size > 0);
149
150 /* Before using UNIX hashing on the supplied key we base64 encode it, since crypt_r() and friends
151 * expect a NUL terminated string, and we use a binary key */
152 r = base64mem(decrypted_key, decrypted_key_size, &base64_encoded);
153 if (r < 0)
154 return log_error_errno(r, "Failed to base64 encode secret key: %m");
155
156 r = hash_password(base64_encoded, &hashed);
157 if (r < 0)
158 return log_error_errno(errno_or_else(EINVAL), "Failed to UNIX hash secret key: %m");
159
160 r = json_build(&e, JSON_BUILD_OBJECT(
161 JSON_BUILD_PAIR("uri", JSON_BUILD_STRING(uri)),
162 JSON_BUILD_PAIR("data", JSON_BUILD_BASE64(encrypted_key, encrypted_key_size)),
163 JSON_BUILD_PAIR("hashedPassword", JSON_BUILD_STRING(hashed))));
164 if (r < 0)
165 return log_error_errno(r, "Failed to build encrypted JSON key object: %m");
166
167 w = json_variant_ref(json_variant_by_key(*v, "privileged"));
168 l = json_variant_ref(json_variant_by_key(w, "pkcs11EncryptedKey"));
169
170 r = json_variant_append_array(&l, e);
171 if (r < 0)
172 return log_error_errno(r, "Failed append PKCS#11 encrypted key: %m");
173
174 r = json_variant_set_field(&w, "pkcs11EncryptedKey", l);
175 if (r < 0)
176 return log_error_errno(r, "Failed to set PKCS#11 encrypted key: %m");
177
178 r = json_variant_set_field(v, "privileged", w);
179 if (r < 0)
180 return log_error_errno(r, "Failed to update privileged field: %m");
181
182 return 0;
183 }
184
185 static int add_pkcs11_token_uri(JsonVariant **v, const char *uri) {
186 _cleanup_(json_variant_unrefp) JsonVariant *w = NULL;
187 _cleanup_strv_free_ char **l = NULL;
188 int r;
189
190 assert(v);
191 assert(uri);
192
193 w = json_variant_ref(json_variant_by_key(*v, "pkcs11TokenUri"));
194 if (w) {
195 r = json_variant_strv(w, &l);
196 if (r < 0)
197 return log_error_errno(r, "Failed to parse PKCS#11 token list: %m");
198
199 if (strv_contains(l, uri))
200 return 0;
201 }
202
203 r = strv_extend(&l, uri);
204 if (r < 0)
205 return log_oom();
206
207 w = json_variant_unref(w);
208 r = json_variant_new_array_strv(&w, l);
209 if (r < 0)
210 return log_error_errno(r, "Failed to create PKCS#11 token URI JSON: %m");
211
212 r = json_variant_set_field(v, "pkcs11TokenUri", w);
213 if (r < 0)
214 return log_error_errno(r, "Failed to update PKCS#11 token URI list: %m");
215
216 return 0;
217 }
218
219 int identity_add_token_pin(JsonVariant **v, const char *pin) {
220 _cleanup_(json_variant_unrefp) JsonVariant *w = NULL, *l = NULL;
221 _cleanup_(strv_free_erasep) char **pins = NULL;
222 int r;
223
224 assert(v);
225
226 if (isempty(pin))
227 return 0;
228
229 w = json_variant_ref(json_variant_by_key(*v, "secret"));
230 l = json_variant_ref(json_variant_by_key(w, "tokenPin"));
231
232 r = json_variant_strv(l, &pins);
233 if (r < 0)
234 return log_error_errno(r, "Failed to convert PIN array: %m");
235
236 if (strv_find(pins, pin))
237 return 0;
238
239 r = strv_extend(&pins, pin);
240 if (r < 0)
241 return log_oom();
242
243 strv_uniq(pins);
244
245 l = json_variant_unref(l);
246
247 r = json_variant_new_array_strv(&l, pins);
248 if (r < 0)
249 return log_error_errno(r, "Failed to allocate new PIN array JSON: %m");
250
251 json_variant_sensitive(l);
252
253 r = json_variant_set_field(&w, "tokenPin", l);
254 if (r < 0)
255 return log_error_errno(r, "Failed to update PIN field: %m");
256
257 r = json_variant_set_field(v, "secret", w);
258 if (r < 0)
259 return log_error_errno(r, "Failed to update secret object: %m");
260
261 return 1;
262 }
263
264 int identity_add_pkcs11_key_data(JsonVariant **v, const char *uri) {
265 _cleanup_(erase_and_freep) void *decrypted_key = NULL, *encrypted_key = NULL;
266 _cleanup_(erase_and_freep) char *pin = NULL;
267 size_t decrypted_key_size, encrypted_key_size;
268 _cleanup_(X509_freep) X509 *cert = NULL;
269 EVP_PKEY *pkey;
270 RSA *rsa;
271 int bits;
272 int r;
273
274 assert(v);
275
276 r = acquire_pkcs11_certificate(uri, &cert, &pin);
277 if (r < 0)
278 return r;
279
280 pkey = X509_get0_pubkey(cert);
281 if (!pkey)
282 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to extract public key from X.509 certificate.");
283
284 if (EVP_PKEY_base_id(pkey) != EVP_PKEY_RSA)
285 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "X.509 certificate does not refer to RSA key.");
286
287 rsa = EVP_PKEY_get0_RSA(pkey);
288 if (!rsa)
289 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to acquire RSA public key from X.509 certificate.");
290
291 bits = RSA_bits(rsa);
292 log_debug("Bits in RSA key: %i", bits);
293
294 /* We use PKCS#1 padding for the RSA cleartext, hence let's leave some extra space for it, hence only
295 * generate a random key half the size of the RSA length */
296 decrypted_key_size = bits / 8 / 2;
297
298 if (decrypted_key_size < 1)
299 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Uh, RSA key size too short?");
300
301 log_debug("Generating %zu bytes random key.", decrypted_key_size);
302
303 decrypted_key = malloc(decrypted_key_size);
304 if (!decrypted_key)
305 return log_oom();
306
307 r = genuine_random_bytes(decrypted_key, decrypted_key_size, RANDOM_BLOCK);
308 if (r < 0)
309 return log_error_errno(r, "Failed to generate random key: %m");
310
311 r = encrypt_bytes(pkey, decrypted_key, decrypted_key_size, &encrypted_key, &encrypted_key_size);
312 if (r < 0)
313 return log_error_errno(r, "Failed to encrypt key: %m");
314
315 /* Add the token URI to the public part of the record. */
316 r = add_pkcs11_token_uri(v, uri);
317 if (r < 0)
318 return r;
319
320 /* Include the encrypted version of the random key we just generated in the privileged part of the record */
321 r = add_pkcs11_encrypted_key(
322 v,
323 uri,
324 encrypted_key, encrypted_key_size,
325 decrypted_key, decrypted_key_size);
326 if (r < 0)
327 return r;
328
329 /* If we acquired the PIN also include it in the secret section of the record, so that systemd-homed
330 * can use it if it needs to, given that it likely needs to decrypt the key again to pass to LUKS or
331 * fscrypt. */
332 r = identity_add_token_pin(v, pin);
333 if (r < 0)
334 return r;
335
336 return 0;
337 }
338
339 #if HAVE_P11KIT
340 static int list_callback(
341 CK_FUNCTION_LIST *m,
342 CK_SESSION_HANDLE session,
343 CK_SLOT_ID slot_id,
344 const CK_SLOT_INFO *slot_info,
345 const CK_TOKEN_INFO *token_info,
346 P11KitUri *uri,
347 void *userdata) {
348
349 _cleanup_free_ char *token_uri_string = NULL, *token_label = NULL, *token_manufacturer_id = NULL, *token_model = NULL;
350 _cleanup_(p11_kit_uri_freep) P11KitUri *token_uri = NULL;
351 Table *t = userdata;
352 int uri_result, r;
353
354 assert(slot_info);
355 assert(token_info);
356
357 /* We only care about hardware devices here with a token inserted. Let's filter everything else
358 * out. (Note that the user can explicitly specify non-hardware tokens if they like, but during
359 * enumeration we'll filter those, since software tokens are typically the system certificate store
360 * and such, and it's typically not what people want to bind their home directories to.) */
361 if (!FLAGS_SET(token_info->flags, CKF_HW_SLOT|CKF_TOKEN_PRESENT))
362 return -EAGAIN;
363
364 token_label = pkcs11_token_label(token_info);
365 if (!token_label)
366 return log_oom();
367
368 token_manufacturer_id = pkcs11_token_manufacturer_id(token_info);
369 if (!token_manufacturer_id)
370 return log_oom();
371
372 token_model = pkcs11_token_model(token_info);
373 if (!token_model)
374 return log_oom();
375
376 token_uri = uri_from_token_info(token_info);
377 if (!token_uri)
378 return log_oom();
379
380 uri_result = p11_kit_uri_format(token_uri, P11_KIT_URI_FOR_ANY, &token_uri_string);
381 if (uri_result != P11_KIT_URI_OK)
382 return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN), "Failed to format slot URI: %s", p11_kit_uri_message(uri_result));
383
384 r = table_add_many(
385 t,
386 TABLE_STRING, token_uri_string,
387 TABLE_STRING, token_label,
388 TABLE_STRING, token_manufacturer_id,
389 TABLE_STRING, token_model);
390 if (r < 0)
391 return table_log_add_error(r);
392
393 return -EAGAIN; /* keep scanning */
394 }
395 #endif
396
397 int list_pkcs11_tokens(void) {
398 #if HAVE_P11KIT
399 _cleanup_(table_unrefp) Table *t = NULL;
400 int r;
401
402 t = table_new("uri", "label", "manufacturer", "model");
403 if (!t)
404 return log_oom();
405
406 r = pkcs11_find_token(NULL, list_callback, t);
407 if (r < 0 && r != -EAGAIN)
408 return r;
409
410 if (table_get_rows(t) <= 1) {
411 log_info("No suitable PKCS#11 tokens found.");
412 return 0;
413 }
414
415 r = table_print(t, stdout);
416 if (r < 0)
417 return log_error_errno(r, "Failed to show device table: %m");
418
419 return 0;
420 #else
421 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
422 "PKCS#11 tokens not supported on this build.");
423 #endif
424 }
425
426 #if HAVE_P11KIT
427 static int auto_callback(
428 CK_FUNCTION_LIST *m,
429 CK_SESSION_HANDLE session,
430 CK_SLOT_ID slot_id,
431 const CK_SLOT_INFO *slot_info,
432 const CK_TOKEN_INFO *token_info,
433 P11KitUri *uri,
434 void *userdata) {
435
436 _cleanup_(p11_kit_uri_freep) P11KitUri *token_uri = NULL;
437 char **t = userdata;
438 int uri_result;
439
440 assert(slot_info);
441 assert(token_info);
442
443 if (!FLAGS_SET(token_info->flags, CKF_HW_SLOT|CKF_TOKEN_PRESENT))
444 return -EAGAIN;
445
446 if (*t)
447 return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ),
448 "More than one suitable PKCS#11 token found.");
449
450 token_uri = uri_from_token_info(token_info);
451 if (!token_uri)
452 return log_oom();
453
454 uri_result = p11_kit_uri_format(token_uri, P11_KIT_URI_FOR_ANY, t);
455 if (uri_result != P11_KIT_URI_OK)
456 return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN), "Failed to format slot URI: %s", p11_kit_uri_message(uri_result));
457
458 return 0;
459 }
460 #endif
461
462 int find_pkcs11_token_auto(char **ret) {
463 #if HAVE_P11KIT
464 int r;
465
466 r = pkcs11_find_token(NULL, auto_callback, ret);
467 if (r == -EAGAIN)
468 return log_error_errno(SYNTHETIC_ERRNO(ENODEV), "No suitable PKCS#11 tokens found.");
469 if (r < 0)
470 return r;
471
472 return 0;
473 #else
474 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
475 "PKCS#11 tokens not supported on this build.");
476 #endif
477 }