]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/boot/measure.c
Merge pull request #24790 from poettering/run-chdir
[thirdparty/systemd.git] / src / boot / measure.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <getopt.h>
4 #include <unistd.h>
5
6 #include "alloc-util.h"
7 #include "efi-loader.h"
8 #include "fd-util.h"
9 #include "fileio.h"
10 #include "hexdecoct.h"
11 #include "json.h"
12 #include "main-func.h"
13 #include "openssl-util.h"
14 #include "parse-argument.h"
15 #include "parse-util.h"
16 #include "pretty-print.h"
17 #include "sha256.h"
18 #include "terminal-util.h"
19 #include "tpm-pcr.h"
20 #include "tpm2-util.h"
21 #include "verbs.h"
22
23 /* Tool for pre-calculating expected TPM PCR values based on measured resources. This is intended to be used
24 * to pre-calculate suitable values for PCR 11, the way sd-stub measures into it. */
25
26 static char *arg_sections[_UNIFIED_SECTION_MAX] = {};
27 static char **arg_banks = NULL;
28 static char *arg_tpm2_device = NULL;
29 static char *arg_private_key = NULL;
30 static char *arg_public_key = NULL;
31 static JsonFormatFlags arg_json_format_flags = JSON_FORMAT_PRETTY_AUTO|JSON_FORMAT_COLOR_AUTO|JSON_FORMAT_OFF;
32 static PagerFlags arg_pager_flags = 0;
33 static bool arg_current = false;
34 static char **arg_phase = NULL;
35
36 STATIC_DESTRUCTOR_REGISTER(arg_banks, strv_freep);
37 STATIC_DESTRUCTOR_REGISTER(arg_tpm2_device, freep);
38 STATIC_DESTRUCTOR_REGISTER(arg_private_key, freep);
39 STATIC_DESTRUCTOR_REGISTER(arg_public_key, freep);
40 STATIC_DESTRUCTOR_REGISTER(arg_phase, strv_freep);
41
42 static inline void free_sections(char*(*sections)[_UNIFIED_SECTION_MAX]) {
43 for (UnifiedSection c = 0; c < _UNIFIED_SECTION_MAX; c++)
44 free((*sections)[c]);
45 }
46
47 STATIC_DESTRUCTOR_REGISTER(arg_sections, free_sections);
48
49 static int help(int argc, char *argv[], void *userdata) {
50 _cleanup_free_ char *link = NULL;
51 int r;
52
53 r = terminal_urlify_man("systemd-measure", "1", &link);
54 if (r < 0)
55 return log_oom();
56
57 printf("%1$s [OPTIONS...] COMMAND ...\n"
58 "\n%5$sPre-calculate and sign PCR hash for a unified kernel image (UKI).%6$s\n"
59 "\n%3$sCommands:%4$s\n"
60 " status Show current PCR values\n"
61 " calculate Calculate expected PCR values\n"
62 " sign Calculate and sign expected PCR values\n"
63 "\n%3$sOptions:%4$s\n"
64 " -h --help Show this help\n"
65 " --version Print version\n"
66 " --no-pager Do not pipe output into a pager\n"
67 " -c --current Use current PCR values\n"
68 " --phase=PHASE Specify a boot phase to sign for\n"
69 " --bank=DIGEST Select TPM bank (SHA1, SHA256, SHA384, SHA512)\n"
70 " --tpm2-device=PATH Use specified TPM2 device\n"
71 " --private-key=KEY Private key (PEM) to sign with\n"
72 " --public-key=KEY Public key (PEM) to validate against\n"
73 " --json=MODE Output as JSON\n"
74 " -j Same as --json=pretty on tty, --json=short otherwise\n"
75 "\n%3$sUKI PE Section Options:%4$s %3$sUKI PE Section%4$s\n"
76 " --linux=PATH Path to Linux kernel image file %7$s .linux\n"
77 " --osrel=PATH Path to os-release file %7$s .osrel\n"
78 " --cmdline=PATH Path to file with kernel command line %7$s .cmdline\n"
79 " --initrd=PATH Path to initrd image file %7$s .initrd\n"
80 " --splash=PATH Path to splash bitmap file %7$s .splash\n"
81 " --dtb=PATH Path to Devicetree file %7$s .dtb\n"
82 " --pcrpkey=PATH Path to public key for PCR signatures %7$s .pcrpkey\n"
83 "\nSee the %2$s for details.\n",
84 program_invocation_short_name,
85 link,
86 ansi_underline(),
87 ansi_normal(),
88 ansi_highlight(),
89 ansi_normal(),
90 special_glyph(SPECIAL_GLYPH_ARROW_RIGHT));
91
92 return 0;
93 }
94
95 static char *normalize_phase(const char *s) {
96 _cleanup_strv_free_ char **l = NULL;
97
98 /* Let's normalize phase expressions. We split the series of colon-separated words up, then remove
99 * all empty ones, and glue them back together again. In other words we remove duplicate ":", as well
100 * as leading and trailing ones. */
101
102 l = strv_split(s, ":"); /* Split series of words */
103 if (!l)
104 return NULL;
105
106 /* Remove all empty words and glue things back together */
107 return strv_join(strv_remove(l, ""), ":");
108 }
109
110 static int parse_argv(int argc, char *argv[]) {
111 enum {
112 ARG_VERSION = 0x100,
113 ARG_NO_PAGER,
114 _ARG_SECTION_FIRST,
115 ARG_LINUX = _ARG_SECTION_FIRST,
116 ARG_OSREL,
117 ARG_CMDLINE,
118 ARG_INITRD,
119 ARG_SPLASH,
120 ARG_DTB,
121 _ARG_PCRSIG, /* the .pcrsig section is not input for signing, hence not actually an argument here */
122 _ARG_SECTION_LAST,
123 ARG_PCRPKEY = _ARG_SECTION_LAST,
124 ARG_BANK,
125 ARG_PRIVATE_KEY,
126 ARG_PUBLIC_KEY,
127 ARG_TPM2_DEVICE,
128 ARG_JSON,
129 ARG_PHASE,
130 };
131
132 static const struct option options[] = {
133 { "help", no_argument, NULL, 'h' },
134 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
135 { "version", no_argument, NULL, ARG_VERSION },
136 { "linux", required_argument, NULL, ARG_LINUX },
137 { "osrel", required_argument, NULL, ARG_OSREL },
138 { "cmdline", required_argument, NULL, ARG_CMDLINE },
139 { "initrd", required_argument, NULL, ARG_INITRD },
140 { "splash", required_argument, NULL, ARG_SPLASH },
141 { "dtb", required_argument, NULL, ARG_DTB },
142 { "pcrpkey", required_argument, NULL, ARG_PCRPKEY },
143 { "current", no_argument, NULL, 'c' },
144 { "bank", required_argument, NULL, ARG_BANK },
145 { "tpm2-device", required_argument, NULL, ARG_TPM2_DEVICE },
146 { "private-key", required_argument, NULL, ARG_PRIVATE_KEY },
147 { "public-key", required_argument, NULL, ARG_PUBLIC_KEY },
148 { "json", required_argument, NULL, ARG_JSON },
149 { "phase", required_argument, NULL, ARG_PHASE },
150 {}
151 };
152
153 int c, r;
154
155 assert(argc >= 0);
156 assert(argv);
157
158 /* Make sure the arguments list and the section list, stays in sync */
159 assert_cc(_ARG_SECTION_FIRST + _UNIFIED_SECTION_MAX == _ARG_SECTION_LAST + 1);
160
161 while ((c = getopt_long(argc, argv, "hjc", options, NULL)) >= 0)
162 switch (c) {
163
164 case 'h':
165 help(0, NULL, NULL);
166 return 0;
167
168 case ARG_VERSION:
169 return version();
170
171 case ARG_NO_PAGER:
172 arg_pager_flags |= PAGER_DISABLE;
173 break;
174
175 case _ARG_SECTION_FIRST..._ARG_SECTION_LAST: {
176 UnifiedSection section = c - _ARG_SECTION_FIRST;
177
178 r = parse_path_argument(optarg, /* suppress_root= */ false, arg_sections + section);
179 if (r < 0)
180 return r;
181 break;
182 }
183
184 case 'c':
185 arg_current = true;
186 break;
187
188 case ARG_BANK: {
189 const EVP_MD *implementation;
190
191 implementation = EVP_get_digestbyname(optarg);
192 if (!implementation)
193 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown bank '%s', refusing.", optarg);
194
195 if (strv_extend(&arg_banks, EVP_MD_name(implementation)) < 0)
196 return log_oom();
197
198 break;
199 }
200
201 case ARG_PRIVATE_KEY:
202 r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_private_key);
203 if (r < 0)
204 return r;
205
206 break;
207
208 case ARG_PUBLIC_KEY:
209 r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_public_key);
210 if (r < 0)
211 return r;
212
213 break;
214
215 case ARG_TPM2_DEVICE: {
216 _cleanup_free_ char *device = NULL;
217
218 if (streq(optarg, "list"))
219 return tpm2_list_devices();
220
221 if (!streq(optarg, "auto")) {
222 device = strdup(optarg);
223 if (!device)
224 return log_oom();
225 }
226
227 free_and_replace(arg_tpm2_device, device);
228 break;
229 }
230
231 case 'j':
232 arg_json_format_flags = JSON_FORMAT_PRETTY_AUTO|JSON_FORMAT_COLOR_AUTO;
233 break;
234
235 case ARG_JSON:
236 r = parse_json_argument(optarg, &arg_json_format_flags);
237 if (r <= 0)
238 return r;
239
240 break;
241
242 case ARG_PHASE: {
243 char *n;
244
245 n = normalize_phase(optarg);
246 if (!n)
247 return log_oom();
248
249 r = strv_consume(&arg_phase, TAKE_PTR(n));
250 if (r < 0)
251 return r;
252
253 break;
254 }
255
256 case '?':
257 return -EINVAL;
258
259 default:
260 assert_not_reached();
261 }
262
263 if (strv_isempty(arg_banks)) {
264 /* If no banks are specifically selected, pick all known banks */
265 arg_banks = strv_new("SHA1", "SHA256", "SHA384", "SHA512");
266 if (!arg_banks)
267 return log_oom();
268 }
269
270 strv_sort(arg_banks);
271 strv_uniq(arg_banks);
272
273 if (arg_current)
274 for (UnifiedSection us = 0; us < _UNIFIED_SECTION_MAX; us++)
275 if (arg_sections[us])
276 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "The --current switch cannot be used in combination with --linux= and related switches.");
277
278 if (strv_isempty(arg_phase)) {
279 /* If no phases are specifically selected, pick everything from the beginning of the initrd
280 * to the beginning of shutdown. */
281 if (strv_extend_strv(&arg_phase,
282 STRV_MAKE("enter-initrd",
283 "enter-initrd:leave-initrd",
284 "enter-initrd:leave-initrd:ready"),
285 /* filter_duplicates= */ false) < 0)
286 return log_oom();
287 } else {
288 strv_sort(arg_phase);
289 strv_uniq(arg_phase);
290 }
291
292 _cleanup_free_ char *j = NULL;
293 j = strv_join(arg_phase, ", ");
294 if (!j)
295 return log_oom();
296
297 log_debug("Measuring boot phases: %s", j);
298 return 1;
299 }
300
301 /* The PCR 11 state for one specific bank */
302 typedef struct PcrState {
303 char *bank;
304 const EVP_MD *md;
305 void *value;
306 size_t value_size;
307 void *saved_value; /* A copy of the original value we calculated, used by pcr_states_save()/pcr_states_restore() to come later back to */
308 } PcrState;
309
310 static void pcr_state_free_all(PcrState **pcr_state) {
311 assert(pcr_state);
312
313 if (!*pcr_state)
314 return;
315
316 for (size_t i = 0; (*pcr_state)[i].value; i++) {
317 free((*pcr_state)[i].bank);
318 free((*pcr_state)[i].value);
319 free((*pcr_state)[i].saved_value);
320 }
321
322 *pcr_state = mfree(*pcr_state);
323 }
324
325 static void evp_md_ctx_free_all(EVP_MD_CTX **md[]) {
326 assert(md);
327
328 if (!*md)
329 return;
330
331 for (size_t i = 0; (*md)[i]; i++)
332 EVP_MD_CTX_free((*md)[i]);
333
334 *md = mfree(*md);
335 }
336
337 static int pcr_state_extend(PcrState *pcr_state, const void *data, size_t sz) {
338 _cleanup_(EVP_MD_CTX_freep) EVP_MD_CTX *mc = NULL;
339 unsigned value_size;
340
341 assert(pcr_state);
342 assert(data || sz == 0);
343 assert(pcr_state->md);
344 assert(pcr_state->value);
345 assert(pcr_state->value_size > 0);
346
347 /* Extends a (virtual) PCR by the given data */
348
349 mc = EVP_MD_CTX_new();
350 if (!mc)
351 return log_oom();
352
353 if (EVP_DigestInit_ex(mc, pcr_state->md, NULL) != 1)
354 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to initialize %s context.", pcr_state->bank);
355
356 /* First thing we do, is hash the old PCR value */
357 if (EVP_DigestUpdate(mc, pcr_state->value, pcr_state->value_size) != 1)
358 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to run digest.");
359
360 /* Then, we hash the new data */
361 if (EVP_DigestUpdate(mc, data, sz) != 1)
362 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to run digest.");
363
364 if (EVP_DigestFinal_ex(mc, pcr_state->value, &value_size) != 1)
365 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to finalize hash context.");
366
367 assert(value_size == pcr_state->value_size);
368 return 0;
369 }
370
371 #define BUFFER_SIZE (16U * 1024U)
372
373 static int measure_kernel(PcrState *pcr_states, size_t n) {
374 _cleanup_free_ void *buffer = NULL;
375 int r;
376
377 assert(n > 0);
378 assert(pcr_states);
379
380 /* Virtually measures the components of a unified kernel image into PCR 11 */
381
382 if (arg_current) {
383 /* Shortcut things, if we should just use the current PCR value */
384
385 for (size_t i = 0; i < n; i++) {
386 _cleanup_free_ char *p = NULL, *s = NULL;
387 _cleanup_free_ void *v = NULL;
388 size_t sz;
389
390 if (asprintf(&p, "/sys/class/tpm/tpm0/pcr-%s/%" PRIu32, pcr_states[i].bank, TPM_PCR_INDEX_KERNEL_IMAGE) < 0)
391 return log_oom();
392
393 r = read_virtual_file(p, 4096, &s, NULL);
394 if (r == -ENOENT && access("/sys/class/tpm/tpm0/", F_OK) >= 0)
395 return log_error_errno(r, "TPM device exists, but cannot open '%s'; either the kernel is too old, or selected PCR bank is not supported: %m", p);
396 if (r < 0)
397 return log_error_errno(r, "Failed to read '%s': %m", p);
398
399 r = unhexmem(strstrip(s), SIZE_MAX, &v, &sz);
400 if (r < 0)
401 return log_error_errno(r, "Failed to decode PCR value '%s': %m", s);
402
403 assert(pcr_states[i].value_size == sz);
404 memcpy(pcr_states[i].value, v, sz);
405 }
406
407 return 0;
408 }
409
410 buffer = malloc(BUFFER_SIZE);
411 if (!buffer)
412 return log_oom();
413
414 for (UnifiedSection c = 0; c < _UNIFIED_SECTION_MAX; c++) {
415 _cleanup_(evp_md_ctx_free_all) EVP_MD_CTX **mdctx = NULL;
416 _cleanup_close_ int fd = -1;
417 uint64_t m = 0;
418
419 if (!arg_sections[c])
420 continue;
421
422 fd = open(arg_sections[c], O_RDONLY|O_CLOEXEC);
423 if (fd < 0)
424 return log_error_errno(errno, "Failed to open '%s': %m", arg_sections[c]);
425
426 /* Allocate one message digest context per bank (NULL terminated) */
427 mdctx = new0(EVP_MD_CTX*, n + 1);
428 if (!mdctx)
429 return log_oom();
430
431 for (size_t i = 0; i < n; i++) {
432 mdctx[i] = EVP_MD_CTX_new();
433 if (!mdctx[i])
434 return log_oom();
435
436 if (EVP_DigestInit_ex(mdctx[i], pcr_states[i].md, NULL) != 1)
437 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to initialize data %s context.", pcr_states[i].bank);
438 }
439
440 for (;;) {
441 ssize_t sz;
442
443 sz = read(fd, buffer, BUFFER_SIZE);
444 if (sz < 0)
445 return log_error_errno(errno, "Failed to read '%s': %m", arg_sections[c]);
446 if (sz == 0) /* EOF */
447 break;
448
449 for (size_t i = 0; i < n; i++)
450 if (EVP_DigestUpdate(mdctx[i], buffer, sz) != 1)
451 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to run digest.");
452
453 m += sz;
454 }
455
456 fd = safe_close(fd);
457
458 if (m == 0) /* We skip over empty files, the stub does so too */
459 continue;
460
461 for (size_t i = 0; i < n; i++) {
462 _cleanup_free_ void *data_hash = NULL;
463 unsigned data_hash_size;
464
465 data_hash = malloc(pcr_states[i].value_size);
466 if (!data_hash)
467 return log_oom();
468
469 /* Measure name of section */
470 if (EVP_Digest(unified_sections[c], strlen(unified_sections[c]) + 1, data_hash, &data_hash_size, pcr_states[i].md, NULL) != 1)
471 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to hash section name with %s.", pcr_states[i].bank);
472
473 assert(data_hash_size == (unsigned) pcr_states[i].value_size);
474
475 r = pcr_state_extend(pcr_states + i, data_hash, data_hash_size);
476 if (r < 0)
477 return r;
478
479 /* Retrieve hash of data and measure it */
480 if (EVP_DigestFinal_ex(mdctx[i], data_hash, &data_hash_size) != 1)
481 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to finalize hash context.");
482
483 assert(data_hash_size == (unsigned) pcr_states[i].value_size);
484
485 r = pcr_state_extend(pcr_states + i, data_hash, data_hash_size);
486 if (r < 0)
487 return r;
488 }
489 }
490
491 return 0;
492 }
493
494 static int measure_phase(PcrState *pcr_states, size_t n, const char *phase) {
495 _cleanup_strv_free_ char **l = NULL;
496 int r;
497
498 assert(pcr_states);
499 assert(n > 0);
500
501 /* Measure a phase string into PCR 11. This splits up the "phase" expression at colons, and then
502 * virtually extends each specified word into PCR 11, to model how during boot we measure a series of
503 * words into PCR 11, one for each phase. */
504
505 l = strv_split(phase, ":");
506 if (!l)
507 return log_oom();
508
509 STRV_FOREACH(word, l) {
510 size_t wl;
511
512 if (isempty(*word))
513 continue;
514
515 wl = strlen(*word);
516
517 for (size_t i = 0; i < n; i++) { /* For each bank */
518 _cleanup_free_ void *b = NULL;
519 int bsz;
520
521 bsz = EVP_MD_size(pcr_states[i].md);
522 assert(bsz > 0);
523
524 b = malloc(bsz);
525 if (!b)
526 return log_oom();
527
528 /* First hash the word itself */
529 if (EVP_Digest(*word, wl, b, NULL, pcr_states[i].md, NULL) != 1)
530 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Failed to hash word '%s'.", *word);
531
532 /* And then extend the PCR with the resulting hash */
533 r = pcr_state_extend(pcr_states + i, b, bsz);
534 if (r < 0)
535 return r;
536 }
537 }
538
539 return 0;
540 }
541
542 static int pcr_states_allocate(PcrState **ret) {
543 _cleanup_(pcr_state_free_all) PcrState *pcr_states = NULL;
544 size_t n = 0;
545
546 pcr_states = new0(PcrState, strv_length(arg_banks) + 1);
547 if (!pcr_states)
548 return log_oom();
549
550 /* Allocate a PCR state structure, one for each bank */
551 STRV_FOREACH(d, arg_banks) {
552 const EVP_MD *implementation;
553 _cleanup_free_ void *v = NULL;
554 _cleanup_free_ char *b = NULL;
555 int sz;
556
557 assert_se(implementation = EVP_get_digestbyname(*d)); /* Must work, we already checked while parsing command line */
558
559 b = strdup(EVP_MD_name(implementation));
560 if (!b)
561 return log_oom();
562
563 sz = EVP_MD_size(implementation);
564 if (sz <= 0 || sz >= INT_MAX)
565 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unexpected digest size: %i", sz);
566
567 v = malloc0(sz); /* initial PCR state is all zeroes */
568 if (!v)
569 return log_oom();
570
571 pcr_states[n++] = (struct PcrState) {
572 .bank = ascii_strlower(TAKE_PTR(b)),
573 .md = implementation,
574 .value = TAKE_PTR(v),
575 .value_size = sz,
576 };
577 }
578
579 *ret = TAKE_PTR(pcr_states);
580 return (int) n;
581 }
582
583 static int pcr_states_save(PcrState *pcr_states, size_t n) {
584 assert(pcr_states);
585 assert(n > 0);
586
587 for (size_t i = 0; i < n; i++) {
588 _cleanup_free_ void *saved = NULL;
589
590 if (!pcr_states[i].value)
591 continue;
592
593 saved = memdup(pcr_states[i].value, pcr_states[i].value_size);
594 if (!saved)
595 return log_oom();
596
597 free_and_replace(pcr_states[i].saved_value, saved);
598 }
599
600 return 0;
601 }
602
603 static void pcr_states_restore(PcrState *pcr_states, size_t n) {
604 assert(pcr_states);
605 assert(n > 0);
606
607 for (size_t i = 0; i < n; i++) {
608
609 assert(pcr_states[i].value);
610 assert(pcr_states[i].saved_value);
611
612 memcpy(pcr_states[i].value, pcr_states[i].saved_value, pcr_states[i].value_size);
613 }
614 }
615
616 static int verb_calculate(int argc, char *argv[], void *userdata) {
617 _cleanup_(json_variant_unrefp) JsonVariant *w = NULL;
618 _cleanup_(pcr_state_free_all) PcrState *pcr_states = NULL;
619 size_t n;
620 int r;
621
622 if (!arg_sections[UNIFIED_SECTION_LINUX] && !arg_current)
623 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Either --linux= or --current must be specified, refusing.");
624
625 r = pcr_states_allocate(&pcr_states);
626 if (r < 0)
627 return r;
628
629 n = (size_t) r;
630
631 r = measure_kernel(pcr_states, n);
632 if (r < 0)
633 return r;
634
635 /* Save the current state, so that we later can restore to it. This way we can measure the PCR values
636 * for multiple different boot phases without heaving to start from zero each time */
637 r = pcr_states_save(pcr_states, n);
638 if (r < 0)
639 return r;
640
641 STRV_FOREACH(phase, arg_phase) {
642
643 r = measure_phase(pcr_states, n, *phase);
644 if (r < 0)
645 return r;
646
647 for (size_t i = 0; i < n; i++) {
648 if (arg_json_format_flags & JSON_FORMAT_OFF) {
649 _cleanup_free_ char *hd = NULL;
650
651 if (i == 0) {
652 fflush(stdout);
653 fprintf(stderr, "%s# PCR[%" PRIu32 "] Phase <%s>%s\n",
654 ansi_grey(),
655 TPM_PCR_INDEX_KERNEL_IMAGE,
656 isempty(*phase) ? ":" : *phase,
657 ansi_normal());
658 fflush(stderr);
659 }
660
661 hd = hexmem(pcr_states[i].value, pcr_states[i].value_size);
662 if (!hd)
663 return log_oom();
664
665 printf("%" PRIu32 ":%s=%s\n", TPM_PCR_INDEX_KERNEL_IMAGE, pcr_states[i].bank, hd);
666 } else {
667 _cleanup_(json_variant_unrefp) JsonVariant *bv = NULL, *array = NULL;
668
669 array = json_variant_ref(json_variant_by_key(w, pcr_states[i].bank));
670
671 r = json_build(&bv,
672 JSON_BUILD_OBJECT(
673 JSON_BUILD_PAIR_CONDITION(!isempty(*phase), "phase", JSON_BUILD_STRING(*phase)),
674 JSON_BUILD_PAIR("pcr", JSON_BUILD_INTEGER(TPM_PCR_INDEX_KERNEL_IMAGE)),
675 JSON_BUILD_PAIR("hash", JSON_BUILD_HEX(pcr_states[i].value, pcr_states[i].value_size))
676 )
677 );
678 if (r < 0)
679 return log_error_errno(r, "Failed to build JSON object: %m");
680
681 r = json_variant_append_array(&array, bv);
682 if (r < 0)
683 return log_error_errno(r, "Failed to append JSON object to array: %m");
684
685 r = json_variant_set_field(&w, pcr_states[i].bank, array);
686 if (r < 0)
687 return log_error_errno(r, "Failed to add bank info to object: %m");
688 }
689 }
690
691 /* Return to the original kernel measurement for the next phase calculation */
692 pcr_states_restore(pcr_states, n);
693 }
694
695 if (!FLAGS_SET(arg_json_format_flags, JSON_FORMAT_OFF)) {
696
697 if (arg_json_format_flags & (JSON_FORMAT_PRETTY|JSON_FORMAT_PRETTY_AUTO))
698 pager_open(arg_pager_flags);
699
700 json_variant_dump(w, arg_json_format_flags, stdout, NULL);
701 }
702
703 return 0;
704 }
705
706 static int verb_sign(int argc, char *argv[], void *userdata) {
707 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
708 _cleanup_(pcr_state_free_all) PcrState *pcr_states = NULL;
709 _cleanup_(EVP_PKEY_freep) EVP_PKEY *privkey = NULL, *pubkey = NULL;
710 _cleanup_(tpm2_context_destroy) struct tpm2_context c = {};
711 _cleanup_fclose_ FILE *privkeyf = NULL;
712 ESYS_TR session_handle = ESYS_TR_NONE;
713 TSS2_RC rc;
714 size_t n;
715 int r;
716
717 if (!arg_sections[UNIFIED_SECTION_LINUX] && !arg_current)
718 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Either --linux= or --current must be specified, refusing.");
719
720 if (!arg_private_key)
721 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No private key specified, use --private-key=.");
722
723 /* When signing we only support JSON output */
724 arg_json_format_flags &= ~JSON_FORMAT_OFF;
725
726 privkeyf = fopen(arg_private_key, "re");
727 if (!privkeyf)
728 return log_error_errno(errno, "Failed to open private key file '%s': %m", arg_private_key);
729
730 privkey = PEM_read_PrivateKey(privkeyf, NULL, NULL, NULL);
731 if (!privkey)
732 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to parse private key '%s'.", arg_private_key);
733
734 if (arg_public_key) {
735 _cleanup_fclose_ FILE *pubkeyf = NULL;
736
737 pubkeyf = fopen(arg_public_key, "re");
738 if (!pubkeyf)
739 return log_error_errno(errno, "Failed to open public key file '%s': %m", arg_public_key);
740
741 pubkey = PEM_read_PUBKEY(pubkeyf, NULL, NULL, NULL);
742 if (!pubkey)
743 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to parse public key '%s'.", arg_public_key);
744 } else {
745 _cleanup_free_ char *data = NULL;
746 _cleanup_fclose_ FILE *tf = NULL;
747 size_t sz;
748
749 /* No public key was specified, let's derive it automatically, if we can */
750
751 tf = open_memstream_unlocked(&data, &sz);
752 if (!tf)
753 return log_oom();
754
755 if (i2d_PUBKEY_fp(tf, privkey) != 1)
756 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to extract public key from private key file '%s'.", arg_private_key);
757
758 fflush(tf);
759 rewind(tf);
760
761 if (!d2i_PUBKEY_fp(tf, &pubkey))
762 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to parse extracted public key of private key file '%s'.", arg_private_key);
763 }
764
765 r = pcr_states_allocate(&pcr_states);
766 if (r < 0)
767 return r;
768
769 n = (size_t) r;
770
771 r = measure_kernel(pcr_states, n);
772 if (r < 0)
773 return r;
774
775 r = dlopen_tpm2();
776 if (r < 0)
777 return r;
778
779 r = tpm2_context_init(arg_tpm2_device, &c);
780 if (r < 0)
781 return r;
782
783 for (size_t i = 0; i < n; i++) {
784 static const TPMT_SYM_DEF symmetric = {
785 .algorithm = TPM2_ALG_AES,
786 .keyBits.aes = 128,
787 .mode.aes = TPM2_ALG_CFB,
788 };
789 PcrState *p = pcr_states + i;
790
791 rc = sym_Esys_StartAuthSession(
792 c.esys_context,
793 ESYS_TR_NONE,
794 ESYS_TR_NONE,
795 ESYS_TR_NONE,
796 ESYS_TR_NONE,
797 ESYS_TR_NONE,
798 NULL,
799 TPM2_SE_TRIAL,
800 &symmetric,
801 TPM2_ALG_SHA256,
802 &session_handle);
803 if (rc != TSS2_RC_SUCCESS) {
804 r = log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
805 "Failed to open session in TPM: %s", sym_Tss2_RC_Decode(rc));
806 goto finish;
807 }
808
809 /* Generate a single hash value from the PCRs included in our policy. Given that that's
810 * exactly one, the calculation is trivial. */
811 TPM2B_DIGEST intermediate_digest = {
812 .size = SHA256_DIGEST_SIZE,
813 };
814 assert(sizeof(intermediate_digest.buffer) >= SHA256_DIGEST_SIZE);
815 sha256_direct(p->value, p->value_size, intermediate_digest.buffer);
816
817 int tpmalg = tpm2_pcr_bank_from_string(EVP_MD_name(p->md));
818 if (tpmalg < 0) {
819 log_error_errno(tpmalg, "Unsupported PCR bank");
820 goto finish;
821 }
822
823 TPML_PCR_SELECTION pcr_selection;
824 tpm2_pcr_mask_to_selection(1 << TPM_PCR_INDEX_KERNEL_IMAGE, tpmalg, &pcr_selection);
825
826 rc = sym_Esys_PolicyPCR(
827 c.esys_context,
828 session_handle,
829 ESYS_TR_NONE,
830 ESYS_TR_NONE,
831 ESYS_TR_NONE,
832 &intermediate_digest,
833 &pcr_selection);
834 if (rc != TSS2_RC_SUCCESS) {
835 r = log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
836 "Failed to push PCR policy into TPM: %s", sym_Tss2_RC_Decode(rc));
837 goto finish;
838 }
839
840 _cleanup_(Esys_Freep) TPM2B_DIGEST *pcr_policy_digest = NULL;
841 rc = sym_Esys_PolicyGetDigest(
842 c.esys_context,
843 session_handle,
844 ESYS_TR_NONE,
845 ESYS_TR_NONE,
846 ESYS_TR_NONE,
847 &pcr_policy_digest);
848 if (rc != TSS2_RC_SUCCESS) {
849 r = log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
850 "Failed to get policy digest from TPM: %s", sym_Tss2_RC_Decode(rc));
851 goto finish;
852 }
853
854 session_handle = tpm2_flush_context_verbose(c.esys_context, session_handle);
855
856 _cleanup_(EVP_MD_CTX_freep) EVP_MD_CTX* mdctx = NULL;
857 mdctx = EVP_MD_CTX_new();
858 if (!mdctx) {
859 r = log_oom();
860 goto finish;
861 }
862
863 if (EVP_DigestSignInit(mdctx, NULL, p->md, NULL, privkey) != 1) {
864 r = log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
865 "Failed to initialize signature context.");
866 goto finish;
867 }
868
869 if (EVP_DigestSignUpdate(mdctx, pcr_policy_digest->buffer, pcr_policy_digest->size) != 1) {
870 r = log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
871 "Failed to sign data.");
872 goto finish;
873 }
874
875 size_t ss;
876 if (EVP_DigestSignFinal(mdctx, NULL, &ss) != 1) {
877 r = log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
878 "Failed to finalize signature");
879 goto finish;
880 }
881
882 _cleanup_free_ void *sig = malloc(ss);
883 if (!ss) {
884 r = log_oom();
885 goto finish;
886 }
887
888 if (EVP_DigestSignFinal(mdctx, sig, &ss) != 1) {
889 r = log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
890 "Failed to acquire signature data");
891 goto finish;
892 }
893
894 _cleanup_free_ void *pubkey_fp = NULL;
895 size_t pubkey_fp_size = 0;
896 r = pubkey_fingerprint(pubkey, EVP_sha256(), &pubkey_fp, &pubkey_fp_size);
897 if (r < 0)
898 goto finish;
899
900 _cleanup_(json_variant_unrefp) JsonVariant *bv = NULL, *a = NULL;
901
902 r = tpm2_make_pcr_json_array(UINT64_C(1) << TPM_PCR_INDEX_KERNEL_IMAGE, &a);
903 if (r < 0) {
904 log_error_errno(r, "Failed to build JSON PCR mask array: %m");
905 goto finish;
906 }
907
908 r = json_build(&bv, JSON_BUILD_ARRAY(
909 JSON_BUILD_OBJECT(
910 JSON_BUILD_PAIR("pcrs", JSON_BUILD_VARIANT(a)), /* PCR mask */
911 JSON_BUILD_PAIR("pkfp", JSON_BUILD_HEX(pubkey_fp, pubkey_fp_size)), /* SHA256 fingerprint of public key (DER) used for the signature */
912 JSON_BUILD_PAIR("pol", JSON_BUILD_HEX(pcr_policy_digest->buffer, pcr_policy_digest->size)), /* TPM2 policy hash that is signed */
913 JSON_BUILD_PAIR("sig", JSON_BUILD_BASE64(sig, ss))))); /* signature data */
914 if (r < 0) {
915 log_error_errno(r, "Failed to build JSON object: %m");
916 goto finish;
917 }
918
919 r = json_variant_set_field(&v, p->bank, bv);
920 if (r < 0) {
921 log_error_errno(r, "Failed to add JSON field: %m");
922 goto finish;
923 }
924 }
925
926 if (!v)
927 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unable to find a single working PCR bank.");
928
929 if (arg_json_format_flags & (JSON_FORMAT_PRETTY|JSON_FORMAT_PRETTY_AUTO))
930 pager_open(arg_pager_flags);
931
932 json_variant_dump(v, arg_json_format_flags, stdout, NULL);
933 r = 0;
934
935 finish:
936 session_handle = tpm2_flush_context_verbose(c.esys_context, session_handle);
937 return r;
938 }
939
940 static int compare_reported_pcr_nr(uint32_t pcr, const char *varname, const char *description) {
941 _cleanup_free_ char *s = NULL;
942 uint32_t v;
943 int r;
944
945 r = efi_get_variable_string(varname, &s);
946 if (r == -ENOENT)
947 return 0;
948 if (r < 0)
949 return log_error_errno(r, "Failed to read EFI variable '%s': %m", varname);
950
951 r = safe_atou32(s, &v);
952 if (r < 0)
953 return log_error_errno(r, "Failed to parse EFI variable '%s': %s", varname, s);
954
955 if (pcr != v)
956 log_warning("PCR number reported by stub for %s (%" PRIu32 ") different from our expectation (%" PRIu32 ").\n"
957 "The measurements are likely inconsistent.", description, v, pcr);
958
959 return 0;
960 }
961
962 static int validate_stub(void) {
963 uint64_t features;
964 bool found = false;
965 int r;
966
967 if (tpm2_support() != TPM2_SUPPORT_FULL)
968 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Sorry, system lacks full TPM2 support.");
969
970 r = efi_stub_get_features(&features);
971 if (r < 0)
972 return log_error_errno(r, "Unable to get stub features: %m");
973
974 if (!FLAGS_SET(features, EFI_STUB_FEATURE_THREE_PCRS))
975 log_warning("Warning: current kernel image does not support measuring itself, the command line or initrd system extension images.\n"
976 "The PCR measurements seen are unlikely to be valid.");
977
978 r = compare_reported_pcr_nr(TPM_PCR_INDEX_KERNEL_IMAGE, EFI_LOADER_VARIABLE("StubPcrKernelImage"), "kernel image");
979 if (r < 0)
980 return r;
981
982 r = compare_reported_pcr_nr(TPM_PCR_INDEX_KERNEL_PARAMETERS, EFI_LOADER_VARIABLE("StubPcrKernelParameters"), "kernel parameters");
983 if (r < 0)
984 return r;
985
986 r = compare_reported_pcr_nr(TPM_PCR_INDEX_INITRD_SYSEXTS, EFI_LOADER_VARIABLE("StubPcrInitRDSysExts"), "initrd system extension images");
987 if (r < 0)
988 return r;
989
990 STRV_FOREACH(bank, arg_banks) {
991 _cleanup_free_ char *b = NULL, *p = NULL;
992
993 b = strdup(*bank);
994 if (!b)
995 return log_oom();
996
997 if (asprintf(&p, "/sys/class/tpm/tpm0/pcr-%s/", ascii_strlower(b)) < 0)
998 return log_oom();
999
1000 if (access(p, F_OK) < 0) {
1001 if (errno != ENOENT)
1002 return log_error_errno(errno, "Failed to detect if '%s' exists: %m", b);
1003 } else
1004 found = true;
1005 }
1006
1007 if (!found)
1008 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "None of the select PCR banks appear to exist.");
1009
1010 return 0;
1011 }
1012
1013 static int verb_status(int argc, char *argv[], void *userdata) {
1014 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
1015
1016 static const struct {
1017 uint32_t nr;
1018 const char *description;
1019 } relevant_pcrs[] = {
1020 { TPM_PCR_INDEX_KERNEL_IMAGE, "Unified Kernel Image" },
1021 { TPM_PCR_INDEX_KERNEL_PARAMETERS, "Kernel Parameters" },
1022 { TPM_PCR_INDEX_INITRD_SYSEXTS, "initrd System Extensions" },
1023 };
1024
1025 int r;
1026
1027 r = validate_stub();
1028 if (r < 0)
1029 return r;
1030
1031 for (size_t i = 0; i < ELEMENTSOF(relevant_pcrs); i++) {
1032
1033 STRV_FOREACH(bank, arg_banks) {
1034 _cleanup_free_ char *b = NULL, *p = NULL, *s = NULL;
1035 _cleanup_free_ void *h = NULL;
1036 size_t l;
1037
1038 b = strdup(*bank);
1039 if (!b)
1040 return log_oom();
1041
1042 if (asprintf(&p, "/sys/class/tpm/tpm0/pcr-%s/%" PRIu32, ascii_strlower(b), relevant_pcrs[i].nr) < 0)
1043 return log_oom();
1044
1045 r = read_virtual_file(p, 4096, &s, NULL);
1046 if (r == -ENOENT)
1047 continue;
1048 if (r < 0)
1049 return log_error_errno(r, "Failed to read '%s': %m", p);
1050
1051 r = unhexmem(strstrip(s), SIZE_MAX, &h, &l);
1052 if (r < 0)
1053 return log_error_errno(r, "Failed to decode PCR value '%s': %m", s);
1054
1055 if (arg_json_format_flags & JSON_FORMAT_OFF) {
1056 _cleanup_free_ char *f = NULL;
1057
1058 f = hexmem(h, l);
1059 if (!h)
1060 return log_oom();
1061
1062 if (bank == arg_banks) {
1063 /* before the first line for each PCR, write a short descriptive text to
1064 * stderr, and leave the primary content on stdout */
1065 fflush(stdout);
1066 fprintf(stderr, "%s# PCR[%" PRIu32 "] %s%s%s\n",
1067 ansi_grey(),
1068 relevant_pcrs[i].nr,
1069 relevant_pcrs[i].description,
1070 memeqzero(h, l) ? " (NOT SET!)" : "",
1071 ansi_normal());
1072 fflush(stderr);
1073 }
1074
1075 printf("%" PRIu32 ":%s=%s\n", relevant_pcrs[i].nr, b, f);
1076
1077 } else {
1078 _cleanup_(json_variant_unrefp) JsonVariant *bv = NULL, *a = NULL;
1079
1080 r = json_build(&bv,
1081 JSON_BUILD_OBJECT(
1082 JSON_BUILD_PAIR("pcr", JSON_BUILD_INTEGER(relevant_pcrs[i].nr)),
1083 JSON_BUILD_PAIR("hash", JSON_BUILD_HEX(h, l))
1084 )
1085 );
1086 if (r < 0)
1087 return log_error_errno(r, "Failed to build JSON object: %m");
1088
1089 a = json_variant_ref(json_variant_by_key(v, b));
1090
1091 r = json_variant_append_array(&a, bv);
1092 if (r < 0)
1093 return log_error_errno(r, "Failed to append PCR entry to JSON array: %m");
1094
1095 r = json_variant_set_field(&v, b, a);
1096 if (r < 0)
1097 return log_error_errno(r, "Failed to add bank info to object: %m");
1098 }
1099 }
1100 }
1101
1102 if (!FLAGS_SET(arg_json_format_flags, JSON_FORMAT_OFF)) {
1103 if (arg_json_format_flags & (JSON_FORMAT_PRETTY|JSON_FORMAT_PRETTY_AUTO))
1104 pager_open(arg_pager_flags);
1105
1106 json_variant_dump(v, arg_json_format_flags, stdout, NULL);
1107 }
1108
1109 return 0;
1110 }
1111
1112 static int measure_main(int argc, char *argv[]) {
1113 static const Verb verbs[] = {
1114 { "help", VERB_ANY, VERB_ANY, 0, help },
1115 { "status", VERB_ANY, 1, VERB_DEFAULT, verb_status },
1116 { "calculate", VERB_ANY, 1, 0, verb_calculate },
1117 { "sign", VERB_ANY, 1, 0, verb_sign },
1118 {}
1119 };
1120
1121 return dispatch_verb(argc, argv, verbs, NULL);
1122 }
1123
1124 static int run(int argc, char *argv[]) {
1125 int r;
1126
1127 log_show_color(true);
1128 log_parse_environment();
1129 log_open();
1130
1131 r = parse_argv(argc, argv);
1132 if (r <= 0)
1133 return r;
1134
1135 return measure_main(argc, argv);
1136 }
1137
1138 DEFINE_MAIN_FUNCTION(run);