HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/shared/tpm2-util.c

506,230 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 4aac8538339b20bce33c9a3fc2508a4679393682

Lines 9001–10000 of 12,273

                        &pcr_selection,
                        &init->public,
                        NVPCR_INIT_POLICY_REF,
                        init->fingerprint.iov_base, init->fingerprint.iov_len,
                        init->signature_json,
                        /* ret_policy_digest= */ NULL);
        if (r < 0)
                return r;
 
        r = tpm2_nvpcr_policy_or_written(c, session, &init->digest);
        if (r < 0)
                return r;
 
        *ret_session = TAKE_PTR(session);
        return 0;
}
 
/* Opens a policy session that satisfies the PolicyNvWritten(true) branch of an NvPCR's write policy, for all
 * writes after the initializing one. 'init_policy' is the digest of the init branch, needed for the
 * PolicyOR. */
static int tpm2_nvpcr_open_extend_session(
                Tpm2Context *c,
                const TPM2B_DIGEST *init_policy,
                Tpm2Handle **ret_session) {
 
        _cleanup_(tpm2_handle_freep) Tpm2Handle *session = NULL;
        int r;
 
        assert(c);
        assert(init_policy);
        assert(ret_session);
 
        r = tpm2_make_policy_session(c, /* primary= */ NULL, /* encryption_session= */ NULL, &session);
        if (r < 0)
                return r;
 
        r = tpm2_policy_nv_written(c, session, /* written_set= */ true, /* ret_policy_digest= */ NULL);
        if (r < 0)
                return r;
 
        r = tpm2_nvpcr_policy_or_written(c, session, init_policy);
        if (r < 0)
                return r;
 
        *ret_session = TAKE_PTR(session);
        return 0;
}
#endif
 
static int nvpcr_extend_bytes(
                Tpm2Context *c,
                const Tpm2Handle *session,
                const char *name,
                const struct iovec *data,
                const struct iovec *secret,
                Tpm2UserspaceEventType event_type,
                const char *description) {
 
#if HAVE_OPENSSL
        _cleanup_close_ int log_fd = -EBADF;
        int r;
 
        assert(c);
        assert(name);
        assert(iovec_is_valid(data));
        assert(iovec_is_valid(secret));
 
        r = dlopen_libcrypto(LOG_DEBUG);
        if (r < 0)
                return r;
 
        _cleanup_(nvpcr_data_done) NvPCRData p = {};
        r = nvpcr_data_load(name, &p);
        if (r < 0)
                return r;
 
        /* Open + lock the log file *before* we start measuring, so that no one else can come between our log
         * and our measurement and change either */
        log_fd = tpm2_userspace_log_open();
 
        /* Read the stored init policy digest. Its presence also tells us this NvPCR has been
         * initialized; we need it to reconstruct the TPM2_PolicyOR below. */
        TPM2B_DIGEST init_policy;
        r = tpm2_nvpcr_read_init_policy(name, &init_policy);
        if (r < 0)
                return r;
 
        const char *an = tpm2_hash_alg_to_string(p.algorithm);
        if (!an)
                return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Unsupported algorithm for NvPCR, refusing.");
 
        const EVP_MD *implementation;
        assert_se(implementation = sym_EVP_get_digestbyname(an));
 
        _cleanup_(iovec_done) struct iovec digest = {
                .iov_len = sym_EVP_MD_get_size(implementation),
        };
 
        digest.iov_base = malloc(digest.iov_len);
        if (!digest.iov_base)
                return log_oom_debug();
 
        if (!iovec_is_set(data))
                data = &iovec_empty;
 
        if (iovec_is_set(secret)) {
                if (!sym_HMAC(implementation, secret->iov_base, secret->iov_len, data->iov_base, data->iov_len, digest.iov_base, NULL))
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Failed to calculate HMAC of data to measure.");
        } else if (sym_EVP_Digest(data->iov_base, data->iov_len, digest.iov_base, NULL, implementation, NULL) != 1)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Failed to hash data to measure.");
 
        _cleanup_(tpm2_handle_freep) Tpm2Handle *nv_handle = NULL;
        r = tpm2_index_to_handle(
                        c,
                        p.nv_index,
                        session,
                        /* ret_name= */ NULL,
                        &nv_handle);
        if (r < 0)
                return log_debug_errno(r, "Failed to acquire handle to NV index 0x%" PRIu32 ".", p.nv_index);
        if (r == 0)
                return log_debug_errno(SYNTHETIC_ERRNO(ENODEV),
                                       "NvPCR '%s' is anchored but its NV index 0x%" PRIx32 " is no longer present on the TPM, refusing extend.",
                                       name, p.nv_index);
 
        log_debug("Successfully acquired handle to existing NV index 0x%" PRIx32 ".", p.nv_index);
 
        /* Open a policy session that satisfies the write policy via the PolicyNvWritten(true) branch
         * (the index was already written during initialization). */
        _cleanup_(tpm2_handle_freep) Tpm2Handle *policy_session = NULL;
        r = tpm2_nvpcr_open_extend_session(c, &init_policy, &policy_session);
        if (r < 0)
                return r;
 
        bool reset_marker = tpm2_userspace_log_dirty(log_fd) >= 0;
 
        r = tpm2_extend_nvpcr_nv_index(
                        c,
                        p.nv_index,
                        nv_handle,
                        policy_session,
                        &digest);
        if (r < 0)
                return r;
 
        TPML_DIGEST_VALUES digest_values = {
                .count = 1,
                .digests[0].hashAlg = p.algorithm,
        };
        memcpy(&digest_values.digests[0].digest, digest.iov_base, digest.iov_len);
 
        /* Now, write what we just extended to the log, too. */
        (void) tpm2_userspace_log(
                        log_fd,
                        /* pcr_index= */ UINT_MAX,
                        p.nv_index,
                        name,
                        &digest_values,
                        event_type,
                        description,
                        reset_marker);
 
        return 0;
#else /* HAVE_OPENSSL */
        return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "OpenSSL support is disabled.");
#endif
}
 
int tpm2_nvpcr_extend_bytes(
                Tpm2Context *c,
                const Tpm2Handle *session,
                const char *name,
                const struct iovec *data,
                const struct iovec *secret,
                Tpm2UserspaceEventType event_type,
                const char *description) {
 
        int r;
 
        r = nvpcr_extend_bytes(c, session, name, data, secret, event_type, description);
        if (r != -ENETDOWN)
                return r;
 
        /* The NvPCR isn't initialized yet, i.e. systemd-tpm2-setup hasn't run.
         * Initialize it now and extend again. This can only run in the initrd. */
        if (!in_initrd())
                return log_debug_errno(r, "NvPCR is not initialized and lazy initialization is only available in the initrd, refusing.");
 
        r = tpm2_nvpcr_initialize(c, session, name);
        if (r == -ENOKEY) /* Can't be initialized in this boot, report it as not initialized. */
                return -ENETDOWN;
        if (r < 0)
                return log_debug_errno(r, "Failed to initialize NvPCR '%s': %m", name);
 
        return nvpcr_extend_bytes(c, session, name, data, secret, event_type, description);
}
 
#if HAVE_OPENSSL
static int tpm2_context_can_nvindex(Tpm2Context *c) {
        int r;
 
        assert(c);
 
        if (!streq_ptr(c->tcti_driver, "device")) {
                log_debug("Not checking udev database, because not using 'device' TCTI.");
                return 1;
        }
 
        if (!c->tcti_param) {
                log_debug("No device specified, not checking udev database.");
                return 1;
        }
 
        _cleanup_(sd_device_unrefp) sd_device *d = NULL;
        r = sd_device_new_from_devname(&d, c->tcti_param);
        if (r < 0)
                return log_debug_errno(r, "Failed to acquire udev entry for device '%s': %m", c->tcti_param);
 
        r = device_get_property_bool(d, "TPM2_BROKEN_NVPCR");
        if (r == -ENOENT) {
                log_device_debug_errno(d, r, "No TPM2_BROKEN_NVPCR property for '%s', assuming NvPCRs work.", c->tcti_param);
                return 1;
        }
        if (r < 0)
                return log_device_debug_errno(d, r, "Failed to query TPM2_BROKEN_NVPCR for '%s': %m", c->tcti_param);
        if (r > 0) {
                log_device_debug(d, "TPM2_BROKEN_NVPCR property for '%s' explicitly set, NvPCRs do not work.", c->tcti_param);
                return 0;
        }
 
        log_device_debug(d, "TPM2_BROKEN_NVPCR property for '%s' explicitly set to false, hence NvPCRs work.", c->tcti_param);
        return 1;
}
#endif
 
/* The maximum number of times to try initializing a NvPCR before failing if PCR values change under our feet. */
#define RETRY_NVPCR_INIT_MAX 30u
 
#if HAVE_OPENSSL
/* Calculate the init policy for an NvPCR protected by a signed PCR policy:
 * PolicyAuthorize is bound to 'public' and the "initrd" policy reference. */
static int tpm2_nvpcr_calculate_signed_init_policy(
                const TPM2B_PUBLIC *public,
                TPM2B_DIGEST *ret) {
 
        TPM2B_NONCE policy_ref;
        TPM2B_DIGEST init_policy;
        int r;
 
        assert(public);
        assert(ret);
 
        tpm2_make_policy_ref(NVPCR_INIT_POLICY_REF, &policy_ref);
 
        init_policy = TPM2B_DIGEST_MAKE(NULL, SHA256_DIGEST_SIZE);
        r = tpm2_calculate_policy_authorize(public, &policy_ref, &init_policy);
        if (r < 0)
                return r;
 
        *ret = init_policy;
        return 0;
}
#endif
 
int tpm2_nvpcr_initialize(
                Tpm2Context *c,
                const Tpm2Handle *session,
                const char *name) {
 
#if HAVE_OPENSSL
        int r;
 
        assert(c);
        assert(name);
 
        r = tpm2_context_can_nvindex(c);
        if (r < 0)
                return r;
        if (r == 0)
                return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "TPM2 device does not support NvPCRs, not initializing.");
 
        _cleanup_(nvpcr_data_done) NvPCRData p = {};
        r = nvpcr_data_load(name, &p);
        if (r < 0)
                return r;
 
        /* Open + lock the log file *before* we check for the *.auth flag file. */
        _cleanup_close_ int log_fd = tpm2_userspace_log_open();
 
        _cleanup_close_ int dfd = open_mkdir("/run/systemd/nvpcr", O_CLOEXEC, 0755);
        if (dfd < 0)
                return log_debug_errno(dfd, "Failed to open directory '/run/systemd/nvpcr': %m");
 
        const char *auth_fname = strjoina(name, ".auth");
        if (faccessat(dfd, auth_fname, F_OK, AT_SYMLINK_NOFOLLOW) < 0) {
                if (errno != ENOENT)
                        return log_debug_errno(errno, "Failed to check if /run/systemd/nvpcr/%s exists: %m", auth_fname);
        } else {
                log_debug("NvPCR '%s' is already initialized.", name);
                return 0;
        }
 
        if (!in_initrd())
                return log_debug_errno(SYNTHETIC_ERRNO(ENOKEY), "NvPCR '%s' is not initialized yet and initialization is only available in the initrd, refusing.", name);
 
        r = dlopen_libcrypto(LOG_DEBUG);
        if (r < 0)
                return r;
 
        /* XXX: As NvPCRs use a write policy with PolicyAuthorize, the name algorithm and signed policy
         * algorithm must match. Currently, signed policies are restricted to SHA256, so reject anything else
         * for now. This can only be relaxed when:
         * - The various tpm2_calculate_policy_* and tpm2_digest_* functions support more than SHA256.
         * - Signed policies have a new policy algorithm field in the JSON metadata.
         * - systemd-measure has a new argument to select the policy algorithm.
         * - the name algorithm is plumbed through to tpm2_make_policy_session, tpm2_policy_authorize and
         *   find_signature.
         * - find_signature filters on the new policy algorithm field.
         *
         * Note that the policy algorithm is distinct from the signing algorithm. For PolicyAuthorize
         * signatures, the signature algorithm has to match the name algorithm of the signing key, but this
         * doesn't have to be the same as the algorithm of the signed policy. Signature algorithms are
         * currently hardcoded to SHA256 too. */
        if (p.algorithm != TPM2_ALG_SHA256)
                return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Only SHA256 is currently supported for NvPCR, refusing.");
 
        int digest_size = tpm2_hash_alg_to_size(p.algorithm);
        if (digest_size < 0)
                return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Unsupported algorithm for NvPCR, refusing.");
 
        if ((size_t) digest_size > sizeof_field(TPM2B_MAX_NV_BUFFER, buffer))
                return log_debug_errno(SYNTHETIC_ERRNO(E2BIG), "Hash function result too large for TPM, refusing.");
 
        _cleanup_(nvpcr_init_policy_done) NvPCRInitPolicy init = {};
 
        /* Load the PCR public key. Its signatures authorize the initializing write to the NvPCR via the
         * PolicyAuthorize branch of the write policy. */
        r = tpm2_nvpcr_load_pcr_public_key(/* path= */ NULL, &init.public, &init.fingerprint);
        if (r == -ENOENT)
                /* Avoid failing systemd-tpm2-setup if there is no PCR public key attached to the UKI. */
                return log_debug_errno(SYNTHETIC_ERRNO(ENOKEY),
                                       "No PCR public key available, cannot initialize NvPCR '%s'.", name);
        if (r < 0)
                return r;
 
        /* Load the signed PCR policy, which authorizes the initializing write. */
        r = tpm2_load_pcr_signature(/* path= */ NULL, &init.signature_json);
        if (r == -ENOENT)
                /* Avoid failing systemd-tpm2-setup if there are no PCR signatures attached to the UKI. */
                return log_debug_errno(SYNTHETIC_ERRNO(ENOKEY),
                                       "No signed PCR policy available, cannot initialize NvPCR '%s'.", name);
        if (r < 0)
                return log_debug_errno(r, "Failed to load PCR signature for NvPCR initialization: %m");
 
        /* Check that there's a signed policy for the initializing write at all before we allocate anything
         * on the TPM. This avoids failing systemd-tpm2-setup if there are no policies signed for the "initrd"
         * policy reference. We don't check the policy digest here: if there is a matching policy but it doesn't
         * match the current PCR state, or its signature is invalid, then that's a real error which we
         * want to report below. */
        tpm2_tpml_pcr_selection_from_mask(NVPCR_INIT_PCRMASK, TPM2_ALG_SHA256, &init.pcr_selection);
        r = find_signature(
                        init.signature_json,
                        &init.pcr_selection,
                        init.fingerprint.iov_base, init.fingerprint.iov_len,
                        NVPCR_INIT_POLICY_REF,
                        /* policy= */ NULL, /* policy_size= */ 0,
                        /* ret_signature= */ NULL, /* ret_signature_size= */ NULL);
        if (r == -ENOSTR)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOKEY),
                                       "No signed PCR policy with reference '%s' available, cannot initialize NvPCR '%s'.",
                                       NVPCR_INIT_POLICY_REF, name);
        if (r < 0)
                return r;
 
        r = tpm2_nvpcr_calculate_signed_init_policy(&init.public, &init.digest);
        if (r < 0)
                return r;
 
        _cleanup_(tpm2_handle_freep) Tpm2Handle *nv_handle = NULL;
        r = tpm2_define_nvpcr_nv_index(
                        c,
                        session,
                        p.nv_index,
                        p.algorithm,
                        &init.digest,
                        p.orderly,
                        &nv_handle);
        if (r < 0)
                return r;
 
        log_debug("Successfully acquired handle to NV index 0x%" PRIx32 ".", p.nv_index);
 
        bool reset_marker;
        for (unsigned i = RETRY_NVPCR_INIT_MAX;; i--) {
                /* Open a policy session to perform the initializing write. */
                _cleanup_(tpm2_handle_freep) Tpm2Handle *policy_session = NULL;
                r = tpm2_nvpcr_open_init_session(c, &init, &policy_session);
                if (r == -EUCLEAN) {
                        /* A PCR was extended while we submitted the policy, so this session is unusable.
                         * Same situation as below, just observed while building the policy rather than
                         * while writing. */
                        if (i > 0)
                                continue;
                }
                if (r < 0)
                        return r;
 
                _cleanup_free_ void *zero = malloc0(digest_size);
                if (!zero)
                        return log_oom_debug();
 
                reset_marker = tpm2_userspace_log_dirty(log_fd) >= 0;
 
                r = tpm2_extend_nvpcr_nv_index(
                                c,
                                p.nv_index,
                                nv_handle,
                                policy_session,
                                &IOVEC_MAKE(zero, digest_size));
                if (r == -ESTALE) {
                        /* PCR values changed under our feet. This shouldn't happen from userspace
                         * measurements because we hold the measurement log lock, but the kernel can still
                         * perform IMA measurements. */
                        tpm2_userspace_log_clean(log_fd, reset_marker);
                        if (i > 0)
                                continue;
                }
                if (r < 0)
                        return r;
 
                log_debug("Successfully performed initializing write to NvPCR '%s'.", name);
                break;
        }
 
        /* Persist the init policy digest. The extend path needs it to reconstruct the
         * TPM2_PolicyOR, and its presence doubles as an indication that this NvPCR is initialized. */
        _cleanup_free_ char *h = hexmem(init.digest.buffer, init.digest.size);
        if (!h)
                return log_oom_debug();
 
        r = write_string_file_at(dfd, auth_fname, h, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC);
        if (r < 0)
                return log_debug_errno(r, "Failed to write auth file: %m");
 
        (void) tpm2_userspace_log_clean(log_fd, reset_marker);
        log_fd = safe_close(log_fd);
 
        /* Acquire the name of the newly created index. This is done after the first write when the
         * TPMA_NV_WRITTEN flag is already set. */
        _cleanup_(Esys_Freep) TPM2B_NAME *nv_name = NULL;
        r = tpm2_get_name(c, nv_handle, &nv_name);
        if (r < 0)
                return r;
 
        /* Now also measure the initialization into PCR 9, so that there's a trace of it in regular PCRs. You
         * might wonder why PCR 9? Well, we have very few PCRs available, and PCR 9 appears to be the least
         * bad for this. It typically contains stuff that in our world is hard to predict anyway
         * (i.e. possibly some overly verbose Grub stuff, as well as all initrds – those generated on-the-fly
         * and those prepared beforehand – mangled into one), quite differently from all other PCRs we could
         * use. Moreover PCR 11 already contains most stuff from PCR 9, as it contains the same data
         * (i.e. initrds) in a more sensible fashion, clearly separated from on-the-fly generated ones. Note
         * that we only do all this measurement stuff if we are booted as UKI, and hence when PCR 11 is
         * available, but PCR 9 is not predictable. */
        _cleanup_strv_free_ char **banks = NULL;
        r = tpm2_get_good_pcr_banks_strv(c, UINT32_C(1) << TPM2_PCR_KERNEL_INITRD, &banks);
        if (r < 0)
                return log_error_errno(r, "Could not verify PCR banks: %m");
 
        _cleanup_free_ char *nv_name_h = hexmem(nv_name->name, nv_name->size);
        if (!nv_name_h)
                return log_oom_debug();
 
        _cleanup_free_ char *word = NULL;
        if (asprintf(&word, "nvpcr-init:%s:0x%x:%s", name, p.nv_index, nv_name_h) < 0)
                return log_oom();
 
        r = tpm2_pcr_extend_bytes(
                        c,
                        banks,
                        TPM2_PCR_KERNEL_INITRD,
                        &IOVEC_MAKE_STRING(word),
                        /* secret= */ NULL,
                        TPM2_EVENT_NVPCR_INIT,
                        word);
        if (r < 0)
                return log_error_errno(r, "Could not extend PCR %i: %m", TPM2_PCR_KERNEL_INITRD);
 
        return 1;
#else /* HAVE_OPENSSL */
        return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "OpenSSL support is disabled.");
#endif
}
 
int tpm2_nvpcr_read(
                Tpm2Context *c,
                const Tpm2Handle *session,
                const char *name,
                struct iovec *ret_value,
                uint32_t *ret_nv_index,
                uint64_t *ret_priority) {
 
#if HAVE_OPENSSL
        int r;
 
        assert(c);
        assert(name);
 
        if (!tpm2_nvpcr_name_is_valid(name))
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Attempt to read from NvPCR with invalid name, refusing: %s", name);
 
        _cleanup_(nvpcr_data_done) NvPCRData p = {};
        r = nvpcr_data_load(name, &p);
        if (r < 0)
                return r;
 
        /* Check if the NvPCR is already initialized */
        const char *auth_fname = strjoina("/run/systemd/nvpcr/", name, ".auth");
        r = access_nofollow(auth_fname, F_OK);
        if (r < 0) {
                if (r != -ENOENT)
                        return log_debug_errno(r, "Failed to check if '%s' exists: %m", auth_fname);
 
                /* valid, but not initialized */
                *ret_value = (struct iovec) {};
                if (ret_nv_index)
                        *ret_nv_index = p.nv_index;
                if (ret_priority)
                        *ret_priority = p.priority;
 
                return 0;
        }
 
        _cleanup_(tpm2_handle_freep) Tpm2Handle *nv_handle = NULL;
        r = tpm2_index_to_handle(
                        c,
                        p.nv_index,
                        session,
                        /* ret_name= */ NULL,
                        &nv_handle);
        if (r < 0)
                return log_debug_errno(r, "Failed to acquire handle to NV index 0x%" PRIu32 ".", p.nv_index);
 
        log_debug("Successfully acquired handle to NV index 0x%" PRIx32 ".", p.nv_index);
 
        if (r > 0) {
                r = tpm2_read_nv_index(
                                c,
                                /* session= */ NULL,
                                p.nv_index,
                                nv_handle,
                                ret_value);
                if (r < 0)
                        return r;
 
                r = 1;
        } else {
                *ret_value = (struct iovec) {};
                r = 0;
        }
 
        if (ret_nv_index)
                *ret_nv_index = p.nv_index;
        if (ret_priority)
                *ret_priority = p.priority;
 
        return r;
#else /* HAVE_OPENSSL */
        return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "OpenSSL support is disabled.");
#endif
}
 
TPM2B_DIGEST *tpm2_pcr_prediction_result_get_hash(Tpm2PCRPredictionResult *result, uint16_t alg) {
        size_t alg_idx;
 
        assert(result);
 
        alg_idx = tpm2_hash_algorithm_index(alg);
        if (alg_idx == SIZE_MAX) /* Algorithm not known? */
                return NULL;
 
        if (result->hash[alg_idx].size <= 0) /* No hash value for this algorithm? */
                return NULL;
 
        return result->hash + alg_idx;
}
 
void tpm2_pcr_prediction_done(Tpm2PCRPrediction *p) {
        assert(p);
 
        for (uint32_t pcr = 0; pcr < TPM2_PCRS_MAX; pcr++)
                ordered_set_free(p->results[pcr]);
}
 
static void tpm2_pcr_prediction_result_hash_func(const Tpm2PCRPredictionResult *banks, struct siphash *state) {
        assert(banks);
 
        for (size_t i = 0; i < TPM2_N_HASH_ALGORITHMS; i++)
                siphash24_compress_safe(banks->hash[i].buffer, banks->hash[i].size, state);
}
 
static int tpm2_pcr_prediction_result_compare_func(const Tpm2PCRPredictionResult *a, const Tpm2PCRPredictionResult *b) {
        int r;
 
        assert(a);
        assert(b);
 
        for (size_t i = 0; i < TPM2_N_HASH_ALGORITHMS; i++) {
                r = memcmp_nn(a->hash[i].buffer, a->hash[i].size,
                              b->hash[i].buffer, b->hash[i].size);
                if (r != 0)
                        return r;
        }
 
        return 0;
}
 
DEFINE_HASH_OPS_WITH_VALUE_DESTRUCTOR(
                tpm2_pcr_prediction_result_hash_ops,
                Tpm2PCRPredictionResult,
                tpm2_pcr_prediction_result_hash_func,
                tpm2_pcr_prediction_result_compare_func,
                Tpm2PCRPredictionResult,
                free);
 
static Tpm2PCRPredictionResult *find_prediction_result_by_algorithm(OrderedSet *set, Tpm2PCRPredictionResult *result, size_t alg_idx) {
        Tpm2PCRPredictionResult *f;
 
        assert(result);
        assert(alg_idx != SIZE_MAX);
 
        f = ordered_set_get(set, result); /* Full match? */
        if (f)
                return f;
 
        /* If this doesn't match full, then see if there an entry that at least matches by the relevant
         * algorithm (we are fine if predictions are "incomplete" in some algorithms) */
 
        ORDERED_SET_FOREACH(f, set)
                if (memcmp_nn(result->hash[alg_idx].buffer, result->hash[alg_idx].size,
                              f->hash[alg_idx].buffer, f->hash[alg_idx].size) == 0)
                        return f;
 
        return NULL;
}
 
bool tpm2_pcr_prediction_equal(
                Tpm2PCRPrediction *a,
                Tpm2PCRPrediction *b,
                uint16_t algorithm) {
 
        if (a == b)
                return true;
        if (!a || !b)
                return false;
 
        if (a->pcrs != b->pcrs)
                return false;
 
        size_t alg_idx = tpm2_hash_algorithm_index(algorithm);
        if (alg_idx == SIZE_MAX)
                return false;
 
        for (uint32_t pcr = 0; pcr < TPM2_PCRS_MAX; pcr++) {
                Tpm2PCRPredictionResult *banks;
 
                ORDERED_SET_FOREACH(banks, a->results[pcr])
                        if (!find_prediction_result_by_algorithm(b->results[pcr], banks, alg_idx))
                                return false;
 
                ORDERED_SET_FOREACH(banks, b->results[pcr])
                        if (!find_prediction_result_by_algorithm(a->results[pcr], banks, alg_idx))
                                return false;
        }
 
        return true;
}
 
int tpm2_pcr_prediction_to_json(
                const Tpm2PCRPrediction *prediction,
                uint16_t algorithm,
                sd_json_variant **ret) {
 
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *aj = NULL;
        int r;
 
        assert(prediction);
        assert(ret);
 
        for (uint32_t pcr = 0; pcr < TPM2_PCRS_MAX; pcr++) {
                _cleanup_(sd_json_variant_unrefp) sd_json_variant *vj = NULL;
                Tpm2PCRPredictionResult *banks;
 
                if (!BIT_SET(prediction->pcrs, pcr))
                        continue;
 
                ORDERED_SET_FOREACH(banks, prediction->results[pcr]) {
 
                        TPM2B_DIGEST *hash = tpm2_pcr_prediction_result_get_hash(banks, algorithm);
                        if (!hash)
                                continue;
 
                        r = sd_json_variant_append_arrayb(
                                        &vj,
                                        SD_JSON_BUILD_HEX(hash->buffer, hash->size));
                        if (r < 0)
                                return log_error_errno(r, "Failed to append hash variant to JSON array: %m");
                }
 
                if (!vj)
                        continue;
 
                r = sd_json_variant_append_arraybo(
                                &aj,
                                SD_JSON_BUILD_PAIR_INTEGER("pcr", pcr),
                                SD_JSON_BUILD_PAIR_VARIANT("values", vj));
                if (r < 0)
                        return log_error_errno(r, "Failed to append PCR variants to JSON array: %m");
        }
 
        if (!aj) {
                r = sd_json_variant_new_array(&aj, NULL, 0);
                if (r < 0)
                        return r;
        }
 
        *ret = TAKE_PTR(aj);
        return 0;
}
 
int tpm2_pcr_prediction_from_json(
                Tpm2PCRPrediction *prediction,
                uint16_t algorithm,
                sd_json_variant *aj) {
 
        int r;
 
        assert(prediction);
 
        size_t alg_index = tpm2_hash_algorithm_index(algorithm);
        assert(alg_index < TPM2_N_HASH_ALGORITHMS);
 
        if (!sd_json_variant_is_array(aj))
                return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "PCR variant array is not an array.");
 
        sd_json_variant *pcr;
        JSON_VARIANT_ARRAY_FOREACH(pcr, aj) {
                sd_json_variant *nr, *values;
 
                nr = sd_json_variant_by_key(pcr, "pcr");
                if (!nr)
                        return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "PCR array entry lacks PCR index field");
 
                if (!sd_json_variant_is_unsigned(nr) ||
                    sd_json_variant_unsigned(nr) >= TPM2_PCRS_MAX)
                        return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "PCR array entry PCR index is not an integer in the range 0…23");
 
                values = sd_json_variant_by_key(pcr, "values");
                if (!values)
                        return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "PCR array entry lacks values field");
 
                if (!sd_json_variant_is_array(values))
                        return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "PCR array entry values field is not an array");
 
                prediction->pcrs |= UINT32_C(1) << sd_json_variant_unsigned(nr);
 
                sd_json_variant *v;
                JSON_VARIANT_ARRAY_FOREACH(v, values) {
                        _cleanup_free_ void *buffer = NULL;
                        size_t size;
 
                        r = sd_json_variant_unhex(v, &buffer, &size);
                        if (r < 0)
                                return log_error_errno(r, "Failed to decode PCR policy array hash value");
 
                        if (size <= 0)
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "PCR policy array hash value is zero.");
 
                        if (size > sizeof_field(TPM2B_DIGEST, buffer))
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "PCR policy array hash value is too large.");
 
                        _cleanup_free_ Tpm2PCRPredictionResult *banks = new0(Tpm2PCRPredictionResult, 1);
                        if (!banks)
                                return log_oom();
 
                        memcpy(banks->hash[alg_index].buffer, buffer, size);
                        banks->hash[alg_index].size = size;
 
                        r = ordered_set_ensure_put(prediction->results + sd_json_variant_unsigned(nr), &tpm2_pcr_prediction_result_hash_ops, banks);
                        if (r == -EEXIST) /* Let's allow duplicates */
                                continue;
                        if (r < 0)
                                return log_error_errno(r, "Failed to insert result into set: %m");
 
                        TAKE_PTR(banks);
                }
        }
 
        return 0;
}
 
int tpm2_calculate_policy_super_pcr(
                Tpm2PCRPrediction *prediction,
                uint16_t algorithm,
                TPM2B_DIGEST *pcr_policy) {
 
        int r;
 
        assert_se(prediction);
        assert_se(pcr_policy);
 
        /* Start with a zero policy if not specified otherwise. */
        TPM2B_DIGEST super_pcr_policy_digest = *pcr_policy;
 
        /* First we look for all PCRs that have exactly one allowed hash value, and generate a single PolicyPCR policy from them */
        _cleanup_free_ Tpm2PCRValue *single_values = NULL;
        size_t n_single_values = 0;
        BIT_FOREACH(pcr, prediction->pcrs) {
                if (ordered_set_size(prediction->results[pcr]) != 1)
                        continue;
 
                log_debug("Including PCR %i in single value PolicyPCR expression", pcr);
 
                Tpm2PCRPredictionResult *banks = ASSERT_PTR(ordered_set_first(prediction->results[pcr]));
 
                TPM2B_DIGEST *hash = tpm2_pcr_prediction_result_get_hash(banks, algorithm);
                if (!hash)
                        continue;
 
                if (!GREEDY_REALLOC(single_values, n_single_values + 1))
                        return -ENOMEM;
 
                single_values[n_single_values++] = TPM2_PCR_VALUE_MAKE(pcr, algorithm, *hash);
        }
 
        if (n_single_values > 0) {
                /* Evolve policy based on the expected PCR value for what we found. */
                r = tpm2_calculate_policy_pcr(
                                single_values,
                                n_single_values,
                                &super_pcr_policy_digest);
                if (r < 0)
                        return r;
        }
 
        /* Now deal with the PCRs for which we have variants, i.e. more than one allowed values */
        for (uint32_t pcr = 0; pcr < TPM2_PCRS_MAX; pcr++) {
                _cleanup_free_ TPM2B_DIGEST *pcr_policy_digest_variants = NULL;
                size_t n_pcr_policy_digest_variants = 0;
                Tpm2PCRPredictionResult *banks;
 
                if (!BIT_SET(prediction->pcrs, pcr))
                        continue;
 
                if (ordered_set_size(prediction->results[pcr]) <= 1) /* We only care for PCRs with 2 or more variants in this loop */
                        continue;
 
                if (ordered_set_size(prediction->results[pcr]) > 8)
                        return log_error_errno(SYNTHETIC_ERRNO(E2BIG), "PCR policies with more than 8 alternatives per PCR are currently not supported.");
 
                ORDERED_SET_FOREACH(banks, prediction->results[pcr]) {
                        /* Start from the super PCR policy from the previous PCR we looked at so far. */
                        TPM2B_DIGEST pcr_policy_digest = super_pcr_policy_digest;
 
                        TPM2B_DIGEST *hash = tpm2_pcr_prediction_result_get_hash(banks, algorithm);
                        if (!hash)
                                continue;
 
                        /* Evolve it based on the expected PCR value for this PCR */
                        r = tpm2_calculate_policy_pcr(
                                        &TPM2_PCR_VALUE_MAKE(
                                                        pcr,
                                                        algorithm,
                                                        *hash),
                                        /* n_pcr_values= */ 1,
                                        &pcr_policy_digest);
                        if (r < 0)
                                return r;
 
                        /* Store away this new variant */
                        if (!GREEDY_REALLOC(pcr_policy_digest_variants, n_pcr_policy_digest_variants + 1))
                                return log_oom();
 
                        pcr_policy_digest_variants[n_pcr_policy_digest_variants++] = pcr_policy_digest;
 
                        log_debug("Calculated PCR policy variant %zu for PCR %" PRIu32, n_pcr_policy_digest_variants, pcr);
                }
 
                assert_se(n_pcr_policy_digest_variants >= 2);
                assert_se(n_pcr_policy_digest_variants <= 8);
 
                /* Now combine all our variant into one OR policy */
                r = tpm2_calculate_policy_or(
                                pcr_policy_digest_variants,
                                n_pcr_policy_digest_variants,
                                &super_pcr_policy_digest);
                if (r < 0)
                        return r;
 
                log_debug("Combined %zu variants in OR policy.", n_pcr_policy_digest_variants);
        }
 
        *pcr_policy = super_pcr_policy_digest;
        return 0;
}
 
int tpm2_policy_super_pcr(
                Tpm2Context *c,
                const Tpm2Handle *session,
                const Tpm2PCRPrediction *prediction,
                uint16_t algorithm) {
 
        int r;
 
        assert_se(c);
        assert_se(session);
        assert_se(prediction);
 
        TPM2B_DIGEST previous_policy_digest = TPM2B_DIGEST_MAKE(NULL, TPM2_SHA256_DIGEST_SIZE);
 
        uint32_t single_value_pcrs = 0;
 
        /* Look for all PCRs that have only a singled allowed hash value, and synthesize a single PolicyPCR policy item for them */
        for (uint32_t pcr = 0; pcr < TPM2_PCRS_MAX; pcr++) {
                if (!BIT_SET(prediction->pcrs, pcr))
                        continue;
 
                if (ordered_set_size(prediction->results[pcr]) != 1)
                        continue;
 
                log_debug("Including PCR %" PRIu32 " in single value PolicyPCR expression", pcr);
 
                single_value_pcrs |= UINT32_C(1) << pcr;
        }
 
        if (single_value_pcrs != 0) {
                TPML_PCR_SELECTION pcr_selection;
                tpm2_tpml_pcr_selection_from_mask(single_value_pcrs, algorithm, &pcr_selection);
 
                _cleanup_free_ TPM2B_DIGEST *current_policy_digest = NULL;
                r = tpm2_policy_pcr(
                                c,
                                session,
                                &pcr_selection,
                                &current_policy_digest);
                /* -EUCLEAN means some PCR got extended while we were submitting the policy. That's
                 * transient, so only log at debug level and let the caller restart the session. */
                if (r == -EUCLEAN)
                        return log_debug_errno(r, "PCR state changed while submitting the combined PolicyPCR expression, session needs to be restarted.");
                if (r < 0)
                        return log_error_errno(r, "Failed to submit PCR policy to TPM: %m");
 
                previous_policy_digest = *current_policy_digest;
        }
 
        for (uint32_t pcr = 0; pcr < TPM2_PCRS_MAX; pcr++) {
                size_t n_branches;
 
                if (!BIT_SET(prediction->pcrs, pcr))
                        continue;
 
                n_branches = ordered_set_size(prediction->results[pcr]);
                if (n_branches < 1 || n_branches > 8)
                        return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Number of variants per PCR not in range 1…8");
 
                if (n_branches == 1) /* Single choice PCRs are already covered by the loop above */
                        continue;
 
                log_debug("Submitting PCR/OR policy for PCR %" PRIu32, pcr);
 
                TPML_PCR_SELECTION pcr_selection;
                tpm2_tpml_pcr_selection_from_mask(UINT32_C(1) << pcr, algorithm, &pcr_selection);
 
                _cleanup_free_ TPM2B_DIGEST *current_policy_digest = NULL;
                r = tpm2_policy_pcr(
                                c,
                                session,
                                &pcr_selection,
                                &current_policy_digest);
                if (r == -EUCLEAN)
                        return log_debug_errno(r, "PCR state changed while submitting the PolicyPCR expression for PCR %" PRIu32 ", session needs to be restarted.", pcr);
                if (r < 0)
                        return log_error_errno(r, "Failed to submit PCR policy to TPM: %m");
 
                _cleanup_free_ TPM2B_DIGEST *branches = NULL;
                branches = new0(TPM2B_DIGEST, n_branches);
                if (!branches)
                        return log_oom();
 
                Tpm2PCRPredictionResult *banks;
                size_t i = 0;
                ORDERED_SET_FOREACH(banks, prediction->results[pcr]) {
                        TPM2B_DIGEST pcr_policy_digest = previous_policy_digest;
 
                        TPM2B_DIGEST *hash = tpm2_pcr_prediction_result_get_hash(banks, algorithm);
                        if (!hash)
                                continue;
 
                        /* Evolve it based on the expected PCR value for this PCR */
                        r = tpm2_calculate_policy_pcr(
                                        &TPM2_PCR_VALUE_MAKE(