HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/pcrlock/pcrlock.c

228,316 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: c798c78489257ecc6f87eead6fa509ad2027c886

Lines 1–1000 of 5,877

/* SPDX-License-Identifier: LGPL-2.1-or-later */
 
#include <sys/file.h>
#include <sys/stat.h>
#include <unistd.h>
 
#include "sd-device.h"
#include "sd-json.h"
#include "sd-varlink.h"
 
#include "alloc-util.h"
#include "ansi-color.h"
#include "ask-password-api.h"
#include "bitfield.h"
#include "blockdev-util.h"
#include "boot-entry.h"
#include "build.h"
#include "chase.h"
#include "color-util.h"
#include "conf-files.h"
#include "copy.h"
#include "creds-util.h"
#include "crypto-util.h"
#include "dlopen-note.h"
#include "efi-api.h"
#include "efivars.h"
#include "env-util.h"
#include "errno-util.h"
#include "escape.h"
#include "extract-word.h"
#include "fd-util.h"
#include "fileio.h"
#include "format-table.h"
#include "format-util.h"
#include "fs-util.h"
#include "glyph-util.h"
#include "gpt.h"
#include "hexdecoct.h"
#include "initrd-util.h"
#include "json-util.h"
#include "label-util.h"
#include "list.h"
#include "main-func.h"
#include "mkdir.h"
#include "ordered-set.h"
#include "parse-argument.h"
#include "parse-util.h"
#include "path-util.h"
#include "pcrextend-util.h"
#include "pcrlock-firmware.h"
#include "pe-binary.h"
#include "proc-cmdline.h"
#include "recovery-key.h"
#include "sort-util.h"
#include "string-table.h"
#include "string-util.h"
#include "strv.h"
#include "time-util.h"
#include "tmpfile-util.h"
#include "tpm2-pcr.h"
#include "tpm2-util.h"
#include "unaligned.h"
#include "unit-name.h"
#include "utf8.h"
#include "varlink-io.systemd.PCRLock.h"
#include "varlink-io.systemd.SysUpdate.Notify.h"
#include "varlink-util.h"
#include "verbs.h"
 
typedef enum RecoveryPinMode {
        RECOVERY_PIN_HIDE,           /* generate a recovery PIN automatically, but don't show it (alias: "no") */
        RECOVERY_PIN_SHOW,           /* generate a recovery PIN automatically, and display it to the user */
        RECOVERY_PIN_QUERY,          /* asks the user for a PIN to use interactively (alias: "yes") */
        _RECOVERY_PIN_MODE_MAX,
        _RECOVERY_PIN_MODE_INVALID = -EINVAL,
} RecoveryPinMode;
 
static PagerFlags arg_pager_flags = 0;
static sd_json_format_flags_t arg_json_format_flags = SD_JSON_FORMAT_OFF|SD_JSON_FORMAT_NEWLINE;
static char **arg_components = NULL;
static uint32_t arg_pcr_mask = 0;
static char *arg_pcrlock_path = NULL;
static bool arg_pcrlock_auto = true;
static bool arg_raw_description = false;
static char *arg_location_start = NULL;
static char *arg_location_end = NULL;
static TPM2_HANDLE arg_nv_index = 0;
static RecoveryPinMode arg_recovery_pin = RECOVERY_PIN_HIDE;
static char *arg_policy_path = NULL;
static bool arg_force = false;
static BootEntryTokenType arg_entry_token_type = BOOT_ENTRY_TOKEN_AUTO;
static bool arg_strict = false;
static char *arg_entry_token = NULL;
static bool arg_varlink = false;
static bool arg_quiet = false;
/* abbreviate to 7 chars, just like git */
static size_t arg_abbreviate_hash = 7;
 
STATIC_DESTRUCTOR_REGISTER(arg_components, strv_freep);
STATIC_DESTRUCTOR_REGISTER(arg_pcrlock_path, freep);
STATIC_DESTRUCTOR_REGISTER(arg_location_start, freep);
STATIC_DESTRUCTOR_REGISTER(arg_location_end, freep);
STATIC_DESTRUCTOR_REGISTER(arg_policy_path, freep);
STATIC_DESTRUCTOR_REGISTER(arg_entry_token, freep);
 
COMMAND(
        "systemd-pcrlock\0",
        "Manage a TPM2 PCR lock.",
        .man_pages = "systemd-pcrlock(8)\0",
        .pager_flags = &arg_pager_flags,
);
 
#define PCRLOCK_SECUREBOOT_POLICY_PATH      "/var/lib/pcrlock.d/240-secureboot-policy.pcrlock.d/generated.pcrlock"
#define PCRLOCK_FIRMWARE_CODE_EARLY_PATH    "/var/lib/pcrlock.d/250-firmware-code-early.pcrlock.d/generated.pcrlock"
#define PCRLOCK_FIRMWARE_CONFIG_EARLY_PATH  "/var/lib/pcrlock.d/250-firmware-config-early.pcrlock.d/generated.pcrlock"
#define PCRLOCK_FIRMWARE_CODE_LATE_PATH     "/var/lib/pcrlock.d/550-firmware-code-late.pcrlock.d/generated.pcrlock"
#define PCRLOCK_FIRMWARE_CONFIG_LATE_PATH   "/var/lib/pcrlock.d/550-firmware-config-late.pcrlock.d/generated.pcrlock"
#define PCRLOCK_GPT_PATH                    "/var/lib/pcrlock.d/600-gpt.pcrlock.d/generated.pcrlock"
#define PCRLOCK_SECUREBOOT_AUTHORITY_PATH   "/var/lib/pcrlock.d/620-secureboot-authority.pcrlock.d/generated.pcrlock"
#define PCRLOCK_KERNEL_CMDLINE_PATH         "/var/lib/pcrlock.d/710-kernel-cmdline.pcrlock.d/generated.pcrlock"
#define PCRLOCK_KERNEL_INITRD_PATH          "/var/lib/pcrlock.d/720-kernel-initrd.pcrlock.d/generated.pcrlock"
#define PCRLOCK_MACHINE_ID_PATH             "/var/lib/pcrlock.d/820-machine-id.pcrlock"
#define PCRLOCK_ROOT_FILE_SYSTEM_PATH       "/var/lib/pcrlock.d/830-root-file-system.pcrlock"
#define PCRLOCK_FILE_SYSTEM_PATH_PREFIX     "/var/lib/pcrlock.d/840-file-system-"
#define PCRLOCK_PE_INPUT_MAX                (2U * U64_GB)
 
/* Maximum number of retries when PCR values keep changing while we submit the policy for, or unseal, the
 * recovery PIN */
#define PCRLOCK_RETRY_UNSEAL_MAX            16U
 
/* The default set of PCRs to lock to */
#define DEFAULT_PCR_MASK                                     \
        ((UINT32_C(1) << TPM2_PCR_PLATFORM_CODE) |           \
         (UINT32_C(1) << TPM2_PCR_PLATFORM_CONFIG) |         \
         (UINT32_C(1) << TPM2_PCR_EXTERNAL_CODE) |           \
         (UINT32_C(1) << TPM2_PCR_EXTERNAL_CONFIG) |         \
         (UINT32_C(1) << TPM2_PCR_BOOT_LOADER_CODE) |        \
         (UINT32_C(1) << TPM2_PCR_BOOT_LOADER_CONFIG) |      \
         (UINT32_C(1) << TPM2_PCR_SECURE_BOOT_POLICY) |      \
         (UINT32_C(1) << TPM2_PCR_KERNEL_BOOT) |             \
         /* Note: we do not add PCR12/TPM2_PCR_KERNEL_CONFIG here, since our pcrlock policy ends up in there, and this would hence result in a conceptual loop */ \
         (UINT32_C(1) << TPM2_PCR_SYSEXTS) |                 \
         (UINT32_C(1) << TPM2_PCR_SHIM_POLICY) |             \
         (UINT32_C(1) << TPM2_PCR_SYSTEM_IDENTITY))
 
static const char* recovery_pin_mode_table[_RECOVERY_PIN_MODE_MAX] = {
        [RECOVERY_PIN_HIDE]  = "hide",
        [RECOVERY_PIN_SHOW]  = "show",
        [RECOVERY_PIN_QUERY] = "query",
};
 
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING_WITH_BOOLEAN(recovery_pin_mode, RecoveryPinMode, RECOVERY_PIN_QUERY);
 
typedef struct EventLogRecordBank EventLogRecordBank;
typedef struct EventLogRecord EventLogRecord;
typedef struct EventLogRegisterBank EventLogRegisterBank;
typedef struct EventLogRegister EventLogRegister;
typedef struct EventLogComponentVariant EventLogComponentVariant;
typedef struct EventLogComponent EventLogComponent;
typedef struct EventLog EventLog;
 
struct EventLogRecordBank {
        uint16_t algorithm;
        TPM2B_DIGEST hash;
        LIST_FIELDS(EventLogRecordBank, banks);
};
 
typedef enum EventPayloadValid {
        EVENT_PAYLOAD_VALID_YES,
        EVENT_PAYLOAD_VALID_NO,
        EVENT_PAYLOAD_VALID_DONT_KNOW,
        _EVENT_PAYLOAD_VALID_MAX,
        _EVENT_PAYLOAD_VALID_INVALID = -EINVAL,
} EventPayloadValid;
 
struct EventLogRecord {
        EventLog *event_log;
 
        uint32_t pcr;      /* Either 'pcr' or 'nv_index' are set, but not both. Other one is UINT32_MAX. */
        uint32_t nv_index;
 
        const char *source;
        char *description;
 
        /* Data for firmware events (i.e. "TCG PC Client Platform Firmware Profile Specification" events) */
        uint32_t firmware_event_type;
        void *firmware_payload;
        size_t firmware_payload_size;
 
        /* Data for userspace events (i.e. those generated by systemd in userspace */
        Tpm2UserspaceEventType userspace_event_type;
        sd_json_variant *userspace_content;
 
        /* Validation result for the event payload itself, if the record contains enough information to validate the hash */
        EventPayloadValid event_payload_valid;
 
        /* If this record matches an variant of one of our defined components */
        EventLogComponentVariant **mapped;
        size_t n_mapped;
 
        /* If this record is part of an EventLogComponentVariant */
        EventLogComponentVariant *owning_component_variant;
 
        LIST_HEAD(EventLogRecordBank, banks);
};
 
#define EVENT_LOG_RECORD_IS_FIRMWARE(record) ((record)->firmware_event_type != UINT32_MAX)
#define EVENT_LOG_RECORD_IS_USERSPACE(record) ((record)->userspace_event_type >= 0)
#define EVENT_LOG_RECORD_IS_PCR(record) ((record)->pcr != UINT32_MAX)
#define EVENT_LOG_RECORD_IS_NV_INDEX(record) ((record)->nv_index != UINT32_MAX)
 
struct EventLogRegisterBank {
        TPM2B_DIGEST observed;
        TPM2B_DIGEST calculated;
};
 
struct EventLogRegister {
        char *color;
        unsigned n_measurements;
        bool fully_recognized; /* true if all measurements in this register have been recognized to match components */
        EventLogRegisterBank *banks;
};
 
struct EventLogComponentVariant {
        EventLogComponent *component;
 
        char *id;
        char *path;
 
        EventLogRecord **records;
        size_t n_records;
};
 
struct EventLogComponent {
        char *id;
 
        EventLogComponentVariant **variants;
        size_t n_variants;
};
 
struct EventLog {
        EventLogRecord **records;
        size_t n_records;
 
        uint16_t *algorithms;
        size_t n_algorithms;
        bool algorithms_locked; /* if algorithms where set explicitly by user, and we should not determine them automatically */
 
        const EVP_MD **mds;
 
        /* The hash algorithm which we focus on for matching up components */
        uint16_t primary_algorithm;
 
        uint8_t startup_locality;
        bool startup_locality_found;
 
        EventLogRegister registers[TPM2_PCRS_MAX];
 
        EventLogComponent **components;
        size_t n_components;
 
        /* Number of components which we couldn't find in the event log */
        size_t n_missing_components;
 
        /* PCRs mask indicating all PCRs touched by unrecognized components */
        uint32_t missing_component_pcrs;
 
        /* PCRs mask indicating component found for the pcr */
        uint32_t has_component_pcrs;
};
 
static EventLogRecordBank *event_log_record_bank_free(EventLogRecordBank *bank) {
        return mfree(bank);
}
 
DEFINE_TRIVIAL_CLEANUP_FUNC(EventLogRecordBank*, event_log_record_bank_free);
 
static EventLogRecord *event_log_record_free(EventLogRecord *record) {
        EventLogRecordBank *bank;
 
        if (!record)
                return NULL;
 
        free(record->description);
        free(record->firmware_payload);
        sd_json_variant_unref(record->userspace_content);
 
        while ((bank = LIST_POP(banks, record->banks)))
                event_log_record_bank_free(bank);
 
        free(record->mapped);
 
        return mfree(record);
}
 
DEFINE_TRIVIAL_CLEANUP_FUNC(EventLogRecord*, event_log_record_free);
 
static void event_log_register_done(EventLog *el, EventLogRegister *reg) {
        assert(reg);
 
        free(reg->color);
        free(reg->banks);
}
 
static EventLogComponentVariant* event_log_component_variant_free(EventLogComponentVariant *variant) {
        if (!variant)
                return NULL;
 
        free(variant->id);
        free(variant->path);
 
        FOREACH_ARRAY(record, variant->records, variant->n_records)
                event_log_record_free(*record);
 
        free(variant->records);
 
        return mfree(variant);
}
 
DEFINE_TRIVIAL_CLEANUP_FUNC(EventLogComponentVariant*, event_log_component_variant_free);
 
static EventLogComponent* event_log_component_free(EventLogComponent *component) {
        if (!component)
                return NULL;
 
        FOREACH_ARRAY(variant, component->variants, component->n_variants)
                event_log_component_variant_free(*variant);
        free(component->variants);
 
        free(component->id);
 
        return mfree(component);
}
 
DEFINE_TRIVIAL_CLEANUP_FUNC(EventLogComponent*, event_log_component_free);
 
static EventLog* event_log_free(EventLog *el) {
        if (!el)
                return NULL;
 
        FOREACH_ARRAY(p, el->registers, TPM2_PCRS_MAX)
                event_log_register_done(el, p);
 
        FOREACH_ARRAY(rr, el->records, el->n_records)
                event_log_record_free(*rr);
        free(el->records);
 
        FOREACH_ARRAY(c, el->components, el->n_components)
                event_log_component_free(*c);
        free(el->components);
 
        free(el->algorithms);
        free(el->mds);
 
        return mfree(el);
}
 
DEFINE_TRIVIAL_CLEANUP_FUNC(EventLog*, event_log_free);
 
static EventLogRecord* event_log_record_new(EventLog *el) {
        EventLogRecord *record;
 
        record = new(EventLogRecord, 1);
        if (!record)
                return NULL;
 
        *record = (EventLogRecord) {
                .event_log = el,
                .pcr = UINT32_MAX,
                .nv_index = UINT32_MAX,
                .firmware_event_type = UINT32_MAX,
                .userspace_event_type = _TPM2_USERSPACE_EVENT_TYPE_INVALID,
                .event_payload_valid = _EVENT_PAYLOAD_VALID_INVALID,
        };
 
        return record;
}
 
static int event_log_add_record(
                EventLog *el,
                EventLogRecord **ret) {
 
        _cleanup_(event_log_record_freep) EventLogRecord *record = NULL;
 
        assert(el);
 
        if (!GREEDY_REALLOC(el->records, el->n_records+1))
                return -ENOMEM;
 
        record = event_log_record_new(el);
        if (!record)
                return -ENOMEM;
 
        el->records[el->n_records++] = record;
 
        if (ret)
                *ret = record;
 
        TAKE_PTR(record);
 
        return 0;
}
 
static int event_log_add_algorithm(EventLog *el, uint16_t alg) {
        assert(el);
 
        if (el->algorithms_locked) /* algorithms configured via env var, don't add any further automatically */
                return 0;
 
        if (typesafe_bsearch(&alg, el->algorithms, el->n_algorithms, cmp_uint16))
                return 0;
 
        if (!GREEDY_REALLOC(el->algorithms, el->n_algorithms+1))
                return -ENOMEM;
 
        el->algorithms[el->n_algorithms++] = alg;
 
        typesafe_qsort(el->algorithms, el->n_algorithms, cmp_uint16);
 
        return 1;
}
 
static int event_log_add_algorithms_from_environment(EventLog *el) {
        const char *e;
        int r;
 
        assert(el);
 
        e = secure_getenv("SYSTEMD_TPM2_HASH_ALGORITHMS");
        if (!e)
                return 0;
 
        for (;;) {
                _cleanup_free_ char *word = NULL;
 
                r = extract_first_word(&e, &word, ":", 0);
                if (r < 0)
                        return r;
                if (r == 0)
                        break;
 
                r = tpm2_hash_alg_from_string(word);
                if (r < 0)
                        return log_error_errno(r, "Unknown hash algorithm '%s'.", word);
 
                r = event_log_add_algorithm(el, r);
                if (r < 0)
                        return log_error_errno(r, "Failed to add hash algorithm '%s'.", word);
        }
 
        if (el->n_algorithms > 0)
                el->algorithms_locked = true;
 
        return 0;
}
 
static EventLogRecordBank *event_log_record_find_bank(
                const EventLogRecord *record,
                uint16_t alg) {
 
        assert(record);
 
        LIST_FOREACH(banks, i, record->banks)
                if (i->algorithm == alg)
                        return i;
 
        return NULL;
}
 
static int event_log_record_add_bank(
                EventLogRecord *record,
                uint16_t algorithm,
                const void *hash,
                size_t hash_size,
                EventLogRecordBank **ret) {
 
        _cleanup_(event_log_record_bank_freep) EventLogRecordBank *bank = NULL;
        _cleanup_free_ void *h = NULL;
 
        assert(record);
        assert(hash || hash_size == 0);
 
        if (event_log_record_find_bank(record, algorithm))
                return -EEXIST;
 
        if (hash_size > sizeof_field(TPM2B_DIGEST, buffer))
                return -E2BIG;
 
        h = memdup(hash, hash_size);
        if (!h)
                return -ENOMEM;
 
        bank = new(EventLogRecordBank, 1);
        if (!bank)
                return -ENOMEM;
 
        *bank = (EventLogRecordBank) {
                .algorithm = algorithm,
                .hash = TPM2B_DIGEST_MAKE(hash, hash_size),
        };
 
        LIST_PREPEND(banks, record->banks, bank);
 
        if (ret)
                *ret = bank;
 
        TAKE_PTR(bank);
 
        return 0;
}
 
static bool event_log_record_is_stub(EventLogRecord *rec) {
        assert(rec);
 
        /* Recognizes the special EV_IPL events systemd-stub generates. Since EV_IPL can be used by almost
         * anything, we'll check for the PCR values, to see if it's one of ours. */
 
        if (rec->firmware_event_type != EV_IPL)
                return false;
 
        if (!EVENT_LOG_RECORD_IS_FIRMWARE(rec))
                return false;
 
        if (!IN_SET(rec->pcr,
                    TPM2_PCR_KERNEL_BOOT,        /* 11 */
                    TPM2_PCR_KERNEL_CONFIG,      /* 12 */
                    TPM2_PCR_SYSEXTS))           /* 13 */
                return false;
 
        return true;
}
 
static int event_log_record_parse_variable_data(
                EventLogRecord *rec,
                sd_id128_t *ret_variable_uuid,
                char **ret_variable_name) {
 
        _cleanup_free_ char16_t *p16 = NULL;
        _cleanup_free_ char *p = NULL;
 
        assert(rec);
        assert(ret_variable_uuid);
        assert(ret_variable_name);
 
        if (rec->firmware_payload_size < sizeof(UEFI_VARIABLE_DATA))
                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "EFI variable field too short.");
 
        const UEFI_VARIABLE_DATA *vdata = rec->firmware_payload;
 
        if (vdata->unicodeNameLength > (SIZE_MAX - offsetof(UEFI_VARIABLE_DATA, unicodeNameLength)) / 2)
                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "Unicode name length too large.");
 
        size_t m = offsetof(UEFI_VARIABLE_DATA, unicodeName) + vdata->unicodeNameLength * 2;
 
        if (vdata->variableDataLength > SIZE_MAX - m)
                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "Oversize EFI variable data size.");
 
        if (rec->firmware_payload_size != m + vdata->variableDataLength)
                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "EFI variable data has wrong size.");
 
        p16 = memdup(vdata->unicodeName, vdata->unicodeNameLength * 2); /* Copy out, to align properly */
        if (!p16)
                return log_oom_debug();
 
        p = utf16_to_utf8(p16, vdata->unicodeNameLength * 2);
        if (!p)
                return log_oom_debug();
 
        if (!string_is_safe(p, STRING_ALLOW_GLOBS))
                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "Unsafe EFI variable string in record.");
 
        *ret_variable_uuid = efi_guid_to_id128(vdata->variableName);
        *ret_variable_name = TAKE_PTR(p);
 
        return 0;
}
 
static int event_log_record_extract_firmware_description(EventLogRecord *rec) {
        _cleanup_free_ char *fallback = NULL;
        int r;
 
        assert(rec);
 
        if (!EVENT_LOG_RECORD_IS_FIRMWARE(rec))
                return 0;
 
        if (arg_raw_description)
                goto catchall;
 
        switch (rec->firmware_event_type) {
 
        case EV_EFI_VARIABLE_DRIVER_CONFIG:
        case EV_EFI_VARIABLE_BOOT:
        case EV_EFI_VARIABLE_BOOT2:
        case EV_EFI_VARIABLE_AUTHORITY: {
                _cleanup_free_ char *p = NULL;
                sd_id128_t uuid;
 
                r = event_log_record_parse_variable_data(rec, &uuid, &p);
                if (r == -ENOMEM)
                        return log_oom();
                if (r < 0) {
                        log_warning_errno(r, "EFI variable data invalid, ignoring.");
                        goto invalid;
                }
 
                if (asprintf(&rec->description, "%s: %s-" SD_ID128_UUID_FORMAT_STR,
                             rec->firmware_event_type == EV_EFI_VARIABLE_AUTHORITY ? "Authority" : "Variable",
                             p,
                             SD_ID128_FORMAT_VAL(uuid)) < 0)
                        return log_oom();
 
                return 1;
        }
 
        case EV_SEPARATOR: {
                if (rec->firmware_payload_size != sizeof(uint32_t)) {
                        log_warning("EFI separator field has wrong size, ignoring.");
                        goto invalid;
                }
 
                uint32_t val = unaligned_read_ne32(rec->firmware_payload);
 
                switch (val) {
 
                case 0:
                case UINT32_C(0xffffffff):
                        (void) asprintf(&rec->description, "Separator: Success (0x%02" PRIx32 ")", val);
                        break;
 
                case 1:
                        rec->description = strdup("Separator: Error (0x01)");
                        break;
 
                default:
                        log_warning("Unexpected separator payload %" PRIu32 ", ignoring.", val);
                        goto invalid;
                }
 
                if (!rec->description)
                        return log_oom();
 
                return 1;
        }
 
        case EV_EFI_ACTION: {
                _cleanup_free_ char *d = NULL;
 
                r = make_cstring(rec->firmware_payload, rec->firmware_payload_size, MAKE_CSTRING_ALLOW_TRAILING_NUL, &d);
                if (r < 0)
                        return log_error_errno(r, "Failed to make C string from EFI action string: %m");
 
                if (!string_is_safe(d, STRING_ALLOW_GLOBS|STRING_ALLOW_EMPTY|STRING_ALLOW_BACKSLASHES)) {
                        log_warning("Unsafe EFI action string in record, ignoring.");
                        goto invalid;
                }
 
                rec->description = strjoin("Action: ", d);
                if (!rec->description)
                        return log_oom();
                return 1;
        }
 
        case EV_EFI_GPT_EVENT: {
                if (rec->firmware_payload_size < sizeof(GptHeader)) {
                        log_warning("GPT measurement too short, ignoring.");
                        goto invalid;
                }
 
                const GptHeader *h = rec->firmware_payload;
 
                if (!gpt_header_has_signature(h)) {
                        log_warning("GPT measurement does not cover a GPT partition table header, ignoring.");
                        goto invalid;
                }
 
                if (asprintf(&rec->description, "GPT: disk " SD_ID128_UUID_FORMAT_STR, SD_ID128_FORMAT_VAL(efi_guid_to_id128(h->disk_guid))) < 0)
                        return log_oom();
 
                return 1;
        }
 
        case EV_IPL: {
                _cleanup_free_ char *d = NULL;
 
                /* EV_IPL can be anything, only try to parse the description on PCRs we "own" */
                if (!event_log_record_is_stub(rec))
                        break;
 
                /* sd-stub always sets a description string as text for these */
 
                d = utf16_to_utf8(rec->firmware_payload, rec->firmware_payload_size);
                if (!d)
                        return log_oom();
 
                if (string_has_cc(d, NULL)) {
                        log_warning("Unsafe EFI action string in record, ignoring.");
                        goto invalid;
                }
 
                rec->description = strjoin("String: ", d);
                if (!rec->description)
                        return log_oom();
 
                return 1;
        }
 
        case EV_EVENT_TAG: {
                TCG_PCClientTaggedEvent *tag = rec->firmware_payload;
                size_t left = rec->firmware_payload_size;
 
                if (left == 0) {
                        log_warning("Empty tagged PC client event, ignoring.");
                        goto invalid;
                }
 
                for (;;) {
                        uint64_t m;
 
                        if (left < offsetof(TCG_PCClientTaggedEvent, taggedEventData)) {
                                log_warning("Tagged PC client event too short, ignoring.");
                                goto invalid;
                        }
 
                        m = offsetof(TCG_PCClientTaggedEvent, taggedEventData) + (uint64_t) tag->taggedEventDataSize;
                        if (left < m) {
                                log_warning("Tagged PC client event data too short, ignoring.");
                                goto invalid;
                        }
 
                        switch (tag->taggedEventID) {
 
                        /* Linux kernel's own measurements: */
                        case INITRD_EVENT_TAG_ID:
                                /* The tagged event payload is just a constant string, hence don't show it */
                                if (!strextend_with_separator(&rec->description, ", ", "Linux: initrd"))
                                        return log_oom();
                                break;
 
                        case LOAD_OPTIONS_EVENT_TAG_ID:
                                /* As above. */
                                if (!strextend_with_separator(&rec->description, ", ", "Linux: kernel command line"))
                                        return log_oom();
                                break;
 
                        /* systemd's measurements: */
                        case LOADER_CONF_EVENT_TAG_ID:
                                /* As above. */
                                if (!strextend_with_separator(&rec->description, ", ", "systemd-boot: loader.conf"))
                                        return log_oom();
                                break;
 
                        case DEVICETREE_ADDON_EVENT_TAG_ID: {
                                _cleanup_free_ char *raw = NULL, *s = NULL;
 
                                raw = utf16_to_utf8((const char16_t*) tag->taggedEventData, tag->taggedEventDataSize);
                                if (!raw)
                                        return log_oom();
 
                                s = cescape(raw);
                                if (!s)
                                        return log_oom();
 
                                r = strextendf_with_separator(&rec->description, ", ", "systemd-stub: devicetree addon %s", s);
                                if (r < 0)
                                        return log_error_errno(r, "Failed to format EV_EVENT_TAG description string: %m");
                                break;
                        }
 
                        /* SMBIOS structures measured by sd-boot/sd-stub. The tagged event payload is just a
                         * constant identifying string ("smbios:typeN"), hence don't show it. */
                        case SMBIOS_TYPE1_EVENT_TAG_ID:
                                if (!strextend_with_separator(&rec->description, ", ", "systemd: SMBIOS system information (type 1)"))
                                        return log_oom();
                                break;
 
                        case SMBIOS_TYPE2_EVENT_TAG_ID:
                                if (!strextend_with_separator(&rec->description, ", ", "systemd: SMBIOS baseboard information (type 2)"))
                                        return log_oom();
                                break;
 
                        case SMBIOS_TYPE11_EVENT_TAG_ID:
                                if (!strextend_with_separator(&rec->description, ", ", "systemd: SMBIOS OEM strings (type 11)"))
                                        return log_oom();
                                break;
 
                        default: {
                                _cleanup_free_ char *s = NULL;
 
                                s = cescape_length((char*) tag->taggedEventData, tag->taggedEventDataSize);
                                if (!s)
                                        return log_oom();
 
                                r = strextendf_with_separator(&rec->description, ", ", "Tag 0x%" PRIx32 ": %s", tag->taggedEventID, s);
                                if (r < 0)
                                        return log_error_errno(r, "Failed to format EV_EVENT_TAG description string: %m");
                        }}
 
                        tag = (TCG_PCClientTaggedEvent*) ((uint8_t*) tag + m);
                        left -= m;
 
                        if (left == 0)
                                break;
                }
 
                return 1;
        }
 
        case EV_EFI_PLATFORM_FIRMWARE_BLOB: {
                const UEFI_PLATFORM_FIRMWARE_BLOB *blob;
                if (rec->firmware_payload_size != sizeof(UEFI_PLATFORM_FIRMWARE_BLOB)) {
                        log_warning("EV_EFI_PLATFORM_FIRMWARE_BLOB of wrong size, ignoring.");
                        goto invalid;
                }
 
                blob = rec->firmware_payload;
                if (asprintf(&rec->description, "Blob: %s @ 0x%" PRIx64, FORMAT_BYTES(blob->blobLength), blob->blobBase) < 0)
                        return log_oom();
 
                return 1;
        }
 
        case EV_EFI_BOOT_SERVICES_APPLICATION:
        case EV_EFI_BOOT_SERVICES_DRIVER:
        case EV_EFI_RUNTIME_SERVICES_DRIVER: {
                const UEFI_IMAGE_LOAD_EVENT *load;
                _cleanup_free_ char *fn = NULL;
                bool end = false;
 
                if (rec->firmware_payload_size < offsetof(UEFI_IMAGE_LOAD_EVENT, devicePath)) {
                        log_warning("Device path too short, ignoring.");
                        goto invalid;
                }
 
                load = rec->firmware_payload;
                if (load->lengthOfDevicePath !=
                    rec->firmware_payload_size - offsetof(UEFI_IMAGE_LOAD_EVENT, devicePath)) {
                        log_warning("Device path size does not match, ignoring.");
                        goto invalid;
                }
 
                /* device path could be empty. Don't mark that as invalid but leave as don't know.
                 * Happens eg with shim https://github.com/rhboot/shim/issues/642 */
                if (load->lengthOfDevicePath == 0) {
                        rec->description = strdup("File: <unspecified>");
                        if (!rec->description)
                                return log_oom();
 
                        return 1;
                }
 
                const packed_EFI_DEVICE_PATH *dp = (const packed_EFI_DEVICE_PATH*) load->devicePath;
                size_t left = load->lengthOfDevicePath;
 
                for (;;) {
                        if (left == 0) {
                                if (!end) {
                                        log_warning("Garbage after device path end, ignoring.");
                                        goto invalid;
                                }
 
                                break;
                        }
 
                        if (end) {
                                log_warning("Garbage after device path end, ignoring.");
                                goto invalid;
                        }
 
                        if (left < offsetof(packed_EFI_DEVICE_PATH, path) ||
                            dp->length < offsetof(packed_EFI_DEVICE_PATH, path) ||
                            left < dp->length) {
                                log_warning("Device path element too short, ignoring.");
                                goto invalid;
                        }
 
                        if (dp->type == 4 && dp->subType == 4) {
                                /* Filename, store the last node of this type as description, it should contain the file name */
 
                                free(fn);
                                fn = utf16_to_utf8((void*) dp->path, dp->length - offsetof(packed_EFI_DEVICE_PATH, path));
                                if (!fn)
                                        return log_oom();
 
                        } else if (dp->type == 0x7F && dp->subType == 0xFF)
                                /* End of Hardware Device Path */
                                end = true;
                        else
                                log_debug("Ignoring device path element type=0x%02x subtype=0x%02x", dp->type, dp->subType);
 
                        left -= dp->length;
                        dp = (packed_EFI_DEVICE_PATH*) ((uint8_t*) dp + dp->length);
                }
 
                if (fn) {
                        rec->description = strjoin("File: ", fn);
                        if (!rec->description)
                                return log_oom();
 
                        return 1;
                }
 
                break;
        }}
 
catchall:
        /* Catchall: show binary data */
        fallback = cescape_length(rec->firmware_payload, rec->firmware_payload_size);
        if (!fallback)
                return log_oom();
 
        rec->description = strjoin("Raw: ", fallback);
        if (!rec->description)
                return log_oom();
        return 1;
 
invalid:
        /* Mark the payload as invalid, so that we do not bother parsing/validating it any further */
        rec->event_payload_valid = EVENT_PAYLOAD_VALID_NO;
        return 0;
}
 
static int event_log_add_algorithms_from_record(EventLog *el, EventLogRecord *record) {
        int r;
 
        assert(el);
        assert(record);
 
        if (el->algorithms_locked)
                return 0;
 
        LIST_FOREACH(banks, i, record->banks) {
                r = event_log_add_algorithm(el, i->algorithm);
                if (r < 0)
                        return r;
        }
 
        return 0;
}
 
static int event_log_add_firmware_record(
                EventLog *el,
                const char *source,
                uint32_t pcr,
                uint32_t event_type,
                const void *payload,
                size_t payload_size,
                EventLogRecord **ret) {
 
        EventLogRecord *record = NULL;
        int r;
 
        assert(el);
        assert(source);
        assert(payload || payload_size == 0);
        assert(ret);
 
        r = event_log_add_record(el, &record);
        if (r < 0)
                return log_error_errno(r, "Failed to add record to event log: %m");
 
        record->pcr = pcr;
        record->source = source;
        record->firmware_event_type = event_type;
        record->firmware_payload = memdup(payload, payload_size);
        if (!record->firmware_payload)
                return log_oom();
        record->firmware_payload_size = payload_size;
 
        *ret = record;
        return 0;
}
 
static int event_log_load_firmware(EventLog *el, bool keep_no_action) {
        const TCG_EfiSpecIdEventAlgorithmSize *algorithms;
        size_t bufsize = 0, n_algorithms = 0, left = 0;
        _cleanup_free_ void *buf = NULL;
        const TCG_PCR_EVENT2 *event;
        const char *path;
        int r;
 
        assert(el);
 
        path = tpm2_firmware_log_path();
 
        r = read_full_file(path, (char**) &buf, &bufsize);
        if (r == -ENOENT) {
                log_notice_errno(r, "No '%s' file, assuming TPM without firmware support.", path);
                return 0;
        }
        if (r < 0)
                return log_error_errno(r, "Failed to open TPM2 event log '%s': %m", path);
 
        if (bufsize == 0) {
                /* Sometimes it's useful to invoke things with SYSTEMD_MEASURE_LOG_FIRMWARE=/dev/null, let's allow that, and proceed */
                log_warning("Empty firmware event log file, not loading.");
                return 0;
        }
 
        r = validate_firmware_header(buf, bufsize, &algorithms, &n_algorithms, &event, &left);