Debian Codegraph @

src/tpm2-setup/tpm2-setup.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <sys/stat.h>
4 #include <sysexits.h>
5
6 #include "sd-messages.h"
7
8 #include "alloc-util.h"
9 #include "build.h"
10 #include "conf-files.h"
11 #include "constants.h"
12 #include "crypto-util.h"
13 #include "errno-util.h"
14 #include "fd-util.h"
15 #include "fileio.h"
16 #include "format-table.h"
17 #include "fs-util.h"
18 #include "hexdecoct.h"
19 #include "log.h"
20 #include "main-func.h"
21 #include "mkdir.h"
22 #include "options.h"
23 #include "parse-util.h"
24 #include "pretty-print.h"
25 #include "set.h"
26 #include "sort-util.h"
27 #include "string-util.h"
28 #include "strv.h"
29 #include "tmpfile-util.h"
30 #include "tpm2-util.h"
31
32 static char *arg_tpm2_device = NULL;
33 static bool arg_early = false;
34 static bool arg_graceful = false;
35
36 STATIC_DESTRUCTOR_REGISTER(arg_tpm2_device, freep);
37
38 #define TPM2_SRK_PEM_PERSISTENT_PATH "/var/lib/systemd/tpm2-srk-public-key.pem"
39 #define TPM2_SRK_PEM_RUNTIME_PATH "/run/systemd/tpm2-srk-public-key.pem"
40
41 #define TPM2_SRK_TPM2B_PUBLIC_PERSISTENT_PATH "/var/lib/systemd/tpm2-srk-public-key.tpm2b_public"
42 #define TPM2_SRK_TPM2B_PUBLIC_RUNTIME_PATH "/run/systemd/tpm2-srk-public-key.tpm2b_public"
43
44 static int help(void) {
45 _cleanup_free_ char *link = NULL;
46 _cleanup_(table_unrefp) Table *options = NULL;
47 int r;
48
49 r = terminal_urlify_man("systemd-tpm2-setup", "8", &link);
50 if (r < 0)
51 return log_oom();
52
53 r = option_parser_get_help_table(&options);
54 if (r < 0)
55 return r;
56
57 printf("%s [OPTIONS...]\n"
58 "\n%sSet up the TPM2 Storage Root Key (SRK), and initialize NvPCRs.%s\n"
59 "\n%sOptions:%s\n",
60 program_invocation_short_name,
61 ansi_highlight(),
62 ansi_normal(),
63 ansi_underline(),
64 ansi_normal());
65
66 r = table_print_or_warn(options);
67 if (r < 0)
68 return r;
69
70 printf("\nSee the %s for details.\n", link);
71 return 0;
72 }
73
74 static int parse_argv(int argc, char *argv[]) {
75 int r;
76
77 assert(argc >= 0);
78 assert(argv);
79
80 OptionParser opts = { argc, argv };
81
82 FOREACH_OPTION_OR_RETURN(c, &opts)
83 switch (c) {
84
85 OPTION_COMMON_HELP:
86 return help();
87
88 OPTION_COMMON_VERSION:
89 return version();
90
91 OPTION_LONG("tpm2-device", "PATH", "Pick TPM2 device"):
92 if (streq(opts.arg, "list"))
93 return tpm2_list_devices(/* legend= */ true, /* quiet= */ false);
94
95 if (free_and_strdup(&arg_tpm2_device, streq(opts.arg, "auto") ? NULL : opts.arg) < 0)
96 return log_oom();
97 break;
98
99 OPTION_LONG("early", "BOOL", "Store SRK public key in /run/ rather than /var/lib/"):
100 r = parse_boolean(opts.arg);
101 if (r < 0)
102 return log_error_errno(r, "Failed to parse --early= argument: %s", opts.arg);
103
104 arg_early = r;
105 break;
106
107 OPTION_LONG("graceful", NULL, "Exit gracefully if no TPM2 device is found"):
108 arg_graceful = true;
109 break;
110 }
111
112 if (option_parser_get_n_args(&opts) != 0)
113 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "This program expects no argument.");
114
115 return 1;
116 }
117
118 struct public_key_data {
119 EVP_PKEY *pkey; /* as OpenSSL object */
120 TPM2B_PUBLIC *public; /* in TPM2 format */
121 void *fingerprint;
122 size_t fingerprint_size;
123 char *fingerprint_hex;
124 char *path;
125 };
126
127 static void public_key_data_done(struct public_key_data *d) {
128 assert(d);
129
130 if (d->pkey) {
131 sym_EVP_PKEY_free(d->pkey);
132 d->pkey = NULL;
133 }
134 if (d->public) {
135 Esys_Freep(&d->public);
136 d->public = NULL;
137 }
138 d->fingerprint = mfree(d->fingerprint);
139 d->fingerprint_size = 0;
140 d->fingerprint_hex = mfree(d->fingerprint_hex);
141 d->path = mfree(d->path);
142 }
143
144 static int public_key_make_fingerprint(struct public_key_data *d) {
145 int r;
146
147 assert(d);
148 assert(d->pkey);
149 assert(!d->fingerprint);
150 assert(!d->fingerprint_hex);
151
152 r = pubkey_fingerprint(d->pkey, sym_EVP_sha256(), &d->fingerprint, &d->fingerprint_size);
153 if (r < 0)
154 return log_error_errno(r, "Failed to calculate fingerprint of public key: %m");
155
156 d->fingerprint_hex = hexmem(d->fingerprint, d->fingerprint_size);
157 if (!d->fingerprint_hex)
158 return log_oom();
159
160 return 0;
161 }
162
163 static int load_public_key_disk(const char *path, struct public_key_data *ret) {
164 _cleanup_(public_key_data_done) struct public_key_data data = {};
165 _cleanup_free_ char *blob = NULL;
166 size_t blob_size;
167 int r;
168
169 assert(path);
170 assert(ret);
171
172 r = read_full_file(path, &blob, &blob_size);
173 if (r < 0) {
174 if (r != -ENOENT)
175 return log_error_errno(r, "Failed to read '%s': %m", path);
176
177 log_debug("SRK public key file '%s' does not exist.", path);
178 } else {
179 log_debug("Loaded SRK public key from '%s'.", path);
180
181 r = openssl_pubkey_from_pem(blob, blob_size, &data.pkey);
182 if (r < 0)
183 return log_error_errno(r, "Failed to parse SRK public key file '%s': %m", path);
184
185 r = public_key_make_fingerprint(&data);
186 if (r < 0)
187 return r;
188
189 log_debug("Loaded SRK public key fingerprint: %s", data.fingerprint_hex);
190 }
191
192 data.path = strdup(path);
193 if (!data.path)
194 return log_oom();
195
196 *ret = data;
197 data = (struct public_key_data) {};
198
199 return 0;
200 }
201
202 static int load_public_key_tpm2(struct public_key_data *ret) {
203 _cleanup_(public_key_data_done) struct public_key_data data = {};
204 _cleanup_(tpm2_context_unrefp) Tpm2Context *c = NULL;
205 int r;
206
207 assert(ret);
208
209 r = tpm2_context_new_or_warn(arg_tpm2_device, &c);
210 if (r < 0)
211 return r;
212
213 r = tpm2_get_or_create_srk(
214 c,
215 /* session= */ NULL,
216 &data.public,
217 /* ret_name= */ NULL,
218 /* ret_qname= */ NULL,
219 NULL);
220 if (r == -EDEADLK)
221 return r;
222 if (r < 0)
223 return log_error_errno(r, "Failed to get or create SRK: %m");
224 if (r > 0)
225 log_info("New SRK generated and stored in the TPM.");
226 else
227 log_info("SRK already stored in the TPM.");
228
229 r = tpm2_tpm2b_public_to_openssl_pkey(data.public, &data.pkey);
230 if (r < 0)
231 return log_error_errno(r, "Failed to convert TPM2 SRK public key to OpenSSL public key: %m");
232
233 r = public_key_make_fingerprint(&data);
234 if (r < 0)
235 return r;
236
237 log_info("SRK fingerprint is %s.", data.fingerprint_hex);
238
239 *ret = data;
240 data = (struct public_key_data) {};
241
242 return 0;
243 }
244
245 static int setup_srk(void) {
246 int r;
247
248 _cleanup_(public_key_data_done) struct public_key_data runtime_key = {}, persistent_key = {}, tpm2_key = {};
249
250 r = load_public_key_disk(TPM2_SRK_PEM_RUNTIME_PATH, &runtime_key);
251 if (r < 0)
252 return r;
253
254 if (!arg_early) {
255 r = load_public_key_disk(TPM2_SRK_PEM_PERSISTENT_PATH, &persistent_key);
256 if (r < 0)
257 return r;
258
259 if (runtime_key.pkey && persistent_key.pkey &&
260 memcmp_nn(runtime_key.fingerprint, runtime_key.fingerprint_size,
261 persistent_key.fingerprint, persistent_key.fingerprint_size) != 0) {
262
263 /* One of those days we might want to add a stricter policy option here, that refuses
264 * to boot when the SRK changes. For now, let's just warn and proceed, in order not
265 * to break OS images that are moved around PCs. */
266
267 log_notice("Saved persistent SRK (%s) and runtime SRK differ (fingerprint %s vs. %s), updating persistent SRK.",
268 persistent_key.path, persistent_key.fingerprint_hex, runtime_key.fingerprint_hex);
269
270 public_key_data_done(&persistent_key);
271 }
272 }
273
274 r = load_public_key_tpm2(&tpm2_key);
275 if (r == -EDEADLK) {
276 log_struct_errno(LOG_INFO, r,
277 LOG_MESSAGE("Insufficient permissions to access TPM, not generating SRK."),
278 LOG_MESSAGE_ID(SD_MESSAGE_SRK_ENROLLMENT_NEEDS_AUTHORIZATION_STR));
279 return EX_PROTOCOL; /* Special return value which means "Insufficient permissions to access TPM,
280 * cannot generate SRK". This isn't really an error when called at boot. */;
281 }
282 if (r < 0)
283 return r;
284
285 assert(tpm2_key.pkey);
286
287 if (runtime_key.pkey) {
288 if (memcmp_nn(tpm2_key.fingerprint, tpm2_key.fingerprint_size,
289 runtime_key.fingerprint, runtime_key.fingerprint_size) != 0)
290 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
291 "Saved runtime SRK differs from TPM SRK, refusing.");
292
293 if (arg_early) {
294 log_info("SRK saved in '%s' matches SRK in TPM2.", runtime_key.path);
295 return 0;
296 }
297 }
298
299 if (persistent_key.pkey) {
300 if (memcmp_nn(tpm2_key.fingerprint, tpm2_key.fingerprint_size,
301 persistent_key.fingerprint, persistent_key.fingerprint_size) == 0) {
302 log_info("SRK saved in '%s' matches SRK in TPM2.", persistent_key.path);
303 return 0;
304 }
305
306 /* As above, we probably want a stricter policy option here, one day. */
307
308 log_notice("Saved persistent SRK (%s) and TPM SRK differ (fingerprint %s vs. %s), updating persistent SRK.",
309 persistent_key.path, persistent_key.fingerprint_hex, tpm2_key.fingerprint_hex);
310
311 public_key_data_done(&persistent_key);
312 }
313
314 const char *pem_path = arg_early ? TPM2_SRK_PEM_RUNTIME_PATH : TPM2_SRK_PEM_PERSISTENT_PATH;
315 (void) mkdir_parents(pem_path, 0755);
316
317 /* Write out public key (note that we only do that as a help to the user, we don't make use of this ever */
318 _cleanup_(unlink_and_freep) char *t = NULL;
319 _cleanup_fclose_ FILE *f = NULL;
320 r = fopen_tmpfile_linkable(pem_path, O_WRONLY|O_CLOEXEC, &t, &f);
321 if (r < 0)
322 return log_error_errno(r, "Failed to open SRK public key file '%s' for writing: %m", pem_path);
323
324 if (sym_PEM_write_PUBKEY(f, tpm2_key.pkey) <= 0)
325 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to write SRK public key file '%s'.", pem_path);
326
327 if (fchmod(fileno(f), 0444) < 0)
328 return log_error_errno(errno, "Failed to adjust access mode of SRK public key file '%s' to 0444: %m", pem_path);
329
330 r = flink_tmpfile(f, t, pem_path, LINK_TMPFILE_SYNC|LINK_TMPFILE_REPLACE);
331 if (r < 0)
332 return log_error_errno(r, "Failed to move SRK public key file to '%s': %m", pem_path);
333
334 f = safe_fclose(f);
335 t = mfree(t);
336
337 log_info("SRK public key saved to '%s' in PEM format.", pem_path);
338
339 const char *tpm2b_public_path = arg_early ? TPM2_SRK_TPM2B_PUBLIC_RUNTIME_PATH : TPM2_SRK_TPM2B_PUBLIC_PERSISTENT_PATH;
340 (void) mkdir_parents(tpm2b_public_path, 0755);
341
342 /* Now also write this out in TPM2B_PUBLIC format */
343 r = fopen_tmpfile_linkable(tpm2b_public_path, O_WRONLY|O_CLOEXEC, &t, &f);
344 if (r < 0)
345 return log_error_errno(r, "Failed to open SRK public key file '%s' for writing: %m", tpm2b_public_path);
346
347 _cleanup_free_ void *marshalled = NULL;
348 size_t marshalled_size = 0;
349 r = tpm2_marshal_public(tpm2_key.public, &marshalled, &marshalled_size);
350 if (r < 0)
351 return log_error_errno(r, "Failed to marshal TPM2_PUBLIC key.");
352
353 if (fwrite(marshalled, 1, marshalled_size, f) != marshalled_size)
354 return log_error_errno(SYNTHETIC_ERRNO(EIO),
355 "Failed to write SRK public key file '%s'.", tpm2b_public_path);
356
357 if (fchmod(fileno(f), 0444) < 0)
358 return log_error_errno(errno, "Failed to adjust access mode of SRK public key file '%s' to 0444: %m", tpm2b_public_path);
359
360 r = flink_tmpfile(f, t, tpm2b_public_path, LINK_TMPFILE_SYNC|LINK_TMPFILE_REPLACE);
361 if (r < 0)
362 return log_error_errno(r, "Failed to move SRK public key file to '%s': %m", tpm2b_public_path);
363
364 t = mfree(t);
365
366 log_info("SRK public key saved to '%s' in TPM2B_PUBLIC format.", tpm2b_public_path);
367 return 0;
368 }
369
370 typedef struct SetupNvPCRContext {
371 Tpm2Context *tpm2_context;
372 struct iovec anchor_secret;
373 size_t n_already, n_anchored, n_failed, n_skipped;
374 bool nv_space_exhausted; /* Set once the TPM ran out of NV index space, so we skip the rest. */
375 Set *done;
376 } SetupNvPCRContext;
377
378 static void setup_nvpcr_context_done(SetupNvPCRContext *c) {
379 assert(c);
380
381 iovec_done_erase(&c->anchor_secret);
382 c->tpm2_context = tpm2_context_unref(c->tpm2_context);
383 c->done = set_free(c->done);
384 }
385
386 static int setup_nvpcr_one(
387 SetupNvPCRContext *c,
388 const char *name) {
389 int r;
390
391 assert(c);
392 assert(name);
393 assert(c->tpm2_context);
394
395 if (set_contains(c->done, name))
396 return 0;
397
398 /* If the TPM already ran out of NV index space, don't even try to allocate further NvPCRs. As
399 * NvPCRs are processed in order of priority (most important first), everything still pending is
400 * less important than what already didn't fit. */
401 if (c->nv_space_exhausted) {
402 log_debug("TPM NV index space already exhausted, skipping allocation of NvPCR '%s'.", name);
403 c->n_skipped++;
404 return 0;
405 }
406
407 r = tpm2_nvpcr_initialize(c->tpm2_context, /* session= */ NULL, name, &c->anchor_secret);
408 if (r == -EUNATCH) {
409 assert(!iovec_is_set(&c->anchor_secret));
410
411 /* If we get EUNATCH this means we actually need to initialize this NvPCR
412 * now, and haven't provided the anchor secret yet. Hence acquire it now. */
413
414 r = tpm2_nvpcr_acquire_anchor_secret(&c->anchor_secret, /* sync_secondary= */ !arg_early);
415 if (r < 0)
416 return log_error_errno(r, "Failed to acquire anchor secret: %m");
417
418 r = tpm2_nvpcr_initialize(c->tpm2_context, /* session= */ NULL, name, &c->anchor_secret);
419 }
420 if (r == -EOPNOTSUPP) {
421 c->n_failed++;
422 return log_struct_errno(LOG_ERR, r,
423 LOG_MESSAGE("The TPM does not correctly support NV indexes in NT_EXTEND mode, unable to allocate NvPCR '%s': %m", name),
424 LOG_MESSAGE_ID(SD_MESSAGE_TPM_NVPCR_UNSUPPORTED_STR));
425 }
426 if (r == -ENOSPC) {
427 /* The TPM's NV index space is exhausted. Remember this so we skip the remaining (less
428 * important) NvPCRs, and report it gracefully at the end rather than failing the boot.
429 * Logged at notice level, not error. */
430 c->nv_space_exhausted = true;
431 c->n_skipped++;
432 return log_struct_errno(LOG_NOTICE, r,
433 LOG_MESSAGE("The TPM's NV index space is exhausted, skipping allocation of NvPCR '%s' and any less important ones: %m", name),
434 LOG_MESSAGE_ID(SD_MESSAGE_TPM_NVINDEX_EXHAUSTED_STR));
435 }
436 if (r < 0) {
437 c->n_failed++;
438 return log_error_errno(r, "Failed to extend NvPCR index with anchor secret: %m");
439 }
440
441 if (r > 0)
442 c->n_anchored++;
443 else
444 c->n_already++;
445
446 if (set_put_strdup(&c->done, name) < 0)
447 return log_oom();
448
449 return 0;
450 }
451
452 typedef struct NvPCREntry {
453 const char *name; /* points into the strv 'l' in setup_nvpcr() */
454 uint64_t priority;
455 } NvPCREntry;
456
457 static int nvpcr_entry_compare(const NvPCREntry *a, const NvPCREntry *b) {
458 int r;
459
460 assert(a);
461 assert(b);
462
463 /* Lower priority value means more important, hence allocate it first. Break ties by name
464 * (ascending) so the resulting order is fully deterministic. */
465 r = CMP(a->priority, b->priority);
466 if (r != 0)
467 return r;
468
469 return strcmp(a->name, b->name);
470 }
471
472 static int setup_nvpcr(void) {
473 _cleanup_(setup_nvpcr_context_done) SetupNvPCRContext c = {};
474 int r;
475
476 _cleanup_strv_free_ char **l = NULL;
477 r = conf_files_list_nulstr(
478 &l,
479 ".nvpcr",
480 /* root= */ NULL,
481 CONF_FILES_REGULAR|CONF_FILES_BASENAME|CONF_FILES_FILTER_MASKED|CONF_FILES_TRUNCATE_SUFFIX|CONF_FILES_WARN,
482 CONF_PATHS_NULSTR("nvpcr"));
483 if (r < 0)
484 return log_error_errno(r, "Failed to find .nvpcr files: %m");
485
486 /* Pair each NvPCR name with its allocation priority, then sort, so that we allocate the most
487 * important NvPCRs first. This matters when the TPM's NV index space is too small to fit all of
488 * them: we then degrade gracefully, skipping the least important NvPCRs. */
489 size_t n = strv_length(l);
490 _cleanup_free_ NvPCREntry *entries = new(NvPCREntry, n);
491 if (!entries)
492 return log_oom();
493
494 for (size_t i = 0; i < n; i++) {
495 uint64_t priority = TPM2_NVPCR_PRIORITY_DEFAULT;
496
497 r = tpm2_nvpcr_get_index(l[i], /* ret_nv_index= */ NULL, &priority);
498 if (r < 0)
499 /* If we can't read the definition, assume the default priority and let the
500 * per-NvPCR error path in setup_nvpcr_one() report the actual problem. */
501 log_warning_errno(r, "Failed to read priority of NvPCR '%s', assuming default priority %" PRIu64 ": %m", l[i], priority);
502
503 entries[i] = (NvPCREntry) {
504 .name = l[i],
505 .priority = priority,
506 };
507 }
508
509 typesafe_qsort(entries, n, nvpcr_entry_compare);
510
511 int ret = 0;
512 FOREACH_ARRAY(e, entries, n) {
513 if (!c.tpm2_context) {
514 /* Inability to contact the TPM shall be fatal for us */
515 r = tpm2_context_new_or_warn(arg_tpm2_device, &c.tpm2_context);
516 if (r < 0)
517 return r;
518 }
519
520 log_debug("Setting up NvPCR '%s' (priority %" PRIu64 ").", e->name, e->priority);
521
522 /* But if we fail to initialize some NvPCR, we go on */
523 RET_GATHER(ret, setup_nvpcr_one(&c, e->name));
524 }
525
526 if (c.n_already > 0 && c.n_anchored == 0 && !arg_early)
527 /* If we didn't anchor anything right now, but we anchored something earlier, then it might
528 * have happened in the initrd, and thus the anchor ID was not committed to /var/ or the ESP
529 * yet. Hence, let's explicitly do so now, to catch up. */
530 RET_GATHER(ret, tpm2_nvpcr_acquire_anchor_secret(/* ret= */ NULL, /* sync_secondary= */ true));
531
532 if (c.nv_space_exhausted)
533 log_notice("Skipped %zu lowest-priority NvPCR(s) because the TPM's NV index space is exhausted, proceeding anyway.", c.n_skipped);
534
535 if (c.n_failed > 0)
536 log_warning("%zu NvPCRs failed to initialize, proceeding anyway.", c.n_failed);
537
538 if (c.n_anchored > 0) {
539 if (c.n_already == 0)
540 log_info("%zu NvPCRs initialized.", c.n_anchored);
541 else
542 log_info("%zu NvPCRs initialized. (%zu NvPCRs were already initialized.)", c.n_anchored, c.n_already);
543 } else if (c.n_already > 0)
544 log_info("%zu NvPCRs already initialized.", c.n_already);
545 else if (c.n_failed == 0 && c.n_skipped == 0)
546 log_debug("No NvPCRs defined, nothing initialized.");
547
548 /* Turn some errors into recognizable ones, which we can catch with
549 * SuccessExitStatus= in the service unit file. */
550 if (ret == -EOPNOTSUPP)
551 return EX_UNAVAILABLE; /* e.g. no NvPCR support in TPM */
552 if (ret == -ENOSPC)
553 return EX_CANTCREAT; /* NV index space on TPM exhausted */
554
555 return ret;
556 }
557
558 static int run(int argc, char *argv[]) {
559 int r;
560
561 log_setup();
562
563 r = parse_argv(argc, argv);
564 if (r <= 0)
565 return r;
566
567 if (arg_graceful && !tpm2_is_mostly_supported()) {
568 log_notice("No complete TPM2 support detected, exiting gracefully.");
569 return EXIT_SUCCESS;
570 }
571
572 r = DLOPEN_LIBCRYPTO(LOG_ERR, SD_ELF_NOTE_DLOPEN_PRIORITY_REQUIRED);
573 if (r < 0)
574 return r;
575
576 umask(0022);
577
578 /* Execute both jobs, and then return unlisted errors preferably, and listed errors
579 * (i.e. EX_UNAVAILABLE, EX_CANTCREAT, EX_PROTOCOL) otherwise. */
580 r = setup_srk();
581 int k = setup_nvpcr();
582 if (r < 0)
583 return r;
584 if (k < 0)
585 return k;
586 return r != EXIT_SUCCESS ? r : k;
587 }
588
589 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);