Debian Codegraph @

src/measure/measure-tool.c

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