Debian Codegraph @

src/cryptenroll/cryptenroll-tpm2.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include "sd-json.h"
4
5 #include "alloc-util.h"
6 #include "ask-password-api.h"
7 #include "cryptenroll-tpm2.h"
8 #include "cryptsetup-tpm2.h"
9 #include "cryptsetup-util.h"
10 #include "env-util.h"
11 #include "errno-util.h"
12 #include "hexdecoct.h"
13 #include "json-util.h"
14 #include "log.h"
15 #include "memory-util.h"
16 #include "random-util.h"
17 #include "sha256.h"
18 #include "strv.h"
19 #include "tpm2-util.h"
20
21 #if HAVE_TPM2
22 static int search_policy_hash(
23 struct crypt_device *cd,
24 const struct iovec policy_hash[],
25 size_t n_policy_hash) {
26
27 int r;
28
29 assert(cd);
30
31 /* Searches among the already enrolled TPM2 tokens for one that matches the exact set of policies specified */
32
33 if (n_policy_hash == 0)
34 return -ENOENT;
35
36 for (int token = 0; token < sym_crypt_token_max(CRYPT_LUKS2); token++) {
37 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
38 int keyslot;
39 sd_json_variant *w;
40
41 r = cryptsetup_get_token_as_json(cd, token, "systemd-tpm2", &v);
42 if (IN_SET(r, -ENOENT, -EINVAL, -EMEDIUMTYPE))
43 continue;
44 if (r < 0)
45 return log_error_errno(r, "Failed to read JSON token data off disk: %m");
46
47 keyslot = cryptsetup_get_keyslot_from_token(v);
48 if (keyslot < 0) {
49 /* Handle parsing errors of the keyslots field gracefully, since it's not 'owned' by
50 * us, but by the LUKS2 spec */
51 log_warning_errno(keyslot, "Failed to determine keyslot of JSON token %i, skipping: %m", token);
52 continue;
53 }
54
55 w = sd_json_variant_by_key(v, "tpm2-policy-hash");
56 if (!w)
57 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
58 "TPM2 token data lacks 'tpm2-policy-hash' field.");
59
60 /* This is either an array of strings (for sharded enrollments), or a single string */
61 if (sd_json_variant_is_array(w)) {
62
63 if (sd_json_variant_elements(w) == n_policy_hash) {
64 sd_json_variant *i;
65 bool match = true;
66 size_t j = 0;
67
68 JSON_VARIANT_ARRAY_FOREACH(i, w) {
69 _cleanup_(iovec_done) struct iovec thash = {};
70
71 r = sd_json_variant_unhex(i, &thash.iov_base, &thash.iov_len);
72 if (r < 0)
73 return log_error_errno(r, "Invalid hex data in 'tpm2-policy-hash' field item : %m");
74
75 if (!iovec_equal(policy_hash + j, &thash)) {
76 match = false;
77 break;
78 }
79
80 j++;
81 }
82
83 if (match) /* Found entry with the exact same set of hashes */
84 return keyslot;
85 }
86
87 } else if (n_policy_hash == 1) {
88 _cleanup_(iovec_done) struct iovec thash = {};
89
90 r = sd_json_variant_unhex(w, &thash.iov_base, &thash.iov_len);
91 if (r < 0)
92 return log_error_errno(r, "Invalid hex data in 'tpm2-policy-hash' field: %m");
93
94 if (iovec_equal(policy_hash + 0, &thash))
95 return keyslot; /* Found entry with same hash. */
96 }
97 }
98
99 return -ENOENT; /* Not found */
100 }
101
102 static int get_pin(char **ret_pin_str, TPM2Flags *ret_flags) {
103 _cleanup_(erase_and_freep) char *pin_str = NULL;
104 TPM2Flags flags = 0;
105 int r;
106
107 assert(ret_pin_str);
108 assert(ret_flags);
109
110 r = getenv_steal_erase("NEWPIN", &pin_str);
111 if (r < 0)
112 return log_error_errno(r, "Failed to acquire PIN from environment: %m");
113 if (r > 0)
114 flags |= TPM2_FLAGS_USE_PIN;
115 else {
116 for (size_t i = 5;; i--) {
117 _cleanup_strv_free_erase_ char **pin = NULL, **pin2 = NULL;
118
119 if (i <= 0)
120 return log_error_errno(
121 SYNTHETIC_ERRNO(ENOKEY), "Too many attempts, giving up.");
122
123 AskPasswordRequest req = {
124 .tty_fd = -EBADF,
125 .message = "Please enter TPM2 PIN:",
126 .icon = "drive-harddisk",
127 .keyring = "tpm2-pin",
128 .credential = "cryptenroll.new-tpm2-pin",
129 .until = USEC_INFINITY,
130 .hup_fd = -EBADF,
131 };
132
133 pin = strv_free_erase(pin);
134 r = ask_password_auto(
135 &req,
136 /* flags= */ 0,
137 &pin);
138 if (r < 0)
139 return log_error_errno(r, "Failed to ask for user pin: %m");
140 assert(strv_length(pin) == 1);
141
142 req.message = "Please enter TPM2 PIN (repeat):";
143
144 r = ask_password_auto(
145 &req,
146 /* flags= */ 0,
147 &pin2);
148 if (r < 0)
149 return log_error_errno(r, "Failed to ask for user pin: %m");
150 assert(strv_length(pin) == 1);
151
152 if (strv_equal(pin, pin2)) {
153 pin_str = strdup(*pin);
154 if (!pin_str)
155 return log_oom();
156 flags |= TPM2_FLAGS_USE_PIN;
157 break;
158 }
159
160 log_error("PINs didn't match, please try again!");
161 }
162 }
163
164 *ret_flags = flags;
165 *ret_pin_str = TAKE_PTR(pin_str);
166
167 return 0;
168 }
169 #endif
170
171 int load_volume_key_tpm2(
172 struct crypt_device *cd,
173 const char *cd_node,
174 const char *device,
175 void *ret_vk,
176 size_t *ret_vks) {
177
178 #if HAVE_TPM2
179 _cleanup_(iovec_done_erase) struct iovec decrypted_key = {};
180 _cleanup_(erase_and_freep) char *passphrase = NULL;
181 ssize_t passphrase_size;
182 int r;
183
184 assert_se(cd);
185 assert_se(cd_node);
186 assert_se(ret_vk);
187 assert_se(ret_vks);
188
189 bool found_some = false;
190 int token = 0; /* first token to look at */
191
192 for (;;) {
193 _cleanup_(iovec_done) struct iovec pubkey = {}, salt = {}, srk = {}, pcrlock_nv = {};
194 struct iovec *blobs = NULL, *policy_hash = NULL;
195 size_t n_blobs = 0, n_policy_hash = 0;
196 uint32_t hash_pcr_mask, pubkey_pcr_mask;
197 uint16_t pcr_bank, primary_alg;
198 TPM2Flags tpm2_flags;
199 int keyslot;
200
201 CLEANUP_ARRAY(policy_hash, n_policy_hash, iovec_array_free);
202 CLEANUP_ARRAY(blobs, n_blobs, iovec_array_free);
203
204 r = find_tpm2_auto_data(
205 cd,
206 UINT32_MAX,
207 token,
208 &hash_pcr_mask,
209 &pcr_bank,
210 &pubkey,
211 &pubkey_pcr_mask,
212 &primary_alg,
213 &blobs,
214 &n_blobs,
215 &policy_hash,
216 &n_policy_hash,
217 &salt,
218 &srk,
219 &pcrlock_nv,
220 &tpm2_flags,
221 &keyslot,
222 &token);
223 if (r == -ENXIO)
224 return log_full_errno(LOG_NOTICE,
225 SYNTHETIC_ERRNO(EAGAIN),
226 found_some
227 ? "No TPM2 metadata matching the current system state found in LUKS2 header."
228 : "No TPM2 metadata enrolled in LUKS2 header.");
229 if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
230 /* TPM2 support not compiled in? */
231 return log_debug_errno(SYNTHETIC_ERRNO(EAGAIN), "TPM2 support not available.");
232 if (r < 0)
233 return r;
234
235 found_some = true;
236
237 r = acquire_tpm2_key(
238 cd_node,
239 device,
240 hash_pcr_mask,
241 pcr_bank,
242 &pubkey,
243 pubkey_pcr_mask,
244 /* signature_path= */ NULL,
245 /* pcrlock_path= */ NULL,
246 primary_alg,
247 /* key_file= */ NULL, /* key_file_size= */ 0, /* key_file_offset= */ 0, /* no key file */
248 blobs,
249 n_blobs,
250 policy_hash,
251 n_policy_hash,
252 &salt,
253 &srk,
254 &pcrlock_nv,
255 tpm2_flags,
256 /* until= */ 0,
257 "cryptenroll.tpm2-pin",
258 /* askpw_flags= */ 0,
259 &decrypted_key);
260 if (IN_SET(r, -EACCES, -ENOLCK))
261 return log_notice_errno(SYNTHETIC_ERRNO(EAGAIN), "TPM2 PIN unlock failed");
262 if (r != -EPERM)
263 break;
264
265 token++; /* try a different token next time */
266 }
267
268 if (r < 0)
269 return log_error_errno(r, "Unlocking via TPM2 device failed: %m");
270
271 passphrase_size = base64mem(decrypted_key.iov_base, decrypted_key.iov_len, &passphrase);
272 if (passphrase_size < 0)
273 return log_oom();
274
275 r = sym_crypt_volume_key_get(
276 cd,
277 CRYPT_ANY_SLOT,
278 ret_vk,
279 ret_vks,
280 passphrase,
281 passphrase_size);
282 if (r < 0)
283 return log_error_errno(r, "Unlocking via TPM2 device failed: %m");
284
285 return r;
286 #else
287 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "TPM2 unlocking not supported.");
288 #endif
289 }
290
291 int enroll_tpm2(struct crypt_device *cd,
292 const struct iovec *volume_key,
293 const char *device,
294 uint32_t seal_key_handle,
295 const char *device_key,
296 Tpm2PCRValue *hash_pcr_values,
297 size_t n_hash_pcr_values,
298 const char *pcr_pubkey_path,
299 bool load_pcr_pubkey,
300 uint32_t pubkey_pcr_mask,
301 const char *signature_path,
302 bool use_pin,
303 const char *pcrlock_path,
304 int *ret_slot_to_wipe) {
305
306 #if HAVE_TPM2
307 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL, *signature_json = NULL;
308 _cleanup_(erase_and_freep) char *base64_encoded = NULL;
309 _cleanup_(iovec_done) struct iovec srk = {}, pubkey = {};
310 _cleanup_(iovec_done_erase) struct iovec secret = {};
311 const char *node;
312 _cleanup_(erase_and_freep) char *pin_str = NULL;
313 ssize_t base64_encoded_size;
314 int r, keyslot, slot_to_wipe = -1;
315 TPM2Flags flags = 0;
316 uint16_t primary_alg = 0;
317 uint8_t binary_salt[SHA256_DIGEST_SIZE] = {};
318 /*
319 * erase the salt, we'd rather attempt to not have this in a coredump
320 * as an attacker would have all the parameters but pin used to create
321 * the session key. This problem goes away when we move to a trusted
322 * primary key, aka the SRK.
323 */
324 CLEANUP_ERASE(binary_salt);
325
326 assert(cd);
327 assert(iovec_is_set(volume_key));
328 assert(tpm2_pcr_values_valid(hash_pcr_values, n_hash_pcr_values));
329 assert(TPM2_PCR_MASK_VALID(pubkey_pcr_mask));
330 assert(ret_slot_to_wipe);
331
332 assert_se(node = sym_crypt_get_device_name(cd));
333
334 if (use_pin) {
335 r = get_pin(&pin_str, &flags);
336 if (r < 0)
337 return r;
338
339 r = crypto_random_bytes(binary_salt, sizeof(binary_salt));
340 if (r < 0)
341 return log_error_errno(r, "Failed to acquire random salt: %m");
342
343 uint8_t salted_pin[SHA256_DIGEST_SIZE] = {};
344 CLEANUP_ERASE(salted_pin);
345 r = tpm2_util_pbkdf2_hmac_sha256(pin_str, strlen(pin_str), binary_salt, sizeof(binary_salt), salted_pin);
346 if (r < 0)
347 return log_error_errno(r, "Failed to perform PBKDF2: %m");
348
349 pin_str = erase_and_free(pin_str);
350 /* re-stringify pin_str */
351 base64_encoded_size = base64mem(salted_pin, sizeof(salted_pin), &pin_str);
352 if (base64_encoded_size < 0)
353 return log_error_errno(base64_encoded_size, "Failed to base64 encode salted pin: %m");
354 }
355
356 TPM2B_PUBLIC public = {};
357 if (pcr_pubkey_path || load_pcr_pubkey) {
358 r = tpm2_load_pcr_public_key(pcr_pubkey_path, &pubkey.iov_base, &pubkey.iov_len);
359 if (r < 0) {
360 if (pcr_pubkey_path || signature_path || r != -ENOENT)
361 return log_error_errno(r, "Failed to read TPM PCR public key: %m");
362
363 log_debug_errno(r, "Failed to read TPM2 PCR public key, proceeding without: %m");
364 pubkey_pcr_mask = 0;
365 } else {
366 r = tpm2_tpm2b_public_from_pem(pubkey.iov_base, pubkey.iov_len, &public);
367 if (r < 0)
368 return log_error_errno(r, "Could not convert public key to TPM2B_PUBLIC: %m");
369
370 if (signature_path) {
371 /* Also try to load the signature JSON object, to verify that our enrollment will work.
372 * This is optional however, skip it if it's not explicitly provided. */
373
374 r = tpm2_load_pcr_signature(signature_path, &signature_json);
375 if (r < 0)
376 return log_error_errno(r, "Failed to read TPM PCR signature: %m");
377 }
378 }
379 } else
380 pubkey_pcr_mask = 0;
381
382 bool any_pcr_value_specified = tpm2_pcr_values_has_any_values(hash_pcr_values, n_hash_pcr_values);
383
384 _cleanup_(tpm2_pcrlock_policy_done) Tpm2PCRLockPolicy pcrlock_policy = {};
385 if (pcrlock_path) {
386 r = tpm2_pcrlock_policy_load(pcrlock_path, &pcrlock_policy);
387 if (r < 0)
388 return r;
389 if (r == 0)
390 return log_error_errno(SYNTHETIC_ERRNO(ENOENT), "Couldn't find pcrlock policy %s.", pcrlock_path);
391
392 any_pcr_value_specified = true;
393 flags |= TPM2_FLAGS_USE_PCRLOCK;
394 }
395
396 _cleanup_(tpm2_context_unrefp) Tpm2Context *tpm2_context = NULL;
397 TPM2B_PUBLIC device_key_public = {};
398 if (device_key) {
399 r = tpm2_load_public_key_file(device_key, &device_key_public);
400 if (r < 0)
401 return r;
402
403 if (!tpm2_pcr_values_has_all_values(hash_pcr_values, n_hash_pcr_values))
404 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
405 "Must provide all PCR values when using TPM2 device key.");
406
407 primary_alg = device_key_public.publicArea.type;
408 } else {
409 r = tpm2_context_new_or_warn(device, &tpm2_context);
410 if (r < 0)
411 return r;
412
413 if (!tpm2_pcr_values_has_all_values(hash_pcr_values, n_hash_pcr_values)) {
414 r = tpm2_pcr_read_missing_values(tpm2_context, hash_pcr_values, n_hash_pcr_values);
415 if (r < 0)
416 return log_error_errno(r, "Could not read pcr values: %m");
417 }
418 }
419
420 uint16_t hash_pcr_bank = 0;
421 uint32_t hash_pcr_mask = 0;
422
423 if (n_hash_pcr_values > 0) {
424 size_t hash_count;
425
426 r = tpm2_pcr_values_hash_count(hash_pcr_values, n_hash_pcr_values, &hash_count);
427 if (r < 0)
428 return log_error_errno(r, "Could not get hash count: %m");
429
430 if (hash_count > 1)
431 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Multiple PCR banks selected.");
432
433 /* If we use a literal PCR value policy, derive the bank to use from the algorithm specified on the hash values */
434 hash_pcr_bank = hash_pcr_values[0].hash;
435 r = tpm2_pcr_values_to_mask(hash_pcr_values, n_hash_pcr_values, hash_pcr_bank, &hash_pcr_mask);
436 if (r < 0)
437 return log_error_errno(r, "Could not get hash mask: %m");
438
439 } else if (pubkey_pcr_mask != 0 && !device_key) {
440
441 /* If no literal PCR value policy is used, then let's determine the mask to use automatically
442 * from the measurements of the TPM. */
443 r = tpm2_get_best_pcr_bank(
444 tpm2_context,
445 pubkey_pcr_mask,
446 &hash_pcr_bank);
447 if (r < 0)
448 return log_error_errno(r, "Failed to determine best PCR bank: %m");
449 }
450
451 /* Unfortunately TPM2 policy semantics make it very hard to combine PolicyAuthorize (which we need
452 * for signed PCR policies) and PolicyAuthorizeNV (which we need for pcrlock policies). Hence, let's
453 * use a "sharded" secret, and lock the first shard to the signed PCR policy, and the 2nd to the
454 * pcrlock – if both are requested. */
455
456 TPM2B_DIGEST policy_hash[2] = {
457 TPM2B_DIGEST_MAKE(NULL, TPM2_SHA256_DIGEST_SIZE),
458 TPM2B_DIGEST_MAKE(NULL, TPM2_SHA256_DIGEST_SIZE),
459 };
460 size_t n_policy_hash = 1;
461
462 /* If both PCR public key unlock and pcrlock unlock is selected, then we create the one for PCR public key unlock first. */
463 r = tpm2_calculate_sealing_policy(
464 hash_pcr_values,
465 n_hash_pcr_values,
466 iovec_is_set(&pubkey) ? &public : NULL,
467 use_pin,
468 pcrlock_path && !iovec_is_set(&pubkey) ? &pcrlock_policy : NULL,
469 policy_hash + 0);
470 if (r < 0)
471 return r;
472
473 if (pcrlock_path && iovec_is_set(&pubkey)) {
474 r = tpm2_calculate_sealing_policy(
475 hash_pcr_values,
476 n_hash_pcr_values,
477 /* public= */ NULL, /* This one is off now */
478 use_pin,
479 &pcrlock_policy, /* And this one on instead. */
480 policy_hash + 1);
481 if (r < 0)
482 return r;
483
484 n_policy_hash ++;
485 }
486
487 struct iovec *blobs = NULL;
488 size_t n_blobs = 0;
489 CLEANUP_ARRAY(blobs, n_blobs, iovec_array_free);
490
491 if (device_key) {
492 if (n_policy_hash > 1)
493 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
494 "Combined signed PCR policies and pcrlock policies cannot be calculated offline, currently.");
495
496 blobs = new0(struct iovec, 1);
497 if (!blobs)
498 return log_oom();
499
500 n_blobs = 1;
501
502 r = tpm2_calculate_seal(
503 seal_key_handle,
504 &device_key_public,
505 /* attributes= */ NULL,
506 /* secret= */ NULL,
507 policy_hash + 0,
508 pin_str,
509 &secret,
510 blobs + 0,
511 &srk);
512 } else
513 r = tpm2_seal(tpm2_context,
514 seal_key_handle,
515 policy_hash,
516 n_policy_hash,
517 pin_str,
518 &secret,
519 &blobs,
520 &n_blobs,
521 &primary_alg,
522 &srk);
523 if (r < 0)
524 return log_error_errno(r, "Failed to seal to TPM2: %m");
525
526 struct iovec policy_hash_as_iovec[2] = {
527 IOVEC_MAKE(policy_hash[0].buffer, policy_hash[0].size),
528 IOVEC_MAKE(policy_hash[1].buffer, policy_hash[1].size),
529 };
530
531 /* Let's see if we already have this specific PCR policy hash enrolled, if so, exit early. */
532 r = search_policy_hash(cd, policy_hash_as_iovec, n_policy_hash);
533 if (r == -ENOENT)
534 log_debug_errno(r, "PCR policy hash not yet enrolled, enrolling now.");
535 else if (r < 0)
536 return r;
537 else if (use_pin) {
538 log_debug("This PCR set is already enrolled, re-enrolling anyway to update PIN.");
539 slot_to_wipe = r;
540 } else {
541 log_info("This PCR set is already enrolled, executing no operation.");
542 *ret_slot_to_wipe = -1;
543 return r; /* return existing keyslot, so that wiping won't kill it */
544 }
545
546 /* If possible, verify the sealed data object. */
547 if ((!iovec_is_set(&pubkey) || signature_json) && !any_pcr_value_specified && !device_key) {
548 _cleanup_(iovec_done_erase) struct iovec secret2 = {};
549
550 log_debug("Unsealing for verification...");
551 r = tpm2_unseal(tpm2_context,
552 hash_pcr_mask,
553 hash_pcr_bank,
554 &pubkey,
555 pubkey_pcr_mask,
556 signature_json,
557 pin_str,
558 pcrlock_path ? &pcrlock_policy : NULL,
559 primary_alg,
560 blobs,
561 n_blobs,
562 policy_hash_as_iovec,
563 n_policy_hash,
564 &srk,
565 &secret2);
566 if (r < 0)
567 return log_error_errno(r, "Failed to unseal secret using TPM2: %m");
568
569 if (!iovec_equal(&secret, &secret2))
570 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "TPM2 seal/unseal verification failed.");
571 }
572
573 /* let's base64 encode the key to use, for compat with homed (and it's easier to every type it in by keyboard, if that might end up being necessary. */
574 base64_encoded_size = base64mem(secret.iov_base, secret.iov_len, &base64_encoded);
575 if (base64_encoded_size < 0)
576 return log_error_errno(base64_encoded_size, "Failed to base64 encode secret key: %m");
577
578 r = cryptsetup_set_minimal_pbkdf(cd);
579 if (r < 0)
580 return log_error_errno(r, "Failed to set minimal PBKDF: %m");
581
582 keyslot = sym_crypt_keyslot_add_by_volume_key(
583 cd,
584 CRYPT_ANY_SLOT,
585 volume_key->iov_base,
586 volume_key->iov_len,
587 base64_encoded,
588 base64_encoded_size);
589 if (keyslot < 0)
590 return log_error_errno(keyslot, "Failed to add new TPM2 key to %s: %m", node);
591
592 r = tpm2_make_luks2_json(
593 keyslot,
594 hash_pcr_mask,
595 hash_pcr_bank,
596 &pubkey,
597 pubkey_pcr_mask,
598 primary_alg,
599 blobs,
600 n_blobs,
601 policy_hash_as_iovec,
602 n_policy_hash,
603 use_pin ? &IOVEC_MAKE(binary_salt, sizeof(binary_salt)) : NULL,
604 &srk,
605 pcrlock_path ? &pcrlock_policy.nv_handle : NULL,
606 flags,
607 &v);
608 if (r < 0)
609 return log_error_errno(r, "Failed to prepare TPM2 JSON token object: %m");
610
611 r = cryptsetup_add_token_json(cd, v);
612 if (r < 0)
613 return log_error_errno(r, "Failed to add TPM2 JSON token to LUKS2 header: %m");
614
615 log_info("New TPM2 token enrolled as key slot %i.", keyslot);
616
617 *ret_slot_to_wipe = slot_to_wipe;
618 return keyslot;
619 #else
620 return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "TPM2 key enrollment not supported.");
621 #endif
622 }