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 8001–9000 of 12,273

        new_handle->flush = false; /* This is a persistent NV index, don't flush hence */
 
        rc = sym_Esys_NV_DefineSpace(
                        c->esys_context,
                        /* authHandle= */ ESYS_TR_RH_OWNER,
                        /* shandle1= */ session ? session->esys_handle : ESYS_TR_PASSWORD,
                        /* shandle2= */ ESYS_TR_NONE,
                        /* shandle3= */ ESYS_TR_NONE,
                        /* auth= */ NULL,
                        &public_info,
                        &new_handle->esys_handle);
        if (rc == TPM2_RC_NV_SPACE) {
                /* Remember that we ran out of NV index space for this orderly mode, so that we don't keep
                 * retrying the (doomed) allocation until reboot. */
                r = touch(exhausted_flag);
                if (r < 0)
                        log_debug_errno(r, "Failed to create %s flag file, ignoring: %m", exhausted_flag);
                return log_debug_errno(SYNTHETIC_ERRNO(ENOBUFS),
                                        "NV index space on TPM exhausted, cannot allocate NvPCR.");
        }
        if (rc == TPM2_RC_NV_DEFINED) {
                /* Someone else defined the index after we checked for it above, which is possible as the
                 * measurement log lock is only taken best-effort. Treat it like we found it above. */
                log_debug("NV index 0x%" PRIx32 " was defined concurrently, checking it again.", nv_index);
 
                r = tpm2_reuse_or_redefine_nvpcr_nv_index(c, session, /* exhausted= */ false, nv_index, &public_info, &handle);
                if (r < 0)
                        return r;
 
                if (ret_nv_handle)
                        *ret_nv_handle = TAKE_PTR(handle);
 
                return r;
        }
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                        "Failed to allocate NV index: %s", sym_Tss2_RC_Decode(rc));
 
        log_debug("NV index 0x%" PRIx32 " successfully allocated for NvPCR.", nv_index);
 
        if (ret_nv_handle)
                *ret_nv_handle = TAKE_PTR(new_handle);
 
        return 1;
}
 
static int tpm2_extend_nvpcr_nv_index(
                Tpm2Context *c,
                TPM2_HANDLE nv_index,
                const Tpm2Handle *nv_handle,
                const Tpm2Handle *policy_session,
                const struct iovec *digest) {
 
        TPM2_RC rc;
 
        assert(c);
        assert(nv_index);
        assert(nv_handle);
        assert(policy_session);
        assert(iovec_is_set(digest));
 
        if (digest->iov_len > sizeof_field(TPM2B_MAX_NV_BUFFER, buffer))
                return log_debug_errno(SYNTHETIC_ERRNO(E2BIG), "Hash value to extend too long.");
 
        TPM2B_MAX_NV_BUFFER buf = {
                .size = digest->iov_len,
        };
        memcpy(buf.buffer, digest->iov_base, digest->iov_len);
 
        rc = sym_Esys_NV_Extend(
                        c->esys_context,
                        /* authHandle= */ nv_handle->esys_handle,
                        /* nvIndex= */ nv_handle->esys_handle,
                        /* shandle1= */ policy_session->esys_handle,
                        /* shandle2= */ ESYS_TR_NONE,
                        /* shandle3= */ ESYS_TR_NONE,
                        &buf);
        if (rc == TPM2_RC_PCR_CHANGED)
                return log_debug_errno(SYNTHETIC_ERRNO(ESTALE),
                                       "PCR changed while extending NV index.");
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to extend NV index: %s", sym_Tss2_RC_Decode(rc));
 
        if (DEBUG_LOGGING) {
                _cleanup_free_ char *h = NULL;
                h = hexmem(digest->iov_base, digest->iov_len);
                log_debug("Written hash %s to NV index 0x%x", strnull(h), nv_index);
        }
 
        return 0;
}
 
#endif
 
int tpm2_read_nv_index(
                Tpm2Context *c,
                const Tpm2Handle *session,
                TPM2_HANDLE nv_index,
                const Tpm2Handle *nv_handle,
                struct iovec *ret_value) {
 
        TPM2_RC rc;
        int r;
 
        assert(c);
        assert(nv_index);
        assert(nv_handle);
 
        _cleanup_(Esys_Freep) TPM2B_NV_PUBLIC *nv_public = NULL;
        r = tpm2_read_nv_public(c, /* session= */ NULL, nv_handle, &nv_public, /* ret_name= */ NULL);
        if (r < 0)
                return r;
 
        size_t data_size = nv_public->nvPublic.dataSize;
        log_debug("Read public info for nvindex 0x%x, value size is %zu", nv_index, data_size);
 
        /* TPM2_NV_Read returns the data in a TPM2B_MAX_NV_BUFFER, whose maximum size is bounded by the value
         * of the TPM_PT_NV_BUFFER_MAX property. This limits the amount of data that can be read in a single
         * command. As this limit can be smaller than the size of the NV index payload (particularly if the
         * payload contains a X509 certificate with a RSA public key), we read the contents in chunks no
         * larger than what the TPM reports it can return in a single command. */
 
        /* Never ask for more than the buffer the TPM library hands back can hold. */
        size_t max_buffer_size = MIN((size_t) c->max_nv_buffer_size, (size_t) TPM2_MAX_NV_BUFFER_SIZE);
        assert(max_buffer_size > 0); /* tpm2_cache_capabilities sets this to 512 if the TPM reported 0. */
 
        _cleanup_(iovec_done) struct iovec result = {};
        if (data_size > 0) {
                result.iov_base = malloc(data_size);
                if (!result.iov_base)
                        return log_oom_debug();
        }
 
        while (result.iov_len < data_size) {
                size_t chunk_size = MIN(data_size - result.iov_len, max_buffer_size);
 
                _cleanup_(Esys_Freep) TPM2B_MAX_NV_BUFFER *chunk = NULL;
                rc = sym_Esys_NV_Read(
                                c->esys_context,
                                /* authHandle= */ nv_handle->esys_handle,
                                /* nvIndex= */ nv_handle->esys_handle,
                                /* shandle1= */ session ? session->esys_handle : ESYS_TR_PASSWORD,
                                /* shandle2= */ ESYS_TR_NONE,
                                /* shandle3= */ ESYS_TR_NONE,
                                chunk_size,
                                /* offset= */ result.iov_len,
                                &chunk);
                if (rc != TSS2_RC_SUCCESS)
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                               "Failed read contents of nvindex 0x%x: %s", nv_index, sym_Tss2_RC_Decode(rc));
                assert(chunk);
                if (chunk->size != chunk_size)
                        /* On success, TPM2_NV_Read should return exactly what we asked for. */
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                               "TPM returned an unexpected amount of data (%" PRIu16 ") reading nvindex 0x%x.",
                                               chunk->size, nv_index);
 
                memcpy((uint8_t*) result.iov_base + result.iov_len, chunk->buffer, chunk->size);
                result.iov_len += chunk->size;
        }
 
        if (ret_value)
                *ret_value = TAKE_STRUCT(result);
 
        return 0;
}
 
int tpm2_seal_data(
                Tpm2Context *c,
                const struct iovec *data,
                const Tpm2Handle *primary_handle,
                const Tpm2Handle *encryption_session,
                const TPM2B_DIGEST *policy,
                struct iovec *ret_public,
                struct iovec *ret_private) {
 
        int r;
 
        assert(c);
        assert(data);
        assert(primary_handle);
        POINTER_MAY_BE_NULL(policy);
 
        /* This is a generic version of tpm2_seal(), that doesn't imply any policy or any specific
         * combination of the two keypairs in their marshalling. tpm2_seal() is somewhat specific to the FDE
         * usecase. We probably should migrate tpm2_seal() to use tpm2_seal_data() eventually. */
 
        if (data->iov_len >= sizeof_field(TPMS_SENSITIVE_CREATE, data.buffer))
                return -E2BIG;
 
        TPMT_PUBLIC hmac_template = {
                .type = TPM2_ALG_KEYEDHASH,
                .nameAlg = TPM2_ALG_SHA256,
                .objectAttributes = TPMA_OBJECT_FIXEDTPM | TPMA_OBJECT_FIXEDPARENT,
                .parameters.keyedHashDetail.scheme.scheme = TPM2_ALG_NULL,
                .unique.keyedHash.size = data->iov_len,
                .authPolicy = policy ? *policy : TPM2B_DIGEST_MAKE(NULL, TPM2_SHA256_DIGEST_SIZE),
        };
 
        TPMS_SENSITIVE_CREATE hmac_sensitive = {
                .data.size = hmac_template.unique.keyedHash.size,
        };
 
        CLEANUP_ERASE(hmac_sensitive);
 
        memcpy_safe(hmac_sensitive.data.buffer, data->iov_base, data->iov_len);
 
        _cleanup_(Esys_Freep) TPM2B_PUBLIC *public = NULL;
        _cleanup_(Esys_Freep) TPM2B_PRIVATE *private = NULL;
        r = tpm2_create(c, primary_handle, encryption_session, &hmac_template, &hmac_sensitive, &public, &private);
        if (r < 0)
                return r;
 
        _cleanup_(iovec_done) struct iovec public_blob = {}, private_blob = {};
 
        r = tpm2_marshal_private(private, &private_blob.iov_base, &private_blob.iov_len);
        if (r < 0)
                return r;
 
        r = tpm2_marshal_public(public, &public_blob.iov_base, &public_blob.iov_len);
        if (r < 0)
                return r;
 
        if (ret_public)
                *ret_public = TAKE_STRUCT(public_blob);
        if (ret_private)
                *ret_private = TAKE_STRUCT(private_blob);
 
        return 0;
}
 
int tpm2_unseal_data(
                Tpm2Context *c,
                const struct iovec *public_blob,
                const struct iovec *private_blob,
                const Tpm2Handle *primary_handle,
                const Tpm2Handle *policy_session,
                const Tpm2Handle *encryption_session,
                struct iovec *ret_data) {
 
        TSS2_RC rc;
        int r;
 
        assert(c);
        assert(public_blob);
        assert(private_blob);
        assert(primary_handle);
        assert(ret_data);
 
        TPM2B_PUBLIC public;
        r = tpm2_unmarshal_public(public_blob->iov_base, public_blob->iov_len, &public);
        if (r < 0)
                return r;
 
        TPM2B_PRIVATE private;
        r = tpm2_unmarshal_private(private_blob->iov_base, private_blob->iov_len, &private);
        if (r < 0)
                return r;
 
        _cleanup_(tpm2_handle_freep) Tpm2Handle *what = NULL;
        r = tpm2_load(c, primary_handle, NULL, &public, &private, &what);
        if (r < 0)
                return r;
 
        _cleanup_(tpm2b_sensitive_data_erase_and_esys_freep) TPM2B_SENSITIVE_DATA* unsealed = NULL;
        rc = sym_Esys_Unseal(
                        c->esys_context,
                        what->esys_handle,
                        policy_session ? policy_session->esys_handle : ESYS_TR_NONE,
                        encryption_session ? encryption_session->esys_handle : ESYS_TR_NONE,
                        ESYS_TR_NONE,
                        &unsealed);
        if (rc == TPM2_RC_PCR_CHANGED)
                return log_debug_errno(SYNTHETIC_ERRNO(ESTALE),
                                       "PCR changed while unsealing.");
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to unseal data: %s", sym_Tss2_RC_Decode(rc));
 
        _cleanup_(iovec_done) struct iovec d = {
                .iov_base = memdup(unsealed->buffer, unsealed->size),
                .iov_len = unsealed->size,
        };
        if (!d.iov_base)
                return log_oom_debug();
 
        *ret_data = TAKE_STRUCT(d);
        return 0;
}
#endif /* HAVE_TPM2 */
 
int tpm2_list_devices(bool legend, bool quiet) {
#if HAVE_TPM2
        _cleanup_(table_unrefp) Table *t = NULL;
        _cleanup_closedir_ DIR *d = NULL;
        int r;
 
        r = dlopen_tpm2(LOG_ERR);
        if (r < 0)
                return r;
 
        t = table_new("path", "device", "driver");
        if (!t)
                return log_oom();
 
        table_set_header(t, legend);
 
        d = opendir("/sys/class/tpmrm");
        if (!d) {
                log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_ERR, errno, "Failed to open %s: %m", "/sys/class/tpmrm");
                if (errno != ENOENT)
                        return -errno;
        } else {
                for (;;) {
                        _cleanup_free_ char *device_path = NULL, *device = NULL, *driver_path = NULL, *driver = NULL, *node = NULL;
                        struct dirent *de;
 
                        de = readdir_no_dot(d);
                        if (!de)
                                break;
 
                        device_path = path_join("/sys/class/tpmrm", de->d_name, "device");
                        if (!device_path)
                                return log_oom();
 
                        r = readlink_malloc(device_path, &device);
                        if (r < 0)
                                log_debug_errno(r, "Failed to read device symlink %s, ignoring: %m", device_path);
                        else {
                                driver_path = path_join(device_path, "driver");
                                if (!driver_path)
                                        return log_oom();
 
                                r = readlink_malloc(driver_path, &driver);
                                if (r < 0)
                                        log_debug_errno(r, "Failed to read driver symlink %s, ignoring: %m", driver_path);
                        }
 
                        node = path_join("/dev", de->d_name);
                        if (!node)
                                return log_oom();
 
                        r = table_add_many(
                                        t,
                                        TABLE_PATH, node,
                                        TABLE_STRING, device ? last_path_component(device) : NULL,
                                        TABLE_STRING, driver ? last_path_component(driver) : NULL);
                        if (r < 0)
                                return table_log_add_error(r);
                }
        }
 
        if (table_isempty(t) && !quiet) {
                log_info("No suitable TPM2 devices found.");
                return 0;
        }
 
        return table_print_or_warn(t);
#else
        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
                               "TPM2 not supported on this build.");
#endif
}
 
int tpm2_find_device_auto(char **ret) {
#if HAVE_TPM2
        _cleanup_closedir_ DIR *d = NULL;
        int r;
 
        r = dlopen_tpm2(LOG_DEBUG);
        if (r < 0)
                return r;
 
        d = opendir("/sys/class/tpmrm");
        if (!d) {
                log_debug_errno(errno, "Failed to open %s: %m", "/sys/class/tpmrm");
                if (errno != ENOENT)
                        return -errno;
        } else {
                _cleanup_free_ char *node = NULL;
 
                for (;;) {
                        struct dirent *de;
 
                        de = readdir_no_dot(d);
                        if (!de)
                                break;
 
                        if (node)
                                return log_debug_errno(SYNTHETIC_ERRNO(ENOTUNIQ),
                                                       "More than one TPM2 (tpmrm) device found.");
 
                        node = path_join("/dev", de->d_name);
                        if (!node)
                                return log_oom_debug();
                }
 
                if (node) {
                        *ret = TAKE_PTR(node);
                        return 0;
                }
        }
 
        return log_debug_errno(SYNTHETIC_ERRNO(ENODEV), "No TPM2 (tpmrm) device found.");
#else
        return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
                               "TPM2 not supported on this build.");
#endif
}
 
#if HAVE_TPM2
const uint16_t tpm2_hash_algorithms[] = {
        TPM2_ALG_SHA1,
        TPM2_ALG_SHA256,
        TPM2_ALG_SHA384,
        TPM2_ALG_SHA512,
        0,
};
 
assert_cc(ELEMENTSOF(tpm2_hash_algorithms) == TPM2_N_HASH_ALGORITHMS + 1);
 
static size_t tpm2_hash_algorithm_index(uint16_t algorithm) {
        for (size_t i = 0; i < TPM2_N_HASH_ALGORITHMS; i++)
                if (tpm2_hash_algorithms[i] == algorithm)
                        return i;
 
        return SIZE_MAX;
}
 
static int json_dispatch_tpm2_algorithm(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
        uint16_t *algorithm = ASSERT_PTR(userdata);
        int r;
 
        r = tpm2_hash_alg_from_string(sd_json_variant_string(variant));
        if (r < 0 || tpm2_hash_algorithm_index(r) == SIZE_MAX)
                return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "Invalid hash algorithm: %s", sd_json_variant_string(variant));
 
        *algorithm = r;
        return 0;
}
 
static const char* tpm2_userspace_event_type_table[_TPM2_USERSPACE_EVENT_TYPE_MAX] = {
        [TPM2_EVENT_PHASE]           = "phase",
        [TPM2_EVENT_FILESYSTEM]      = "filesystem",
        [TPM2_EVENT_VOLUME_KEY]      = "volume-key",
        [TPM2_EVENT_MACHINE_ID]      = "machine-id",
        [TPM2_EVENT_PRODUCT_ID]      = "product-id",
        [TPM2_EVENT_KEYSLOT]         = "keyslot",
        [TPM2_EVENT_NVPCR_INIT]      = "nvpcr-init",
        [TPM2_EVENT_NVPCR_SEPARATOR] = "nvpcr-separator",
        [TPM2_EVENT_DM_VERITY]       = "dm-verity",
        [TPM2_EVENT_IMDS_USERDATA]   = "imds-userdata",
        [TPM2_EVENT_OS_SEPARATOR]    = "os-separator",
        [TPM2_EVENT_LOGIN]           = "login",
};
 
DEFINE_STRING_TABLE_LOOKUP(tpm2_userspace_event_type, Tpm2UserspaceEventType);
 
const char* tpm2_userspace_log_path(void) {
        return secure_getenv("SYSTEMD_MEASURE_LOG_USERSPACE") ?: "/run/log/systemd/tpm2-measure.log";
}
 
const char* tpm2_firmware_log_path(void) {
        return secure_getenv("SYSTEMD_MEASURE_LOG_FIRMWARE") ?: "/sys/kernel/security/tpm0/binary_bios_measurements";
}
 
#if HAVE_OPENSSL
static int tpm2_userspace_log_open(void) {
        _cleanup_close_ int fd = -EBADF;
        const char *e;
        int r;
 
        e = tpm2_userspace_log_path();
        (void) mkdir_parents(e, 0755);
 
        /* We use access mode 0600 here (even though the measurements should not strictly be confidential),
         * because we use BSD file locking on it, and if anyone but root can access the file they can also
         * lock it, which we want to avoid. */
        fd = open(e, O_CREAT|O_WRONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
        if (fd < 0)
                return log_debug_errno(errno, "Failed to open TPM log file '%s' for writing, ignoring: %m", e);
 
        if (flock(fd, LOCK_EX) < 0)
                return log_debug_errno(errno, "Failed to lock TPM log file '%s', ignoring: %m", e);
 
        r = fd_verify_regular(fd);
        if (r < 0)
                return log_debug_errno(r, "TPM log file '%s' is not regular, ignoring: %m", e);
 
        return TAKE_FD(fd);
}
 
static int tpm2_userspace_log_dirty(int fd) {
        struct stat st;
 
        if (fd < 0) /* Apparently tpm2_local_log_open() failed earlier, let's not complain again */
                return 0;
 
        /* We set the sticky bit when we are about to append to the log file. We'll unset it afterwards
         * again. If we manage to take a lock on a file that has it set we know we didn't write it fully and
         * it is corrupted. We return -ESTALE then; callers shall not reset the marker when they are done,
         * so that the incompleteness remains detectable. Ideally we'd like to use user xattrs for this, but
         * unfortunately tmpfs (which is our assumed backend fs) doesn't know user xattrs. */
 
        if (fstat(fd, &st) < 0)
                return log_debug_errno(errno, "Failed to fstat TPM log file, ignoring: %m");
 
        if (st.st_mode & S_ISVTX)
                return log_debug_errno(SYNTHETIC_ERRNO(ESTALE), "TPM log file aborted, ignoring.");
 
        if (fchmod(fd, 0600 | S_ISVTX) < 0)
                return log_debug_errno(errno, "Failed to chmod() TPM log file, ignoring: %m");
 
        return 0;
}
 
static int tpm2_userspace_log_clean(int fd, bool reset_marker) {
        int r;
 
        if (fd < 0) /* Apparently tpm2_local_log_open() failed earlier, let's not complain again */
                return 0;
 
        if (fsync(fd) < 0)
                return log_debug_errno(errno, "Failed to sync JSON data: %m");
 
        /* If the dirty marker was already set when we acquired the log, an earlier writer died before
         * writing its record, i.e. the log is missing a record. Keep the marker then, so that the
         * incompleteness remains detectable. */
        if (!reset_marker)
                return 0;
 
        /* Unset S_ISVTX again */
        if (fchmod(fd, 0600) < 0)
                return log_debug_errno(errno, "Failed to chmod() TPM log file, ignoring: %m");
 
        r = fsync_full(fd);
        if (r < 0)
                return log_debug_errno(r, "Failed to sync JSON log: %m");
 
        return 0;
}
 
static int tpm2_userspace_log(
                int fd,
                unsigned pcr_index,
                uint32_t nv_index,
                const char *nv_index_name,
                const TPML_DIGEST_VALUES *values,
                Tpm2UserspaceEventType event_type,
                const char *description,
                bool reset_marker) {
 
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL, *array = NULL;
        _cleanup_free_ char *f = NULL;
        sd_id128_t boot_id;
        int r;
 
        assert(values);
        assert(values->count > 0);
 
        /* We maintain a local PCR measurement log. This implements a subset of the TCG Canonical Event Log
         * Format – the JSON flavour –
         * (https://trustedcomputinggroup.org/resource/canonical-event-log-format/), but departs in certain
         * ways from it, specifically:
         *
         * - We don't write out a recnum. It's a bit too vaguely defined which means we'd have to read
         *   through the whole logs (include firmware logs) before knowing what the next value is we should
         *   use. Hence we simply don't write this out as append-time, and instead expect a consumer to add
         *   it in when it uses the data.
         *
         * - We write this out in RFC 7464 application/json-seq rather than as a JSON array. Writing this as
         *   JSON array would mean that for each appending we'd have to read the whole log file fully into
         *   memory before writing it out again. We prefer a strictly append-only write pattern however. (RFC
         *   7464 is what jq --seq eats.) Conversion into a proper JSON array is trivial.
         *
         * It should be possible to convert this format in a relatively straight-forward way into the
         * official TCG Canonical Event Log Format on read, by simply adding in a few more fields that can be
         * determined from the full dataset.
         *
         * We set the 'content_type' field to "systemd" to make clear this data is generated by us, and
         * include various interesting fields in the 'content' subobject, including a CLOCK_BOOTTIME
         * timestamp which can be used to order this measurement against possibly other measurements
         * independently done by other subsystems on the system.
         */
 
        if (fd < 0) /* Apparently tpm2_local_log_open() failed earlier, let's not complain again */
                return 0;
 
        r = dlopen_libcrypto(LOG_DEBUG);
        if (r < 0)
                return r;
 
        for (size_t i = 0; i < values->count; i++) {
                const EVP_MD *implementation;
                const char *a;
 
                assert_se(a = tpm2_hash_alg_to_string(values->digests[i].hashAlg));
                assert_se(implementation = sym_EVP_get_digestbyname(a));
 
                r = sd_json_variant_append_arraybo(
                                &array,
                                SD_JSON_BUILD_PAIR_STRING("hashAlg", a),
                                SD_JSON_BUILD_PAIR_HEX("digest", &values->digests[i].digest, sym_EVP_MD_get_size(implementation)));
                if (r < 0)
                        return log_debug_errno(r, "Failed to append digest object to JSON array: %m");
        }
 
        assert(array);
 
        r = sd_id128_get_boot(&boot_id);
        if (r < 0)
                return log_debug_errno(r, "Failed to acquire boot ID: %m");
 
        r = sd_json_buildo(
                        &v,
                        SD_JSON_BUILD_PAIR_CONDITION(pcr_index != UINT_MAX, "pcr", SD_JSON_BUILD_UNSIGNED(pcr_index)),
                        SD_JSON_BUILD_PAIR_CONDITION(nv_index != UINT32_MAX, "nv_index", SD_JSON_BUILD_UNSIGNED(nv_index)),
                        SD_JSON_BUILD_PAIR_VARIANT("digests", array),
                        SD_JSON_BUILD_PAIR_STRING("content_type", "systemd"),
                        SD_JSON_BUILD_PAIR("content", SD_JSON_BUILD_OBJECT(
                                                           SD_JSON_BUILD_PAIR_CONDITION(!!nv_index_name, "nvIndexName", SD_JSON_BUILD_STRING(nv_index_name)),
                                                           SD_JSON_BUILD_PAIR_CONDITION(!!description, "string", SD_JSON_BUILD_STRING(description)),
                                                           SD_JSON_BUILD_PAIR_ID128("bootId", boot_id),
                                                           SD_JSON_BUILD_PAIR_UNSIGNED("timestamp", now(CLOCK_BOOTTIME)),
                                                           SD_JSON_BUILD_PAIR_CONDITION(event_type >= 0, "eventType", SD_JSON_BUILD_STRING(tpm2_userspace_event_type_to_string(event_type))))));
        if (r < 0)
                return log_debug_errno(r, "Failed to build log record JSON: %m");
 
        r = sd_json_variant_format(v, SD_JSON_FORMAT_SEQ, &f);
        if (r < 0)
                return log_debug_errno(r, "Failed to format JSON: %m");
 
        if (lseek(fd, 0, SEEK_END) < 0)
                return log_debug_errno(errno, "Failed to seek to end of JSON log: %m");
 
        r = loop_write(fd, f, SIZE_MAX);
        if (r < 0)
                return log_debug_errno(r, "Failed to write JSON data to log: %m");
 
        r = tpm2_userspace_log_clean(fd, reset_marker);
        if (r < 0)
                return r;
 
        return 1;
}
#endif
 
int tpm2_pcr_extend_bytes(
                Tpm2Context *c,
                char **banks,
                unsigned pcr_index,
                const struct iovec *data,
                const struct iovec *secret,
                Tpm2UserspaceEventType event_type,
                const char *description) {
 
#if HAVE_OPENSSL
        _cleanup_close_ int log_fd = -EBADF;
        TPML_DIGEST_VALUES values = {};
        TSS2_RC rc;
        int r;
 
        assert(c);
        assert(iovec_is_valid(data));
        assert(iovec_is_valid(secret));
 
        if (pcr_index >= TPM2_PCRS_MAX)
                return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Can't measure into unsupported PCR %u, refusing.", pcr_index);
 
        if (!iovec_is_set(data))
                data = &iovec_empty;
 
        if (strv_isempty(banks))
                return 0;
 
        r = dlopen_libcrypto(LOG_DEBUG);
        if (r < 0)
                return r;
 
        STRV_FOREACH(bank, banks) {
                const EVP_MD *implementation;
                int id;
 
                assert_se(implementation = sym_EVP_get_digestbyname(*bank));
 
                if (values.count >= ELEMENTSOF(values.digests))
                        return log_debug_errno(SYNTHETIC_ERRNO(E2BIG), "Too many banks selected.");
 
                if ((size_t) sym_EVP_MD_get_size(implementation) > sizeof(values.digests[values.count].digest))
                        return log_debug_errno(SYNTHETIC_ERRNO(E2BIG), "Hash result too large for TPM2.");
 
                id = tpm2_hash_alg_from_string(sym_EVP_MD_get0_name(implementation));
                if (id < 0)
                        return log_debug_errno(id, "Can't map hash name to TPM2.");
 
                values.digests[values.count].hashAlg = id;
 
                /* So here's a twist: sometimes we want to measure secrets (e.g. root file system volume
                 * key), but we'd rather not leak a literal hash of the secret to the TPM (given that the
                 * wire is unprotected, and some other subsystem might use the simple, literal hash of the
                 * secret for other purposes, maybe because it needs a shorter secret derived from it for
                 * some unrelated purpose, who knows). Hence we instead measure an HMAC signature of a
                 * private non-secret string instead. */
                if (iovec_is_set(secret) > 0) {
                        if (!sym_HMAC(implementation, secret->iov_base, secret->iov_len, data->iov_base, data->iov_len, (unsigned char*) &values.digests[values.count].digest, 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, (unsigned char*) &values.digests[values.count].digest, NULL, implementation, NULL) != 1)
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Failed to hash data to measure.");
 
                values.count++;
        }
 
        /* 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();
 
        bool reset_marker = tpm2_userspace_log_dirty(log_fd) >= 0;
        rc = sym_Esys_PCR_Extend(
                        c->esys_context,
                        ESYS_TR_PCR0 + pcr_index,
                        ESYS_TR_PASSWORD,
                        ESYS_TR_NONE,
                        ESYS_TR_NONE,
                        &values);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(
                                SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                "Failed to measure into PCR %u: %s",
                                pcr_index,
                                sym_Tss2_RC_Decode(rc));
 
        /* Now, write what we just extended to the log, too. */
        (void) tpm2_userspace_log(
                        log_fd,
                        pcr_index,
                        /* nv_index= */ UINT32_MAX,
                        /* nv_index_name= */ NULL,
                        &values,
                        event_type,
                        description,
                        reset_marker);
 
        return 0;
#else /* HAVE_OPENSSL */
        return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "OpenSSL support is disabled.");
#endif
}
 
typedef struct NvPCRData {
        char *name;
        uint16_t algorithm;
        uint32_t nv_index;
        uint64_t priority;
        bool orderly;
} NvPCRData;
 
static void nvpcr_data_done(NvPCRData *d) {
        assert(d);
 
        free(d->name);
}
 
static int nvpcr_data_load(const char *name, NvPCRData *ret) {
        int r;
 
        assert(ret);
 
        if (!tpm2_nvpcr_name_is_valid(name))
                return -EINVAL;
 
        const char *fname = strjoina(name, ".nvpcr");
 
        _cleanup_free_ char *path = NULL;
        _cleanup_fclose_ FILE *f = NULL;
        r = search_and_fopen_nulstr(fname, "re", /* root= */ NULL, CONF_PATHS_NULSTR("nvpcr"), &f, &path);
        if (r < 0)
                return log_debug_errno(r, "Failed to open NvPCR definition '%s': %m", fname);
 
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
        r = sd_json_parse_file(
                        f,
                        path,
                        /* flags= */ 0,
                        &v,
                        /* reterr_line= */ NULL,
                        /* reterr_column= */ NULL);
        if (r < 0)
                return log_debug_errno(r, "Failed to load '%s': %m", path);
 
        static const sd_json_dispatch_field dispatch_table[] = {
                { "name",      SD_JSON_VARIANT_STRING,        sd_json_dispatch_string,      offsetof(NvPCRData, name),      SD_JSON_MANDATORY },
                { "algorithm", _SD_JSON_VARIANT_TYPE_INVALID, json_dispatch_tpm2_algorithm, offsetof(NvPCRData, algorithm), 0                 },
                { "nvIndex",   _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint32,      offsetof(NvPCRData, nv_index),  SD_JSON_MANDATORY },
                { "priority",  _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint64,      offsetof(NvPCRData, priority),  0                 },
                { "orderly",   SD_JSON_VARIANT_BOOLEAN,       sd_json_dispatch_stdbool,     offsetof(NvPCRData, orderly),   0                 },
                {},
        };
 
        _cleanup_(nvpcr_data_done) NvPCRData p = {
                .algorithm = TPM2_ALG_SHA256,
                .priority = TPM2_NVPCR_PRIORITY_DEFAULT,
                .orderly = true,
        };
        r = sd_json_dispatch(v, dispatch_table, SD_JSON_ALLOW_EXTENSIONS, &p);
        if (r < 0)
                return r;
 
        if (!streq_ptr(p.name, name))
                return log_debug_errno(SYNTHETIC_ERRNO(ESTALE), "NvPCR name doesn't match filename, refusing.");
 
        *ret = TAKE_STRUCT(p);
        return 0;
}
 
int tpm2_nvpcr_all_names(char ***ret_names) {
        int r;
 
        _cleanup_strv_free_ char **paths = NULL;
        r = conf_files_list_nulstr(&paths, ".nvpcr", /* root= */ NULL, CONF_FILES_WARN, CONF_PATHS_NULSTR("nvpcr"));
        if (r < 0)
                return r;
 
        _cleanup_strv_free_ char **names = NULL;
        STRV_FOREACH(p, paths) {
                _cleanup_free_ char *fname = NULL;
                r = path_extract_filename(*p, &fname);
                if (r < 0)
                        return r;
 
                char *e = endswith(fname, ".nvpcr");
                if (!e)
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Unexpected nvpcr config file name '%s'", fname);
                *e = 0;
 
                if (!tpm2_nvpcr_name_is_valid(fname))
                        continue;
 
                r = strv_consume(&names, TAKE_PTR(fname));
                if (r < 0)
                        return r;
        }
 
        if (ret_names)
                *ret_names = TAKE_PTR(names);
        return 0;
}
 
int tpm2_nvpcr_get_index(const char *name, uint32_t *ret_nv_index, uint64_t *ret_priority) {
        int r;
 
        _cleanup_(nvpcr_data_done) NvPCRData p = {};
        r = nvpcr_data_load(name, &p);
        if (r < 0)
                return r;
 
        if (ret_nv_index)
                *ret_nv_index = p.nv_index;
        if (ret_priority)
                *ret_priority = p.priority;
 
        return 0;
}
 
#if HAVE_OPENSSL
static int tpm2_nvpcr_load_pcr_public_key(
                const char *path,
                TPM2B_PUBLIC *ret_public,
                struct iovec *ret_fingerprint) {
 
        int r;
 
        assert(ret_public);
        assert(ret_fingerprint);
 
        _cleanup_(iovec_done) struct iovec pubkey = {};
        r = tpm2_load_pcr_public_key(path, &pubkey.iov_base, &pubkey.iov_len);
        if (r < 0)
                return log_debug_errno(r, "Failed to load PCR public key for NvPCR: %m");
 
        TPM2B_PUBLIC public;
        r = tpm2_tpm2b_public_from_pem(pubkey.iov_base, pubkey.iov_len, &public);
        if (r < 0)
                return log_debug_errno(r, "Failed to convert PCR public key to TPM2B_PUBLIC: %m");
 
        _cleanup_(iovec_done) struct iovec fp = {};
        r = tpm2_tpm2b_public_to_fingerprint(&public, &fp.iov_base, &fp.iov_len);
        if (r < 0)
                return log_debug_errno(r, "Failed to calculate fingerprint of PCR public key: %m");
 
        *ret_public = public;
        *ret_fingerprint = TAKE_STRUCT(fp);
        return 0;
}
 
/* Reads the stored init policy digest of a previously initialized NvPCR. This is written by
 * tpm2_nvpcr_initialize() and is needed to reconstruct the TPM2_PolicyOR for runtime extends. */
static int tpm2_nvpcr_read_init_policy(const char *name, TPM2B_DIGEST *ret) {
        int r;
 
        assert(name);
        assert(ret);
 
        const char *fname = strjoina("/run/systemd/nvpcr/", name, ".auth");
 
        _cleanup_free_ char *h = NULL;
        r = read_one_line_file(fname, &h);
        if (r == -ENOENT)
                return log_debug_errno(SYNTHETIC_ERRNO(ENETDOWN), "NvPCR '%s' not initialized yet, refusing.", name);
        if (r < 0)
                return log_debug_errno(r, "Failed to read NvPCR init policy '%s': %m", fname);
 
        _cleanup_free_ void *d = NULL;
        size_t d_size;
        r = unhexmem(strstrip(h), &d, &d_size);
        if (r < 0)
                return log_debug_errno(r, "Failed to decode NvPCR init policy from '%s': %m", fname);
        if (d_size != SHA256_DIGEST_SIZE)
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "NvPCR init policy in '%s' has unexpected size.", fname);
 
        *ret = TPM2B_DIGEST_MAKE(d, d_size);
        return 0;
}
 
/* Policy reference for the PolicyAuthorize assertion that guards the first write to an NvPCR. */
#define NVPCR_INIT_POLICY_REF "initrd"
 
/* PCR mask for the policy that guards the first write to an NvPCR. */
#define NVPCR_INIT_PCRMASK (UINT32_C(1) << TPM2_PCR_KERNEL_BOOT)
 
/* The init policy of an NvPCR, i.e. the branch of its write policy that guards the initializing write,
 * together with everything needed to satisfy it. */
typedef struct NvPCRInitPolicy {
        TPM2B_DIGEST digest;
        TPML_PCR_SELECTION pcr_selection;
        TPM2B_PUBLIC public;
        struct iovec fingerprint;
        sd_json_variant *signature_json;
} NvPCRInitPolicy;
 
static void nvpcr_init_policy_done(NvPCRInitPolicy *p) {
        assert(p);
 
        iovec_done(&p->fingerprint);
        p->signature_json = sd_json_variant_unref(p->signature_json);
}
 
/* Completes the write policy of an NvPCR in 'session' by submitting PolicyOR('init_policy',
 * PolicyNvWritten(true)). 'session' must already satisfy one of the two branches. */
static int tpm2_nvpcr_policy_or_written(
                Tpm2Context *c,
                const Tpm2Handle *session,
                const TPM2B_DIGEST *init_policy) {
 
        int r;
 
        assert(c);
        assert(session);
        assert(init_policy);
 
        /* Branch order must match tpm2_nvpcr_calculate_write_policy(). */
        TPM2B_DIGEST branches[2] = {
                *init_policy,                                /* Init branch */
                TPM2B_DIGEST_MAKE(NULL, SHA256_DIGEST_SIZE), /* PolicyNvWritten branch */
        };
        r = tpm2_calculate_policy_nv_written(/* written_set= */ true, &branches[1]);
        if (r < 0)
                return r;
 
        return tpm2_policy_or(c, session, branches, ELEMENTSOF(branches), /* ret_policy_digest= */ NULL);
}
 
/* Opens a policy session that satisfies the init branch of an NvPCR's write policy, for the initializing
 * write that sets TPMA_NV_WRITTEN. */
static int tpm2_nvpcr_open_init_session(
                Tpm2Context *c,
                const NvPCRInitPolicy *init,
                Tpm2Handle **ret_session) {
 
        _cleanup_(tpm2_handle_freep) Tpm2Handle *session = NULL;
        TPML_PCR_SELECTION pcr_selection;
        int r;
 
        assert(c);
        assert(init);
        assert(iovec_is_set(&init->fingerprint));
        assert(init->signature_json);
        assert(ret_session);
 
        r = tpm2_make_policy_session(c, /* primary= */ NULL, /* encryption_session= */ NULL, &session);
        if (r < 0)
                return r;
 
        /* tpm2_policy_authorize() takes a non-const selection. */
        pcr_selection = init->pcr_selection;
 
        /* Satisfy the PolicyAuthorize branch using the signed PCR policy. */
        r = tpm2_policy_authorize(
                        c,
                        session,