1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
6 #include "alloc-util.h"
7 #include "efi-loader.h"
10 #include "hexdecoct.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"
18 #include "terminal-util.h"
20 #include "tpm2-util.h"
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. */
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
;
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
);
42 static inline void free_sections(char*(*sections
)[_UNIFIED_SECTION_MAX
]) {
43 for (UnifiedSection c
= 0; c
< _UNIFIED_SECTION_MAX
; c
++)
47 STATIC_DESTRUCTOR_REGISTER(arg_sections
, free_sections
);
49 static int help(int argc
, char *argv
[], void *userdata
) {
50 _cleanup_free_
char *link
= NULL
;
53 r
= terminal_urlify_man("systemd-measure", "1", &link
);
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)\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
,
90 special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
));
95 static char *normalize_phase(const char *s
) {
96 _cleanup_strv_free_
char **l
= NULL
;
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. */
102 l
= strv_split(s
, ":"); /* Split series of words */
106 /* Remove all empty words and glue things back together */
107 return strv_join(strv_remove(l
, ""), ":");
110 static int parse_argv(int argc
, char *argv
[]) {
115 ARG_LINUX
= _ARG_SECTION_FIRST
,
121 _ARG_PCRSIG
, /* the .pcrsig section is not input for signing, hence not actually an argument here */
123 ARG_PCRPKEY
= _ARG_SECTION_LAST
,
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
},
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);
161 while ((c
= getopt_long(argc
, argv
, "hjc", options
, NULL
)) >= 0)
172 arg_pager_flags
|= PAGER_DISABLE
;
175 case _ARG_SECTION_FIRST
..._ARG_SECTION_LAST
: {
176 UnifiedSection section
= c
- _ARG_SECTION_FIRST
;
178 r
= parse_path_argument(optarg
, /* suppress_root= */ false, arg_sections
+ section
);
189 const EVP_MD
*implementation
;
191 implementation
= EVP_get_digestbyname(optarg
);
193 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Unknown bank '%s', refusing.", optarg
);
195 if (strv_extend(&arg_banks
, EVP_MD_name(implementation
)) < 0)
201 case ARG_PRIVATE_KEY
:
202 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_private_key
);
209 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_public_key
);
215 case ARG_TPM2_DEVICE
: {
216 _cleanup_free_
char *device
= NULL
;
218 if (streq(optarg
, "list"))
219 return tpm2_list_devices();
221 if (!streq(optarg
, "auto")) {
222 device
= strdup(optarg
);
227 free_and_replace(arg_tpm2_device
, device
);
232 arg_json_format_flags
= JSON_FORMAT_PRETTY_AUTO
|JSON_FORMAT_COLOR_AUTO
;
236 r
= parse_json_argument(optarg
, &arg_json_format_flags
);
245 n
= normalize_phase(optarg
);
249 r
= strv_consume(&arg_phase
, TAKE_PTR(n
));
260 assert_not_reached();
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");
270 strv_sort(arg_banks
);
271 strv_uniq(arg_banks
);
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.");
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)
288 strv_sort(arg_phase
);
289 strv_uniq(arg_phase
);
292 _cleanup_free_
char *j
= NULL
;
293 j
= strv_join(arg_phase
, ", ");
297 log_debug("Measuring boot phases: %s", j
);
301 /* The PCR 11 state for one specific bank */
302 typedef struct PcrState
{
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 */
310 static void pcr_state_free_all(PcrState
**pcr_state
) {
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
);
322 *pcr_state
= mfree(*pcr_state
);
325 static void evp_md_ctx_free_all(EVP_MD_CTX
**md
[]) {
331 for (size_t i
= 0; (*md
)[i
]; i
++)
332 EVP_MD_CTX_free((*md
)[i
]);
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
;
342 assert(data
|| sz
== 0);
343 assert(pcr_state
->md
);
344 assert(pcr_state
->value
);
345 assert(pcr_state
->value_size
> 0);
347 /* Extends a (virtual) PCR by the given data */
349 mc
= EVP_MD_CTX_new();
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
);
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.");
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.");
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.");
367 assert(value_size
== pcr_state
->value_size
);
371 #define BUFFER_SIZE (16U * 1024U)
373 static int measure_kernel(PcrState
*pcr_states
, size_t n
) {
374 _cleanup_free_
void *buffer
= NULL
;
380 /* Virtually measures the components of a unified kernel image into PCR 11 */
383 /* Shortcut things, if we should just use the current PCR value */
385 for (size_t i
= 0; i
< n
; i
++) {
386 _cleanup_free_
char *p
= NULL
, *s
= NULL
;
387 _cleanup_free_
void *v
= NULL
;
390 if (asprintf(&p
, "/sys/class/tpm/tpm0/pcr-%s/%" PRIu32
, pcr_states
[i
].bank
, TPM_PCR_INDEX_KERNEL_IMAGE
) < 0)
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
);
397 return log_error_errno(r
, "Failed to read '%s': %m", p
);
399 r
= unhexmem(strstrip(s
), SIZE_MAX
, &v
, &sz
);
401 return log_error_errno(r
, "Failed to decode PCR value '%s': %m", s
);
403 assert(pcr_states
[i
].value_size
== sz
);
404 memcpy(pcr_states
[i
].value
, v
, sz
);
410 buffer
= malloc(BUFFER_SIZE
);
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;
419 if (!arg_sections
[c
])
422 fd
= open(arg_sections
[c
], O_RDONLY
|O_CLOEXEC
);
424 return log_error_errno(errno
, "Failed to open '%s': %m", arg_sections
[c
]);
426 /* Allocate one message digest context per bank (NULL terminated) */
427 mdctx
= new0(EVP_MD_CTX
*, n
+ 1);
431 for (size_t i
= 0; i
< n
; i
++) {
432 mdctx
[i
] = EVP_MD_CTX_new();
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
);
443 sz
= read(fd
, buffer
, BUFFER_SIZE
);
445 return log_error_errno(errno
, "Failed to read '%s': %m", arg_sections
[c
]);
446 if (sz
== 0) /* EOF */
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.");
458 if (m
== 0) /* We skip over empty files, the stub does so too */
461 for (size_t i
= 0; i
< n
; i
++) {
462 _cleanup_free_
void *data_hash
= NULL
;
463 unsigned data_hash_size
;
465 data_hash
= malloc(pcr_states
[i
].value_size
);
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
);
473 assert(data_hash_size
== (unsigned) pcr_states
[i
].value_size
);
475 r
= pcr_state_extend(pcr_states
+ i
, data_hash
, data_hash_size
);
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.");
483 assert(data_hash_size
== (unsigned) pcr_states
[i
].value_size
);
485 r
= pcr_state_extend(pcr_states
+ i
, data_hash
, data_hash_size
);
494 static int measure_phase(PcrState
*pcr_states
, size_t n
, const char *phase
) {
495 _cleanup_strv_free_
char **l
= NULL
;
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. */
505 l
= strv_split(phase
, ":");
509 STRV_FOREACH(word
, l
) {
517 for (size_t i
= 0; i
< n
; i
++) { /* For each bank */
518 _cleanup_free_
void *b
= NULL
;
521 bsz
= EVP_MD_size(pcr_states
[i
].md
);
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
);
532 /* And then extend the PCR with the resulting hash */
533 r
= pcr_state_extend(pcr_states
+ i
, b
, bsz
);
542 static int pcr_states_allocate(PcrState
**ret
) {
543 _cleanup_(pcr_state_free_all
) PcrState
*pcr_states
= NULL
;
546 pcr_states
= new0(PcrState
, strv_length(arg_banks
) + 1);
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
;
557 assert_se(implementation
= EVP_get_digestbyname(*d
)); /* Must work, we already checked while parsing command line */
559 b
= strdup(EVP_MD_name(implementation
));
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
);
567 v
= malloc0(sz
); /* initial PCR state is all zeroes */
571 pcr_states
[n
++] = (struct PcrState
) {
572 .bank
= ascii_strlower(TAKE_PTR(b
)),
573 .md
= implementation
,
574 .value
= TAKE_PTR(v
),
579 *ret
= TAKE_PTR(pcr_states
);
583 static int pcr_states_save(PcrState
*pcr_states
, size_t n
) {
587 for (size_t i
= 0; i
< n
; i
++) {
588 _cleanup_free_
void *saved
= NULL
;
590 if (!pcr_states
[i
].value
)
593 saved
= memdup(pcr_states
[i
].value
, pcr_states
[i
].value_size
);
597 free_and_replace(pcr_states
[i
].saved_value
, saved
);
603 static void pcr_states_restore(PcrState
*pcr_states
, size_t n
) {
607 for (size_t i
= 0; i
< n
; i
++) {
609 assert(pcr_states
[i
].value
);
610 assert(pcr_states
[i
].saved_value
);
612 memcpy(pcr_states
[i
].value
, pcr_states
[i
].saved_value
, pcr_states
[i
].value_size
);
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
;
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.");
625 r
= pcr_states_allocate(&pcr_states
);
631 r
= measure_kernel(pcr_states
, n
);
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
);
641 STRV_FOREACH(phase
, arg_phase
) {
643 r
= measure_phase(pcr_states
, n
, *phase
);
647 for (size_t i
= 0; i
< n
; i
++) {
648 if (arg_json_format_flags
& JSON_FORMAT_OFF
) {
649 _cleanup_free_
char *hd
= NULL
;
653 fprintf(stderr
, "%s# PCR[%" PRIu32
"] Phase <%s>%s\n",
655 TPM_PCR_INDEX_KERNEL_IMAGE
,
656 isempty(*phase
) ? ":" : *phase
,
661 hd
= hexmem(pcr_states
[i
].value
, pcr_states
[i
].value_size
);
665 printf("%" PRIu32
":%s=%s\n", TPM_PCR_INDEX_KERNEL_IMAGE
, pcr_states
[i
].bank
, hd
);
667 _cleanup_(json_variant_unrefp
) JsonVariant
*bv
= NULL
, *array
= NULL
;
669 array
= json_variant_ref(json_variant_by_key(w
, pcr_states
[i
].bank
));
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
))
679 return log_error_errno(r
, "Failed to build JSON object: %m");
681 r
= json_variant_append_array(&array
, bv
);
683 return log_error_errno(r
, "Failed to append JSON object to array: %m");
685 r
= json_variant_set_field(&w
, pcr_states
[i
].bank
, array
);
687 return log_error_errno(r
, "Failed to add bank info to object: %m");
691 /* Return to the original kernel measurement for the next phase calculation */
692 pcr_states_restore(pcr_states
, n
);
695 if (!FLAGS_SET(arg_json_format_flags
, JSON_FORMAT_OFF
)) {
697 if (arg_json_format_flags
& (JSON_FORMAT_PRETTY
|JSON_FORMAT_PRETTY_AUTO
))
698 pager_open(arg_pager_flags
);
700 json_variant_dump(w
, arg_json_format_flags
, stdout
, NULL
);
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
, *pubkeyf
= NULL
;
712 ESYS_TR session_handle
= ESYS_TR_NONE
;
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.");
720 if (!arg_private_key
)
721 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "No private key specified, use --private-key=.");
723 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "No public key specified, use --public-key=.");
725 /* When signing we only support JSON output */
726 arg_json_format_flags
&= ~JSON_FORMAT_OFF
;
728 privkeyf
= fopen(arg_private_key
, "re");
730 return log_error_errno(errno
, "Failed to open private key file '%s': %m", arg_private_key
);
732 pubkeyf
= fopen(arg_public_key
, "re");
734 return log_error_errno(errno
, "Failed to open public key file '%s': %m", arg_public_key
);
736 privkey
= PEM_read_PrivateKey(privkeyf
, NULL
, NULL
, NULL
);
738 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to parse private key '%s'.", arg_private_key
);
740 pubkey
= PEM_read_PUBKEY(pubkeyf
, NULL
, NULL
, NULL
);
742 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to parse public key '%s'.", arg_public_key
);
744 r
= pcr_states_allocate(&pcr_states
);
750 r
= measure_kernel(pcr_states
, n
);
758 r
= tpm2_context_init(arg_tpm2_device
, &c
);
762 for (size_t i
= 0; i
< n
; i
++) {
763 static const TPMT_SYM_DEF symmetric
= {
764 .algorithm
= TPM2_ALG_AES
,
766 .mode
.aes
= TPM2_ALG_CFB
,
768 PcrState
*p
= pcr_states
+ i
;
770 rc
= sym_Esys_StartAuthSession(
782 if (rc
!= TSS2_RC_SUCCESS
) {
783 r
= log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
784 "Failed to open session in TPM: %s", sym_Tss2_RC_Decode(rc
));
788 /* Generate a single hash value from the PCRs included in our policy. Given that that's
789 * exactly one, the calculation is trivial. */
790 TPM2B_DIGEST intermediate_digest
= {
791 .size
= SHA256_DIGEST_SIZE
,
793 assert(sizeof(intermediate_digest
.buffer
) >= SHA256_DIGEST_SIZE
);
794 sha256_direct(p
->value
, p
->value_size
, intermediate_digest
.buffer
);
796 int tpmalg
= tpm2_pcr_bank_from_string(EVP_MD_name(p
->md
));
798 log_error_errno(tpmalg
, "Unsupported PCR bank");
802 TPML_PCR_SELECTION pcr_selection
;
803 tpm2_pcr_mask_to_selection(1 << TPM_PCR_INDEX_KERNEL_IMAGE
, tpmalg
, &pcr_selection
);
805 rc
= sym_Esys_PolicyPCR(
811 &intermediate_digest
,
813 if (rc
!= TSS2_RC_SUCCESS
) {
814 r
= log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
815 "Failed to push PCR policy into TPM: %s", sym_Tss2_RC_Decode(rc
));
819 _cleanup_(Esys_Freep
) TPM2B_DIGEST
*pcr_policy_digest
= NULL
;
820 rc
= sym_Esys_PolicyGetDigest(
827 if (rc
!= TSS2_RC_SUCCESS
) {
828 r
= log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
829 "Failed to get policy digest from TPM: %s", sym_Tss2_RC_Decode(rc
));
833 session_handle
= tpm2_flush_context_verbose(c
.esys_context
, session_handle
);
835 _cleanup_(EVP_MD_CTX_freep
) EVP_MD_CTX
* mdctx
= NULL
;
836 mdctx
= EVP_MD_CTX_new();
842 if (EVP_DigestSignInit(mdctx
, NULL
, p
->md
, NULL
, privkey
) != 1) {
843 r
= log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
844 "Failed to initialize signature context.");
848 if (EVP_DigestSignUpdate(mdctx
, pcr_policy_digest
->buffer
, pcr_policy_digest
->size
) != 1) {
849 r
= log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
850 "Failed to sign data.");
855 if (EVP_DigestSignFinal(mdctx
, NULL
, &ss
) != 1) {
856 r
= log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
857 "Failed to finalize signature");
861 _cleanup_free_
void *sig
= malloc(ss
);
867 if (EVP_DigestSignFinal(mdctx
, sig
, &ss
) != 1) {
868 r
= log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
869 "Failed to acquire signature data");
873 _cleanup_free_
void *pubkey_fp
= NULL
;
874 size_t pubkey_fp_size
= 0;
875 r
= pubkey_fingerprint(pubkey
, EVP_sha256(), &pubkey_fp
, &pubkey_fp_size
);
879 _cleanup_(json_variant_unrefp
) JsonVariant
*bv
= NULL
, *a
= NULL
;
881 r
= tpm2_make_pcr_json_array(UINT64_C(1) << TPM_PCR_INDEX_KERNEL_IMAGE
, &a
);
883 log_error_errno(r
, "Failed to build JSON PCR mask array: %m");
887 r
= json_build(&bv
, JSON_BUILD_ARRAY(
889 JSON_BUILD_PAIR("pcrs", JSON_BUILD_VARIANT(a
)), /* PCR mask */
890 JSON_BUILD_PAIR("pkfp", JSON_BUILD_HEX(pubkey_fp
, pubkey_fp_size
)), /* SHA256 fingerprint of public key (DER) used for the signature */
891 JSON_BUILD_PAIR("pol", JSON_BUILD_HEX(pcr_policy_digest
->buffer
, pcr_policy_digest
->size
)), /* TPM2 policy hash that is signed */
892 JSON_BUILD_PAIR("sig", JSON_BUILD_BASE64(sig
, ss
))))); /* signature data */
894 log_error_errno(r
, "Failed to build JSON object: %m");
898 r
= json_variant_set_field(&v
, p
->bank
, bv
);
900 log_error_errno(r
, "Failed to add JSON field: %m");
906 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Unable to find a single working PCR bank.");
908 if (arg_json_format_flags
& (JSON_FORMAT_PRETTY
|JSON_FORMAT_PRETTY_AUTO
))
909 pager_open(arg_pager_flags
);
911 json_variant_dump(v
, arg_json_format_flags
, stdout
, NULL
);
915 session_handle
= tpm2_flush_context_verbose(c
.esys_context
, session_handle
);
919 static int compare_reported_pcr_nr(uint32_t pcr
, const char *varname
, const char *description
) {
920 _cleanup_free_
char *s
= NULL
;
924 r
= efi_get_variable_string(varname
, &s
);
928 return log_error_errno(r
, "Failed to read EFI variable '%s': %m", varname
);
930 r
= safe_atou32(s
, &v
);
932 return log_error_errno(r
, "Failed to parse EFI variable '%s': %s", varname
, s
);
935 log_warning("PCR number reported by stub for %s (%" PRIu32
") different from our expectation (%" PRIu32
").\n"
936 "The measurements are likely inconsistent.", description
, v
, pcr
);
941 static int validate_stub(void) {
946 if (tpm2_support() != TPM2_SUPPORT_FULL
)
947 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "Sorry, system lacks full TPM2 support.");
949 r
= efi_stub_get_features(&features
);
951 return log_error_errno(r
, "Unable to get stub features: %m");
953 if (!FLAGS_SET(features
, EFI_STUB_FEATURE_THREE_PCRS
))
954 log_warning("Warning: current kernel image does not support measuring itself, the command line or initrd system extension images.\n"
955 "The PCR measurements seen are unlikely to be valid.");
957 r
= compare_reported_pcr_nr(TPM_PCR_INDEX_KERNEL_IMAGE
, EFI_LOADER_VARIABLE("StubPcrKernelImage"), "kernel image");
961 r
= compare_reported_pcr_nr(TPM_PCR_INDEX_KERNEL_PARAMETERS
, EFI_LOADER_VARIABLE("StubPcrKernelParameters"), "kernel parameters");
965 r
= compare_reported_pcr_nr(TPM_PCR_INDEX_INITRD_SYSEXTS
, EFI_LOADER_VARIABLE("StubPcrInitRDSysExts"), "initrd system extension images");
969 STRV_FOREACH(bank
, arg_banks
) {
970 _cleanup_free_
char *b
= NULL
, *p
= NULL
;
976 if (asprintf(&p
, "/sys/class/tpm/tpm0/pcr-%s/", ascii_strlower(b
)) < 0)
979 if (access(p
, F_OK
) < 0) {
981 return log_error_errno(errno
, "Failed to detect if '%s' exists: %m", b
);
987 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "None of the select PCR banks appear to exist.");
992 static int verb_status(int argc
, char *argv
[], void *userdata
) {
993 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
995 static const struct {
997 const char *description
;
998 } relevant_pcrs
[] = {
999 { TPM_PCR_INDEX_KERNEL_IMAGE
, "Unified Kernel Image" },
1000 { TPM_PCR_INDEX_KERNEL_PARAMETERS
, "Kernel Parameters" },
1001 { TPM_PCR_INDEX_INITRD_SYSEXTS
, "initrd System Extensions" },
1006 r
= validate_stub();
1010 for (size_t i
= 0; i
< ELEMENTSOF(relevant_pcrs
); i
++) {
1012 STRV_FOREACH(bank
, arg_banks
) {
1013 _cleanup_free_
char *b
= NULL
, *p
= NULL
, *s
= NULL
;
1014 _cleanup_free_
void *h
= NULL
;
1021 if (asprintf(&p
, "/sys/class/tpm/tpm0/pcr-%s/%" PRIu32
, ascii_strlower(b
), relevant_pcrs
[i
].nr
) < 0)
1024 r
= read_virtual_file(p
, 4096, &s
, NULL
);
1028 return log_error_errno(r
, "Failed to read '%s': %m", p
);
1030 r
= unhexmem(strstrip(s
), SIZE_MAX
, &h
, &l
);
1032 return log_error_errno(r
, "Failed to decode PCR value '%s': %m", s
);
1034 if (arg_json_format_flags
& JSON_FORMAT_OFF
) {
1035 _cleanup_free_
char *f
= NULL
;
1041 if (bank
== arg_banks
) {
1042 /* before the first line for each PCR, write a short descriptive text to
1043 * stderr, and leave the primary content on stdout */
1045 fprintf(stderr
, "%s# PCR[%" PRIu32
"] %s%s%s\n",
1047 relevant_pcrs
[i
].nr
,
1048 relevant_pcrs
[i
].description
,
1049 memeqzero(h
, l
) ? " (NOT SET!)" : "",
1054 printf("%" PRIu32
":%s=%s\n", relevant_pcrs
[i
].nr
, b
, f
);
1057 _cleanup_(json_variant_unrefp
) JsonVariant
*bv
= NULL
, *a
= NULL
;
1061 JSON_BUILD_PAIR("pcr", JSON_BUILD_INTEGER(relevant_pcrs
[i
].nr
)),
1062 JSON_BUILD_PAIR("hash", JSON_BUILD_HEX(h
, l
))
1066 return log_error_errno(r
, "Failed to build JSON object: %m");
1068 a
= json_variant_ref(json_variant_by_key(v
, b
));
1070 r
= json_variant_append_array(&a
, bv
);
1072 return log_error_errno(r
, "Failed to append PCR entry to JSON array: %m");
1074 r
= json_variant_set_field(&v
, b
, a
);
1076 return log_error_errno(r
, "Failed to add bank info to object: %m");
1081 if (!FLAGS_SET(arg_json_format_flags
, JSON_FORMAT_OFF
)) {
1082 if (arg_json_format_flags
& (JSON_FORMAT_PRETTY
|JSON_FORMAT_PRETTY_AUTO
))
1083 pager_open(arg_pager_flags
);
1085 json_variant_dump(v
, arg_json_format_flags
, stdout
, NULL
);
1091 static int measure_main(int argc
, char *argv
[]) {
1092 static const Verb verbs
[] = {
1093 { "help", VERB_ANY
, VERB_ANY
, 0, help
},
1094 { "status", VERB_ANY
, 1, VERB_DEFAULT
, verb_status
},
1095 { "calculate", VERB_ANY
, 1, 0, verb_calculate
},
1096 { "sign", VERB_ANY
, 1, 0, verb_sign
},
1100 return dispatch_verb(argc
, argv
, verbs
, NULL
);
1103 static int run(int argc
, char *argv
[]) {
1106 log_show_color(true);
1107 log_parse_environment();
1110 r
= parse_argv(argc
, argv
);
1114 return measure_main(argc
, argv
);
1117 DEFINE_MAIN_FUNCTION(run
);