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 7001–8000 of 12,273

        /* If protected by PIN, a user-selected low-entropy password, enable DA protection.
           Without a PIN, the key's left protected only by a PCR policy, which does not benefit
           from DA protection. */
        hmac_attributes |= pin ? 0 : TPMA_OBJECT_NODA;
 
        /* We use a keyed hash object (i.e. HMAC) to store the secret key we want to use for unlocking the
         * LUKS2 volume with. We don't ever use for HMAC/keyed hash operations however, we just use it
         * because it's a key type that is universally supported and suitable for symmetric binary blobs. */
        TPMT_PUBLIC hmac_template = {
                .type = TPM2_ALG_KEYEDHASH,
                .nameAlg = TPM2_ALG_SHA256,
                .objectAttributes = hmac_attributes,
                .parameters.keyedHashDetail.scheme.scheme = TPM2_ALG_NULL,
                .unique.keyedHash.size = SHA256_DIGEST_SIZE,
        };
 
        TPMS_SENSITIVE_CREATE hmac_sensitive = {
                .data.size = hmac_template.unique.keyedHash.size,
        };
 
        CLEANUP_ERASE(hmac_sensitive);
 
        if (pin) {
                r = tpm2_auth_value_from_pin(TPM2_ALG_SHA256, pin, &hmac_sensitive.userAuth);
                if (r < 0)
                        return r;
        }
 
        assert(sizeof(hmac_sensitive.data.buffer) >= hmac_sensitive.data.size);
 
        (void) tpm2_credit_random(c);
 
        _cleanup_(tpm2_handle_freep) Tpm2Handle *primary_handle = NULL;
        if (ret_srk) {
                _cleanup_(Esys_Freep) TPM2B_PUBLIC *primary_public = NULL;
 
                if (IN_SET(seal_key_handle, 0, TPM2_SRK_HANDLE)) {
                        r = tpm2_get_or_create_srk(
                                        c,
                                        /* session= */ NULL,
                                        &primary_public,
                                        /* ret_name= */ NULL,
                                        /* ret_qname= */ NULL,
                                        &primary_handle);
                        if (r < 0)
                                return r;
                } else if (IN_SET(TPM2_HANDLE_TYPE(seal_key_handle), TPM2_HT_TRANSIENT, TPM2_HT_PERSISTENT)) {
                        r = tpm2_object_index_to_handle(
                                        c,
                                        seal_key_handle,
                                        /* session= */ NULL,
                                        &primary_public,
                                        /* ret_name= */ NULL,
                                        /* ret_qname= */ NULL,
                                        &primary_handle);
                        if (r < 0)
                                return r;
                        if (r == 0)
                                /* We do NOT automatically create anything other than the SRK */
                                return log_debug_errno(SYNTHETIC_ERRNO(ENOENT),
                                                       "No handle found at index 0x%" PRIx32, seal_key_handle);
                } else
                        return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "Seal key handle 0x%" PRIx32 " is neither transient nor persistent.",
                                               seal_key_handle);
 
                primary_alg = primary_public->publicArea.type;
 
                /* Propagate fixedTPM/fixedParent flags from sealing key to hmac key */
                hmac_template.objectAttributes = (hmac_template.objectAttributes & ~(TPMA_OBJECT_FIXEDTPM|TPMA_OBJECT_FIXEDPARENT)) |
                                                 (primary_public->publicArea.objectAttributes & (TPMA_OBJECT_FIXEDTPM|TPMA_OBJECT_FIXEDPARENT));
 
        } else {
                if (seal_key_handle != 0)
                        log_debug("Using primary alg sealing, but seal key handle also provided; ignoring seal key handle.");
 
                /* TODO: force all callers to provide ret_srk, so we can stop sealing with the legacy templates. */
                primary_alg = TPM2_ALG_ECC;
 
                TPM2B_PUBLIC template = {
                        .size = sizeof(TPMT_PUBLIC),
                };
                r = tpm2_get_legacy_template(primary_alg, &template.publicArea);
                if (r < 0)
                        return log_debug_errno(r, "Could not get legacy ECC template: %m");
 
                if (!tpm2_supports_tpmt_public(c, &template.publicArea)) {
                        primary_alg = TPM2_ALG_RSA;
 
                        r = tpm2_get_legacy_template(primary_alg, &template.publicArea);
                        if (r < 0)
                                return log_debug_errno(r, "Could not get legacy RSA template: %m");
 
                        if (!tpm2_supports_tpmt_public(c, &template.publicArea))
                                return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
                                                       "TPM does not support either ECC or RSA legacy template.");
                }
 
                r = tpm2_create_primary(
                                c,
                                /* session= */ NULL,
                                ESYS_TR_RH_OWNER,
                                &template,
                                /* sensitive= */ NULL,
                                /* ret_public= */ NULL,
                                &primary_handle);
                if (r < 0)
                        return r;
        }
 
        _cleanup_(tpm2_handle_freep) Tpm2Handle *encryption_session = NULL;
        r = tpm2_make_encryption_session(c, primary_handle, /* bind_key= */ NULL, &encryption_session);
        if (r < 0)
                return r;
 
        log_debug("Generating secret key data.");
 
        /* At least one shard, and if we have multiple policies, then we need one shard for each */
        size_t n_shards = MAX(n_policy, 1U);
 
        /* Create a large secret which covers all shards we need */
        _cleanup_(iovec_done_erase) struct iovec secret = {};
        r = crypto_random_bytes_allocate_iovec(hmac_sensitive.data.size * n_shards, &secret);
        if (r < 0)
                return log_debug_errno(r, "Failed to generate secret key: %m");
 
        struct iovec *blobs = new0(struct iovec, n_shards);
        size_t n_blobs = 0;
 
        CLEANUP_ARRAY(blobs, n_blobs, iovec_array_free);
 
        for (size_t shard = 0; shard < n_shards; shard++) {
 
                /* Patch this shard's policy into the template */
                if (shard < n_policy)
                        hmac_template.authPolicy = policy[shard];
                else
                        hmac_template.authPolicy = TPM2B_DIGEST_MAKE(NULL, TPM2_SHA256_DIGEST_SIZE);
 
                /* Copy in this shard's secret key */
                memcpy(hmac_sensitive.data.buffer,
                       (const uint8_t*) secret.iov_base + (hmac_sensitive.data.size * shard),
                       hmac_sensitive.data.size);
 
                log_debug("Creating HMAC key on TPM for shard %zu.", shard);
 
                _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;
 
                log_debug("Marshalling private and public part of HMAC key for shard %zu.", shard);
 
                r = tpm2_marshal_blob(public, private, /* seed= */ NULL, &blobs[n_blobs].iov_base, &blobs[n_blobs].iov_len);
                if (r < 0)
                        return log_debug_errno(r, "Could not create sealed blob: %m");
 
                n_blobs++;
        }
 
        if (DEBUG_LOGGING)
                log_debug("Completed TPM2 key sealing in %s.", FORMAT_TIMESPAN(now(CLOCK_MONOTONIC) - start, 1));
 
        if (ret_srk) {
                r = tpm2_serialize(c, primary_handle, ret_srk);
                if (r < 0)
                        return r;
        }
 
        *ret_secret = TAKE_STRUCT(secret);
        *ret_blobs = TAKE_PTR(blobs);
        *ret_n_blobs = n_blobs;
 
        if (ret_primary_alg)
                *ret_primary_alg = primary_alg;
 
        return 0;
}
 
#define RETRY_UNSEAL_MAX 30u
 
int tpm2_unseal(Tpm2Context *c,
                uint32_t hash_pcr_mask,
                uint16_t pcr_bank,
                const struct iovec *pubkey,
                const char *pubkey_policy_ref,
                uint32_t pubkey_pcr_mask,
                sd_json_variant *signature,
                const char *pin,
                const Tpm2PCRLockPolicy *pcrlock_policy,
                uint16_t primary_alg,
                const struct iovec blobs[],
                size_t n_blobs,
                const struct iovec known_policy_hash[],
                size_t n_known_policy_hash,
                const struct iovec *srk,
                struct iovec *ret_secret) {
 
        /* Returns the following errors:
         *
         *   -EREMOTE         → blob is from a different TPM
         *   -EADDRNOTAVAIL   → NV index referenced by policy is missing, unwritten, or unusable
         *   -ENOSTR          → signature JSON has no matching entry for the current PCR policy
         *   -EDEADLK         → couldn't create primary key because authorization failure
         *   -ENOLCK          → TPM is in dictionary lockout mode
         *   -EREMCHG         → submitted policy doesn't match NV index stored policy (in case of PolicyAuthorizeNV)
         *   -ENOANO          → none of the PolicyOR branches of a policy matched current state
         *   -EUCLEAN         → a PCR kept being extended while we were unsealing
         *   -EPERM           → stored policy does not match TPM state
         *   -ENOTRECOVERABLE → all other kinds of TPM errors
         *   -EILSEQ          → bad PIN
         *
         * Of these EREMCHG, ENOANO and EPERM mean that PCR state is not matching expectations. EUCLEAN on
         * the other hand says nothing about the correctness of the policy: it means the TPM's global PCR
         * update counter kept moving while we built the policy or unsealed, i.e. something on this system
         * extends a PCR continuously (the usual suspect is PCR 10 when IMA is enabled directly, or
         * indirectly via secure boot). We make at most RETRY_UNSEAL_MAX + 1 attempts before reporting
         * it. */
 
        TSS2_RC rc;
        int r;
 
        assert(n_blobs > 0);
        assert(blobs);
        assert(iovec_is_valid(pubkey));
        assert(!pubkey_policy_ref || iovec_is_set(pubkey));
        assert(ret_secret);
 
        assert(TPM2_PCR_MASK_VALID(hash_pcr_mask));
        assert(TPM2_PCR_MASK_VALID(pubkey_pcr_mask));
 
        /* So here's what we do here: We connect to the TPM2 chip. As we do when sealing we generate a
         * "primary" key on the TPM2 chip, with the same parameters as well as a PCR-bound policy session.
         * Given we pass the same parameters, this will result in the same "primary" key, and same policy
         * hash (the latter of course, only if the PCR values didn't change in between). We unmarshal the
         * encrypted key we stored in the LUKS2 JSON token header and upload it into the TPM2, where it is
         * decrypted if the seed and the PCR policy were right ("unsealing"). We then download the result,
         * and use it to unlock the LUKS2 volume. */
 
        usec_t start = now(CLOCK_MONOTONIC);
 
        size_t n_shards = pcrlock_policy && iovec_is_set(pubkey) ? 2 : 1;
        if (n_blobs != n_shards)
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Number of provided key blobs (%zu) does not match policy requirements (%zu).", n_blobs, n_shards);
        if (n_known_policy_hash > 0 && n_known_policy_hash != n_shards)
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Number of provided known policy hashes (%zu) does not match policy requirements (%zu or 0).", n_known_policy_hash, n_shards);
 
        /* Older code did not save the pcr_bank, and unsealing needed to detect the best pcr bank to use,
         * so we need to handle that legacy situation. Use the legacy variant, which only ever picks SHA256 or SHA1. */
        if (pcr_bank == UINT16_MAX) {
                r = tpm2_get_best_pcr_bank_legacy(c, hash_pcr_mask|pubkey_pcr_mask, &pcr_bank);
                if (r < 0)
                        return r;
        }
 
        _cleanup_(tpm2_handle_freep) Tpm2Handle *primary_handle = NULL;
        r = tpm2_deserialize(c, srk, &primary_handle);
        if (r < 0)
                return r;
        if (r == 0) {
                /* ECC was the only supported algorithm in systemd < 250, use that as implied default, for compatibility */
                if (primary_alg == 0)
                        primary_alg = TPM2_ALG_ECC;
 
                TPM2B_PUBLIC template = {
                        .size = sizeof(TPMT_PUBLIC),
                };
                r = tpm2_get_legacy_template(primary_alg, &template.publicArea);
                if (r < 0)
                        return log_debug_errno(r, "Could not get legacy template: %m");
 
                r = tpm2_create_primary(
                                c,
                                /* session= */ NULL,
                                ESYS_TR_RH_OWNER,
                                &template,
                                /* sensitive= */ NULL,
                                /* ret_public= */ NULL,
                                &primary_handle);
                if (r < 0)
                        return r;
        }
 
        TPM2B_PUBLIC pubkey_tpm2b;
        _cleanup_(iovec_done) struct iovec fp = {};
        if (iovec_is_set(pubkey)) {
                r = tpm2_tpm2b_public_from_pem(pubkey->iov_base, pubkey->iov_len, &pubkey_tpm2b);
                if (r < 0)
                        return log_debug_errno(r, "Could not create TPMT_PUBLIC: %m");
 
                r = tpm2_tpm2b_public_to_fingerprint(&pubkey_tpm2b, &fp.iov_base, &fp.iov_len);
                if (r < 0)
                        return log_debug_errno(r, "Could not get key fingerprint: %m");
        }
 
        _cleanup_(iovec_done_erase) struct iovec secret = {};
        for (unsigned i = RETRY_UNSEAL_MAX;; i--) {
                bool retry = false;
                iovec_done_erase(&secret); /* clear data from previous unseal attempt */
 
                for (size_t shard = 0; shard < n_blobs; shard++) {
                        TPM2B_PUBLIC public;
                        TPM2B_PRIVATE private;
                        TPM2B_ENCRYPTED_SECRET seed = {};
                        r = tpm2_unmarshal_blob(blobs[shard].iov_base, blobs[shard].iov_len, &public, &private, &seed);
                        if (r < 0)
                                return log_debug_errno(r, "Could not extract parts from blob: %m");
 
                        if (seed.size > 0) {
                                /* This is a calculated (or duplicated) sealed object, and must be imported. */
                                _cleanup_free_ TPM2B_PRIVATE *imported_private = NULL;
                                r = tpm2_import(c,
                                                primary_handle,
                                                /* session= */ NULL,
                                                &public,
                                                &private,
                                                &seed,
                                                /* encryption_key= */ NULL,
                                                /* symmetric= */ NULL,
                                                &imported_private);
                                if (r < 0)
                                        return r;
 
                                private = *imported_private;
                        }
 
                        log_debug("Loading HMAC key into TPM for shard %zu.", shard);
 
                        /* Nothing sensitive on the bus, no need for encryption. Even if an attacker gives
                         * you back a different key, the session initiation will fail. In the SRK model, the
                         * tpmKey is verified. In the non-srk model, with pin, the bindKey provides
                         * protections. */
                        _cleanup_(tpm2_handle_freep) Tpm2Handle *hmac_key = NULL;
                        r = tpm2_load(c, primary_handle, NULL, &public, &private, &hmac_key);
                        if (r < 0)
                                return r;
 
                        /* If a PIN is set for the seal object, use it to bind the session key to that
                         * object. This prevents active bus interposers from faking a TPM and seeing the
                         * unsealed value. An active interposer could fake a TPM, satisfying the encrypted
                         * session, and just forward everything to the *real* TPM. */
                        r = tpm2_set_auth(c, hmac_key, pin);
                        if (r < 0)
                                return r;
 
                        _cleanup_(tpm2_handle_freep) Tpm2Handle *encryption_session = NULL;
                        r = tpm2_make_encryption_session(c, primary_handle, hmac_key, &encryption_session);
                        if (r < 0)
                                return r;
 
                        _cleanup_(tpm2_handle_freep) Tpm2Handle *policy_session = NULL;
                        _cleanup_(Esys_Freep) TPM2B_DIGEST *policy_digest = NULL;
                        r = tpm2_make_policy_session(
                                        c,
                                        primary_handle,
                                        encryption_session,
                                        &policy_session);
                        if (r < 0)
                                return r; /* Will return EILSEQ on auth failure (i.e. bad PIN) */
 
                        /* If both public PCR key and pcrlock policies are requested, then generate the
                         * public PCR policy for the first shared, and the pcrlock policy for the 2nd */
                        r = tpm2_build_sealing_policy(
                                        c,
                                        policy_session,
                                        hash_pcr_mask,
                                        pcr_bank,
                                        shard == 0 && iovec_is_set(pubkey) ? &pubkey_tpm2b : NULL,
                                        shard == 0 ? pubkey_policy_ref : NULL,
                                        fp.iov_base, fp.iov_len,
                                        shard == 0 ? pubkey_pcr_mask : 0,
                                        signature,
                                        !!pin,
                                        (shard == 1 || !iovec_is_set(pubkey)) ? pcrlock_policy : NULL,
                                        &policy_digest);
                        if (r == -EUCLEAN) {
                                if (i == 0)
                                        return log_debug_errno(r, "PCR values kept changing while building the TPM2 policy, giving up after %u unsealing attempts.", RETRY_UNSEAL_MAX + 1);
 
                                log_debug("A PCR value changed during the TPM2 policy session, restarting HMAC key unsealing (%u tries left).", i);
                                retry = true;
                                break;
                        }
                        if (r < 0)
                                return r;
 
                        /* If we know the policy hash to expect, and it doesn't match, we can shortcut things here, and not
                         * wait until the TPM2 tells us to go away. */
                        if (n_known_policy_hash > 0 && memcmp_nn(policy_digest->buffer,
                                                                 policy_digest->size,
                                                                 known_policy_hash[shard].iov_base,
                                                                 known_policy_hash[shard].iov_len) != 0) {
#if HAVE_OPENSSL
                                if (shard == 0 &&
                                    iovec_is_set(pubkey) &&
                                    pubkey_tpm2b.publicArea.type == TPM2_ALG_RSA &&
                                    pubkey_tpm2b.publicArea.parameters.rsaDetail.exponent == TPM2_RSA_DEFAULT_EXPONENT) {
                                        /* Due to bug #30546, if using RSA pubkey with the default exponent, we may
                                         * need to set the exponent to the TPM special-case value of 0 and retry. */
                                        log_debug("Policy hash mismatch, retrying with RSA pubkey exponent set to 0.");
                                        pubkey_tpm2b.publicArea.parameters.rsaDetail.exponent = 0;
                                        retry = true;
                                        break;
                                }
#endif
                                return log_debug_errno(SYNTHETIC_ERRNO(EPERM),
                                                       "Current policy digest does not match stored policy digest, cancelling "
                                                       "TPM2 authentication attempt.");
                        }
 
                        log_debug("Unsealing HMAC key for shard %zu.", shard);
 
                        _cleanup_(tpm2b_sensitive_data_erase_and_esys_freep) TPM2B_SENSITIVE_DATA* unsealed = NULL;
                        rc = sym_Esys_Unseal(
                                        c->esys_context,
                                        hmac_key->esys_handle,
                                        policy_session->esys_handle,
                                        encryption_session->esys_handle, /* use HMAC session to enable parameter encryption */
                                        ESYS_TR_NONE,
                                        &unsealed);
                        if (rc == TPM2_RC_PCR_CHANGED) {
                                if (i == 0)
                                        return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN),
                                                               "PCR values kept changing while unsealing, giving up after %u unsealing attempts.", RETRY_UNSEAL_MAX + 1);
 
                                log_debug("A PCR value changed during the TPM2 policy session, restarting HMAC key unsealing (%u tries left).", i);
                                retry = true;
                                break;
                        }
                        if (rc != TPM2_RC_SUCCESS)
                                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                                       "Failed to unseal HMAC key in TPM: %s", sym_Tss2_RC_Decode(rc));
 
                        if (!iovec_append(&secret, &IOVEC_MAKE(unsealed->buffer, unsealed->size)))
                                return log_oom_debug();
                }
 
                if (!retry)
                        break;
        }
 
        if (DEBUG_LOGGING)
                log_debug("Completed TPM2 key unsealing in %s.", FORMAT_TIMESPAN(now(CLOCK_MONOTONIC) - start, 1));
 
        *ret_secret = TAKE_STRUCT(secret);
        return 0;
}
 
static TPM2_HANDLE generate_random_nv_index(void) {
        return TPM2_NV_INDEX_UNASSIGNED_FIRST +
                (TPM2_HANDLE) random_u64_range(TPM2_NV_INDEX_UNASSIGNED_LAST - TPM2_NV_INDEX_UNASSIGNED_FIRST + 1);
}
 
int tpm2_define_policy_nv_index(
                Tpm2Context *c,
                const Tpm2Handle *session,
                TPM2_HANDLE requested_nv_index,
                const TPM2B_DIGEST *write_policy,
                TPM2_HANDLE *ret_nv_index,
                Tpm2Handle **ret_nv_handle,
                TPM2B_NV_PUBLIC *ret_nv_public) {
 
        _cleanup_(tpm2_handle_freep) Tpm2Handle *new_handle = NULL;
        TSS2_RC rc;
        int r;
 
        assert(c);
 
        /* Allocates an nvindex to store a policy for use in PolicyAuthorizeNV in. This is where pcrlock then
         * stores its predicted PCR policies in. If 'requested_nv_index' will try to allocate the specified
         * nvindex, otherwise will find a free one, and use that. */
 
        r = tpm2_handle_new(c, &new_handle);
        if (r < 0)
                return r;
 
        new_handle->flush = false; /* This is a persistent NV index, don't flush hence */
 
        for (unsigned try = 0; try < 25U; try++) {
                TPM2_HANDLE nv_index;
 
                if (requested_nv_index != 0)
                        nv_index = requested_nv_index;
                else
                        nv_index = generate_random_nv_index();
 
                TPM2B_NV_PUBLIC public_info = {
                        .size = sizeof_field(TPM2B_NV_PUBLIC, nvPublic),
                        .nvPublic = {
                                .nvIndex = nv_index,
                                .nameAlg = TPM2_ALG_SHA256,
                                .attributes = TPM2_NT_ORDINARY | TPMA_NV_WRITEALL | TPMA_NV_POLICYWRITE | TPMA_NV_OWNERREAD,
                                .dataSize = offsetof(TPMT_HA, digest) + tpm2_hash_alg_to_size(TPM2_ALG_SHA256),
                        },
                };
 
                if (write_policy)
                        public_info.nvPublic.authPolicy = *write_policy;
 
                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 == TSS2_RC_SUCCESS) {
                        log_debug("NV Index 0x%" PRIx32 " successfully allocated.", nv_index);
 
                        if (ret_nv_index)
                                *ret_nv_index = nv_index;
 
                        if (ret_nv_handle)
                                *ret_nv_handle = TAKE_PTR(new_handle);
 
                        if (ret_nv_public)
                                *ret_nv_public = public_info;
 
                        return 0;
                }
                if (rc != TPM2_RC_NV_DEFINED)
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                               "Failed to allocate NV index: %s", sym_Tss2_RC_Decode(rc));
 
                if (requested_nv_index != 0) {
                        assert(nv_index == requested_nv_index);
                        return log_debug_errno(SYNTHETIC_ERRNO(EEXIST),
                                               "Requested NV index 0x%" PRIx32 " already taken.", requested_nv_index);
                }
 
                log_debug("NV index 0x%" PRIu32 " already taken, trying another one (%u tries left)", nv_index, try);
        }
 
        return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                               "Too many attempts trying to allocate NV index: %s", sym_Tss2_RC_Decode(rc));
}
 
int tpm2_write_policy_nv_index(
                Tpm2Context *c,
                const Tpm2Handle *policy_session,
                TPM2_HANDLE nv_index,
                const Tpm2Handle *nv_handle,
                const TPM2B_DIGEST *policy_digest) {
 
        TSS2_RC rc;
 
        assert(c);
        assert(policy_session);
        assert(nv_handle);
        assert(policy_digest);
 
        if (policy_digest->size != tpm2_hash_alg_to_size(TPM2_ALG_SHA256))
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Policy to store in NV index has wrong size.");
 
        TPMT_HA ha = {
                .hashAlg = TPM2_ALG_SHA256,
        };
        assert(policy_digest->size <= sizeof_field(TPMT_HA, digest));
        memcpy_safe(&ha.digest, policy_digest->buffer, policy_digest->size);
 
        TPM2B_MAX_NV_BUFFER buffer = {};
        size_t written = 0;
        rc = sym_Tss2_MU_TPMT_HA_Marshal(&ha, buffer.buffer, sizeof(buffer.buffer), &written);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to marshal policy digest.");
 
        buffer.size = written;
 
        rc = sym_Esys_NV_Write(
                        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,
                        &buffer,
                        /* offset= */ 0);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to write NV index: %s", sym_Tss2_RC_Decode(rc));
 
        if (DEBUG_LOGGING) {
                _cleanup_free_ char *h = NULL;
                h = hexmem(policy_digest->buffer, policy_digest->size);
                log_debug("Written policy digest %s to NV index 0x%x", strnull(h), nv_index);
        }
 
        return 0;
}
 
#if HAVE_OPENSSL
/* Calculates the write policy of a NvPCR, which is 'init_policy' OR TPM2_PolicyNvWritten(true).
 * Returns the overall write policy. */
static int tpm2_nvpcr_calculate_write_policy(
                const TPM2B_DIGEST *init_policy,
                TPM2B_DIGEST *ret_write_policy) {
 
        int r;
 
        assert(init_policy);
        assert(init_policy->size == SHA256_DIGEST_SIZE);
        assert(ret_write_policy);
 
        /* Branch order matters here and must match the reconstruction in tpm2_nvpcr_policy_or_written(). */
        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;
 
        TPM2B_DIGEST write_policy = TPM2B_DIGEST_MAKE(NULL, SHA256_DIGEST_SIZE);
        r = tpm2_calculate_policy_or(branches, ELEMENTSOF(branches), &write_policy);
        if (r < 0)
                return r;
 
        *ret_write_policy = write_policy;
        return 0;
}
#endif
 
int tpm2_define_data_nv_index(
                Tpm2Context *c,
                const Tpm2Handle *session,
                TPM2_HANDLE requested_nv_index,
                const struct iovec *data,
                TPM2_HANDLE *ret_nv_index,
                Tpm2Handle **ret_nv_handle) {
 
        _cleanup_(tpm2_handle_freep) Tpm2Handle *new_handle = NULL;
        TPM2_HANDLE nv_index = 0;
        TSS2_RC rc;
        int r;
 
        assert(c);
        assert(iovec_is_set(data));
 
        /* Allocates an ordinary NV index sized to hold 'data' and writes 'data' into it. The index is created
         * with AUTHREAD/AUTHWRITE attributes so it can be read back with tpm2_read_nv_index(). */
 
        if (data->iov_len == 0 || data->iov_len > UINT16_MAX)
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Invalid NV index data size %zu.", data->iov_len);
 
        r = tpm2_handle_new(c, &new_handle);
        if (r < 0)
                return r;
 
        new_handle->flush = false; /* This is a persistent NV index, don't flush hence */
 
        for (unsigned try = 0;; try++) {
                if (requested_nv_index != 0)
                        nv_index = requested_nv_index;
                else
                        nv_index = generate_random_nv_index();
 
                TPM2B_NV_PUBLIC public_info = {
                        .size = sizeof_field(TPM2B_NV_PUBLIC, nvPublic),
                        .nvPublic = {
                                .nvIndex = nv_index,
                                .nameAlg = TPM2_ALG_SHA256,
                                .attributes = TPM2_NT_ORDINARY | TPMA_NV_AUTHWRITE | TPMA_NV_AUTHREAD | TPMA_NV_NO_DA,
                                .dataSize = data->iov_len,
                        },
                };
 
                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 == TSS2_RC_SUCCESS)
                        break;
                if (rc != TPM2_RC_NV_DEFINED)
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                               "Failed to allocate NV index: %s", sym_Tss2_RC_Decode(rc));
                if (requested_nv_index != 0) {
                        assert(nv_index == requested_nv_index);
                        return log_debug_errno(SYNTHETIC_ERRNO(EEXIST),
                                               "Requested NV index 0x%" PRIx32 " already taken.", requested_nv_index);
                }
                if (try >= 24U)
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                               "Too many attempts trying to allocate NV index: %s", sym_Tss2_RC_Decode(rc));
 
                log_debug("NV index 0x%" PRIx32 " already taken, trying another one (%u tries left)", nv_index, 24U - try);
        }
 
        log_debug("NV index 0x%" PRIx32 " successfully allocated.", nv_index);
 
        /* TPM2_NV_Write is bounded by TPM_PT_NV_BUFFER_MAX just like TPM2_NV_Read, so write in chunks no
         * larger than what the TPM accepts in a single command. */
        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);
 
        for (size_t offset = 0; offset < data->iov_len;) {
                size_t chunk_size = MIN(data->iov_len - offset, max_buffer_size);
 
                TPM2B_MAX_NV_BUFFER buffer = { .size = chunk_size };
                memcpy(buffer.buffer, (const uint8_t*) data->iov_base + offset, chunk_size);
 
                rc = sym_Esys_NV_Write(
                                c->esys_context,
                                /* authHandle= */ new_handle->esys_handle,
                                /* nvIndex= */ new_handle->esys_handle,
                                /* shandle1= */ session ? session->esys_handle : ESYS_TR_PASSWORD,
                                /* shandle2= */ ESYS_TR_NONE,
                                /* shandle3= */ ESYS_TR_NONE,
                                &buffer,
                                /* offset= */ offset);
                if (rc != TSS2_RC_SUCCESS) {
                        (void) tpm2_undefine_nv_index(c, session, nv_index, new_handle);
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                               "Failed to write NV index 0x%" PRIx32 ": %s", nv_index, sym_Tss2_RC_Decode(rc));
                }
 
                offset += chunk_size;
        }
 
        if (ret_nv_index)
                *ret_nv_index = nv_index;
        if (ret_nv_handle)
                *ret_nv_handle = TAKE_PTR(new_handle);
 
        return 0;
}
 
int tpm2_undefine_nv_index(
                Tpm2Context *c,
                const Tpm2Handle *session,
                TPM2_HANDLE nv_index,
                const Tpm2Handle *nv_handle) {
 
        TSS2_RC rc;
 
        assert(c);
        assert(nv_handle);
 
        rc = sym_Esys_NV_UndefineSpace(
                        c->esys_context,
                        /* authHandle= */ ESYS_TR_RH_OWNER,
                        /* nvIndex= */ nv_handle->esys_handle,
                        /* shandle1= */ session ? session->esys_handle : ESYS_TR_PASSWORD,
                        /* shandle2= */ ESYS_TR_NONE,
                        /* shandle3= */ ESYS_TR_NONE);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to undefine NV index: %s", sym_Tss2_RC_Decode(rc));
 
        log_debug("Successfully undefined NV index 0x%x.", nv_index);
        return 0;
}
 
#if HAVE_OPENSSL
 
static int tpm2_reuse_or_redefine_nvpcr_nv_index(
                Tpm2Context *c,
                const Tpm2Handle *session,
                bool exhausted,
                TPM2_HANDLE nv_index,
                const TPM2B_NV_PUBLIC *nv_public_info,
                Tpm2Handle **ret_nv_handle) {
 
        int r;
        TSS2_RC rc;
 
        assert(c);
        assert(nv_public_info);
        assert(ret_nv_handle);
 
        log_debug("Checking if there is an existing NV index 0x%" PRIx32 " that can be reused as the requested NvPCR.", nv_index);
 
        _cleanup_(Esys_Freep) TPM2B_NV_PUBLIC *nv_public_real = NULL;
        _cleanup_(Esys_Freep) TPM2B_NAME *nv_name_real = NULL;
        _cleanup_(tpm2_handle_freep) Tpm2Handle *handle = NULL;
        r = tpm2_nv_index_to_handle(
                        c,
                        nv_index,
                        session,
                        &nv_public_real,
                        &nv_name_real,
                        &handle);
        if (r < 0)
                return log_debug_errno(r, "Failed to acquire handle to NV index 0x%" PRIx32 ": %m", nv_index);
        if (r == 0)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOENT), "NV index 0x%" PRIx32 " does not exist yet.", nv_index);
 
        /* Check if the existing index has the same name as the one we're trying to define. We expect
         * this on any system where this NvPCR was created with the current pubkey on a previous
         * boot, and it should always be uninitialized (ie, TPMA_NV_WRITTEN unset) at this point. */
        TPM2B_NAME nv_name_expected;
        r = tpm2_calculate_nv_index_name(&nv_public_info->nvPublic, &nv_name_expected);
        if (r < 0)
                return log_debug_errno(r, "Failed to compute expected NvPCR index name");
        if (memcmp_nn(nv_name_expected.name, nv_name_expected.size, nv_name_real->name, nv_name_real->size) == 0) {
                log_debug("NV index 0x%" PRIx32 " for NvPCR already exists and not yet initialized, reusing.", nv_index);
                *ret_nv_handle = TAKE_PTR(handle);
                return 0;
        }
 
        /* If space for this orderly type is exhausted, don't try to redefine the index if the one we're
         * going to create has a size that is larger than the one we need to undefine. Note that this only
         * considers the data size of the 2 indices. Whilst the size of the authorization policy and the
         * maximum size of the authorization value are dependent on the name algorithm, the reference TPM
         * implementation stores the TPMS_NV_PUBLIC and TPM2B_AUTH structures using a fixed size. */
        if (exhausted &&
            (nv_public_info->nvPublic.attributes & TPMA_NV_ORDERLY) == (nv_public_real->nvPublic.attributes & TPMA_NV_ORDERLY) &&
                nv_public_info->nvPublic.dataSize > nv_public_real->nvPublic.dataSize)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOBUFS),
                                       "NV space is exhausted and undefining the existing NV index 0x%" PRIx32 " won't "
                                       "free sufficient space to allocate the NvPCR.", nv_index);
 
        /* Check if the existing index looks like it might have been a NvPCR - it might have a
         * policy that's different because the signing key for the PolicyAuthorize assertion changed,
         * or it might be an old style NvPCR. In this case, we'll undefine it and create a new one.
         * This handles updates from old style NvPCRs, and rotation of the authorized policy signing
         * key. We just check the attributes here - we know that the nvIndex is the same, and the
         * dataSize for a valid extend index matches the size of nameAlg so we don't need to check that. */
        const TPMA_NV old_expected_attrs =
                TPMA_NV_CLEAR_STCLEAR |
                TPMA_NV_OWNERWRITE |
                TPMA_NV_AUTHWRITE |
                TPMA_NV_OWNERREAD |
                TPMA_NV_AUTHREAD |
                (TPM2_NT_EXTEND << TPMA_NV_TPM2_NT_SHIFT);
        if ((((nv_public_real->nvPublic.attributes ^ nv_public_info->nvPublic.attributes) & ~(TPMA_NV_WRITTEN | TPMA_NV_ORDERLY)) != 0) &&
                (((nv_public_real->nvPublic.attributes ^ old_expected_attrs) & ~(TPMA_NV_WRITTEN | TPMA_NV_ORDERLY)) != 0))
                return log_debug_errno(SYNTHETIC_ERRNO(EEXIST),
                                        "Existing nvindex 0x%" PRIx32 " does not have the attributes expected for a NvPCR.", nv_index);
 
        /* At this point, the existing index looks like a NvPCR - either one that was authenticated using a
         * previous signing key or an old style NvPCR. We'll attempt to replace it with a new one. As we are
         * replacing an existing one, we do this regardless of whether a previous call indicated that NV
         * space is exhausted because it might still work. */
 
        log_debug("Public info for nvindex 0x%" PRIx32 " looks like an existing NvPCR, replacing.", nv_index);
 
        /* Undefine the existing index. */
        r = tpm2_undefine_nv_index(c, session, nv_index, handle);
        if (r < 0)
                return log_debug_errno(r, "Failed to undefine existing nvindex 0x%" PRIx32 ".", nv_index);
 
        /* Try to create the replacement index. */
        _cleanup_(tpm2_handle_freep) Tpm2Handle *new_handle = NULL;
        r = tpm2_handle_new(c, &new_handle);
        if (r < 0)
                return r;
 
        new_handle->flush = false;
 
        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,
                        nv_public_info,
                        &new_handle->esys_handle);
        if (rc == TPM2_RC_NV_SPACE)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOBUFS),
                                       "NV index space on TPM exhausted, cannot allocate NvPCR.");
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to allocate NvPCR index: %s", sym_Tss2_RC_Decode(rc));
 
        *ret_nv_handle = TAKE_PTR(new_handle);
        return 1;
}
 
static int tpm2_define_nvpcr_nv_index(
                Tpm2Context *c,
                const Tpm2Handle *session,
                TPM2_HANDLE nv_index,
                TPMI_ALG_HASH algorithm,
                const TPM2B_DIGEST *init_policy,
                bool orderly,
                Tpm2Handle **ret_nv_handle) {
 
        TSS2_RC rc;
        int r;
 
        assert(c);
        assert(init_policy);
 
        /* Allocates an nvindex to use as a "fake" PCR. We call these "NvPCR" in our codebase. The index is
         * created to require a policy for writing, so that the first write (which sets TPMA_NV_WRITTEN)
         * requires 'init_policy' to be satisfied, while all subsequent writes can be performed using a
         * PolicyNvWritten(true) branch without any further authorization. The intention here is that a
         * NvPCR can only be defined and initialized for as long as 'init_policy' can be satisfied (ie,
         * during an early boot phase). Once it can no longer be satisfied (ie, after the early boot has
         * ended), it is no longer possible to redefine and initialize the same NvPCR in order to spoof its
         * measurements. */
 
        log_debug("Allocating NvPCR index 0x%" PRIx32 ".", nv_index);
 
        if (algorithm == 0)
                algorithm = TPM2_ALG_SHA256;
 
        int digest_size = tpm2_hash_alg_to_size(algorithm);
        if (digest_size < 0)
                return digest_size;
 
        if ((size_t) digest_size > sizeof_field(TPM2B_MAX_NV_BUFFER, buffer))
                return log_debug_errno(SYNTHETIC_ERRNO(E2BIG), "Digest too large for extension.");
 
        /* If we already ran into NV index space exhaustion for this orderly mode during this boot, don't
         * bother trying again — the situation is unlikely to improve until reboot. We track this via a flag
         * file in /run/, with a separate file for orderly and non-orderly NvPCRs, since the two draw on
         * different TPM resources (RAM-backed vs. NVRAM-backed). */
        const char *exhausted_flag = orderly ?
                "/run/systemd/tpm2-nv-space-exhausted-orderly" :
                "/run/systemd/tpm2-nv-space-exhausted-non-orderly";
 
        /* Calculate the write policy, which is init_policy OR TPM2_PolicyNvWritten(true). The init_policy
         * branch is used for the first write and can only be satisfied during early boot. */
        TPM2B_DIGEST write_policy;
        r = tpm2_nvpcr_calculate_write_policy(init_policy, &write_policy);
        if (r < 0)
                return r;
 
        TPM2B_NV_PUBLIC public_info = {
                .size = sizeof_field(TPM2B_NV_PUBLIC, nvPublic),
                .nvPublic = {
                        .nvIndex = nv_index,
                        .nameAlg = algorithm,
                        .attributes = TPMA_NV_CLEAR_STCLEAR |
                                      (orderly ? TPMA_NV_ORDERLY : 0) |
                                      TPMA_NV_POLICYWRITE |
                                      TPMA_NV_OWNERREAD |
                                      TPMA_NV_AUTHREAD |
                                      (TPM2_NT_EXTEND << TPMA_NV_TPM2_NT_SHIFT),
                        .dataSize = digest_size,
                        .authPolicy = write_policy,
                },
        };
 
        if (access(exhausted_flag, F_OK) == 0) {
                log_debug("TPM NV index space previously found exhausted (%s exists), refusing to allocate %s NvPCR, but checking if it already exists.",
                          exhausted_flag, orderly ? "orderly" : "non-orderly");
 
                _cleanup_(tpm2_handle_freep) Tpm2Handle *handle = NULL;
                r = tpm2_reuse_or_redefine_nvpcr_nv_index(c, session, /* exhausted= */ true, nv_index, &public_info, &handle);
                if (r == -ENOENT)
                        r = -ENOBUFS;
                if (r < 0)
                        return log_debug_errno(r, "No existing NvPCR index 0x%" PRIx32 " and NV space is exhausted.", nv_index);
 
                log_debug("NV index 0x%" PRIx32 " successfully %s for NvPCR.", nv_index, r == 0 ? "reused" : "reallocated");
 
                if (ret_nv_handle)
                        *ret_nv_handle = TAKE_PTR(handle);
 
                return r;
        }
 
        if (errno != ENOENT)
                log_debug_errno(errno, "Failed to check whether %s exists, assuming it does not: %m", exhausted_flag);
 
        /* NvPCRs persist across boots, so the index usually exists already. Check for that first, instead
         * of relying on TPM2_NV_DefineSpace() failing with TPM2_RC_NV_DEFINED, which the TSS logs as an
         * error. */
        _cleanup_(tpm2_handle_freep) Tpm2Handle *handle = NULL;
        r = tpm2_reuse_or_redefine_nvpcr_nv_index(c, session, /* exhausted= */ false, nv_index, &public_info, &handle);
        if (r == -ENOBUFS) {
                /* 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 re-allocate NvPCR.");
        }
        if (r >= 0) {
                log_debug("NV index 0x%" PRIx32 " successfully %s for NvPCR.", nv_index, r == 0 ? "reused" : "reallocated");
 
                if (ret_nv_handle)
                        *ret_nv_handle = TAKE_PTR(handle);
 
                return r;
        }
        if (r != -ENOENT)
                return r;
 
        _cleanup_(tpm2_handle_freep) Tpm2Handle *new_handle = NULL;
        r = tpm2_handle_new(c, &new_handle);
        if (r < 0)
                return r;