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
;
36 static char *arg_append
= NULL
;
38 STATIC_DESTRUCTOR_REGISTER(arg_banks
, strv_freep
);
39 STATIC_DESTRUCTOR_REGISTER(arg_tpm2_device
, freep
);
40 STATIC_DESTRUCTOR_REGISTER(arg_private_key
, freep
);
41 STATIC_DESTRUCTOR_REGISTER(arg_public_key
, freep
);
42 STATIC_DESTRUCTOR_REGISTER(arg_phase
, strv_freep
);
43 STATIC_DESTRUCTOR_REGISTER(arg_append
, freep
);
45 static inline void free_sections(char*(*sections
)[_UNIFIED_SECTION_MAX
]) {
46 for (UnifiedSection c
= 0; c
< _UNIFIED_SECTION_MAX
; c
++)
50 STATIC_DESTRUCTOR_REGISTER(arg_sections
, free_sections
);
52 static int help(int argc
, char *argv
[], void *userdata
) {
53 _cleanup_free_
char *link
= NULL
;
56 r
= terminal_urlify_man("systemd-measure", "1", &link
);
60 printf("%1$s [OPTIONS...] COMMAND ...\n"
61 "\n%5$sPre-calculate and sign PCR hash for a unified kernel image (UKI).%6$s\n"
62 "\n%3$sCommands:%4$s\n"
63 " status Show current PCR values\n"
64 " calculate Calculate expected PCR values\n"
65 " sign Calculate and sign expected PCR values\n"
66 "\n%3$sOptions:%4$s\n"
67 " -h --help Show this help\n"
68 " --version Print version\n"
69 " --no-pager Do not pipe output into a pager\n"
70 " -c --current Use current PCR values\n"
71 " --phase=PHASE Specify a boot phase to sign for\n"
72 " --bank=DIGEST Select TPM bank (SHA1, SHA256, SHA384, SHA512)\n"
73 " --tpm2-device=PATH Use specified TPM2 device\n"
74 " --private-key=KEY Private key (PEM) to sign with\n"
75 " --public-key=KEY Public key (PEM) to validate against\n"
76 " --json=MODE Output as JSON\n"
77 " -j Same as --json=pretty on tty, --json=short otherwise\n"
78 " --append=PATH Load specified JSON signature, and append new signature to it\n"
79 "\n%3$sUKI PE Section Options:%4$s %3$sUKI PE Section%4$s\n"
80 " --linux=PATH Path to Linux kernel image file %7$s .linux\n"
81 " --osrel=PATH Path to os-release file %7$s .osrel\n"
82 " --cmdline=PATH Path to file with kernel command line %7$s .cmdline\n"
83 " --initrd=PATH Path to initrd image file %7$s .initrd\n"
84 " --splash=PATH Path to splash bitmap file %7$s .splash\n"
85 " --dtb=PATH Path to Devicetree file %7$s .dtb\n"
86 " --pcrpkey=PATH Path to public key for PCR signatures %7$s .pcrpkey\n"
87 "\nSee the %2$s for details.\n",
88 program_invocation_short_name
,
94 special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
));
99 static char *normalize_phase(const char *s
) {
100 _cleanup_strv_free_
char **l
= NULL
;
102 /* Let's normalize phase expressions. We split the series of colon-separated words up, then remove
103 * all empty ones, and glue them back together again. In other words we remove duplicate ":", as well
104 * as leading and trailing ones. */
106 l
= strv_split(s
, ":"); /* Split series of words */
110 /* Remove all empty words and glue things back together */
111 return strv_join(strv_remove(l
, ""), ":");
114 static int parse_argv(int argc
, char *argv
[]) {
119 ARG_LINUX
= _ARG_SECTION_FIRST
,
125 _ARG_PCRSIG
, /* the .pcrsig section is not input for signing, hence not actually an argument here */
127 ARG_PCRPKEY
= _ARG_SECTION_LAST
,
137 static const struct option options
[] = {
138 { "help", no_argument
, NULL
, 'h' },
139 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
140 { "version", no_argument
, NULL
, ARG_VERSION
},
141 { "linux", required_argument
, NULL
, ARG_LINUX
},
142 { "osrel", required_argument
, NULL
, ARG_OSREL
},
143 { "cmdline", required_argument
, NULL
, ARG_CMDLINE
},
144 { "initrd", required_argument
, NULL
, ARG_INITRD
},
145 { "splash", required_argument
, NULL
, ARG_SPLASH
},
146 { "dtb", required_argument
, NULL
, ARG_DTB
},
147 { "pcrpkey", required_argument
, NULL
, ARG_PCRPKEY
},
148 { "current", no_argument
, NULL
, 'c' },
149 { "bank", required_argument
, NULL
, ARG_BANK
},
150 { "tpm2-device", required_argument
, NULL
, ARG_TPM2_DEVICE
},
151 { "private-key", required_argument
, NULL
, ARG_PRIVATE_KEY
},
152 { "public-key", required_argument
, NULL
, ARG_PUBLIC_KEY
},
153 { "json", required_argument
, NULL
, ARG_JSON
},
154 { "phase", required_argument
, NULL
, ARG_PHASE
},
155 { "append", required_argument
, NULL
, ARG_APPEND
},
164 /* Make sure the arguments list and the section list, stays in sync */
165 assert_cc(_ARG_SECTION_FIRST
+ _UNIFIED_SECTION_MAX
== _ARG_SECTION_LAST
+ 1);
167 while ((c
= getopt_long(argc
, argv
, "hjc", options
, NULL
)) >= 0)
178 arg_pager_flags
|= PAGER_DISABLE
;
181 case _ARG_SECTION_FIRST
..._ARG_SECTION_LAST
: {
182 UnifiedSection section
= c
- _ARG_SECTION_FIRST
;
184 r
= parse_path_argument(optarg
, /* suppress_root= */ false, arg_sections
+ section
);
195 const EVP_MD
*implementation
;
197 implementation
= EVP_get_digestbyname(optarg
);
199 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Unknown bank '%s', refusing.", optarg
);
201 if (strv_extend(&arg_banks
, EVP_MD_name(implementation
)) < 0)
207 case ARG_PRIVATE_KEY
:
208 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_private_key
);
215 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_public_key
);
221 case ARG_TPM2_DEVICE
: {
222 _cleanup_free_
char *device
= NULL
;
224 if (streq(optarg
, "list"))
225 return tpm2_list_devices();
227 if (!streq(optarg
, "auto")) {
228 device
= strdup(optarg
);
233 free_and_replace(arg_tpm2_device
, device
);
238 arg_json_format_flags
= JSON_FORMAT_PRETTY_AUTO
|JSON_FORMAT_COLOR_AUTO
;
242 r
= parse_json_argument(optarg
, &arg_json_format_flags
);
251 n
= normalize_phase(optarg
);
255 r
= strv_consume(&arg_phase
, TAKE_PTR(n
));
263 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_append
);
273 assert_not_reached();
276 if (strv_isempty(arg_banks
)) {
277 /* If no banks are specifically selected, pick all known banks */
278 arg_banks
= strv_new("SHA1", "SHA256", "SHA384", "SHA512");
283 strv_sort(arg_banks
);
284 strv_uniq(arg_banks
);
287 for (UnifiedSection us
= 0; us
< _UNIFIED_SECTION_MAX
; us
++)
288 if (arg_sections
[us
])
289 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
290 "The --current switch cannot be used in combination with --linux= and related switches.");
292 if (strv_isempty(arg_phase
)) {
293 /* If no phases are specifically selected, pick everything from the beginning of the initrd
294 * to the beginning of shutdown. */
295 if (strv_extend_strv(&arg_phase
,
296 STRV_MAKE("enter-initrd",
297 "enter-initrd:leave-initrd",
298 "enter-initrd:leave-initrd:sysinit",
299 "enter-initrd:leave-initrd:sysinit:ready"),
300 /* filter_duplicates= */ false) < 0)
303 strv_sort(arg_phase
);
304 strv_uniq(arg_phase
);
307 _cleanup_free_
char *j
= NULL
;
308 j
= strv_join(arg_phase
, ", ");
312 log_debug("Measuring boot phases: %s", j
);
316 /* The PCR 11 state for one specific bank */
317 typedef struct PcrState
{
322 void *saved_value
; /* A copy of the original value we calculated, used by pcr_states_save()/pcr_states_restore() to come later back to */
325 static void pcr_state_free_all(PcrState
**pcr_state
) {
331 for (size_t i
= 0; (*pcr_state
)[i
].value
; i
++) {
332 free((*pcr_state
)[i
].bank
);
333 free((*pcr_state
)[i
].value
);
334 free((*pcr_state
)[i
].saved_value
);
337 *pcr_state
= mfree(*pcr_state
);
340 static void evp_md_ctx_free_all(EVP_MD_CTX
**md
[]) {
346 for (size_t i
= 0; (*md
)[i
]; i
++)
347 EVP_MD_CTX_free((*md
)[i
]);
352 static int pcr_state_extend(PcrState
*pcr_state
, const void *data
, size_t sz
) {
353 _cleanup_(EVP_MD_CTX_freep
) EVP_MD_CTX
*mc
= NULL
;
357 assert(data
|| sz
== 0);
358 assert(pcr_state
->md
);
359 assert(pcr_state
->value
);
360 assert(pcr_state
->value_size
> 0);
362 /* Extends a (virtual) PCR by the given data */
364 mc
= EVP_MD_CTX_new();
368 if (EVP_DigestInit_ex(mc
, pcr_state
->md
, NULL
) != 1)
369 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to initialize %s context.", pcr_state
->bank
);
371 /* First thing we do, is hash the old PCR value */
372 if (EVP_DigestUpdate(mc
, pcr_state
->value
, pcr_state
->value_size
) != 1)
373 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to run digest.");
375 /* Then, we hash the new data */
376 if (EVP_DigestUpdate(mc
, data
, sz
) != 1)
377 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to run digest.");
379 if (EVP_DigestFinal_ex(mc
, pcr_state
->value
, &value_size
) != 1)
380 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to finalize hash context.");
382 assert(value_size
== pcr_state
->value_size
);
386 #define BUFFER_SIZE (16U * 1024U)
388 static int measure_kernel(PcrState
*pcr_states
, size_t n
) {
389 _cleanup_free_
void *buffer
= NULL
;
395 /* Virtually measures the components of a unified kernel image into PCR 11 */
398 /* Shortcut things, if we should just use the current PCR value */
400 for (size_t i
= 0; i
< n
; i
++) {
401 _cleanup_free_
char *p
= NULL
, *s
= NULL
;
402 _cleanup_free_
void *v
= NULL
;
405 if (asprintf(&p
, "/sys/class/tpm/tpm0/pcr-%s/%" PRIu32
, pcr_states
[i
].bank
, TPM_PCR_INDEX_KERNEL_IMAGE
) < 0)
408 r
= read_virtual_file(p
, 4096, &s
, NULL
);
409 if (r
== -ENOENT
&& access("/sys/class/tpm/tpm0/", F_OK
) >= 0)
410 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
);
412 return log_error_errno(r
, "Failed to read '%s': %m", p
);
414 r
= unhexmem(strstrip(s
), SIZE_MAX
, &v
, &sz
);
416 return log_error_errno(r
, "Failed to decode PCR value '%s': %m", s
);
418 assert(pcr_states
[i
].value_size
== sz
);
419 memcpy(pcr_states
[i
].value
, v
, sz
);
425 buffer
= malloc(BUFFER_SIZE
);
429 for (UnifiedSection c
= 0; c
< _UNIFIED_SECTION_MAX
; c
++) {
430 _cleanup_(evp_md_ctx_free_all
) EVP_MD_CTX
**mdctx
= NULL
;
431 _cleanup_close_
int fd
= -EBADF
;
434 if (!arg_sections
[c
])
437 fd
= open(arg_sections
[c
], O_RDONLY
|O_CLOEXEC
);
439 return log_error_errno(errno
, "Failed to open '%s': %m", arg_sections
[c
]);
441 /* Allocate one message digest context per bank (NULL terminated) */
442 mdctx
= new0(EVP_MD_CTX
*, n
+ 1);
446 for (size_t i
= 0; i
< n
; i
++) {
447 mdctx
[i
] = EVP_MD_CTX_new();
451 if (EVP_DigestInit_ex(mdctx
[i
], pcr_states
[i
].md
, NULL
) != 1)
452 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
453 "Failed to initialize data %s context.", pcr_states
[i
].bank
);
459 sz
= read(fd
, buffer
, BUFFER_SIZE
);
461 return log_error_errno(errno
, "Failed to read '%s': %m", arg_sections
[c
]);
462 if (sz
== 0) /* EOF */
465 for (size_t i
= 0; i
< n
; i
++)
466 if (EVP_DigestUpdate(mdctx
[i
], buffer
, sz
) != 1)
467 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to run digest.");
474 if (m
== 0) /* We skip over empty files, the stub does so too */
477 for (size_t i
= 0; i
< n
; i
++) {
478 _cleanup_free_
void *data_hash
= NULL
;
479 unsigned data_hash_size
;
481 data_hash
= malloc(pcr_states
[i
].value_size
);
485 /* Measure name of section */
486 if (EVP_Digest(unified_sections
[c
], strlen(unified_sections
[c
]) + 1, data_hash
, &data_hash_size
, pcr_states
[i
].md
, NULL
) != 1)
487 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to hash section name with %s.", pcr_states
[i
].bank
);
489 assert(data_hash_size
== (unsigned) pcr_states
[i
].value_size
);
491 r
= pcr_state_extend(pcr_states
+ i
, data_hash
, data_hash_size
);
495 /* Retrieve hash of data and measure it */
496 if (EVP_DigestFinal_ex(mdctx
[i
], data_hash
, &data_hash_size
) != 1)
497 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to finalize hash context.");
499 assert(data_hash_size
== (unsigned) pcr_states
[i
].value_size
);
501 r
= pcr_state_extend(pcr_states
+ i
, data_hash
, data_hash_size
);
510 static int measure_phase(PcrState
*pcr_states
, size_t n
, const char *phase
) {
511 _cleanup_strv_free_
char **l
= NULL
;
517 /* Measure a phase string into PCR 11. This splits up the "phase" expression at colons, and then
518 * virtually extends each specified word into PCR 11, to model how during boot we measure a series of
519 * words into PCR 11, one for each phase. */
521 l
= strv_split(phase
, ":");
525 STRV_FOREACH(word
, l
) {
533 for (size_t i
= 0; i
< n
; i
++) { /* For each bank */
534 _cleanup_free_
void *b
= NULL
;
537 bsz
= EVP_MD_size(pcr_states
[i
].md
);
544 /* First hash the word itself */
545 if (EVP_Digest(*word
, wl
, b
, NULL
, pcr_states
[i
].md
, NULL
) != 1)
546 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
), "Failed to hash word '%s'.", *word
);
548 /* And then extend the PCR with the resulting hash */
549 r
= pcr_state_extend(pcr_states
+ i
, b
, bsz
);
558 static int pcr_states_allocate(PcrState
**ret
) {
559 _cleanup_(pcr_state_free_all
) PcrState
*pcr_states
= NULL
;
562 pcr_states
= new0(PcrState
, strv_length(arg_banks
) + 1);
566 /* Allocate a PCR state structure, one for each bank */
567 STRV_FOREACH(d
, arg_banks
) {
568 const EVP_MD
*implementation
;
569 _cleanup_free_
void *v
= NULL
;
570 _cleanup_free_
char *b
= NULL
;
573 assert_se(implementation
= EVP_get_digestbyname(*d
)); /* Must work, we already checked while parsing command line */
575 b
= strdup(EVP_MD_name(implementation
));
579 sz
= EVP_MD_size(implementation
);
580 if (sz
<= 0 || sz
>= INT_MAX
)
581 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Unexpected digest size: %i", sz
);
583 v
= malloc0(sz
); /* initial PCR state is all zeroes */
587 pcr_states
[n
++] = (struct PcrState
) {
588 .bank
= ascii_strlower(TAKE_PTR(b
)),
589 .md
= implementation
,
590 .value
= TAKE_PTR(v
),
595 *ret
= TAKE_PTR(pcr_states
);
599 static int pcr_states_save(PcrState
*pcr_states
, size_t n
) {
603 for (size_t i
= 0; i
< n
; i
++) {
604 _cleanup_free_
void *saved
= NULL
;
606 if (!pcr_states
[i
].value
)
609 saved
= memdup(pcr_states
[i
].value
, pcr_states
[i
].value_size
);
613 free_and_replace(pcr_states
[i
].saved_value
, saved
);
619 static void pcr_states_restore(PcrState
*pcr_states
, size_t n
) {
623 for (size_t i
= 0; i
< n
; i
++) {
625 assert(pcr_states
[i
].value
);
626 assert(pcr_states
[i
].saved_value
);
628 memcpy(pcr_states
[i
].value
, pcr_states
[i
].saved_value
, pcr_states
[i
].value_size
);
632 static int verb_calculate(int argc
, char *argv
[], void *userdata
) {
633 _cleanup_(json_variant_unrefp
) JsonVariant
*w
= NULL
;
634 _cleanup_(pcr_state_free_all
) PcrState
*pcr_states
= NULL
;
637 if (!arg_sections
[UNIFIED_SECTION_LINUX
] && !arg_current
)
638 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
639 "Either --linux= or --current must be specified, refusing.");
641 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
642 "The --append= switch is only supported for 'sign', not 'calculate'.");
644 assert(!strv_isempty(arg_banks
));
645 assert(!strv_isempty(arg_phase
));
647 r
= pcr_states_allocate(&pcr_states
);
653 r
= measure_kernel(pcr_states
, n
);
657 /* Save the current state, so that we later can restore to it. This way we can measure the PCR values
658 * for multiple different boot phases without heaving to start from zero each time */
659 r
= pcr_states_save(pcr_states
, n
);
663 STRV_FOREACH(phase
, arg_phase
) {
665 r
= measure_phase(pcr_states
, n
, *phase
);
669 for (size_t i
= 0; i
< n
; i
++) {
670 if (arg_json_format_flags
& JSON_FORMAT_OFF
) {
671 _cleanup_free_
char *hd
= NULL
;
675 fprintf(stderr
, "%s# PCR[%" PRIu32
"] Phase <%s>%s\n",
677 TPM_PCR_INDEX_KERNEL_IMAGE
,
678 isempty(*phase
) ? ":" : *phase
,
683 hd
= hexmem(pcr_states
[i
].value
, pcr_states
[i
].value_size
);
687 printf("%" PRIu32
":%s=%s\n", TPM_PCR_INDEX_KERNEL_IMAGE
, pcr_states
[i
].bank
, hd
);
689 _cleanup_(json_variant_unrefp
) JsonVariant
*bv
= NULL
, *array
= NULL
;
691 array
= json_variant_ref(json_variant_by_key(w
, pcr_states
[i
].bank
));
695 JSON_BUILD_PAIR_CONDITION(!isempty(*phase
), "phase", JSON_BUILD_STRING(*phase
)),
696 JSON_BUILD_PAIR("pcr", JSON_BUILD_INTEGER(TPM_PCR_INDEX_KERNEL_IMAGE
)),
697 JSON_BUILD_PAIR("hash", JSON_BUILD_HEX(pcr_states
[i
].value
, pcr_states
[i
].value_size
))
701 return log_error_errno(r
, "Failed to build JSON object: %m");
703 r
= json_variant_append_array(&array
, bv
);
705 return log_error_errno(r
, "Failed to append JSON object to array: %m");
707 r
= json_variant_set_field(&w
, pcr_states
[i
].bank
, array
);
709 return log_error_errno(r
, "Failed to add bank info to object: %m");
713 /* Return to the original kernel measurement for the next phase calculation */
714 pcr_states_restore(pcr_states
, n
);
717 if (!FLAGS_SET(arg_json_format_flags
, JSON_FORMAT_OFF
)) {
719 if (arg_json_format_flags
& (JSON_FORMAT_PRETTY
|JSON_FORMAT_PRETTY_AUTO
))
720 pager_open(arg_pager_flags
);
722 json_variant_dump(w
, arg_json_format_flags
, stdout
, NULL
);
728 static int verb_sign(int argc
, char *argv
[], void *userdata
) {
729 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
730 _cleanup_(pcr_state_free_all
) PcrState
*pcr_states
= NULL
;
731 _cleanup_(EVP_PKEY_freep
) EVP_PKEY
*privkey
= NULL
, *pubkey
= NULL
;
732 _cleanup_fclose_
FILE *privkeyf
= NULL
;
737 if (!arg_sections
[UNIFIED_SECTION_LINUX
] && !arg_current
)
738 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
739 "Either --linux= or --current must be specified, refusing.");
741 if (!arg_private_key
)
742 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
743 "No private key specified, use --private-key=.");
745 assert(!strv_isempty(arg_banks
));
746 assert(!strv_isempty(arg_phase
));
749 r
= json_parse_file(NULL
, arg_append
, 0, &v
, NULL
, NULL
);
751 return log_error_errno(r
, "Failed to parse '%s': %m", arg_append
);
753 if (!json_variant_is_object(v
))
754 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
755 "File '%s' is not a valid JSON object, refusing.", arg_append
);
758 /* When signing we only support JSON output */
759 arg_json_format_flags
&= ~JSON_FORMAT_OFF
;
761 privkeyf
= fopen(arg_private_key
, "re");
763 return log_error_errno(errno
, "Failed to open private key file '%s': %m", arg_private_key
);
765 privkey
= PEM_read_PrivateKey(privkeyf
, NULL
, NULL
, NULL
);
767 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to parse private key '%s'.", arg_private_key
);
769 if (arg_public_key
) {
770 _cleanup_fclose_
FILE *pubkeyf
= NULL
;
772 pubkeyf
= fopen(arg_public_key
, "re");
774 return log_error_errno(errno
, "Failed to open public key file '%s': %m", arg_public_key
);
776 pubkey
= PEM_read_PUBKEY(pubkeyf
, NULL
, NULL
, NULL
);
778 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to parse public key '%s'.", arg_public_key
);
780 _cleanup_free_
char *data
= NULL
;
781 _cleanup_fclose_
FILE *tf
= NULL
;
784 /* No public key was specified, let's derive it automatically, if we can */
786 tf
= open_memstream_unlocked(&data
, &sz
);
790 if (i2d_PUBKEY_fp(tf
, privkey
) != 1)
791 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
792 "Failed to extract public key from private key file '%s'.", arg_private_key
);
797 if (!d2i_PUBKEY_fp(tf
, &pubkey
))
798 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
799 "Failed to parse extracted public key of private key file '%s'.", arg_private_key
);
802 r
= pcr_states_allocate(&pcr_states
);
808 r
= measure_kernel(pcr_states
, n
);
812 r
= pcr_states_save(pcr_states
, n
);
820 _cleanup_tpm2_context_ Tpm2Context
*c
= NULL
;
821 r
= tpm2_context_new(arg_tpm2_device
, &c
);
825 STRV_FOREACH(phase
, arg_phase
) {
827 r
= measure_phase(pcr_states
, n
, *phase
);
831 for (size_t i
= 0; i
< n
; i
++) {
832 static const TPMT_SYM_DEF symmetric
= {
833 .algorithm
= TPM2_ALG_AES
,
835 .mode
.aes
= TPM2_ALG_CFB
,
837 PcrState
*p
= pcr_states
+ i
;
839 _cleanup_tpm2_handle_ Tpm2Handle
*session
= NULL
;
840 r
= tpm2_handle_new(c
, &session
);
844 rc
= sym_Esys_StartAuthSession(
855 &session
->esys_handle
);
856 if (rc
!= TSS2_RC_SUCCESS
)
857 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
858 "Failed to open session in TPM: %s", sym_Tss2_RC_Decode(rc
));
860 /* Generate a single hash value from the PCRs included in our policy. Given that that's
861 * exactly one, the calculation is trivial. */
862 TPM2B_DIGEST intermediate_digest
= {
863 .size
= SHA256_DIGEST_SIZE
,
865 assert(sizeof(intermediate_digest
.buffer
) >= SHA256_DIGEST_SIZE
);
866 sha256_direct(p
->value
, p
->value_size
, intermediate_digest
.buffer
);
868 int tpmalg
= tpm2_hash_alg_from_string(EVP_MD_name(p
->md
));
870 return log_error_errno(tpmalg
, "Unsupported PCR bank");
872 TPML_PCR_SELECTION pcr_selection
;
873 tpm2_tpml_pcr_selection_from_mask(1 << TPM_PCR_INDEX_KERNEL_IMAGE
,
877 rc
= sym_Esys_PolicyPCR(
879 session
->esys_handle
,
883 &intermediate_digest
,
885 if (rc
!= TSS2_RC_SUCCESS
)
886 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
887 "Failed to push PCR policy into TPM: %s", sym_Tss2_RC_Decode(rc
));
889 _cleanup_(Esys_Freep
) TPM2B_DIGEST
*pcr_policy_digest
= NULL
;
890 rc
= sym_Esys_PolicyGetDigest(
892 session
->esys_handle
,
897 if (rc
!= TSS2_RC_SUCCESS
)
898 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
899 "Failed to get policy digest from TPM: %s", sym_Tss2_RC_Decode(rc
));
901 _cleanup_(EVP_MD_CTX_freep
) EVP_MD_CTX
* mdctx
= NULL
;
902 mdctx
= EVP_MD_CTX_new();
906 if (EVP_DigestSignInit(mdctx
, NULL
, p
->md
, NULL
, privkey
) != 1)
907 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
908 "Failed to initialize signature context.");
910 if (EVP_DigestSignUpdate(mdctx
, pcr_policy_digest
->buffer
, pcr_policy_digest
->size
) != 1)
911 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
912 "Failed to sign data.");
915 if (EVP_DigestSignFinal(mdctx
, NULL
, &ss
) != 1)
916 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
917 "Failed to finalize signature");
919 _cleanup_free_
void *sig
= malloc(ss
);
923 if (EVP_DigestSignFinal(mdctx
, sig
, &ss
) != 1)
924 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
),
925 "Failed to acquire signature data");
927 _cleanup_free_
void *pubkey_fp
= NULL
;
928 size_t pubkey_fp_size
= 0;
929 r
= pubkey_fingerprint(pubkey
, EVP_sha256(), &pubkey_fp
, &pubkey_fp_size
);
933 _cleanup_(json_variant_unrefp
) JsonVariant
*a
= NULL
;
934 r
= tpm2_make_pcr_json_array(UINT64_C(1) << TPM_PCR_INDEX_KERNEL_IMAGE
, &a
);
936 return log_error_errno(r
, "Failed to build JSON PCR mask array: %m");
938 _cleanup_(json_variant_unrefp
) JsonVariant
*bv
= NULL
;
939 r
= json_build(&bv
, JSON_BUILD_OBJECT(
940 JSON_BUILD_PAIR("pcrs", JSON_BUILD_VARIANT(a
)), /* PCR mask */
941 JSON_BUILD_PAIR("pkfp", JSON_BUILD_HEX(pubkey_fp
, pubkey_fp_size
)), /* SHA256 fingerprint of public key (DER) used for the signature */
942 JSON_BUILD_PAIR("pol", JSON_BUILD_HEX(pcr_policy_digest
->buffer
, pcr_policy_digest
->size
)), /* TPM2 policy hash that is signed */
943 JSON_BUILD_PAIR("sig", JSON_BUILD_BASE64(sig
, ss
)))); /* signature data */
945 return log_error_errno(r
, "Failed to build JSON object: %m");
947 _cleanup_(json_variant_unrefp
) JsonVariant
*av
= NULL
;
948 av
= json_variant_ref(json_variant_by_key(v
, p
->bank
));
950 r
= json_variant_append_array_nodup(&av
, bv
);
952 return log_error_errno(r
, "Failed to append JSON object: %m");
954 r
= json_variant_set_field(&v
, p
->bank
, av
);
956 return log_error_errno(r
, "Failed to add JSON field: %m");
959 /* Return to the original kernel measurement for the next phase calculation */
960 pcr_states_restore(pcr_states
, n
);
963 if (arg_json_format_flags
& (JSON_FORMAT_PRETTY
|JSON_FORMAT_PRETTY_AUTO
))
964 pager_open(arg_pager_flags
);
966 json_variant_dump(v
, arg_json_format_flags
, stdout
, NULL
);
971 static int compare_reported_pcr_nr(uint32_t pcr
, const char *varname
, const char *description
) {
972 _cleanup_free_
char *s
= NULL
;
976 r
= efi_get_variable_string(varname
, &s
);
980 return log_error_errno(r
, "Failed to read EFI variable '%s': %m", varname
);
982 r
= safe_atou32(s
, &v
);
984 return log_error_errno(r
, "Failed to parse EFI variable '%s': %s", varname
, s
);
987 log_warning("PCR number reported by stub for %s (%" PRIu32
") different from our expectation (%" PRIu32
").\n"
988 "The measurements are likely inconsistent.", description
, v
, pcr
);
993 static int validate_stub(void) {
998 if (tpm2_support() != TPM2_SUPPORT_FULL
)
999 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "Sorry, system lacks full TPM2 support.");
1001 r
= efi_stub_get_features(&features
);
1003 return log_error_errno(r
, "Unable to get stub features: %m");
1005 if (!FLAGS_SET(features
, EFI_STUB_FEATURE_THREE_PCRS
))
1006 log_warning("Warning: current kernel image does not support measuring itself, the command line or initrd system extension images.\n"
1007 "The PCR measurements seen are unlikely to be valid.");
1009 r
= compare_reported_pcr_nr(TPM_PCR_INDEX_KERNEL_IMAGE
, EFI_LOADER_VARIABLE(StubPcrKernelImage
), "kernel image");
1013 r
= compare_reported_pcr_nr(TPM_PCR_INDEX_KERNEL_PARAMETERS
, EFI_LOADER_VARIABLE(StubPcrKernelParameters
), "kernel parameters");
1017 r
= compare_reported_pcr_nr(TPM_PCR_INDEX_INITRD_SYSEXTS
, EFI_LOADER_VARIABLE(StubPcrInitRDSysExts
), "initrd system extension images");
1021 STRV_FOREACH(bank
, arg_banks
) {
1022 _cleanup_free_
char *b
= NULL
, *p
= NULL
;
1028 if (asprintf(&p
, "/sys/class/tpm/tpm0/pcr-%s/", ascii_strlower(b
)) < 0)
1031 if (access(p
, F_OK
) < 0) {
1032 if (errno
!= ENOENT
)
1033 return log_error_errno(errno
, "Failed to detect if '%s' exists: %m", b
);
1039 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
), "None of the select PCR banks appear to exist.");
1044 static int verb_status(int argc
, char *argv
[], void *userdata
) {
1045 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
1047 static const struct {
1049 const char *description
;
1050 } relevant_pcrs
[] = {
1051 { TPM_PCR_INDEX_KERNEL_IMAGE
, "Unified Kernel Image" },
1052 { TPM_PCR_INDEX_KERNEL_PARAMETERS
, "Kernel Parameters" },
1053 { TPM_PCR_INDEX_INITRD_SYSEXTS
, "initrd System Extensions" },
1058 r
= validate_stub();
1062 for (size_t i
= 0; i
< ELEMENTSOF(relevant_pcrs
); i
++) {
1064 STRV_FOREACH(bank
, arg_banks
) {
1065 _cleanup_free_
char *b
= NULL
, *p
= NULL
, *s
= NULL
;
1066 _cleanup_free_
void *h
= NULL
;
1073 if (asprintf(&p
, "/sys/class/tpm/tpm0/pcr-%s/%" PRIu32
, ascii_strlower(b
), relevant_pcrs
[i
].nr
) < 0)
1076 r
= read_virtual_file(p
, 4096, &s
, NULL
);
1080 return log_error_errno(r
, "Failed to read '%s': %m", p
);
1082 r
= unhexmem(strstrip(s
), SIZE_MAX
, &h
, &l
);
1084 return log_error_errno(r
, "Failed to decode PCR value '%s': %m", s
);
1086 if (arg_json_format_flags
& JSON_FORMAT_OFF
) {
1087 _cleanup_free_
char *f
= NULL
;
1093 if (bank
== arg_banks
) {
1094 /* before the first line for each PCR, write a short descriptive text to
1095 * stderr, and leave the primary content on stdout */
1097 fprintf(stderr
, "%s# PCR[%" PRIu32
"] %s%s%s\n",
1099 relevant_pcrs
[i
].nr
,
1100 relevant_pcrs
[i
].description
,
1101 memeqzero(h
, l
) ? " (NOT SET!)" : "",
1106 printf("%" PRIu32
":%s=%s\n", relevant_pcrs
[i
].nr
, b
, f
);
1109 _cleanup_(json_variant_unrefp
) JsonVariant
*bv
= NULL
, *a
= NULL
;
1113 JSON_BUILD_PAIR("pcr", JSON_BUILD_INTEGER(relevant_pcrs
[i
].nr
)),
1114 JSON_BUILD_PAIR("hash", JSON_BUILD_HEX(h
, l
))
1118 return log_error_errno(r
, "Failed to build JSON object: %m");
1120 a
= json_variant_ref(json_variant_by_key(v
, b
));
1122 r
= json_variant_append_array(&a
, bv
);
1124 return log_error_errno(r
, "Failed to append PCR entry to JSON array: %m");
1126 r
= json_variant_set_field(&v
, b
, a
);
1128 return log_error_errno(r
, "Failed to add bank info to object: %m");
1133 if (!FLAGS_SET(arg_json_format_flags
, JSON_FORMAT_OFF
)) {
1134 if (arg_json_format_flags
& (JSON_FORMAT_PRETTY
|JSON_FORMAT_PRETTY_AUTO
))
1135 pager_open(arg_pager_flags
);
1137 json_variant_dump(v
, arg_json_format_flags
, stdout
, NULL
);
1143 static int measure_main(int argc
, char *argv
[]) {
1144 static const Verb verbs
[] = {
1145 { "help", VERB_ANY
, VERB_ANY
, 0, help
},
1146 { "status", VERB_ANY
, 1, VERB_DEFAULT
, verb_status
},
1147 { "calculate", VERB_ANY
, 1, 0, verb_calculate
},
1148 { "sign", VERB_ANY
, 1, 0, verb_sign
},
1152 return dispatch_verb(argc
, argv
, verbs
, NULL
);
1155 static int run(int argc
, char *argv
[]) {
1158 log_show_color(true);
1159 log_parse_environment();
1162 r
= parse_argv(argc
, argv
);
1166 return measure_main(argc
, argv
);
1169 DEFINE_MAIN_FUNCTION(run
);