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