1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
6 #include "alloc-util.h"
8 #include "efi-loader.h"
11 #include "hexdecoct.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"
19 #include "terminal-util.h"
21 #include "tpm2-util.h"
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. */
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
;
37 STATIC_DESTRUCTOR_REGISTER(arg_banks
, strv_freep
);
38 STATIC_DESTRUCTOR_REGISTER(arg_tpm2_device
, freep
);
39 STATIC_DESTRUCTOR_REGISTER(arg_private_key
, freep
);
40 STATIC_DESTRUCTOR_REGISTER(arg_public_key
, freep
);
41 STATIC_DESTRUCTOR_REGISTER(arg_phase
, strv_freep
);
43 static inline void free_sections(char*(*sections
)[_UNIFIED_SECTION_MAX
]) {
44 for (UnifiedSection c
= 0; c
< _UNIFIED_SECTION_MAX
; c
++)
48 STATIC_DESTRUCTOR_REGISTER(arg_sections
, free_sections
);
50 static int help(int argc
, char *argv
[], void *userdata
) {
51 _cleanup_free_
char *link
= NULL
;
54 r
= terminal_urlify_man("systemd-measure", "1", &link
);
58 printf("%1$s [OPTIONS...] COMMAND ...\n"
59 "\n%5$sPre-calculate and sign PCR hash for a unified kernel image (UKI).%6$s\n"
60 "\n%3$sCommands:%4$s\n"
61 " status Show current PCR values\n"
62 " calculate Calculate expected PCR values\n"
63 " sign Calculate and sign expected PCR values\n"
64 "\n%3$sOptions:%4$s\n"
65 " -h --help Show this help\n"
66 " --version Print version\n"
67 " --no-pager Do not pipe output into a pager\n"
68 " -c --current Use current PCR values\n"
69 " --phase=PHASE Specify a boot phase to sign for\n"
70 " --bank=DIGEST Select TPM bank (SHA1, SHA256, SHA384, SHA512)\n"
71 " --tpm2-device=PATH Use specified TPM2 device\n"
72 " --private-key=KEY Private key (PEM) to sign with\n"
73 " --public-key=KEY Public key (PEM) to validate against\n"
74 " --json=MODE Output as JSON\n"
75 " -j Same as --json=pretty on tty, --json=short otherwise\n"
76 "\n%3$sUKI PE Section Options:%4$s %3$sUKI PE Section%4$s\n"
77 " --linux=PATH Path to Linux kernel image file %7$s .linux\n"
78 " --osrel=PATH Path to os-release file %7$s .osrel\n"
79 " --cmdline=PATH Path to file with kernel command line %7$s .cmdline\n"
80 " --initrd=PATH Path to initrd image file %7$s .initrd\n"
81 " --splash=PATH Path to splash bitmap file %7$s .splash\n"
82 " --dtb=PATH Path to Devicetree file %7$s .dtb\n"
83 " --pcrpkey=PATH Path to public key for PCR signatures %7$s .pcrpkey\n"
84 "\nSee the %2$s for details.\n",
85 program_invocation_short_name
,
91 special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
));
96 static char *normalize_phase(const char *s
) {
97 _cleanup_strv_free_
char **l
= NULL
;
99 /* Let's normalize phase expressions. We split the series of colon-separated words up, then remove
100 * all empty ones, and glue them back together again. In other words we remove duplicate ":", as well
101 * as leading and trailing ones. */
103 l
= strv_split(s
, ":"); /* Split series of words */
107 /* Remove all empty words and glue things back together */
108 return strv_join(strv_remove(l
, ""), ":");
111 static int parse_argv(int argc
, char *argv
[]) {
116 ARG_LINUX
= _ARG_SECTION_FIRST
,
122 _ARG_PCRSIG
, /* the .pcrsig section is not input for signing, hence not actually an argument here */
124 ARG_PCRPKEY
= _ARG_SECTION_LAST
,
133 static const struct option options
[] = {
134 { "help", no_argument
, NULL
, 'h' },
135 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
136 { "version", no_argument
, NULL
, ARG_VERSION
},
137 { "linux", required_argument
, NULL
, ARG_LINUX
},
138 { "osrel", required_argument
, NULL
, ARG_OSREL
},
139 { "cmdline", required_argument
, NULL
, ARG_CMDLINE
},
140 { "initrd", required_argument
, NULL
, ARG_INITRD
},
141 { "splash", required_argument
, NULL
, ARG_SPLASH
},
142 { "dtb", required_argument
, NULL
, ARG_DTB
},
143 { "pcrpkey", required_argument
, NULL
, ARG_PCRPKEY
},
144 { "current", no_argument
, NULL
, 'c' },
145 { "bank", required_argument
, NULL
, ARG_BANK
},
146 { "tpm2-device", required_argument
, NULL
, ARG_TPM2_DEVICE
},
147 { "private-key", required_argument
, NULL
, ARG_PRIVATE_KEY
},
148 { "public-key", required_argument
, NULL
, ARG_PUBLIC_KEY
},
149 { "json", required_argument
, NULL
, ARG_JSON
},
150 { "phase", required_argument
, NULL
, ARG_PHASE
},
159 /* Make sure the arguments list and the section list, stays in sync */
160 assert_cc(_ARG_SECTION_FIRST
+ _UNIFIED_SECTION_MAX
== _ARG_SECTION_LAST
+ 1);
162 while ((c
= getopt_long(argc
, argv
, "hjc", options
, NULL
)) >= 0)
173 arg_pager_flags
|= PAGER_DISABLE
;
176 case _ARG_SECTION_FIRST
..._ARG_SECTION_LAST
: {
177 UnifiedSection section
= c
- _ARG_SECTION_FIRST
;
179 r
= parse_path_argument(optarg
, /* suppress_root= */ false, arg_sections
+ section
);
190 const EVP_MD
*implementation
;
192 implementation
= EVP_get_digestbyname(optarg
);
194 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Unknown bank '%s', refusing.", optarg
);
196 if (strv_extend(&arg_banks
, EVP_MD_name(implementation
)) < 0)
202 case ARG_PRIVATE_KEY
:
203 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_private_key
);
210 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_public_key
);
216 case ARG_TPM2_DEVICE
: {
217 _cleanup_free_
char *device
= NULL
;
219 if (streq(optarg
, "list"))
220 return tpm2_list_devices();
222 if (!streq(optarg
, "auto")) {
223 device
= strdup(optarg
);
228 free_and_replace(arg_tpm2_device
, device
);
233 arg_json_format_flags
= JSON_FORMAT_PRETTY_AUTO
|JSON_FORMAT_COLOR_AUTO
;
237 r
= parse_json_argument(optarg
, &arg_json_format_flags
);
246 n
= normalize_phase(optarg
);
250 r
= strv_consume(&arg_phase
, TAKE_PTR(n
));
261 assert_not_reached();
264 if (strv_isempty(arg_banks
)) {
265 /* If no banks are specifically selected, pick all known banks */
266 arg_banks
= strv_new("SHA1", "SHA256", "SHA384", "SHA512");
271 strv_sort(arg_banks
);
272 strv_uniq(arg_banks
);
275 for (UnifiedSection us
= 0; us
< _UNIFIED_SECTION_MAX
; us
++)
276 if (arg_sections
[us
])
277 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "The --current switch cannot be used in combination with --linux= and related switches.");
279 if (strv_isempty(arg_phase
)) {
280 /* If no phases are specifically selected, pick everything from the beginning of the initrd
281 * to the beginning of shutdown. */
282 if (strv_extend_strv(&arg_phase
,
283 STRV_MAKE("enter-initrd",
284 "enter-initrd:leave-initrd",
285 "enter-initrd:leave-initrd:sysinit",
286 "enter-initrd:leave-initrd:sysinit:ready"),
287 /* filter_duplicates= */ false) < 0)
290 strv_sort(arg_phase
);
291 strv_uniq(arg_phase
);
294 _cleanup_free_
char *j
= NULL
;
295 j
= strv_join(arg_phase
, ", ");
299 log_debug("Measuring boot phases: %s", j
);
303 /* The PCR 11 state for one specific bank */
304 typedef struct PcrState
{
309 void *saved_value
; /* A copy of the original value we calculated, used by pcr_states_save()/pcr_states_restore() to come later back to */
312 static void pcr_state_free_all(PcrState
**pcr_state
) {
318 for (size_t i
= 0; (*pcr_state
)[i
].value
; i
++) {
319 free((*pcr_state
)[i
].bank
);
320 free((*pcr_state
)[i
].value
);
321 free((*pcr_state
)[i
].saved_value
);
324 *pcr_state
= mfree(*pcr_state
);
327 static void evp_md_ctx_free_all(EVP_MD_CTX
**md
[]) {
333 for (size_t i
= 0; (*md
)[i
]; i
++)
334 EVP_MD_CTX_free((*md
)[i
]);
339 static int pcr_state_extend(PcrState
*pcr_state
, const void *data
, size_t sz
) {
340 _cleanup_(EVP_MD_CTX_freep
) EVP_MD_CTX
*mc
= NULL
;
344 assert(data
|| sz
== 0);
345 assert(pcr_state
->md
);
346 assert(pcr_state
->value
);
347 assert(pcr_state
->value_size
> 0);
349 /* Extends a (virtual) PCR by the given data */
351 mc
= EVP_MD_CTX_new();
355 if (EVP_DigestInit_ex(mc
, pcr_state
->md
, NULL
) != 1)
356 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to initialize %s context.", pcr_state
->bank
);
358 /* First thing we do, is hash the old PCR value */
359 if (EVP_DigestUpdate(mc
, pcr_state
->value
, pcr_state
->value_size
) != 1)
360 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to run digest.");
362 /* Then, we hash the new data */
363 if (EVP_DigestUpdate(mc
, data
, sz
) != 1)
364 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to run digest.");
366 if (EVP_DigestFinal_ex(mc
, pcr_state
->value
, &value_size
) != 1)
367 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to finalize hash context.");
369 assert(value_size
== pcr_state
->value_size
);
373 #define BUFFER_SIZE (16U * 1024U)
375 static int measure_kernel(PcrState
*pcr_states
, size_t n
) {
376 _cleanup_free_
void *buffer
= NULL
;
382 /* Virtually measures the components of a unified kernel image into PCR 11 */
385 /* Shortcut things, if we should just use the current PCR value */
387 for (size_t i
= 0; i
< n
; i
++) {
388 _cleanup_free_
char *p
= NULL
, *s
= NULL
;
389 _cleanup_free_
void *v
= NULL
;
392 if (asprintf(&p
, "/sys/class/tpm/tpm0/pcr-%s/%" PRIu32
, pcr_states
[i
].bank
, TPM_PCR_INDEX_KERNEL_IMAGE
) < 0)
395 r
= read_virtual_file(p
, 4096, &s
, NULL
);
396 if (r
== -ENOENT
&& access("/sys/class/tpm/tpm0/", F_OK
) >= 0)
397 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
);
399 return log_error_errno(r
, "Failed to read '%s': %m", p
);
401 r
= unhexmem(strstrip(s
), SIZE_MAX
, &v
, &sz
);
403 return log_error_errno(r
, "Failed to decode PCR value '%s': %m", s
);
405 assert(pcr_states
[i
].value_size
== sz
);
406 memcpy(pcr_states
[i
].value
, v
, sz
);
412 buffer
= malloc(BUFFER_SIZE
);
416 for (UnifiedSection c
= 0; c
< _UNIFIED_SECTION_MAX
; c
++) {
417 _cleanup_(evp_md_ctx_free_all
) EVP_MD_CTX
**mdctx
= NULL
;
418 _cleanup_close_
int fd
= -1;
421 if (!arg_sections
[c
])
424 fd
= open(arg_sections
[c
], O_RDONLY
|O_CLOEXEC
);
426 return log_error_errno(errno
, "Failed to open '%s': %m", arg_sections
[c
]);
428 /* Allocate one message digest context per bank (NULL terminated) */
429 mdctx
= new0(EVP_MD_CTX
*, n
+ 1);
433 for (size_t i
= 0; i
< n
; i
++) {
434 mdctx
[i
] = EVP_MD_CTX_new();
438 if (EVP_DigestInit_ex(mdctx
[i
], pcr_states
[i
].md
, NULL
) != 1)
439 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to initialize data %s context.", pcr_states
[i
].bank
);
445 sz
= read(fd
, buffer
, BUFFER_SIZE
);
447 return log_error_errno(errno
, "Failed to read '%s': %m", arg_sections
[c
]);
448 if (sz
== 0) /* EOF */
451 for (size_t i
= 0; i
< n
; i
++)
452 if (EVP_DigestUpdate(mdctx
[i
], buffer
, sz
) != 1)
453 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to run digest.");
460 if (m
== 0) /* We skip over empty files, the stub does so too */
463 for (size_t i
= 0; i
< n
; i
++) {
464 _cleanup_free_
void *data_hash
= NULL
;
465 unsigned data_hash_size
;
467 data_hash
= malloc(pcr_states
[i
].value_size
);
471 /* Measure name of section */
472 if (EVP_Digest(unified_sections
[c
], strlen(unified_sections
[c
]) + 1, data_hash
, &data_hash_size
, pcr_states
[i
].md
, NULL
) != 1)
473 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to hash section name with %s.", pcr_states
[i
].bank
);
475 assert(data_hash_size
== (unsigned) pcr_states
[i
].value_size
);
477 r
= pcr_state_extend(pcr_states
+ i
, data_hash
, data_hash_size
);
481 /* Retrieve hash of data and measure it */
482 if (EVP_DigestFinal_ex(mdctx
[i
], data_hash
, &data_hash_size
) != 1)
483 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to finalize hash context.");
485 assert(data_hash_size
== (unsigned) pcr_states
[i
].value_size
);
487 r
= pcr_state_extend(pcr_states
+ i
, data_hash
, data_hash_size
);
496 static int measure_phase(PcrState
*pcr_states
, size_t n
, const char *phase
) {
497 _cleanup_strv_free_
char **l
= NULL
;
503 /* Measure a phase string into PCR 11. This splits up the "phase" expression at colons, and then
504 * virtually extends each specified word into PCR 11, to model how during boot we measure a series of
505 * words into PCR 11, one for each phase. */
507 l
= strv_split(phase
, ":");
511 STRV_FOREACH(word
, l
) {
519 for (size_t i
= 0; i
< n
; i
++) { /* For each bank */
520 _cleanup_free_
void *b
= NULL
;
523 bsz
= EVP_MD_size(pcr_states
[i
].md
);
530 /* First hash the word itself */
531 if (EVP_Digest(*word
, wl
, b
, NULL
, pcr_states
[i
].md
, NULL
) != 1)
532 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
), "Failed to hash word '%s'.", *word
);
534 /* And then extend the PCR with the resulting hash */
535 r
= pcr_state_extend(pcr_states
+ i
, b
, bsz
);
544 static int pcr_states_allocate(PcrState
**ret
) {
545 _cleanup_(pcr_state_free_all
) PcrState
*pcr_states
= NULL
;
548 pcr_states
= new0(PcrState
, strv_length(arg_banks
) + 1);
552 /* Allocate a PCR state structure, one for each bank */
553 STRV_FOREACH(d
, arg_banks
) {
554 const EVP_MD
*implementation
;
555 _cleanup_free_
void *v
= NULL
;
556 _cleanup_free_
char *b
= NULL
;
559 assert_se(implementation
= EVP_get_digestbyname(*d
)); /* Must work, we already checked while parsing command line */
561 b
= strdup(EVP_MD_name(implementation
));
565 sz
= EVP_MD_size(implementation
);
566 if (sz
<= 0 || sz
>= INT_MAX
)
567 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Unexpected digest size: %i", sz
);
569 v
= malloc0(sz
); /* initial PCR state is all zeroes */
573 pcr_states
[n
++] = (struct PcrState
) {
574 .bank
= ascii_strlower(TAKE_PTR(b
)),
575 .md
= implementation
,
576 .value
= TAKE_PTR(v
),
581 *ret
= TAKE_PTR(pcr_states
);
585 static int pcr_states_save(PcrState
*pcr_states
, size_t n
) {
589 for (size_t i
= 0; i
< n
; i
++) {
590 _cleanup_free_
void *saved
= NULL
;
592 if (!pcr_states
[i
].value
)
595 saved
= memdup(pcr_states
[i
].value
, pcr_states
[i
].value_size
);
599 free_and_replace(pcr_states
[i
].saved_value
, saved
);
605 static void pcr_states_restore(PcrState
*pcr_states
, size_t n
) {
609 for (size_t i
= 0; i
< n
; i
++) {
611 assert(pcr_states
[i
].value
);
612 assert(pcr_states
[i
].saved_value
);
614 memcpy(pcr_states
[i
].value
, pcr_states
[i
].saved_value
, pcr_states
[i
].value_size
);
618 static int verb_calculate(int argc
, char *argv
[], void *userdata
) {
619 _cleanup_(json_variant_unrefp
) JsonVariant
*w
= NULL
;
620 _cleanup_(pcr_state_free_all
) PcrState
*pcr_states
= NULL
;
624 if (!arg_sections
[UNIFIED_SECTION_LINUX
] && !arg_current
)
625 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Either --linux= or --current must be specified, refusing.");
627 assert(!strv_isempty(arg_banks
));
628 assert(!strv_isempty(arg_phase
));
630 r
= pcr_states_allocate(&pcr_states
);
636 r
= measure_kernel(pcr_states
, n
);
640 /* Save the current state, so that we later can restore to it. This way we can measure the PCR values
641 * for multiple different boot phases without heaving to start from zero each time */
642 r
= pcr_states_save(pcr_states
, n
);
646 STRV_FOREACH(phase
, arg_phase
) {
648 r
= measure_phase(pcr_states
, n
, *phase
);
652 for (size_t i
= 0; i
< n
; i
++) {
653 if (arg_json_format_flags
& JSON_FORMAT_OFF
) {
654 _cleanup_free_
char *hd
= NULL
;
658 fprintf(stderr
, "%s# PCR[%" PRIu32
"] Phase <%s>%s\n",
660 TPM_PCR_INDEX_KERNEL_IMAGE
,
661 isempty(*phase
) ? ":" : *phase
,
666 hd
= hexmem(pcr_states
[i
].value
, pcr_states
[i
].value_size
);
670 printf("%" PRIu32
":%s=%s\n", TPM_PCR_INDEX_KERNEL_IMAGE
, pcr_states
[i
].bank
, hd
);
672 _cleanup_(json_variant_unrefp
) JsonVariant
*bv
= NULL
, *array
= NULL
;
674 array
= json_variant_ref(json_variant_by_key(w
, pcr_states
[i
].bank
));
678 JSON_BUILD_PAIR_CONDITION(!isempty(*phase
), "phase", JSON_BUILD_STRING(*phase
)),
679 JSON_BUILD_PAIR("pcr", JSON_BUILD_INTEGER(TPM_PCR_INDEX_KERNEL_IMAGE
)),
680 JSON_BUILD_PAIR("hash", JSON_BUILD_HEX(pcr_states
[i
].value
, pcr_states
[i
].value_size
))
684 return log_error_errno(r
, "Failed to build JSON object: %m");
686 r
= json_variant_append_array(&array
, bv
);
688 return log_error_errno(r
, "Failed to append JSON object to array: %m");
690 r
= json_variant_set_field(&w
, pcr_states
[i
].bank
, array
);
692 return log_error_errno(r
, "Failed to add bank info to object: %m");
696 /* Return to the original kernel measurement for the next phase calculation */
697 pcr_states_restore(pcr_states
, n
);
700 if (!FLAGS_SET(arg_json_format_flags
, JSON_FORMAT_OFF
)) {
702 if (arg_json_format_flags
& (JSON_FORMAT_PRETTY
|JSON_FORMAT_PRETTY_AUTO
))
703 pager_open(arg_pager_flags
);
705 json_variant_dump(w
, arg_json_format_flags
, stdout
, NULL
);
711 static int verb_sign(int argc
, char *argv
[], void *userdata
) {
712 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
713 _cleanup_(pcr_state_free_all
) PcrState
*pcr_states
= NULL
;
714 _cleanup_(EVP_PKEY_freep
) EVP_PKEY
*privkey
= NULL
, *pubkey
= NULL
;
715 _cleanup_(tpm2_context_destroy
) struct tpm2_context c
= {};
716 _cleanup_fclose_
FILE *privkeyf
= NULL
;
717 ESYS_TR session_handle
= ESYS_TR_NONE
;
722 if (!arg_sections
[UNIFIED_SECTION_LINUX
] && !arg_current
)
723 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Either --linux= or --current must be specified, refusing.");
725 if (!arg_private_key
)
726 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "No private key specified, use --private-key=.");
728 assert(!strv_isempty(arg_banks
));
729 assert(!strv_isempty(arg_phase
));
731 /* When signing we only support JSON output */
732 arg_json_format_flags
&= ~JSON_FORMAT_OFF
;
734 privkeyf
= fopen(arg_private_key
, "re");
736 return log_error_errno(errno
, "Failed to open private key file '%s': %m", arg_private_key
);
738 privkey
= PEM_read_PrivateKey(privkeyf
, NULL
, NULL
, NULL
);
740 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to parse private key '%s'.", arg_private_key
);
742 if (arg_public_key
) {
743 _cleanup_fclose_
FILE *pubkeyf
= NULL
;
745 pubkeyf
= fopen(arg_public_key
, "re");
747 return log_error_errno(errno
, "Failed to open public key file '%s': %m", arg_public_key
);
749 pubkey
= PEM_read_PUBKEY(pubkeyf
, NULL
, NULL
, NULL
);
751 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to parse public key '%s'.", arg_public_key
);
753 _cleanup_free_
char *data
= NULL
;
754 _cleanup_fclose_
FILE *tf
= NULL
;
757 /* No public key was specified, let's derive it automatically, if we can */
759 tf
= open_memstream_unlocked(&data
, &sz
);
763 if (i2d_PUBKEY_fp(tf
, privkey
) != 1)
764 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to extract public key from private key file '%s'.", arg_private_key
);
769 if (!d2i_PUBKEY_fp(tf
, &pubkey
))
770 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to parse extracted public key of private key file '%s'.", arg_private_key
);
773 r
= pcr_states_allocate(&pcr_states
);
779 r
= measure_kernel(pcr_states
, n
);
783 r
= pcr_states_save(pcr_states
, n
);
791 r
= tpm2_context_init(arg_tpm2_device
, &c
);
795 STRV_FOREACH(phase
, arg_phase
) {
797 r
= measure_phase(pcr_states
, n
, *phase
);
801 for (size_t i
= 0; i
< n
; i
++) {
802 static const TPMT_SYM_DEF symmetric
= {
803 .algorithm
= TPM2_ALG_AES
,
805 .mode
.aes
= TPM2_ALG_CFB
,
807 PcrState
*p
= pcr_states
+ i
;
809 rc
= sym_Esys_StartAuthSession(
821 if (rc
!= TSS2_RC_SUCCESS
) {
822 r
= log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
823 "Failed to open session in TPM: %s", sym_Tss2_RC_Decode(rc
));
827 /* Generate a single hash value from the PCRs included in our policy. Given that that's
828 * exactly one, the calculation is trivial. */
829 TPM2B_DIGEST intermediate_digest
= {
830 .size
= SHA256_DIGEST_SIZE
,
832 assert(sizeof(intermediate_digest
.buffer
) >= SHA256_DIGEST_SIZE
);
833 sha256_direct(p
->value
, p
->value_size
, intermediate_digest
.buffer
);
835 int tpmalg
= tpm2_pcr_bank_from_string(EVP_MD_name(p
->md
));
837 log_error_errno(tpmalg
, "Unsupported PCR bank");
841 TPML_PCR_SELECTION pcr_selection
;
842 tpm2_pcr_mask_to_selection(1 << TPM_PCR_INDEX_KERNEL_IMAGE
, tpmalg
, &pcr_selection
);
844 rc
= sym_Esys_PolicyPCR(
850 &intermediate_digest
,
852 if (rc
!= TSS2_RC_SUCCESS
) {
853 r
= log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
854 "Failed to push PCR policy into TPM: %s", sym_Tss2_RC_Decode(rc
));
858 _cleanup_(Esys_Freep
) TPM2B_DIGEST
*pcr_policy_digest
= NULL
;
859 rc
= sym_Esys_PolicyGetDigest(
866 if (rc
!= TSS2_RC_SUCCESS
) {
867 r
= log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
868 "Failed to get policy digest from TPM: %s", sym_Tss2_RC_Decode(rc
));
872 session_handle
= tpm2_flush_context_verbose(c
.esys_context
, session_handle
);
874 _cleanup_(EVP_MD_CTX_freep
) EVP_MD_CTX
* mdctx
= NULL
;
875 mdctx
= EVP_MD_CTX_new();
881 if (EVP_DigestSignInit(mdctx
, NULL
, p
->md
, NULL
, privkey
) != 1) {
882 r
= log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
883 "Failed to initialize signature context.");
887 if (EVP_DigestSignUpdate(mdctx
, pcr_policy_digest
->buffer
, pcr_policy_digest
->size
) != 1) {
888 r
= log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
889 "Failed to sign data.");
894 if (EVP_DigestSignFinal(mdctx
, NULL
, &ss
) != 1) {
895 r
= log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
896 "Failed to finalize signature");
900 _cleanup_free_
void *sig
= malloc(ss
);
906 if (EVP_DigestSignFinal(mdctx
, sig
, &ss
) != 1) {
907 r
= log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
908 "Failed to acquire signature data");
912 _cleanup_free_
void *pubkey_fp
= NULL
;
913 size_t pubkey_fp_size
= 0;
914 r
= pubkey_fingerprint(pubkey
, EVP_sha256(), &pubkey_fp
, &pubkey_fp_size
);
918 _cleanup_(json_variant_unrefp
) JsonVariant
*a
= NULL
;
919 r
= tpm2_make_pcr_json_array(UINT64_C(1) << TPM_PCR_INDEX_KERNEL_IMAGE
, &a
);
921 log_error_errno(r
, "Failed to build JSON PCR mask array: %m");
925 _cleanup_(json_variant_unrefp
) JsonVariant
*bv
= NULL
;
926 r
= json_build(&bv
, JSON_BUILD_OBJECT(
927 JSON_BUILD_PAIR("pcrs", JSON_BUILD_VARIANT(a
)), /* PCR mask */
928 JSON_BUILD_PAIR("pkfp", JSON_BUILD_HEX(pubkey_fp
, pubkey_fp_size
)), /* SHA256 fingerprint of public key (DER) used for the signature */
929 JSON_BUILD_PAIR("pol", JSON_BUILD_HEX(pcr_policy_digest
->buffer
, pcr_policy_digest
->size
)), /* TPM2 policy hash that is signed */
930 JSON_BUILD_PAIR("sig", JSON_BUILD_BASE64(sig
, ss
)))); /* signature data */
932 log_error_errno(r
, "Failed to build JSON object: %m");
936 _cleanup_(json_variant_unrefp
) JsonVariant
*av
= NULL
;
937 av
= json_variant_ref(json_variant_by_key(v
, p
->bank
));
939 r
= json_variant_append_array(&av
, bv
);
941 log_error_errno(r
, "Failed to append JSON object: %m");
945 r
= json_variant_set_field(&v
, p
->bank
, av
);
947 log_error_errno(r
, "Failed to add JSON field: %m");
952 /* Return to the original kernel measurement for the next phase calculation */
953 pcr_states_restore(pcr_states
, n
);
956 if (arg_json_format_flags
& (JSON_FORMAT_PRETTY
|JSON_FORMAT_PRETTY_AUTO
))
957 pager_open(arg_pager_flags
);
959 json_variant_dump(v
, arg_json_format_flags
, stdout
, NULL
);
963 session_handle
= tpm2_flush_context_verbose(c
.esys_context
, session_handle
);
967 static int compare_reported_pcr_nr(uint32_t pcr
, const char *varname
, const char *description
) {
968 _cleanup_free_
char *s
= NULL
;
972 r
= efi_get_variable_string(varname
, &s
);
976 return log_error_errno(r
, "Failed to read EFI variable '%s': %m", varname
);
978 r
= safe_atou32(s
, &v
);
980 return log_error_errno(r
, "Failed to parse EFI variable '%s': %s", varname
, s
);
983 log_warning("PCR number reported by stub for %s (%" PRIu32
") different from our expectation (%" PRIu32
").\n"
984 "The measurements are likely inconsistent.", description
, v
, pcr
);
989 static int validate_stub(void) {
994 if (tpm2_support() != TPM2_SUPPORT_FULL
)
995 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "Sorry, system lacks full TPM2 support.");
997 r
= efi_stub_get_features(&features
);
999 return log_error_errno(r
, "Unable to get stub features: %m");
1001 if (!FLAGS_SET(features
, EFI_STUB_FEATURE_THREE_PCRS
))
1002 log_warning("Warning: current kernel image does not support measuring itself, the command line or initrd system extension images.\n"
1003 "The PCR measurements seen are unlikely to be valid.");
1005 r
= compare_reported_pcr_nr(TPM_PCR_INDEX_KERNEL_IMAGE
, EFI_LOADER_VARIABLE("StubPcrKernelImage"), "kernel image");
1009 r
= compare_reported_pcr_nr(TPM_PCR_INDEX_KERNEL_PARAMETERS
, EFI_LOADER_VARIABLE("StubPcrKernelParameters"), "kernel parameters");
1013 r
= compare_reported_pcr_nr(TPM_PCR_INDEX_INITRD_SYSEXTS
, EFI_LOADER_VARIABLE("StubPcrInitRDSysExts"), "initrd system extension images");
1017 STRV_FOREACH(bank
, arg_banks
) {
1018 _cleanup_free_
char *b
= NULL
, *p
= NULL
;
1024 if (asprintf(&p
, "/sys/class/tpm/tpm0/pcr-%s/", ascii_strlower(b
)) < 0)
1027 if (access(p
, F_OK
) < 0) {
1028 if (errno
!= ENOENT
)
1029 return log_error_errno(errno
, "Failed to detect if '%s' exists: %m", b
);
1035 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "None of the select PCR banks appear to exist.");
1040 static int verb_status(int argc
, char *argv
[], void *userdata
) {
1041 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
1043 static const struct {
1045 const char *description
;
1046 } relevant_pcrs
[] = {
1047 { TPM_PCR_INDEX_KERNEL_IMAGE
, "Unified Kernel Image" },
1048 { TPM_PCR_INDEX_KERNEL_PARAMETERS
, "Kernel Parameters" },
1049 { TPM_PCR_INDEX_INITRD_SYSEXTS
, "initrd System Extensions" },
1054 r
= validate_stub();
1058 for (size_t i
= 0; i
< ELEMENTSOF(relevant_pcrs
); i
++) {
1060 STRV_FOREACH(bank
, arg_banks
) {
1061 _cleanup_free_
char *b
= NULL
, *p
= NULL
, *s
= NULL
;
1062 _cleanup_free_
void *h
= NULL
;
1069 if (asprintf(&p
, "/sys/class/tpm/tpm0/pcr-%s/%" PRIu32
, ascii_strlower(b
), relevant_pcrs
[i
].nr
) < 0)
1072 r
= read_virtual_file(p
, 4096, &s
, NULL
);
1076 return log_error_errno(r
, "Failed to read '%s': %m", p
);
1078 r
= unhexmem(strstrip(s
), SIZE_MAX
, &h
, &l
);
1080 return log_error_errno(r
, "Failed to decode PCR value '%s': %m", s
);
1082 if (arg_json_format_flags
& JSON_FORMAT_OFF
) {
1083 _cleanup_free_
char *f
= NULL
;
1089 if (bank
== arg_banks
) {
1090 /* before the first line for each PCR, write a short descriptive text to
1091 * stderr, and leave the primary content on stdout */
1093 fprintf(stderr
, "%s# PCR[%" PRIu32
"] %s%s%s\n",
1095 relevant_pcrs
[i
].nr
,
1096 relevant_pcrs
[i
].description
,
1097 memeqzero(h
, l
) ? " (NOT SET!)" : "",
1102 printf("%" PRIu32
":%s=%s\n", relevant_pcrs
[i
].nr
, b
, f
);
1105 _cleanup_(json_variant_unrefp
) JsonVariant
*bv
= NULL
, *a
= NULL
;
1109 JSON_BUILD_PAIR("pcr", JSON_BUILD_INTEGER(relevant_pcrs
[i
].nr
)),
1110 JSON_BUILD_PAIR("hash", JSON_BUILD_HEX(h
, l
))
1114 return log_error_errno(r
, "Failed to build JSON object: %m");
1116 a
= json_variant_ref(json_variant_by_key(v
, b
));
1118 r
= json_variant_append_array(&a
, bv
);
1120 return log_error_errno(r
, "Failed to append PCR entry to JSON array: %m");
1122 r
= json_variant_set_field(&v
, b
, a
);
1124 return log_error_errno(r
, "Failed to add bank info to object: %m");
1129 if (!FLAGS_SET(arg_json_format_flags
, JSON_FORMAT_OFF
)) {
1130 if (arg_json_format_flags
& (JSON_FORMAT_PRETTY
|JSON_FORMAT_PRETTY_AUTO
))
1131 pager_open(arg_pager_flags
);
1133 json_variant_dump(v
, arg_json_format_flags
, stdout
, NULL
);
1139 static int measure_main(int argc
, char *argv
[]) {
1140 static const Verb verbs
[] = {
1141 { "help", VERB_ANY
, VERB_ANY
, 0, help
},
1142 { "status", VERB_ANY
, 1, VERB_DEFAULT
, verb_status
},
1143 { "calculate", VERB_ANY
, 1, 0, verb_calculate
},
1144 { "sign", VERB_ANY
, 1, 0, verb_sign
},
1148 return dispatch_verb(argc
, argv
, verbs
, NULL
);
1151 static int run(int argc
, char *argv
[]) {
1154 log_show_color(true);
1155 log_parse_environment();
1158 r
= parse_argv(argc
, argv
);
1162 return measure_main(argc
, argv
);
1165 DEFINE_MAIN_FUNCTION(run
);