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