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 1001–2000 of 5,877

        if (r < 0)
                return r;
 
        if (keep_no_action) {
                /* The log header is an EV_NO_ACTION event (the Spec ID event), which carries the version
                 * of the TCG PC Client Platform Firmware Profile Specification the log follows. Retain it if
                 * requested. Note that unlike all other events it is in the legacy event format, and hence
                 * comes with a single (all-zero) SHA1 digest. */
                const TCG_PCClientPCREvent *h = buf;
                EventLogRecord *record;
 
                r = event_log_add_firmware_record(el, path, h->pcrIndex, h->eventType, h->event, h->eventDataSize, &record);
                if (r < 0)
                        return r;
 
                r = event_log_record_add_bank(record, TPM2_ALG_SHA1, h->digest, sizeof(h->digest), /* ret= */ NULL);
                if (r < 0)
                        return log_error_errno(r, "Failed to add bank to event log record: %m");
        }
 
        for (const TCG_PCR_EVENT2 *next_event = NULL;; event = next_event) {
                EventLogRecord *record = NULL;
                const void *payload;
                size_t payload_size;
 
                r = validate_firmware_event(
                                event,
                                left,
                                algorithms,
                                n_algorithms,
                                &next_event,
                                &left,
                                &payload,
                                &payload_size);
                if (r < 0)
                        return r;
                if (r == 0)
                        break;
 
                if (event->eventType == EV_NO_ACTION &&
                    event->pcrIndex == 0 &&
                    payload_size == 17 &&
                    memcmp(payload, "StartupLocality", sizeof("StartupLocality")) == 0) {
                        if (el->startup_locality_found)
                                return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "StartupLocality event found twice.");
 
                        el->startup_locality = ((const uint8_t*) payload)[sizeof("StartupLocality")];
                        el->startup_locality_found = true;
                        log_debug("Found StartupLocality event: %u", el->startup_locality);
                }
 
                /* Ignore pseudo events that don't result in a measurement, unless we are asked to keep
                 * them. They carry information that may be useful to consumers of the event log (e.g.
                 * verifiers of TPM2 reports), such as the StartupLocality event, which determines the
                 * initial value of PCR 0. */
                if (event->eventType == EV_NO_ACTION && !keep_no_action) {
                        log_debug("Skipping NO_ACTION event.");
                        continue;
                }
 
                if (event->pcrIndex >= TPM2_PCRS_MAX) {
                        log_debug("Skipping event on PCR %" PRIu32 " (out of range).", event->pcrIndex);
                        continue;
                }
 
                r = event_log_add_firmware_record(el, path, event->pcrIndex, event->eventType, payload, payload_size, &record);
                if (r < 0)
                        return r;
 
                const void *ha, *ha_next = NULL;
                ha = (const uint8_t*) event + offsetof(TCG_PCR_EVENT2, digests.digests);
                assert(event->digests.count == n_algorithms);
 
                for (size_t i = 0; i < n_algorithms; i++, ha = ha_next) {
                        /* The TPMT_HA is not aligned in the record, hence read the hashAlg field via an unaligned read */
                        assert_cc(__builtin_types_compatible_p(uint16_t, typeof(TPMI_ALG_HASH)));
                        uint16_t hash_alg = unaligned_read_ne16((const uint8_t*) ha + offsetof(TPMT_HA, hashAlg));
 
                        /* On some systems (some HyperV?) the order of hash algorithms announced in the
                         * header does not match the order in the records. Let's hence search for the right
                         * mapping */
                        size_t j;
                        for (j = 0; j < n_algorithms; j++)
                                if (hash_alg == algorithms[j].algorithmId)
                                        break;
                        if (j >= n_algorithms)
                                return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Hash algorithms in event log record not among those advertised by log header.");
 
                        ha_next = (const uint8_t*) ha + offsetof(TPMT_HA, digest) + algorithms[j].digestSize;
 
                        if (!tpm2_hash_alg_to_string(hash_alg))
                                continue;
 
                        r = event_log_record_add_bank(
                                        record,
                                        hash_alg,
                                        (const uint8_t*) ha + offsetof(TPMT_HA, digest),
                                        algorithms[j].digestSize,
                                        /* ret= */ NULL);
                        if (r < 0)
                                return log_error_errno(r, "Failed to add bank to event log record: %m");
                }
 
                /* Try to extract a descriptive text */
                r = event_log_record_extract_firmware_description(record);
                if (r < 0)
                        return r;
 
                r = event_log_add_algorithms_from_record(el, record);
                if (r < 0)
                        return r;
        }
 
        return 0;
}
 
static int event_log_record_parse_json(EventLogRecord *record, sd_json_variant *j) {
        int r;
 
        assert(record);
        assert(j);
 
        if (!sd_json_variant_is_object(j))
                return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "record object is not an object.");
 
        sd_json_variant *jp = sd_json_variant_by_key(j, "pcr");
        sd_json_variant *jn = sd_json_variant_by_key(j, "nv_index");
        if (jp) {
                uint64_t u;
                if (jn)
                        return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Both 'pcr' and 'nv_index' field found in TPM measurement log file entry.");
                if (!sd_json_variant_is_unsigned(jp))
                        return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "'pcr' field is not an integer.");
 
                u = sd_json_variant_unsigned(jp);
                if (u >= TPM2_PCRS_MAX)
                        return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "'pcr' field is out of range.");
 
                record->pcr = u;
                record->nv_index = UINT32_MAX;
        } else {
                uint64_t u;
 
                if (!jn)
                        return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Neither 'pcr' nor 'nv_index' field found in TPM measurement log file entry.");
                if (!sd_json_variant_is_unsigned(jn))
                        return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "'nv_index' field is not an integer.");
 
                u = sd_json_variant_unsigned(jn);
                if (u >= UINT32_MAX)
                        return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "'nv_index' field is out of range.");
 
                record->nv_index = u;
                record->pcr = UINT32_MAX;
        }
 
        sd_json_variant *x = sd_json_variant_by_key(j, "digests");
        if (!x)
                return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "'digests' field missing from TPM measurement log file entry.");
        if (!sd_json_variant_is_array(x))
                return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "'digests' field is not an array.");
 
        sd_json_variant *k;
        JSON_VARIANT_ARRAY_FOREACH(k, x) {
                _cleanup_free_ void *hash = NULL;
                size_t hash_size;
                sd_json_variant *a, *h;
                int na;
 
                a = sd_json_variant_by_key(k, "hashAlg");
                if (!a)
                        return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "'digests' field element lacks 'hashAlg' field.");
                if (!sd_json_variant_is_string(a))
                        return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "'hashAlg' field is not a string.");
 
                na = tpm2_hash_alg_from_string(sd_json_variant_string(a));
                if (na < 0) {
                        log_debug_errno(na, "Unsupported hash '%s' in userspace event log, ignoring: %m", sd_json_variant_string(a));
                        continue;
                }
 
                h = sd_json_variant_by_key(k, "digest");
                if (!h)
                        return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "'digests' field lacks 'digest' field.");
 
                r = sd_json_variant_unhex(h, &hash, &hash_size);
                if (r < 0)
                        return log_error_errno(r, "Failed to decode digest: %m");
 
                r = event_log_record_add_bank(
                                record,
                                na,
                                hash,
                                hash_size,
                                /* ret= */ NULL);
                if (r < 0)
                        return log_error_errno(r, "Failed to add bank to event log record: %m");
        }
 
        const char *rectype = NULL;
        x = sd_json_variant_by_key(j, "content_type");
        if (!x)
                log_debug("'content_type' missing from TPM measurement log file entry, ignoring.");
        else {
                if (!sd_json_variant_is_string(x))
                        return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "'content_type' field is not a string.");
 
                rectype = sd_json_variant_string(x);
        }
 
        if (streq_ptr(rectype, "systemd")) {
                sd_json_variant *y;
 
                x = sd_json_variant_by_key(j, "content");
                if (!x)
                        return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "'content' field missing from TPM measurement log file entry.");
                if (!sd_json_variant_is_object(x))
                        return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "'content' sub-object is not an object.");
 
                y = sd_json_variant_by_key(x, "string");
                if (y) {
                        if (!sd_json_variant_is_string(y))
                                return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "'string' field is not a string.");
 
                        r = free_and_strdup_warn(&record->description, sd_json_variant_string(y));
                        if (r < 0)
                                return r;
                }
 
                y = sd_json_variant_by_key(x, "eventType");
                if (y) {
                        if (!sd_json_variant_is_string(y))
                                return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "'eventType' field is not a string.");
 
                        record->userspace_event_type = tpm2_userspace_event_type_from_string(sd_json_variant_string(y));
                        if (record->userspace_event_type < 0)
                                log_debug_errno(record->userspace_event_type, "Unknown userspace event type '%s', ignoring.", sd_json_variant_string(y));
                }
 
                sd_json_variant_unref(record->userspace_content);
                record->userspace_content = sd_json_variant_ref(x);
        }
 
        return 0;
}
 
static int event_log_load_userspace(EventLog *el) {
        _cleanup_fclose_ FILE *f = NULL;
        _cleanup_free_ char *b = NULL;
        bool beginning = true;
        const char *path;
        struct stat st;
        size_t bn = 0;
        int r;
 
        assert(el);
 
        path = tpm2_userspace_log_path();
 
        f = fopen(path, "re");
        if (!f) {
                if (errno != ENOENT)
                        return log_error_errno(errno, "Failed to open userspace TPM measurement log file: %m");
 
                return 0;
        }
 
        if (flock(fileno(f), LOCK_SH) < 0)
                return log_error_errno(errno, "Failed to lock userspace TPM measurement log file: %m");
 
        /* The sticky bit marks the log as incomplete: a writer died between updating a PCR and appending
         * the matching record. Load the log anyway, the affected PCRs will simply fail validation. */
        if (fstat(fileno(f), &st) < 0)
                log_warning_errno(errno, "Failed to stat userspace TPM measurement log file, cannot determine whether it is complete, ignoring: %m");
        else if (FLAGS_SET(st.st_mode, S_ISVTX))
                log_warning("Userspace TPM measurement log file is marked as incomplete, PCR validation may fail.");
 
        for (;;) {
                _cleanup_(sd_json_variant_unrefp) sd_json_variant *j = NULL;
                EventLogRecord *record;
                int ch;
 
                ch = fgetc(f);
                if (ch == EOF) {
                        if (ferror(f))
                                return log_error_errno(errno, "Failed to read local TPM measurement log file: %m");
 
                        if (beginning)
                                break;
                } else if (ch != 0x1EU) {
                        if (!GREEDY_REALLOC(b, bn + 2))
                                return log_oom();
 
                        b[bn++] = (char) ch;
                        continue;
                }
 
                if (beginning) {
                        beginning = false;
                        continue;
                }
 
                if (!GREEDY_REALLOC(b, bn + 1))
                        return log_oom();
 
                b[bn] = 0; /* Turn it into a string */
 
                if (memchr(b, 0, bn)) {
                        log_warning("Found record with embedded NUL byte, skipping.");
                        continue;
                }
 
                r = sd_json_parse(b, 0, &j, NULL, NULL);
                if (r < 0)
                        return log_error_errno(r, "Failed to parse local TPM measurement log file: %m");
 
                r = event_log_add_record(el, &record);
                if (r < 0)
                        return log_error_errno(r, "Failed to add record to event log: %m");
 
                record->source = path;
 
                r = event_log_record_parse_json(record, j);
                if (r < 0)
                        return r;
 
                r = event_log_add_algorithms_from_record(el, record);
                if (r < 0)
                        return r;
 
                if (ch == EOF)
                        break;
 
                b = mfree(b);
                bn = 0;
        }
 
        return 0;
}
 
static EventLog *event_log_new(void) {
        _cleanup_(event_log_freep) EventLog *el = NULL;
 
        el = new(EventLog, 1);
        if (!el)
                return NULL;
 
        *el = (EventLog) {
                .primary_algorithm = UINT16_MAX,
        };
 
        return TAKE_PTR(el);
}
 
static int event_log_load(EventLog *el, bool keep_fw_no_action) {
        int r;
 
        assert(el);
 
        r = event_log_load_firmware(el, keep_fw_no_action);
        if (r < 0)
                return r;
 
        r = event_log_load_userspace(el);
        if (r < 0)
                return r;
 
        return 0;
}
 
static int event_log_read_pcrs(EventLog *el) {
        _cleanup_(tpm2_context_unrefp) Tpm2Context *tc = NULL;
        int r;
 
        assert(el);
 
        r = tpm2_context_new_or_warn(/* device= */ NULL, &tc);
        if (r < 0)
                return r;
 
        FOREACH_ARRAY(rr, el->registers, TPM2_PCRS_MAX) {
                if (rr->banks)
                        continue;
 
                rr->banks = new0(EventLogRegisterBank, el->n_algorithms);
                if (!rr->banks)
                        return log_oom();
        }
 
        for (size_t a = 0; a < el->n_algorithms; a++) {
                _cleanup_free_ Tpm2PCRValue *pcr_values = NULL;
                size_t n_pcr_values;
                TPML_PCR_SELECTION selection;
 
                tpm2_tpml_pcr_selection_from_mask(TPM2_PCRS_MASK, el->algorithms[a], &selection);
                r = tpm2_pcr_read(tc, &selection, &pcr_values, &n_pcr_values);
                if (r < 0)
                        return r;
 
                FOREACH_ARRAY(v, pcr_values, n_pcr_values) {
                        assert(v->hash == el->algorithms[a]);
                        el->registers[v->index].banks[a].observed = v->value;
                }
        }
 
        return 0;
}
 
static void event_log_initial_pcr_state(EventLog *el, uint32_t pcr, size_t size, TPM2B_DIGEST *ret) {
        assert(el);
        assert(pcr < TPM2_PCRS_MAX);
        assert(size > 0);
        assert(size <= sizeof_field(TPM2B_DIGEST, buffer));
        assert(ret);
 
        ret->size = size;
 
        switch (pcr) {
 
        case 0:
                memzero(ret->buffer, ret->size-1);
                ((uint8_t*) ret->buffer)[ret->size-1] = el->startup_locality_found ? el->startup_locality : 0;
                break;
 
        case 1 ... 16:
        case 23:
                memzero(ret->buffer, ret->size);
                break;
 
        case 17 ... 22:
                memset(ret->buffer, 0xffu, ret->size);
                break;
 
        default:
                assert_not_reached();
        }
}
 
static int event_log_calculate_pcrs(EventLog *el) {
        assert(el);
 
        /* Iterates through the event log an calculates the expected hash values based on all listed records */
 
        assert(!el->mds);
        el->mds = new(const EVP_MD*, el->n_algorithms);
        if (!el->mds)
                return log_oom();
 
        for (size_t i = 0; i < el->n_algorithms; i++) {
                const EVP_MD *md;
                const char *a;
 
                assert_se(a = tpm2_hash_alg_to_string(el->algorithms[i]));
                assert_se(md = sym_EVP_get_digestbyname(a));
 
                el->mds[i] = md;
        }
 
        for (uint32_t pcr = 0; pcr < TPM2_PCRS_MAX; pcr++)
                for (size_t i = 0; i < el->n_algorithms; i++) {
                        EventLogRegisterBank *b = el->registers[pcr].banks + i;
                        event_log_initial_pcr_state(el, pcr, sym_EVP_MD_get_size(el->mds[i]), &b->calculated);
                }
 
        FOREACH_ARRAY(rr, el->records, el->n_records) {
 
                if (!EVENT_LOG_RECORD_IS_PCR(*rr))
                        continue;
 
                EventLogRegister *reg = el->registers + (*rr)->pcr;
 
                for (size_t i = 0; i < el->n_algorithms; i++) {
                        const char *n = tpm2_hash_alg_to_string(el->algorithms[i]);
                        _cleanup_(EVP_MD_CTX_freep) EVP_MD_CTX *mc = NULL;
                        EventLogRegisterBank *reg_b;
                        EventLogRecordBank *rec_b;
                        unsigned sz;
 
                        rec_b = event_log_record_find_bank(*rr, el->algorithms[i]);
                        if (!rec_b) {
                                log_warning("Record with missing bank '%s', ignoring.", n);
                                continue;
                        }
 
                        reg_b = reg->banks + i;
 
                        mc = sym_EVP_MD_CTX_new();
                        if (!mc)
                                return log_oom();
 
                        if (sym_EVP_DigestInit_ex(mc, el->mds[i], NULL) != 1)
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to initialize %s message digest context.", n);
 
                        if (sym_EVP_DigestUpdate(mc, reg_b->calculated.buffer, reg_b->calculated.size) != 1)
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to run digest.");
 
                        if (sym_EVP_DigestUpdate(mc, rec_b->hash.buffer, rec_b->hash.size) != 1)
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to run digest.");
 
                        if (sym_EVP_DigestFinal_ex(mc, reg_b->calculated.buffer, &sz) != 1)
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to finalize hash context.");
 
                        assert(sz == reg_b->calculated.size);
                }
 
                reg->n_measurements++;
        }
 
        return 0;
}
 
static int event_log_record_validate_hash_firmware(
                EventLogRecord *record,
                EventLogRecordBank *bank,
                const EVP_MD *md) {
 
        _cleanup_free_ void *hdata_alternative = NULL;
        size_t hsz, hsz_alternative = 0;
        bool strict = false;
        const void *hdata;
 
        assert(record);
        assert(bank);
        assert(md);
 
        if (!EVENT_LOG_RECORD_IS_FIRMWARE(record))
                return 0;
 
        switch (record->firmware_event_type) {
 
        case EV_EFI_ACTION:
        case EV_EFI_GPT_EVENT:
        case EV_EFI_VARIABLE_BOOT2:
        case EV_EFI_VARIABLE_DRIVER_CONFIG:
        case EV_EFI_VARIABLE_AUTHORITY:
        case EV_SEPARATOR:
        case EV_S_CRTM_VERSION:
                /* Here the extended hash value is the hash value of the event payload. Note that
                 * EV_PLATFORM_CONFIG_FLAGS (according to the TCG PC Client Platform Firmware Profile
                 * Specification) is also supposed to be like this. But ovmf doesn't follow this requirement,
                 * hence be lenient on that one, and don't include it here. */
                hdata = record->firmware_payload;
                hsz = record->firmware_payload_size;
                strict = true;
                break;
 
        case EV_EFI_VARIABLE_BOOT: {
                const UEFI_VARIABLE_DATA *vdata = record->firmware_payload;
                size_t skip;
 
                /* Here the extended hash value is the hash value of the variable data (i.e. excluding the
                 * name).
                 *
                 * Note: we already checked the general validity of the UEFI_VARIABLE_DATA structure, hence
                 * no need to do so again. */
 
                assert(record->firmware_payload_size >= offsetof(UEFI_VARIABLE_DATA, unicodeName));
                skip = offsetof(UEFI_VARIABLE_DATA, unicodeName) + vdata->unicodeNameLength * 2;
 
                assert(record->firmware_payload_size >= skip);
                hdata = (const uint8_t*) record->firmware_payload + skip;
                hsz = record->firmware_payload_size - skip;
                strict = true;
                break;
        }
 
        case EV_IPL:
                if (event_log_record_is_stub(record)) {
                        /* The PE section names have a descriptive string in UTF-16 in the payload, but the
                         * hash is over the UTF-8 version (with suffixing 0), hence let's convert the payload
                         * into that format here, and see if it checks out. */
                        hdata_alternative = utf16_to_utf8(record->firmware_payload, record->firmware_payload_size);
                        if (!hdata_alternative)
                                return log_oom();
 
                        hsz_alternative = strlen(hdata_alternative) + 1; /* with NUL byte */
                }
 
                _fallthrough_;
 
        default:
                /* For the others check the data too, just in case. But usually this will not match, hence
                 * only report if the checksum matches, but don't complain if it does not. */
                hdata = record->firmware_payload;
                hsz = record->firmware_payload_size;
                strict = false;
        }
 
        int mdsz = sym_EVP_MD_get_size(md);
        assert(mdsz > 0);
        assert((size_t) mdsz <= sizeof_field(TPM2B_DIGEST, buffer));
 
        TPM2B_DIGEST payload_hash = {
                .size = mdsz,
        };
 
        unsigned dsz = mdsz;
 
        if (sym_EVP_Digest(hdata, hsz, payload_hash.buffer, &dsz, md, NULL) != 1)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to calculate event payload hash.");
        assert(dsz == (unsigned) mdsz);
 
        /* If this didn't match then let's try the alternative format here, if we have one, and check things then. */
        if (memcmp_nn(bank->hash.buffer, bank->hash.size, payload_hash.buffer, payload_hash.size) != 0 && hdata_alternative) {
                if (sym_EVP_Digest(hdata_alternative, hsz_alternative, payload_hash.buffer, &dsz, md, NULL) != 1)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to calculate event payload hash.");
                assert(dsz == (unsigned) mdsz);
        }
 
        if (memcmp_nn(bank->hash.buffer, bank->hash.size, payload_hash.buffer, payload_hash.size) != 0) {
                if (strict)
                        record->event_payload_valid = EVENT_PAYLOAD_VALID_NO;
                else if (record->event_payload_valid != EVENT_PAYLOAD_VALID_NO)
                        record->event_payload_valid = EVENT_PAYLOAD_VALID_DONT_KNOW;
        } else if (record->event_payload_valid < 0)
                record->event_payload_valid = EVENT_PAYLOAD_VALID_YES;
 
        return 1;
}
 
static int event_log_record_validate_hash_userspace(
                EventLogRecord *record,
                EventLogRecordBank *bank,
                const EVP_MD *md) {
 
        _cleanup_free_ unsigned char *payload_hash = NULL;
        unsigned payload_hash_size;
        sd_json_variant *js;
        const char *s;
        int mdsz;
 
        assert(record);
        assert(bank);
        assert(md);
 
        if (!EVENT_LOG_RECORD_IS_USERSPACE(record))
                return 0;
 
        if (!record->userspace_content)
                return 0;
 
        js = sd_json_variant_by_key(record->userspace_content, "string");
        if (!js)
                return 0;
 
        assert(sd_json_variant_is_string(js));
        s = sd_json_variant_string(js);
 
        mdsz = sym_EVP_MD_get_size(md);
        assert(mdsz > 0);
 
        payload_hash_size = mdsz;
        payload_hash = malloc(payload_hash_size);
        if (!payload_hash)
                return log_oom();
 
        if (sym_EVP_Digest(s, strlen(s), payload_hash, &payload_hash_size, md, NULL) != 1)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to calculate event payload hash.");
 
        assert((int) payload_hash_size == mdsz);
        if (memcmp_nn(bank->hash.buffer, bank->hash.size, payload_hash, payload_hash_size) != 0)
                record->event_payload_valid = EVENT_PAYLOAD_VALID_NO;
        else if (record->event_payload_valid < 0)
                record->event_payload_valid = EVENT_PAYLOAD_VALID_YES;
 
        return 0;
}
 
static int event_log_validate_record_hashes(EventLog *el) {
        int r;
 
        assert(el);
 
        /* For records which contain the full data to validate the hashes, do so. */
 
        FOREACH_ARRAY(rr, el->records, el->n_records) {
 
                LIST_FOREACH(banks, bank, (*rr)->banks) {
                        const EVP_MD *md;
                        const char *a;
 
                        assert_se(a = tpm2_hash_alg_to_string(bank->algorithm));
                        assert_se(md = sym_EVP_get_digestbyname(a));
 
                        r = event_log_record_validate_hash_firmware(*rr, bank, md);
                        if (r < 0)
                                return r;
 
                        r = event_log_record_validate_hash_userspace(*rr, bank, md);
                        if (r < 0)
                                return r;
                }
        }
 
        return 0;
}
 
static int event_log_component_cmp(EventLogComponent *const*a, EventLogComponent *const*b) {
        const EventLogComponent *x = ASSERT_PTR(*ASSERT_PTR(a)), *y = ASSERT_PTR(*ASSERT_PTR(b));
 
        return strcmp(x->id, y->id);
}
 
static EventLogComponent *event_log_find_component(EventLog *el, const char *id) {
        EventLogComponent k = {
                .id = (char*) id,
        };
        EventLogComponent *kk = &k, **found;
 
        assert(el);
        assert(id);
 
        found = typesafe_bsearch(
                        &kk,
                        el->components,
                        el->n_components,
                        event_log_component_cmp);
        if (!found)
                return NULL;
 
        return *found;
}
 
static int event_log_add_component(EventLog *el, const char *id, EventLogComponent **ret) {
        _cleanup_(event_log_component_freep) EventLogComponent *component = NULL;
        _cleanup_free_ char *id_copy = NULL;
        EventLogComponent *found;
 
        assert(el);
        assert(ret);
 
        found = event_log_find_component(el, id);
        if (found) {
                *ret = found;
                return 0;
        }
 
        if (!GREEDY_REALLOC(el->components, el->n_components+1))
                return log_oom();
 
        id_copy = strdup(id);
        if (!id_copy)
                return log_oom();
 
        component = new(EventLogComponent, 1);
        if (!component)
                return log_oom();
 
        *component = (EventLogComponent) {
                .id = TAKE_PTR(id_copy),
        };
 
        if (ret)
                *ret = component;
 
        el->components[el->n_components++] = TAKE_PTR(component);
        return 1;
}
 
static int event_log_record_equal(const EventLogRecord *a, const EventLogRecord *b) {
        EventLogRecordBank *x, *y;
 
        assert(a);
        assert(a->event_log);
        assert(b);
        assert(b->event_log);
        assert(a->event_log == b->event_log);
 
        if (a->pcr != b->pcr)
                return false;
 
        if (a->nv_index != b->nv_index)
                return false;
 
        x = event_log_record_find_bank(a, a->event_log->primary_algorithm);
        y = event_log_record_find_bank(b, b->event_log->primary_algorithm);
        if (!x || !y)
                return false;
 
        assert(x->algorithm == a->event_log->primary_algorithm);
        assert(y->algorithm == b->event_log->primary_algorithm);
 
        return memcmp_nn(x->hash.buffer, x->hash.size, y->hash.buffer, y->hash.size) == 0;
}
 
static int event_log_add_component_file(EventLog *el, EventLogComponent *component, const char *path) {
        _cleanup_(event_log_component_variant_freep) EventLogComponentVariant *variant = NULL;
        _cleanup_free_ char *fname = NULL, *id = NULL, *path_copy = NULL;
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *j = NULL;
        sd_json_variant *records;
        const char *e;
        int r;
 
        assert(el);
 
        r = path_extract_filename(path, &fname);
        if (r < 0)
                return log_error_errno(r, "Failed to extract basename from path %s: %m", path);
 
        e = endswith(fname, ".pcrlock");
        if (!e)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Bad suffix: %s", fname);
 
        id = strndup(fname, e - fname);
        if (!id)
                return log_oom();
 
        if (!component) {
                r = event_log_add_component(el, id, &component);
                if (r < 0)
                        return r;
        }
 
        if (!GREEDY_REALLOC(component->variants, component->n_variants+1))
                return log_oom();
 
        r = sd_json_parse_file(
                        /* f= */ NULL,
                        path,
                        /* flags= */ 0,
                        &j,
                        /* reterr_line= */ NULL,
                        /* ret_column= */ NULL);
        if (r < 0) {
                log_warning_errno(r, "Failed to parse component file %s, ignoring: %m", path);
                return 0;
        }
 
        if (!sd_json_variant_is_object(j)) {
                log_warning("Component file %s does not contain JSON object, ignoring.", path);
                return 0;
        }
 
        path_copy = strdup(path);
        if (!path_copy)
                return log_oom();
 
        variant = new(EventLogComponentVariant, 1);
        if (!variant)
                return log_oom();
 
        *variant = (EventLogComponentVariant) {
                .component = component,
                .path = TAKE_PTR(path_copy),
                .id = TAKE_PTR(id),
        };
 
        records = sd_json_variant_by_key(j, "records");
        if (records) {
                sd_json_variant *rj;
 
                if (!sd_json_variant_is_array(records)) {
                        log_warning("Component records field of file %s is not an array, ignoring.", path);
                        return 0;
                }
 
                JSON_VARIANT_ARRAY_FOREACH(rj, records) {
                        _cleanup_(event_log_record_freep) EventLogRecord *record = NULL;
 
                        if (!GREEDY_REALLOC(variant->records, variant->n_records+1))
                                return log_oom();
 
                        record = event_log_record_new(el);
                        if (!record)
                                return log_oom();
 
                        r = event_log_record_parse_json(record, rj);
                        if (r < 0)
                                return r;
 
                        record->owning_component_variant = variant;
                        variant->records[variant->n_records++] = TAKE_PTR(record);
                }
        }
 
        component->variants[component->n_variants++] = TAKE_PTR(variant);
        return 1;
}
 
static int event_log_add_component_dir(EventLog *el, const char *path, char **base_search) {
        _cleanup_free_ char *fname = NULL, *id = NULL;
        _cleanup_strv_free_ char **files = NULL;
        EventLogComponent *component;
        const char *e;
        int r;
 
        assert(el);
 
        r = path_extract_filename(path, &fname);
        if (r < 0)
                return log_error_errno(r, "Failed to extract basename from path %s: %m", path);
 
        e = endswith(fname, ".pcrlock.d");
        if (!e)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Bad suffix: %s", fname);
 
        id = strndup(fname, e - fname);
        if (!id)
                return log_oom();
 
        r = event_log_add_component(el, id, &component);
        if (r < 0)
                return r;
 
        _cleanup_strv_free_ char **search = NULL;
 
        STRV_FOREACH(b, base_search) {
                _cleanup_free_ char *q = NULL;
 
                q = path_join(*b, fname);
                if (!q)
                        return log_oom();
 
                r = strv_consume(&search, TAKE_PTR(q));
                if (r < 0)
                        return log_oom();
        }
 
        r = conf_files_list_strv(&files, ".pcrlock", /* root= */ NULL,
                                 CONF_FILES_REGULAR|CONF_FILES_WARN,
                                 (const char*const*) search);
        if (r < 0)
                return log_error_errno(r, "Failed to enumerate .pcrlock files for component '%s': %m", id);
 
        STRV_FOREACH(f, files) {
                r = event_log_add_component_file(el, component, *f);
                if (r < 0)
                        return r;
        }
 
        return 0;
}
 
static int event_log_load_components(EventLog *el) {
        _cleanup_strv_free_ char **files = NULL;
        char **dirs;
        int r;
 
        assert(el);
 
        dirs = arg_components ?:
                STRV_MAKE("/etc/pcrlock.d",
                          "/run/pcrlock.d",
                          "/var/lib/pcrlock.d",
                          "/usr/local/lib/pcrlock.d",
                          "/usr/lib/pcrlock.d");
 
        r = conf_files_list_strv(&files, /* suffix= */ NULL, /* root= */ NULL,
                                 CONF_FILES_REGULAR|CONF_FILES_DIRECTORY|CONF_FILES_FILTER_MASKED|CONF_FILES_WARN,
                                 (const char*const*) dirs);
        if (r < 0)
                return log_error_errno(r, "Failed to enumerate .pcrlock files: %m");
 
        STRV_FOREACH(f, files) {
                if (endswith(*f, ".pcrlock.d"))
                        r = event_log_add_component_dir(el, *f, dirs);
                else if (endswith(*f, ".pcrlock"))
                        r = event_log_add_component_file(el, NULL, *f);
                else
                        continue;
                if (r < 0)
                        return r;
        }
 
        return 0;
}
 
static void event_log_unload_empty_components(EventLog *el) {
        assert(el);
 
        /* Remove components that have no defined variants from our list, because they'd reduce the set of
         * valid policies to zero. */
 
        size_t i = 0;
        while (i < el->n_components) {
                EventLogComponent *c = el->components[i];
 
                if (c->n_variants > 0) {
                        i++;
                        continue;
                }
 
                log_notice("Component '%s' has no defined variants, removing.", c->id);
                event_log_component_free(c);
 
                memmove(el->components + i, el->components + i + 1, (el->n_components - i - 1) * sizeof(el->components[0]));
                el->n_components--;
 
                /* Continue without increasing i */
        }
}
 
static int event_log_validate_fully_recognized(EventLog *el) {
 
        for (uint32_t pcr = 0; pcr < ELEMENTSOF(el->registers); pcr++) {
                bool fully_recognized = true;
 
                FOREACH_ARRAY(rr, el->records, el->n_records) {
                        EventLogRecord *rec = *rr;