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 "memstream-util.h"
15 #include "openssl-util.h"
16 #include "parse-argument.h"
17 #include "parse-util.h"
18 #include "pretty-print.h"
20 #include "terminal-util.h"
22 #include "tpm2-util.h"
25 /* Tool for pre-calculating expected TPM PCR values based on measured resources. This is intended to be used
26 * to pre-calculate suitable values for PCR 11, the way sd-stub measures into it. */
28 static char *arg_sections
[_UNIFIED_SECTION_MAX
] = {};
29 static char **arg_banks
= NULL
;
30 static char *arg_tpm2_device
= NULL
;
31 static char *arg_private_key
= NULL
;
32 static char *arg_public_key
= NULL
;
33 static JsonFormatFlags arg_json_format_flags
= JSON_FORMAT_PRETTY_AUTO
|JSON_FORMAT_COLOR_AUTO
|JSON_FORMAT_OFF
;
34 static PagerFlags arg_pager_flags
= 0;
35 static bool arg_current
= false;
36 static char **arg_phase
= NULL
;
37 static char *arg_append
= NULL
;
39 STATIC_DESTRUCTOR_REGISTER(arg_banks
, strv_freep
);
40 STATIC_DESTRUCTOR_REGISTER(arg_tpm2_device
, freep
);
41 STATIC_DESTRUCTOR_REGISTER(arg_private_key
, freep
);
42 STATIC_DESTRUCTOR_REGISTER(arg_public_key
, freep
);
43 STATIC_DESTRUCTOR_REGISTER(arg_phase
, strv_freep
);
44 STATIC_DESTRUCTOR_REGISTER(arg_append
, freep
);
46 static inline void free_sections(char*(*sections
)[_UNIFIED_SECTION_MAX
]) {
47 for (UnifiedSection c
= 0; c
< _UNIFIED_SECTION_MAX
; c
++)
51 STATIC_DESTRUCTOR_REGISTER(arg_sections
, free_sections
);
53 static int help(int argc
, char *argv
[], void *userdata
) {
54 _cleanup_free_
char *link
= NULL
;
57 r
= terminal_urlify_man("systemd-measure", "1", &link
);
61 printf("%1$s [OPTIONS...] COMMAND ...\n"
62 "\n%5$sPre-calculate and sign PCR hash for a unified kernel image (UKI).%6$s\n"
63 "\n%3$sCommands:%4$s\n"
64 " status Show current PCR values\n"
65 " calculate Calculate expected PCR values\n"
66 " sign Calculate and sign expected PCR values\n"
67 "\n%3$sOptions:%4$s\n"
68 " -h --help Show this help\n"
69 " --version Print version\n"
70 " --no-pager Do not pipe output into a pager\n"
71 " -c --current Use current PCR values\n"
72 " --phase=PHASE Specify a boot phase to sign for\n"
73 " --bank=DIGEST Select TPM bank (SHA1, SHA256, SHA384, SHA512)\n"
74 " --tpm2-device=PATH Use specified TPM2 device\n"
75 " --private-key=KEY Private key (PEM) to sign with\n"
76 " --public-key=KEY Public key (PEM) to validate against\n"
77 " --json=MODE Output as JSON\n"
78 " -j Same as --json=pretty on tty, --json=short otherwise\n"
79 " --append=PATH Load specified JSON signature, and append new signature to it\n"
80 "\n%3$sUKI PE Section Options:%4$s %3$sUKI PE Section%4$s\n"
81 " --linux=PATH Path to Linux kernel image file %7$s .linux\n"
82 " --osrel=PATH Path to os-release file %7$s .osrel\n"
83 " --cmdline=PATH Path to file with kernel command line %7$s .cmdline\n"
84 " --initrd=PATH Path to initrd image file %7$s .initrd\n"
85 " --splash=PATH Path to splash bitmap file %7$s .splash\n"
86 " --dtb=PATH Path to Devicetree file %7$s .dtb\n"
87 " --uname=PATH Path to 'uname -r' file %7$s .uname\n"
88 " --pcrpkey=PATH Path to public key for PCR signatures %7$s .pcrpkey\n"
89 "\nSee the %2$s for details.\n",
90 program_invocation_short_name
,
96 special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
));
101 static char *normalize_phase(const char *s
) {
102 _cleanup_strv_free_
char **l
= NULL
;
104 /* Let's normalize phase expressions. We split the series of colon-separated words up, then remove
105 * all empty ones, and glue them back together again. In other words we remove duplicate ":", as well
106 * as leading and trailing ones. */
108 l
= strv_split(s
, ":"); /* Split series of words */
112 /* Remove all empty words and glue things back together */
113 return strv_join(strv_remove(l
, ""), ":");
116 static int parse_argv(int argc
, char *argv
[]) {
121 ARG_LINUX
= _ARG_SECTION_FIRST
,
128 _ARG_PCRSIG
, /* the .pcrsig section is not input for signing, hence not actually an argument here */
130 ARG_PCRPKEY
= _ARG_SECTION_LAST
,
140 static const struct option options
[] = {
141 { "help", no_argument
, NULL
, 'h' },
142 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
143 { "version", no_argument
, NULL
, ARG_VERSION
},
144 { "linux", required_argument
, NULL
, ARG_LINUX
},
145 { "osrel", required_argument
, NULL
, ARG_OSREL
},
146 { "cmdline", required_argument
, NULL
, ARG_CMDLINE
},
147 { "initrd", required_argument
, NULL
, ARG_INITRD
},
148 { "splash", required_argument
, NULL
, ARG_SPLASH
},
149 { "dtb", required_argument
, NULL
, ARG_DTB
},
150 { "uname", required_argument
, NULL
, ARG_UNAME
},
151 { "pcrpkey", required_argument
, NULL
, ARG_PCRPKEY
},
152 { "current", no_argument
, NULL
, 'c' },
153 { "bank", required_argument
, NULL
, ARG_BANK
},
154 { "tpm2-device", required_argument
, NULL
, ARG_TPM2_DEVICE
},
155 { "private-key", required_argument
, NULL
, ARG_PRIVATE_KEY
},
156 { "public-key", required_argument
, NULL
, ARG_PUBLIC_KEY
},
157 { "json", required_argument
, NULL
, ARG_JSON
},
158 { "phase", required_argument
, NULL
, ARG_PHASE
},
159 { "append", required_argument
, NULL
, ARG_APPEND
},
168 /* Make sure the arguments list and the section list, stays in sync */
169 assert_cc(_ARG_SECTION_FIRST
+ _UNIFIED_SECTION_MAX
== _ARG_SECTION_LAST
+ 1);
171 while ((c
= getopt_long(argc
, argv
, "hjc", options
, NULL
)) >= 0)
182 arg_pager_flags
|= PAGER_DISABLE
;
185 case _ARG_SECTION_FIRST
..._ARG_SECTION_LAST
: {
186 UnifiedSection section
= c
- _ARG_SECTION_FIRST
;
188 r
= parse_path_argument(optarg
, /* suppress_root= */ false, arg_sections
+ section
);
199 const EVP_MD
*implementation
;
201 implementation
= EVP_get_digestbyname(optarg
);
203 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Unknown bank '%s', refusing.", optarg
);
205 if (strv_extend(&arg_banks
, EVP_MD_name(implementation
)) < 0)
211 case ARG_PRIVATE_KEY
:
212 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_private_key
);
219 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_public_key
);
225 case ARG_TPM2_DEVICE
: {
226 _cleanup_free_
char *device
= NULL
;
228 if (streq(optarg
, "list"))
229 return tpm2_list_devices();
231 if (!streq(optarg
, "auto")) {
232 device
= strdup(optarg
);
237 free_and_replace(arg_tpm2_device
, device
);
242 arg_json_format_flags
= JSON_FORMAT_PRETTY_AUTO
|JSON_FORMAT_COLOR_AUTO
;
246 r
= parse_json_argument(optarg
, &arg_json_format_flags
);
255 n
= normalize_phase(optarg
);
259 r
= strv_consume(&arg_phase
, TAKE_PTR(n
));
267 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_append
);
277 assert_not_reached();
280 if (strv_isempty(arg_banks
)) {
281 /* If no banks are specifically selected, pick all known banks */
282 arg_banks
= strv_new("SHA1", "SHA256", "SHA384", "SHA512");
287 strv_sort(arg_banks
);
288 strv_uniq(arg_banks
);
291 for (UnifiedSection us
= 0; us
< _UNIFIED_SECTION_MAX
; us
++)
292 if (arg_sections
[us
])
293 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
294 "The --current switch cannot be used in combination with --linux= and related switches.");
296 if (strv_isempty(arg_phase
)) {
297 /* If no phases are specifically selected, pick everything from the beginning of the initrd
298 * to the beginning of shutdown. */
299 if (strv_extend_strv(&arg_phase
,
300 STRV_MAKE("enter-initrd",
301 "enter-initrd:leave-initrd",
302 "enter-initrd:leave-initrd:sysinit",
303 "enter-initrd:leave-initrd:sysinit:ready"),
304 /* filter_duplicates= */ false) < 0)
307 strv_sort(arg_phase
);
308 strv_uniq(arg_phase
);
311 _cleanup_free_
char *j
= NULL
;
312 j
= strv_join(arg_phase
, ", ");
316 log_debug("Measuring boot phases: %s", j
);
320 /* The PCR 11 state for one specific bank */
321 typedef struct PcrState
{
326 void *saved_value
; /* A copy of the original value we calculated, used by pcr_states_save()/pcr_states_restore() to come later back to */
329 static void pcr_state_free_all(PcrState
**pcr_state
) {
335 for (size_t i
= 0; (*pcr_state
)[i
].value
; i
++) {
336 free((*pcr_state
)[i
].bank
);
337 free((*pcr_state
)[i
].value
);
338 free((*pcr_state
)[i
].saved_value
);
341 *pcr_state
= mfree(*pcr_state
);
344 static void evp_md_ctx_free_all(EVP_MD_CTX
**md
[]) {
350 for (size_t i
= 0; (*md
)[i
]; i
++)
351 EVP_MD_CTX_free((*md
)[i
]);
356 static int pcr_state_extend(PcrState
*pcr_state
, const void *data
, size_t sz
) {
357 _cleanup_(EVP_MD_CTX_freep
) EVP_MD_CTX
*mc
= NULL
;
361 assert(data
|| sz
== 0);
362 assert(pcr_state
->md
);
363 assert(pcr_state
->value
);
364 assert(pcr_state
->value_size
> 0);
366 /* Extends a (virtual) PCR by the given data */
368 mc
= EVP_MD_CTX_new();
372 if (EVP_DigestInit_ex(mc
, pcr_state
->md
, NULL
) != 1)
373 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to initialize %s context.", pcr_state
->bank
);
375 /* First thing we do, is hash the old PCR value */
376 if (EVP_DigestUpdate(mc
, pcr_state
->value
, pcr_state
->value_size
) != 1)
377 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to run digest.");
379 /* Then, we hash the new data */
380 if (EVP_DigestUpdate(mc
, data
, sz
) != 1)
381 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to run digest.");
383 if (EVP_DigestFinal_ex(mc
, pcr_state
->value
, &value_size
) != 1)
384 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to finalize hash context.");
386 assert(value_size
== pcr_state
->value_size
);
390 #define BUFFER_SIZE (16U * 1024U)
392 static int measure_kernel(PcrState
*pcr_states
, size_t n
) {
393 _cleanup_free_
void *buffer
= NULL
;
399 /* Virtually measures the components of a unified kernel image into PCR 11 */
402 /* Shortcut things, if we should just use the current PCR value */
404 for (size_t i
= 0; i
< n
; i
++) {
405 _cleanup_free_
char *p
= NULL
, *s
= NULL
;
406 _cleanup_free_
void *v
= NULL
;
409 if (asprintf(&p
, "/sys/class/tpm/tpm0/pcr-%s/%" PRIu32
, pcr_states
[i
].bank
, TPM_PCR_INDEX_KERNEL_IMAGE
) < 0)
412 r
= read_virtual_file(p
, 4096, &s
, NULL
);
413 if (r
== -ENOENT
&& access("/sys/class/tpm/tpm0/", F_OK
) >= 0)
414 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
);
416 return log_error_errno(r
, "Failed to read '%s': %m", p
);
418 r
= unhexmem(strstrip(s
), SIZE_MAX
, &v
, &sz
);
420 return log_error_errno(r
, "Failed to decode PCR value '%s': %m", s
);
422 assert(pcr_states
[i
].value_size
== sz
);
423 memcpy(pcr_states
[i
].value
, v
, sz
);
429 buffer
= malloc(BUFFER_SIZE
);
433 for (UnifiedSection c
= 0; c
< _UNIFIED_SECTION_MAX
; c
++) {
434 _cleanup_(evp_md_ctx_free_all
) EVP_MD_CTX
**mdctx
= NULL
;
435 _cleanup_close_
int fd
= -EBADF
;
438 if (!arg_sections
[c
])
441 fd
= open(arg_sections
[c
], O_RDONLY
|O_CLOEXEC
);
443 return log_error_errno(errno
, "Failed to open '%s': %m", arg_sections
[c
]);
445 /* Allocate one message digest context per bank (NULL terminated) */
446 mdctx
= new0(EVP_MD_CTX
*, n
+ 1);
450 for (size_t i
= 0; i
< n
; i
++) {
451 mdctx
[i
] = EVP_MD_CTX_new();
455 if (EVP_DigestInit_ex(mdctx
[i
], pcr_states
[i
].md
, NULL
) != 1)
456 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
457 "Failed to initialize data %s context.", pcr_states
[i
].bank
);
463 sz
= read(fd
, buffer
, BUFFER_SIZE
);
465 return log_error_errno(errno
, "Failed to read '%s': %m", arg_sections
[c
]);
466 if (sz
== 0) /* EOF */
469 for (size_t i
= 0; i
< n
; i
++)
470 if (EVP_DigestUpdate(mdctx
[i
], buffer
, sz
) != 1)
471 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to run digest.");
478 if (m
== 0) /* We skip over empty files, the stub does so too */
481 for (size_t i
= 0; i
< n
; i
++) {
482 _cleanup_free_
void *data_hash
= NULL
;
483 unsigned data_hash_size
;
485 data_hash
= malloc(pcr_states
[i
].value_size
);
489 /* Measure name of section */
490 if (EVP_Digest(unified_sections
[c
], strlen(unified_sections
[c
]) + 1, data_hash
, &data_hash_size
, pcr_states
[i
].md
, NULL
) != 1)
491 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to hash section name with %s.", pcr_states
[i
].bank
);
493 assert(data_hash_size
== (unsigned) pcr_states
[i
].value_size
);
495 r
= pcr_state_extend(pcr_states
+ i
, data_hash
, data_hash_size
);
499 /* Retrieve hash of data and measure it */
500 if (EVP_DigestFinal_ex(mdctx
[i
], data_hash
, &data_hash_size
) != 1)
501 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to finalize hash context.");
503 assert(data_hash_size
== (unsigned) pcr_states
[i
].value_size
);
505 r
= pcr_state_extend(pcr_states
+ i
, data_hash
, data_hash_size
);
514 static int measure_phase(PcrState
*pcr_states
, size_t n
, const char *phase
) {
515 _cleanup_strv_free_
char **l
= NULL
;
521 /* Measure a phase string into PCR 11. This splits up the "phase" expression at colons, and then
522 * virtually extends each specified word into PCR 11, to model how during boot we measure a series of
523 * words into PCR 11, one for each phase. */
525 l
= strv_split(phase
, ":");
529 STRV_FOREACH(word
, l
) {
537 for (size_t i
= 0; i
< n
; i
++) { /* For each bank */
538 _cleanup_free_
void *b
= NULL
;
541 bsz
= EVP_MD_size(pcr_states
[i
].md
);
548 /* First hash the word itself */
549 if (EVP_Digest(*word
, wl
, b
, NULL
, pcr_states
[i
].md
, NULL
) != 1)
550 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
), "Failed to hash word '%s'.", *word
);
552 /* And then extend the PCR with the resulting hash */
553 r
= pcr_state_extend(pcr_states
+ i
, b
, bsz
);
562 static int pcr_states_allocate(PcrState
**ret
) {
563 _cleanup_(pcr_state_free_all
) PcrState
*pcr_states
= NULL
;
566 pcr_states
= new0(PcrState
, strv_length(arg_banks
) + 1);
570 /* Allocate a PCR state structure, one for each bank */
571 STRV_FOREACH(d
, arg_banks
) {
572 const EVP_MD
*implementation
;
573 _cleanup_free_
void *v
= NULL
;
574 _cleanup_free_
char *b
= NULL
;
577 assert_se(implementation
= EVP_get_digestbyname(*d
)); /* Must work, we already checked while parsing command line */
579 b
= strdup(EVP_MD_name(implementation
));
583 sz
= EVP_MD_size(implementation
);
584 if (sz
<= 0 || sz
>= INT_MAX
)
585 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Unexpected digest size: %i", sz
);
587 v
= malloc0(sz
); /* initial PCR state is all zeroes */
591 pcr_states
[n
++] = (struct PcrState
) {
592 .bank
= ascii_strlower(TAKE_PTR(b
)),
593 .md
= implementation
,
594 .value
= TAKE_PTR(v
),
599 *ret
= TAKE_PTR(pcr_states
);
603 static int pcr_states_save(PcrState
*pcr_states
, size_t n
) {
607 for (size_t i
= 0; i
< n
; i
++) {
608 _cleanup_free_
void *saved
= NULL
;
610 if (!pcr_states
[i
].value
)
613 saved
= memdup(pcr_states
[i
].value
, pcr_states
[i
].value_size
);
617 free_and_replace(pcr_states
[i
].saved_value
, saved
);
623 static void pcr_states_restore(PcrState
*pcr_states
, size_t n
) {
627 for (size_t i
= 0; i
< n
; i
++) {
629 assert(pcr_states
[i
].value
);
630 assert(pcr_states
[i
].saved_value
);
632 memcpy(pcr_states
[i
].value
, pcr_states
[i
].saved_value
, pcr_states
[i
].value_size
);
636 static int verb_calculate(int argc
, char *argv
[], void *userdata
) {
637 _cleanup_(json_variant_unrefp
) JsonVariant
*w
= NULL
;
638 _cleanup_(pcr_state_free_all
) PcrState
*pcr_states
= NULL
;
641 if (!arg_sections
[UNIFIED_SECTION_LINUX
] && !arg_current
)
642 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
643 "Either --linux= or --current must be specified, refusing.");
645 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
646 "The --append= switch is only supported for 'sign', not 'calculate'.");
648 assert(!strv_isempty(arg_banks
));
649 assert(!strv_isempty(arg_phase
));
651 r
= pcr_states_allocate(&pcr_states
);
657 r
= measure_kernel(pcr_states
, n
);
661 /* Save the current state, so that we later can restore to it. This way we can measure the PCR values
662 * for multiple different boot phases without heaving to start from zero each time */
663 r
= pcr_states_save(pcr_states
, n
);
667 STRV_FOREACH(phase
, arg_phase
) {
669 r
= measure_phase(pcr_states
, n
, *phase
);
673 for (size_t i
= 0; i
< n
; i
++) {
674 if (arg_json_format_flags
& JSON_FORMAT_OFF
) {
675 _cleanup_free_
char *hd
= NULL
;
679 fprintf(stderr
, "%s# PCR[%" PRIu32
"] Phase <%s>%s\n",
681 TPM_PCR_INDEX_KERNEL_IMAGE
,
682 isempty(*phase
) ? ":" : *phase
,
687 hd
= hexmem(pcr_states
[i
].value
, pcr_states
[i
].value_size
);
691 printf("%" PRIu32
":%s=%s\n", TPM_PCR_INDEX_KERNEL_IMAGE
, pcr_states
[i
].bank
, hd
);
693 _cleanup_(json_variant_unrefp
) JsonVariant
*bv
= NULL
, *array
= NULL
;
695 array
= json_variant_ref(json_variant_by_key(w
, pcr_states
[i
].bank
));
699 JSON_BUILD_PAIR_CONDITION(!isempty(*phase
), "phase", JSON_BUILD_STRING(*phase
)),
700 JSON_BUILD_PAIR("pcr", JSON_BUILD_INTEGER(TPM_PCR_INDEX_KERNEL_IMAGE
)),
701 JSON_BUILD_PAIR("hash", JSON_BUILD_HEX(pcr_states
[i
].value
, pcr_states
[i
].value_size
))
705 return log_error_errno(r
, "Failed to build JSON object: %m");
707 r
= json_variant_append_array(&array
, bv
);
709 return log_error_errno(r
, "Failed to append JSON object to array: %m");
711 r
= json_variant_set_field(&w
, pcr_states
[i
].bank
, array
);
713 return log_error_errno(r
, "Failed to add bank info to object: %m");
717 /* Return to the original kernel measurement for the next phase calculation */
718 pcr_states_restore(pcr_states
, n
);
721 if (!FLAGS_SET(arg_json_format_flags
, JSON_FORMAT_OFF
)) {
723 if (arg_json_format_flags
& (JSON_FORMAT_PRETTY
|JSON_FORMAT_PRETTY_AUTO
))
724 pager_open(arg_pager_flags
);
726 json_variant_dump(w
, arg_json_format_flags
, stdout
, NULL
);
732 static int verb_sign(int argc
, char *argv
[], void *userdata
) {
733 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
734 _cleanup_(pcr_state_free_all
) PcrState
*pcr_states
= NULL
;
735 _cleanup_(EVP_PKEY_freep
) EVP_PKEY
*privkey
= NULL
, *pubkey
= NULL
;
736 _cleanup_fclose_
FILE *privkeyf
= NULL
;
740 if (!arg_sections
[UNIFIED_SECTION_LINUX
] && !arg_current
)
741 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
742 "Either --linux= or --current must be specified, refusing.");
744 if (!arg_private_key
)
745 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
746 "No private key specified, use --private-key=.");
748 assert(!strv_isempty(arg_banks
));
749 assert(!strv_isempty(arg_phase
));
752 r
= json_parse_file(NULL
, arg_append
, 0, &v
, NULL
, NULL
);
754 return log_error_errno(r
, "Failed to parse '%s': %m", arg_append
);
756 if (!json_variant_is_object(v
))
757 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
758 "File '%s' is not a valid JSON object, refusing.", arg_append
);
761 /* When signing we only support JSON output */
762 arg_json_format_flags
&= ~JSON_FORMAT_OFF
;
764 privkeyf
= fopen(arg_private_key
, "re");
766 return log_error_errno(errno
, "Failed to open private key file '%s': %m", arg_private_key
);
768 privkey
= PEM_read_PrivateKey(privkeyf
, NULL
, NULL
, NULL
);
770 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to parse private key '%s'.", arg_private_key
);
772 if (arg_public_key
) {
773 _cleanup_fclose_
FILE *pubkeyf
= NULL
;
775 pubkeyf
= fopen(arg_public_key
, "re");
777 return log_error_errno(errno
, "Failed to open public key file '%s': %m", arg_public_key
);
779 pubkey
= PEM_read_PUBKEY(pubkeyf
, NULL
, NULL
, NULL
);
781 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to parse public key '%s'.", arg_public_key
);
783 _cleanup_(memstream_done
) MemStream m
= {};
786 /* No public key was specified, let's derive it automatically, if we can */
788 tf
= memstream_init(&m
);
792 if (i2d_PUBKEY_fp(tf
, privkey
) != 1)
793 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
794 "Failed to extract public key from private key file '%s'.", arg_private_key
);
799 if (!d2i_PUBKEY_fp(tf
, &pubkey
))
800 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
801 "Failed to parse extracted public key of private key file '%s'.", arg_private_key
);
804 r
= pcr_states_allocate(&pcr_states
);
810 r
= measure_kernel(pcr_states
, n
);
814 r
= pcr_states_save(pcr_states
, n
);
818 STRV_FOREACH(phase
, arg_phase
) {
820 r
= measure_phase(pcr_states
, n
, *phase
);
824 for (size_t i
= 0; i
< n
; i
++) {
825 PcrState
*p
= pcr_states
+ i
;
827 int tpmalg
= tpm2_hash_alg_from_string(EVP_MD_name(p
->md
));
829 return log_error_errno(tpmalg
, "Unsupported PCR bank");
831 TPML_PCR_SELECTION pcr_selection
;
832 tpm2_tpml_pcr_selection_from_mask(1 << TPM_PCR_INDEX_KERNEL_IMAGE
,
836 TPM2B_DIGEST pcr_values
= {
837 .size
= p
->value_size
,
839 assert(sizeof(pcr_values
.buffer
) >= p
->value_size
);
840 memcpy_safe(pcr_values
.buffer
, p
->value
, p
->value_size
);
842 TPM2B_DIGEST pcr_policy_digest
;
843 r
= tpm2_digest_init(TPM2_ALG_SHA256
, &pcr_policy_digest
);
847 r
= tpm2_calculate_policy_pcr(&pcr_selection
, &pcr_values
, 1, &pcr_policy_digest
);
851 _cleanup_(EVP_MD_CTX_freep
) EVP_MD_CTX
* mdctx
= NULL
;
852 mdctx
= EVP_MD_CTX_new();
856 if (EVP_DigestSignInit(mdctx
, NULL
, p
->md
, NULL
, privkey
) != 1)
857 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
858 "Failed to initialize signature context.");
860 if (EVP_DigestSignUpdate(mdctx
, pcr_policy_digest
.buffer
, pcr_policy_digest
.size
) != 1)
861 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
862 "Failed to sign data.");
865 if (EVP_DigestSignFinal(mdctx
, NULL
, &ss
) != 1)
866 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
867 "Failed to finalize signature");
869 _cleanup_free_
void *sig
= malloc(ss
);
873 if (EVP_DigestSignFinal(mdctx
, sig
, &ss
) != 1)
874 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
875 "Failed to acquire signature data");
877 _cleanup_free_
void *pubkey_fp
= NULL
;
878 size_t pubkey_fp_size
= 0;
879 r
= pubkey_fingerprint(pubkey
, EVP_sha256(), &pubkey_fp
, &pubkey_fp_size
);
883 _cleanup_(json_variant_unrefp
) JsonVariant
*a
= NULL
;
884 r
= tpm2_make_pcr_json_array(UINT64_C(1) << TPM_PCR_INDEX_KERNEL_IMAGE
, &a
);
886 return log_error_errno(r
, "Failed to build JSON PCR mask array: %m");
888 _cleanup_(json_variant_unrefp
) JsonVariant
*bv
= NULL
;
889 r
= json_build(&bv
, JSON_BUILD_OBJECT(
890 JSON_BUILD_PAIR("pcrs", JSON_BUILD_VARIANT(a
)), /* PCR mask */
891 JSON_BUILD_PAIR("pkfp", JSON_BUILD_HEX(pubkey_fp
, pubkey_fp_size
)), /* SHA256 fingerprint of public key (DER) used for the signature */
892 JSON_BUILD_PAIR("pol", JSON_BUILD_HEX(pcr_policy_digest
.buffer
, pcr_policy_digest
.size
)), /* TPM2 policy hash that is signed */
893 JSON_BUILD_PAIR("sig", JSON_BUILD_BASE64(sig
, ss
)))); /* signature data */
895 return log_error_errno(r
, "Failed to build JSON object: %m");
897 _cleanup_(json_variant_unrefp
) JsonVariant
*av
= NULL
;
898 av
= json_variant_ref(json_variant_by_key(v
, p
->bank
));
900 r
= json_variant_append_array_nodup(&av
, bv
);
902 return log_error_errno(r
, "Failed to append JSON object: %m");
904 r
= json_variant_set_field(&v
, p
->bank
, av
);
906 return log_error_errno(r
, "Failed to add JSON field: %m");
909 /* Return to the original kernel measurement for the next phase calculation */
910 pcr_states_restore(pcr_states
, n
);
913 if (arg_json_format_flags
& (JSON_FORMAT_PRETTY
|JSON_FORMAT_PRETTY_AUTO
))
914 pager_open(arg_pager_flags
);
916 json_variant_dump(v
, arg_json_format_flags
, stdout
, NULL
);
921 static int compare_reported_pcr_nr(uint32_t pcr
, const char *varname
, const char *description
) {
922 _cleanup_free_
char *s
= NULL
;
926 r
= efi_get_variable_string(varname
, &s
);
930 return log_error_errno(r
, "Failed to read EFI variable '%s': %m", varname
);
932 r
= safe_atou32(s
, &v
);
934 return log_error_errno(r
, "Failed to parse EFI variable '%s': %s", varname
, s
);
937 log_warning("PCR number reported by stub for %s (%" PRIu32
") different from our expectation (%" PRIu32
").\n"
938 "The measurements are likely inconsistent.", description
, v
, pcr
);
943 static int validate_stub(void) {
948 if (tpm2_support() != TPM2_SUPPORT_FULL
)
949 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "Sorry, system lacks full TPM2 support.");
951 r
= efi_stub_get_features(&features
);
953 return log_error_errno(r
, "Unable to get stub features: %m");
955 if (!FLAGS_SET(features
, EFI_STUB_FEATURE_THREE_PCRS
))
956 log_warning("Warning: current kernel image does not support measuring itself, the command line or initrd system extension images.\n"
957 "The PCR measurements seen are unlikely to be valid.");
959 r
= compare_reported_pcr_nr(TPM_PCR_INDEX_KERNEL_IMAGE
, EFI_LOADER_VARIABLE(StubPcrKernelImage
), "kernel image");
963 r
= compare_reported_pcr_nr(TPM_PCR_INDEX_KERNEL_PARAMETERS
, EFI_LOADER_VARIABLE(StubPcrKernelParameters
), "kernel parameters");
967 r
= compare_reported_pcr_nr(TPM_PCR_INDEX_INITRD_SYSEXTS
, EFI_LOADER_VARIABLE(StubPcrInitRDSysExts
), "initrd system extension images");
971 STRV_FOREACH(bank
, arg_banks
) {
972 _cleanup_free_
char *b
= NULL
, *p
= NULL
;
978 if (asprintf(&p
, "/sys/class/tpm/tpm0/pcr-%s/", ascii_strlower(b
)) < 0)
981 if (access(p
, F_OK
) < 0) {
983 return log_error_errno(errno
, "Failed to detect if '%s' exists: %m", b
);
989 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "None of the select PCR banks appear to exist.");
994 static int verb_status(int argc
, char *argv
[], void *userdata
) {
995 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
997 static const struct {
999 const char *description
;
1000 } relevant_pcrs
[] = {
1001 { TPM_PCR_INDEX_KERNEL_IMAGE
, "Unified Kernel Image" },
1002 { TPM_PCR_INDEX_KERNEL_PARAMETERS
, "Kernel Parameters" },
1003 { TPM_PCR_INDEX_INITRD_SYSEXTS
, "initrd System Extensions" },
1008 r
= validate_stub();
1012 for (size_t i
= 0; i
< ELEMENTSOF(relevant_pcrs
); i
++) {
1014 STRV_FOREACH(bank
, arg_banks
) {
1015 _cleanup_free_
char *b
= NULL
, *p
= NULL
, *s
= NULL
;
1016 _cleanup_free_
void *h
= NULL
;
1023 if (asprintf(&p
, "/sys/class/tpm/tpm0/pcr-%s/%" PRIu32
, ascii_strlower(b
), relevant_pcrs
[i
].nr
) < 0)
1026 r
= read_virtual_file(p
, 4096, &s
, NULL
);
1030 return log_error_errno(r
, "Failed to read '%s': %m", p
);
1032 r
= unhexmem(strstrip(s
), SIZE_MAX
, &h
, &l
);
1034 return log_error_errno(r
, "Failed to decode PCR value '%s': %m", s
);
1036 if (arg_json_format_flags
& JSON_FORMAT_OFF
) {
1037 _cleanup_free_
char *f
= NULL
;
1043 if (bank
== arg_banks
) {
1044 /* before the first line for each PCR, write a short descriptive text to
1045 * stderr, and leave the primary content on stdout */
1047 fprintf(stderr
, "%s# PCR[%" PRIu32
"] %s%s%s\n",
1049 relevant_pcrs
[i
].nr
,
1050 relevant_pcrs
[i
].description
,
1051 memeqzero(h
, l
) ? " (NOT SET!)" : "",
1056 printf("%" PRIu32
":%s=%s\n", relevant_pcrs
[i
].nr
, b
, f
);
1059 _cleanup_(json_variant_unrefp
) JsonVariant
*bv
= NULL
, *a
= NULL
;
1063 JSON_BUILD_PAIR("pcr", JSON_BUILD_INTEGER(relevant_pcrs
[i
].nr
)),
1064 JSON_BUILD_PAIR("hash", JSON_BUILD_HEX(h
, l
))
1068 return log_error_errno(r
, "Failed to build JSON object: %m");
1070 a
= json_variant_ref(json_variant_by_key(v
, b
));
1072 r
= json_variant_append_array(&a
, bv
);
1074 return log_error_errno(r
, "Failed to append PCR entry to JSON array: %m");
1076 r
= json_variant_set_field(&v
, b
, a
);
1078 return log_error_errno(r
, "Failed to add bank info to object: %m");
1083 if (!FLAGS_SET(arg_json_format_flags
, JSON_FORMAT_OFF
)) {
1084 if (arg_json_format_flags
& (JSON_FORMAT_PRETTY
|JSON_FORMAT_PRETTY_AUTO
))
1085 pager_open(arg_pager_flags
);
1087 json_variant_dump(v
, arg_json_format_flags
, stdout
, NULL
);
1093 static int measure_main(int argc
, char *argv
[]) {
1094 static const Verb verbs
[] = {
1095 { "help", VERB_ANY
, VERB_ANY
, 0, help
},
1096 { "status", VERB_ANY
, 1, VERB_DEFAULT
, verb_status
},
1097 { "calculate", VERB_ANY
, 1, 0, verb_calculate
},
1098 { "sign", VERB_ANY
, 1, 0, verb_sign
},
1102 return dispatch_verb(argc
, argv
, verbs
, NULL
);
1105 static int run(int argc
, char *argv
[]) {
1108 log_show_color(true);
1109 log_parse_environment();
1112 r
= parse_argv(argc
, argv
);
1116 return measure_main(argc
, argv
);
1119 DEFINE_MAIN_FUNCTION(run
);