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, SHA384, SHA512)\n"
70 " --tpm2-device=PATH Use specified TPM2 device\n"
71 " --private-key=KEY Private key (PEM) to sign with\n"
72 " --public-key=KEY Public key (PEM) to validate against\n"
73 " --json=MODE Output as JSON\n"
74 " -j Same as --json=pretty on tty, --json=short otherwise\n"
75 "\n%3$sUKI PE Section Options:%4$s %3$sUKI PE Section%4$s\n"
76 " --linux=PATH Path to Linux kernel image file %7$s .linux\n"
77 " --osrel=PATH Path to os-release file %7$s .osrel\n"
78 " --cmdline=PATH Path to file with kernel command line %7$s .cmdline\n"
79 " --initrd=PATH Path to initrd image file %7$s .initrd\n"
80 " --splash=PATH Path to splash bitmap file %7$s .splash\n"
81 " --dtb=PATH Path to Devicetree file %7$s .dtb\n"
82 " --pcrpkey=PATH Path to public key for PCR signatures %7$s .pcrpkey\n"
83 "\nSee the %2$s for details.\n",
84 program_invocation_short_name
,
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:sysinit",
285 "enter-initrd:leave-initrd:sysinit:ready"),
286 /* filter_duplicates= */ false) < 0)
289 strv_sort(arg_phase
);
290 strv_uniq(arg_phase
);
293 _cleanup_free_
char *j
= NULL
;
294 j
= strv_join(arg_phase
, ", ");
298 log_debug("Measuring boot phases: %s", j
);
302 /* The PCR 11 state for one specific bank */
303 typedef struct PcrState
{
308 void *saved_value
; /* A copy of the original value we calculated, used by pcr_states_save()/pcr_states_restore() to come later back to */
311 static void pcr_state_free_all(PcrState
**pcr_state
) {
317 for (size_t i
= 0; (*pcr_state
)[i
].value
; i
++) {
318 free((*pcr_state
)[i
].bank
);
319 free((*pcr_state
)[i
].value
);
320 free((*pcr_state
)[i
].saved_value
);
323 *pcr_state
= mfree(*pcr_state
);
326 static void evp_md_ctx_free_all(EVP_MD_CTX
**md
[]) {
332 for (size_t i
= 0; (*md
)[i
]; i
++)
333 EVP_MD_CTX_free((*md
)[i
]);
338 static int pcr_state_extend(PcrState
*pcr_state
, const void *data
, size_t sz
) {
339 _cleanup_(EVP_MD_CTX_freep
) EVP_MD_CTX
*mc
= NULL
;
343 assert(data
|| sz
== 0);
344 assert(pcr_state
->md
);
345 assert(pcr_state
->value
);
346 assert(pcr_state
->value_size
> 0);
348 /* Extends a (virtual) PCR by the given data */
350 mc
= EVP_MD_CTX_new();
354 if (EVP_DigestInit_ex(mc
, pcr_state
->md
, NULL
) != 1)
355 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to initialize %s context.", pcr_state
->bank
);
357 /* First thing we do, is hash the old PCR value */
358 if (EVP_DigestUpdate(mc
, pcr_state
->value
, pcr_state
->value_size
) != 1)
359 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to run digest.");
361 /* Then, we hash the new data */
362 if (EVP_DigestUpdate(mc
, data
, sz
) != 1)
363 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to run digest.");
365 if (EVP_DigestFinal_ex(mc
, pcr_state
->value
, &value_size
) != 1)
366 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to finalize hash context.");
368 assert(value_size
== pcr_state
->value_size
);
372 #define BUFFER_SIZE (16U * 1024U)
374 static int measure_kernel(PcrState
*pcr_states
, size_t n
) {
375 _cleanup_free_
void *buffer
= NULL
;
381 /* Virtually measures the components of a unified kernel image into PCR 11 */
384 /* Shortcut things, if we should just use the current PCR value */
386 for (size_t i
= 0; i
< n
; i
++) {
387 _cleanup_free_
char *p
= NULL
, *s
= NULL
;
388 _cleanup_free_
void *v
= NULL
;
391 if (asprintf(&p
, "/sys/class/tpm/tpm0/pcr-%s/%" PRIu32
, pcr_states
[i
].bank
, TPM_PCR_INDEX_KERNEL_IMAGE
) < 0)
394 r
= read_virtual_file(p
, 4096, &s
, NULL
);
395 if (r
== -ENOENT
&& access("/sys/class/tpm/tpm0/", F_OK
) >= 0)
396 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
);
398 return log_error_errno(r
, "Failed to read '%s': %m", p
);
400 r
= unhexmem(strstrip(s
), SIZE_MAX
, &v
, &sz
);
402 return log_error_errno(r
, "Failed to decode PCR value '%s': %m", s
);
404 assert(pcr_states
[i
].value_size
== sz
);
405 memcpy(pcr_states
[i
].value
, v
, sz
);
411 buffer
= malloc(BUFFER_SIZE
);
415 for (UnifiedSection c
= 0; c
< _UNIFIED_SECTION_MAX
; c
++) {
416 _cleanup_(evp_md_ctx_free_all
) EVP_MD_CTX
**mdctx
= NULL
;
417 _cleanup_close_
int fd
= -1;
420 if (!arg_sections
[c
])
423 fd
= open(arg_sections
[c
], O_RDONLY
|O_CLOEXEC
);
425 return log_error_errno(errno
, "Failed to open '%s': %m", arg_sections
[c
]);
427 /* Allocate one message digest context per bank (NULL terminated) */
428 mdctx
= new0(EVP_MD_CTX
*, n
+ 1);
432 for (size_t i
= 0; i
< n
; i
++) {
433 mdctx
[i
] = EVP_MD_CTX_new();
437 if (EVP_DigestInit_ex(mdctx
[i
], pcr_states
[i
].md
, NULL
) != 1)
438 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to initialize data %s context.", pcr_states
[i
].bank
);
444 sz
= read(fd
, buffer
, BUFFER_SIZE
);
446 return log_error_errno(errno
, "Failed to read '%s': %m", arg_sections
[c
]);
447 if (sz
== 0) /* EOF */
450 for (size_t i
= 0; i
< n
; i
++)
451 if (EVP_DigestUpdate(mdctx
[i
], buffer
, sz
) != 1)
452 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to run digest.");
459 if (m
== 0) /* We skip over empty files, the stub does so too */
462 for (size_t i
= 0; i
< n
; i
++) {
463 _cleanup_free_
void *data_hash
= NULL
;
464 unsigned data_hash_size
;
466 data_hash
= malloc(pcr_states
[i
].value_size
);
470 /* Measure name of section */
471 if (EVP_Digest(unified_sections
[c
], strlen(unified_sections
[c
]) + 1, data_hash
, &data_hash_size
, pcr_states
[i
].md
, NULL
) != 1)
472 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to hash section name with %s.", pcr_states
[i
].bank
);
474 assert(data_hash_size
== (unsigned) pcr_states
[i
].value_size
);
476 r
= pcr_state_extend(pcr_states
+ i
, data_hash
, data_hash_size
);
480 /* Retrieve hash of data and measure it */
481 if (EVP_DigestFinal_ex(mdctx
[i
], data_hash
, &data_hash_size
) != 1)
482 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to finalize hash context.");
484 assert(data_hash_size
== (unsigned) pcr_states
[i
].value_size
);
486 r
= pcr_state_extend(pcr_states
+ i
, data_hash
, data_hash_size
);
495 static int measure_phase(PcrState
*pcr_states
, size_t n
, const char *phase
) {
496 _cleanup_strv_free_
char **l
= NULL
;
502 /* Measure a phase string into PCR 11. This splits up the "phase" expression at colons, and then
503 * virtually extends each specified word into PCR 11, to model how during boot we measure a series of
504 * words into PCR 11, one for each phase. */
506 l
= strv_split(phase
, ":");
510 STRV_FOREACH(word
, l
) {
518 for (size_t i
= 0; i
< n
; i
++) { /* For each bank */
519 _cleanup_free_
void *b
= NULL
;
522 bsz
= EVP_MD_size(pcr_states
[i
].md
);
529 /* First hash the word itself */
530 if (EVP_Digest(*word
, wl
, b
, NULL
, pcr_states
[i
].md
, NULL
) != 1)
531 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
), "Failed to hash word '%s'.", *word
);
533 /* And then extend the PCR with the resulting hash */
534 r
= pcr_state_extend(pcr_states
+ i
, b
, bsz
);
543 static int pcr_states_allocate(PcrState
**ret
) {
544 _cleanup_(pcr_state_free_all
) PcrState
*pcr_states
= NULL
;
547 pcr_states
= new0(PcrState
, strv_length(arg_banks
) + 1);
551 /* Allocate a PCR state structure, one for each bank */
552 STRV_FOREACH(d
, arg_banks
) {
553 const EVP_MD
*implementation
;
554 _cleanup_free_
void *v
= NULL
;
555 _cleanup_free_
char *b
= NULL
;
558 assert_se(implementation
= EVP_get_digestbyname(*d
)); /* Must work, we already checked while parsing command line */
560 b
= strdup(EVP_MD_name(implementation
));
564 sz
= EVP_MD_size(implementation
);
565 if (sz
<= 0 || sz
>= INT_MAX
)
566 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Unexpected digest size: %i", sz
);
568 v
= malloc0(sz
); /* initial PCR state is all zeroes */
572 pcr_states
[n
++] = (struct PcrState
) {
573 .bank
= ascii_strlower(TAKE_PTR(b
)),
574 .md
= implementation
,
575 .value
= TAKE_PTR(v
),
580 *ret
= TAKE_PTR(pcr_states
);
584 static int pcr_states_save(PcrState
*pcr_states
, size_t n
) {
588 for (size_t i
= 0; i
< n
; i
++) {
589 _cleanup_free_
void *saved
= NULL
;
591 if (!pcr_states
[i
].value
)
594 saved
= memdup(pcr_states
[i
].value
, pcr_states
[i
].value_size
);
598 free_and_replace(pcr_states
[i
].saved_value
, saved
);
604 static void pcr_states_restore(PcrState
*pcr_states
, size_t n
) {
608 for (size_t i
= 0; i
< n
; i
++) {
610 assert(pcr_states
[i
].value
);
611 assert(pcr_states
[i
].saved_value
);
613 memcpy(pcr_states
[i
].value
, pcr_states
[i
].saved_value
, pcr_states
[i
].value_size
);
617 static int verb_calculate(int argc
, char *argv
[], void *userdata
) {
618 _cleanup_(json_variant_unrefp
) JsonVariant
*w
= NULL
;
619 _cleanup_(pcr_state_free_all
) PcrState
*pcr_states
= NULL
;
623 if (!arg_sections
[UNIFIED_SECTION_LINUX
] && !arg_current
)
624 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Either --linux= or --current must be specified, refusing.");
626 r
= pcr_states_allocate(&pcr_states
);
632 r
= measure_kernel(pcr_states
, n
);
636 /* Save the current state, so that we later can restore to it. This way we can measure the PCR values
637 * for multiple different boot phases without heaving to start from zero each time */
638 r
= pcr_states_save(pcr_states
, n
);
642 STRV_FOREACH(phase
, arg_phase
) {
644 r
= measure_phase(pcr_states
, n
, *phase
);
648 for (size_t i
= 0; i
< n
; i
++) {
649 if (arg_json_format_flags
& JSON_FORMAT_OFF
) {
650 _cleanup_free_
char *hd
= NULL
;
654 fprintf(stderr
, "%s# PCR[%" PRIu32
"] Phase <%s>%s\n",
656 TPM_PCR_INDEX_KERNEL_IMAGE
,
657 isempty(*phase
) ? ":" : *phase
,
662 hd
= hexmem(pcr_states
[i
].value
, pcr_states
[i
].value_size
);
666 printf("%" PRIu32
":%s=%s\n", TPM_PCR_INDEX_KERNEL_IMAGE
, pcr_states
[i
].bank
, hd
);
668 _cleanup_(json_variant_unrefp
) JsonVariant
*bv
= NULL
, *array
= NULL
;
670 array
= json_variant_ref(json_variant_by_key(w
, pcr_states
[i
].bank
));
674 JSON_BUILD_PAIR_CONDITION(!isempty(*phase
), "phase", JSON_BUILD_STRING(*phase
)),
675 JSON_BUILD_PAIR("pcr", JSON_BUILD_INTEGER(TPM_PCR_INDEX_KERNEL_IMAGE
)),
676 JSON_BUILD_PAIR("hash", JSON_BUILD_HEX(pcr_states
[i
].value
, pcr_states
[i
].value_size
))
680 return log_error_errno(r
, "Failed to build JSON object: %m");
682 r
= json_variant_append_array(&array
, bv
);
684 return log_error_errno(r
, "Failed to append JSON object to array: %m");
686 r
= json_variant_set_field(&w
, pcr_states
[i
].bank
, array
);
688 return log_error_errno(r
, "Failed to add bank info to object: %m");
692 /* Return to the original kernel measurement for the next phase calculation */
693 pcr_states_restore(pcr_states
, n
);
696 if (!FLAGS_SET(arg_json_format_flags
, JSON_FORMAT_OFF
)) {
698 if (arg_json_format_flags
& (JSON_FORMAT_PRETTY
|JSON_FORMAT_PRETTY_AUTO
))
699 pager_open(arg_pager_flags
);
701 json_variant_dump(w
, arg_json_format_flags
, stdout
, NULL
);
707 static int verb_sign(int argc
, char *argv
[], void *userdata
) {
708 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
709 _cleanup_(pcr_state_free_all
) PcrState
*pcr_states
= NULL
;
710 _cleanup_(EVP_PKEY_freep
) EVP_PKEY
*privkey
= NULL
, *pubkey
= NULL
;
711 _cleanup_(tpm2_context_destroy
) struct tpm2_context c
= {};
712 _cleanup_fclose_
FILE *privkeyf
= NULL
;
713 ESYS_TR session_handle
= ESYS_TR_NONE
;
718 if (!arg_sections
[UNIFIED_SECTION_LINUX
] && !arg_current
)
719 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Either --linux= or --current must be specified, refusing.");
721 if (!arg_private_key
)
722 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "No private key specified, use --private-key=.");
724 /* When signing we only support JSON output */
725 arg_json_format_flags
&= ~JSON_FORMAT_OFF
;
727 privkeyf
= fopen(arg_private_key
, "re");
729 return log_error_errno(errno
, "Failed to open private key file '%s': %m", arg_private_key
);
731 privkey
= PEM_read_PrivateKey(privkeyf
, NULL
, NULL
, NULL
);
733 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to parse private key '%s'.", arg_private_key
);
735 if (arg_public_key
) {
736 _cleanup_fclose_
FILE *pubkeyf
= NULL
;
738 pubkeyf
= fopen(arg_public_key
, "re");
740 return log_error_errno(errno
, "Failed to open public key file '%s': %m", arg_public_key
);
742 pubkey
= PEM_read_PUBKEY(pubkeyf
, NULL
, NULL
, NULL
);
744 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to parse public key '%s'.", arg_public_key
);
746 _cleanup_free_
char *data
= NULL
;
747 _cleanup_fclose_
FILE *tf
= NULL
;
750 /* No public key was specified, let's derive it automatically, if we can */
752 tf
= open_memstream_unlocked(&data
, &sz
);
756 if (i2d_PUBKEY_fp(tf
, privkey
) != 1)
757 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to extract public key from private key file '%s'.", arg_private_key
);
762 if (!d2i_PUBKEY_fp(tf
, &pubkey
))
763 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to parse extracted public key of private key file '%s'.", arg_private_key
);
766 r
= pcr_states_allocate(&pcr_states
);
772 r
= measure_kernel(pcr_states
, n
);
780 r
= tpm2_context_init(arg_tpm2_device
, &c
);
784 for (size_t i
= 0; i
< n
; i
++) {
785 static const TPMT_SYM_DEF symmetric
= {
786 .algorithm
= TPM2_ALG_AES
,
788 .mode
.aes
= TPM2_ALG_CFB
,
790 PcrState
*p
= pcr_states
+ i
;
792 rc
= sym_Esys_StartAuthSession(
804 if (rc
!= TSS2_RC_SUCCESS
) {
805 r
= log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
806 "Failed to open session in TPM: %s", sym_Tss2_RC_Decode(rc
));
810 /* Generate a single hash value from the PCRs included in our policy. Given that that's
811 * exactly one, the calculation is trivial. */
812 TPM2B_DIGEST intermediate_digest
= {
813 .size
= SHA256_DIGEST_SIZE
,
815 assert(sizeof(intermediate_digest
.buffer
) >= SHA256_DIGEST_SIZE
);
816 sha256_direct(p
->value
, p
->value_size
, intermediate_digest
.buffer
);
818 int tpmalg
= tpm2_pcr_bank_from_string(EVP_MD_name(p
->md
));
820 log_error_errno(tpmalg
, "Unsupported PCR bank");
824 TPML_PCR_SELECTION pcr_selection
;
825 tpm2_pcr_mask_to_selection(1 << TPM_PCR_INDEX_KERNEL_IMAGE
, tpmalg
, &pcr_selection
);
827 rc
= sym_Esys_PolicyPCR(
833 &intermediate_digest
,
835 if (rc
!= TSS2_RC_SUCCESS
) {
836 r
= log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
837 "Failed to push PCR policy into TPM: %s", sym_Tss2_RC_Decode(rc
));
841 _cleanup_(Esys_Freep
) TPM2B_DIGEST
*pcr_policy_digest
= NULL
;
842 rc
= sym_Esys_PolicyGetDigest(
849 if (rc
!= TSS2_RC_SUCCESS
) {
850 r
= log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
851 "Failed to get policy digest from TPM: %s", sym_Tss2_RC_Decode(rc
));
855 session_handle
= tpm2_flush_context_verbose(c
.esys_context
, session_handle
);
857 _cleanup_(EVP_MD_CTX_freep
) EVP_MD_CTX
* mdctx
= NULL
;
858 mdctx
= EVP_MD_CTX_new();
864 if (EVP_DigestSignInit(mdctx
, NULL
, p
->md
, NULL
, privkey
) != 1) {
865 r
= log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
866 "Failed to initialize signature context.");
870 if (EVP_DigestSignUpdate(mdctx
, pcr_policy_digest
->buffer
, pcr_policy_digest
->size
) != 1) {
871 r
= log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
872 "Failed to sign data.");
877 if (EVP_DigestSignFinal(mdctx
, NULL
, &ss
) != 1) {
878 r
= log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
879 "Failed to finalize signature");
883 _cleanup_free_
void *sig
= malloc(ss
);
889 if (EVP_DigestSignFinal(mdctx
, sig
, &ss
) != 1) {
890 r
= log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
891 "Failed to acquire signature data");
895 _cleanup_free_
void *pubkey_fp
= NULL
;
896 size_t pubkey_fp_size
= 0;
897 r
= pubkey_fingerprint(pubkey
, EVP_sha256(), &pubkey_fp
, &pubkey_fp_size
);
901 _cleanup_(json_variant_unrefp
) JsonVariant
*bv
= NULL
, *a
= NULL
;
903 r
= tpm2_make_pcr_json_array(UINT64_C(1) << TPM_PCR_INDEX_KERNEL_IMAGE
, &a
);
905 log_error_errno(r
, "Failed to build JSON PCR mask array: %m");
909 r
= json_build(&bv
, JSON_BUILD_ARRAY(
911 JSON_BUILD_PAIR("pcrs", JSON_BUILD_VARIANT(a
)), /* PCR mask */
912 JSON_BUILD_PAIR("pkfp", JSON_BUILD_HEX(pubkey_fp
, pubkey_fp_size
)), /* SHA256 fingerprint of public key (DER) used for the signature */
913 JSON_BUILD_PAIR("pol", JSON_BUILD_HEX(pcr_policy_digest
->buffer
, pcr_policy_digest
->size
)), /* TPM2 policy hash that is signed */
914 JSON_BUILD_PAIR("sig", JSON_BUILD_BASE64(sig
, ss
))))); /* signature data */
916 log_error_errno(r
, "Failed to build JSON object: %m");
920 r
= json_variant_set_field(&v
, p
->bank
, bv
);
922 log_error_errno(r
, "Failed to add JSON field: %m");
928 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Unable to find a single working PCR bank.");
930 if (arg_json_format_flags
& (JSON_FORMAT_PRETTY
|JSON_FORMAT_PRETTY_AUTO
))
931 pager_open(arg_pager_flags
);
933 json_variant_dump(v
, arg_json_format_flags
, stdout
, NULL
);
937 session_handle
= tpm2_flush_context_verbose(c
.esys_context
, session_handle
);
941 static int compare_reported_pcr_nr(uint32_t pcr
, const char *varname
, const char *description
) {
942 _cleanup_free_
char *s
= NULL
;
946 r
= efi_get_variable_string(varname
, &s
);
950 return log_error_errno(r
, "Failed to read EFI variable '%s': %m", varname
);
952 r
= safe_atou32(s
, &v
);
954 return log_error_errno(r
, "Failed to parse EFI variable '%s': %s", varname
, s
);
957 log_warning("PCR number reported by stub for %s (%" PRIu32
") different from our expectation (%" PRIu32
").\n"
958 "The measurements are likely inconsistent.", description
, v
, pcr
);
963 static int validate_stub(void) {
968 if (tpm2_support() != TPM2_SUPPORT_FULL
)
969 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "Sorry, system lacks full TPM2 support.");
971 r
= efi_stub_get_features(&features
);
973 return log_error_errno(r
, "Unable to get stub features: %m");
975 if (!FLAGS_SET(features
, EFI_STUB_FEATURE_THREE_PCRS
))
976 log_warning("Warning: current kernel image does not support measuring itself, the command line or initrd system extension images.\n"
977 "The PCR measurements seen are unlikely to be valid.");
979 r
= compare_reported_pcr_nr(TPM_PCR_INDEX_KERNEL_IMAGE
, EFI_LOADER_VARIABLE("StubPcrKernelImage"), "kernel image");
983 r
= compare_reported_pcr_nr(TPM_PCR_INDEX_KERNEL_PARAMETERS
, EFI_LOADER_VARIABLE("StubPcrKernelParameters"), "kernel parameters");
987 r
= compare_reported_pcr_nr(TPM_PCR_INDEX_INITRD_SYSEXTS
, EFI_LOADER_VARIABLE("StubPcrInitRDSysExts"), "initrd system extension images");
991 STRV_FOREACH(bank
, arg_banks
) {
992 _cleanup_free_
char *b
= NULL
, *p
= NULL
;
998 if (asprintf(&p
, "/sys/class/tpm/tpm0/pcr-%s/", ascii_strlower(b
)) < 0)
1001 if (access(p
, F_OK
) < 0) {
1002 if (errno
!= ENOENT
)
1003 return log_error_errno(errno
, "Failed to detect if '%s' exists: %m", b
);
1009 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "None of the select PCR banks appear to exist.");
1014 static int verb_status(int argc
, char *argv
[], void *userdata
) {
1015 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
1017 static const struct {
1019 const char *description
;
1020 } relevant_pcrs
[] = {
1021 { TPM_PCR_INDEX_KERNEL_IMAGE
, "Unified Kernel Image" },
1022 { TPM_PCR_INDEX_KERNEL_PARAMETERS
, "Kernel Parameters" },
1023 { TPM_PCR_INDEX_INITRD_SYSEXTS
, "initrd System Extensions" },
1028 r
= validate_stub();
1032 for (size_t i
= 0; i
< ELEMENTSOF(relevant_pcrs
); i
++) {
1034 STRV_FOREACH(bank
, arg_banks
) {
1035 _cleanup_free_
char *b
= NULL
, *p
= NULL
, *s
= NULL
;
1036 _cleanup_free_
void *h
= NULL
;
1043 if (asprintf(&p
, "/sys/class/tpm/tpm0/pcr-%s/%" PRIu32
, ascii_strlower(b
), relevant_pcrs
[i
].nr
) < 0)
1046 r
= read_virtual_file(p
, 4096, &s
, NULL
);
1050 return log_error_errno(r
, "Failed to read '%s': %m", p
);
1052 r
= unhexmem(strstrip(s
), SIZE_MAX
, &h
, &l
);
1054 return log_error_errno(r
, "Failed to decode PCR value '%s': %m", s
);
1056 if (arg_json_format_flags
& JSON_FORMAT_OFF
) {
1057 _cleanup_free_
char *f
= NULL
;
1063 if (bank
== arg_banks
) {
1064 /* before the first line for each PCR, write a short descriptive text to
1065 * stderr, and leave the primary content on stdout */
1067 fprintf(stderr
, "%s# PCR[%" PRIu32
"] %s%s%s\n",
1069 relevant_pcrs
[i
].nr
,
1070 relevant_pcrs
[i
].description
,
1071 memeqzero(h
, l
) ? " (NOT SET!)" : "",
1076 printf("%" PRIu32
":%s=%s\n", relevant_pcrs
[i
].nr
, b
, f
);
1079 _cleanup_(json_variant_unrefp
) JsonVariant
*bv
= NULL
, *a
= NULL
;
1083 JSON_BUILD_PAIR("pcr", JSON_BUILD_INTEGER(relevant_pcrs
[i
].nr
)),
1084 JSON_BUILD_PAIR("hash", JSON_BUILD_HEX(h
, l
))
1088 return log_error_errno(r
, "Failed to build JSON object: %m");
1090 a
= json_variant_ref(json_variant_by_key(v
, b
));
1092 r
= json_variant_append_array(&a
, bv
);
1094 return log_error_errno(r
, "Failed to append PCR entry to JSON array: %m");
1096 r
= json_variant_set_field(&v
, b
, a
);
1098 return log_error_errno(r
, "Failed to add bank info to object: %m");
1103 if (!FLAGS_SET(arg_json_format_flags
, JSON_FORMAT_OFF
)) {
1104 if (arg_json_format_flags
& (JSON_FORMAT_PRETTY
|JSON_FORMAT_PRETTY_AUTO
))
1105 pager_open(arg_pager_flags
);
1107 json_variant_dump(v
, arg_json_format_flags
, stdout
, NULL
);
1113 static int measure_main(int argc
, char *argv
[]) {
1114 static const Verb verbs
[] = {
1115 { "help", VERB_ANY
, VERB_ANY
, 0, help
},
1116 { "status", VERB_ANY
, 1, VERB_DEFAULT
, verb_status
},
1117 { "calculate", VERB_ANY
, 1, 0, verb_calculate
},
1118 { "sign", VERB_ANY
, 1, 0, verb_sign
},
1122 return dispatch_verb(argc
, argv
, verbs
, NULL
);
1125 static int run(int argc
, char *argv
[]) {
1128 log_show_color(true);
1129 log_parse_environment();
1132 r
= parse_argv(argc
, argv
);
1136 return measure_main(argc
, argv
);
1139 DEFINE_MAIN_FUNCTION(run
);