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