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 6001–7000 of 12,273

                if (r < 0)
                        return log_debug_errno(r, "Could not get RSA key n/e: %m");
 
                r = TPM2B_PUBLIC_KEY_RSA_CHECK_SIZE(n_size);
                if (r < 0)
                        return log_debug_errno(r, "RSA key n size %zu too large.", n_size);
 
                public.unique.rsa = TPM2B_PUBLIC_KEY_RSA_MAKE(n, n_size);
                public.parameters.rsaDetail.keyBits = n_size * 8;
 
                if (sizeof(uint32_t) < e_size)
                        return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "RSA key e size %zu too large.", e_size);
 
                uint32_t exponent = 0;
                memcpy(&exponent, e, e_size);
                exponent = be32toh(exponent) >> (32 - e_size * 8);
 
                /* TPM specification Part 2 ("Structures") section for TPMS_RSA_PARAMS states "An exponent of
                 * zero indicates that the exponent is the default of 2^16 + 1". However, we have no reason
                 * to special case it in our PEM->TPM2B_PUBLIC conversion, and doing so could break backwards
                 * compatibility, so even if it is the "default" value of 0x10001, we do not set it to 0. */
                public.parameters.rsaDetail.exponent = exponent;
 
                break;
        }
        default:
                return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
                                       "EVP_PKEY type %d not supported.", key_id);
        }
 
        *ret = (TPM2B_PUBLIC) {
                .size = sizeof(public),
                .publicArea = public,
        };
 
        return 0;
}
#endif
 
int tpm2_tpm2b_public_to_fingerprint(
                const TPM2B_PUBLIC *public,
                void **ret_fingerprint,
                size_t *ret_fingerprint_size) {
 
#if HAVE_OPENSSL
        int r;
 
        assert(public);
        assert(ret_fingerprint);
        assert(ret_fingerprint_size);
 
        _cleanup_(EVP_PKEY_freep) EVP_PKEY *pkey = NULL;
        r = tpm2_tpm2b_public_to_openssl_pkey(public, &pkey);
        if (r < 0)
                return r;
 
        r = dlopen_libcrypto(LOG_DEBUG);
        if (r < 0)
                return r;
 
        /* Hardcode fingerprint to SHA256 */
        return pubkey_fingerprint(pkey, sym_EVP_sha256(), ret_fingerprint, ret_fingerprint_size);
#else
        return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "OpenSSL support is disabled.");
#endif
}
 
int tpm2_tpm2b_public_from_pem(const void *pem, size_t pem_size, TPM2B_PUBLIC *ret) {
#if HAVE_OPENSSL
        int r;
 
        assert(pem);
        assert(ret);
 
        _cleanup_(EVP_PKEY_freep) EVP_PKEY *pkey = NULL;
        r = openssl_pubkey_from_pem(pem, pem_size, &pkey);
        if (r < 0)
                return r;
 
        return tpm2_tpm2b_public_from_openssl_pkey(pkey, ret);
#else
        return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "OpenSSL support is disabled.");
#endif
}
 
/* Marshal the public, private, and seed objects into a single nonstandard 'blob'. The public and private
 * objects are required, while the seed is optional. This is not a (publicly) standard format, this is
 * specific to how we currently store the sealed object. This 'blob' can be unmarshalled by
 * tpm2_unmarshal_blob(). */
int tpm2_marshal_blob(
                const TPM2B_PUBLIC *public,
                const TPM2B_PRIVATE *private,
                const TPM2B_ENCRYPTED_SECRET *seed,
                void **ret_blob,
                size_t *ret_blob_size) {
 
        TSS2_RC rc;
 
        assert(public);
        assert(private);
        assert(ret_blob);
        assert(ret_blob_size);
 
        size_t max_size = sizeof(*private) + sizeof(*public);
        if (seed)
                max_size += sizeof(*seed);
 
        _cleanup_free_ void *blob = malloc(max_size);
        if (!blob)
                return log_oom_debug();
 
        size_t blob_size = 0;
        rc = sym_Tss2_MU_TPM2B_PRIVATE_Marshal(private, blob, max_size, &blob_size);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to marshal private key: %s", sym_Tss2_RC_Decode(rc));
 
        rc = sym_Tss2_MU_TPM2B_PUBLIC_Marshal(public, blob, max_size, &blob_size);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to marshal public key: %s", sym_Tss2_RC_Decode(rc));
 
        if (seed) {
                rc = sym_Tss2_MU_TPM2B_ENCRYPTED_SECRET_Marshal(seed, blob, max_size, &blob_size);
                if (rc != TSS2_RC_SUCCESS)
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                               "Failed to marshal encrypted seed: %s", sym_Tss2_RC_Decode(rc));
        }
 
        *ret_blob = TAKE_PTR(blob);
        *ret_blob_size = blob_size;
 
        return 0;
}
 
/* Unmarshal the 'blob' into public, private, and seed objects. The public and private objects are required
 * in the 'blob', while the seed is optional. This is not a (publicly) standard format, this is specific to
 * how we currently store the sealed object. This expects the 'blob' to have been created by
 * tpm2_marshal_blob(). */
int tpm2_unmarshal_blob(
                const void *blob,
                size_t blob_size,
                TPM2B_PUBLIC *ret_public,
                TPM2B_PRIVATE *ret_private,
                TPM2B_ENCRYPTED_SECRET *ret_seed) {
 
        TSS2_RC rc;
 
        assert(blob);
        assert(ret_public);
        assert(ret_private);
        assert(ret_seed);
 
        TPM2B_PRIVATE private = {};
        size_t offset = 0;
        rc = sym_Tss2_MU_TPM2B_PRIVATE_Unmarshal(blob, blob_size, &offset, &private);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to unmarshal private key: %s", sym_Tss2_RC_Decode(rc));
 
        TPM2B_PUBLIC public = {};
        rc = sym_Tss2_MU_TPM2B_PUBLIC_Unmarshal(blob, blob_size, &offset, &public);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to unmarshal public key: %s", sym_Tss2_RC_Decode(rc));
 
        TPM2B_ENCRYPTED_SECRET seed = {};
        if (blob_size > offset) {
                rc = sym_Tss2_MU_TPM2B_ENCRYPTED_SECRET_Unmarshal(blob, blob_size, &offset, &seed);
                if (rc != TSS2_RC_SUCCESS)
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                               "Failed to unmarshal encrypted seed: %s", sym_Tss2_RC_Decode(rc));
        }
 
        *ret_public = public;
        *ret_private = private;
        *ret_seed = seed;
 
        return 0;
}
 
/* Calculate a serialized handle. Once the upstream tpm2-tss library provides an api to do this, we can
 * remove this function. The addition of this functionality in tpm2-tss may be tracked here:
 * https://github.com/tpm2-software/tpm2-tss/issues/2575 */
int tpm2_calculate_serialize(
                TPM2_HANDLE handle,
                const TPM2B_NAME *name,
                const TPM2B_PUBLIC *public,
                void **ret_serialized,
                size_t *ret_serialized_size) {
 
        TSS2_RC rc;
 
        assert(name);
        assert(public);
        assert(ret_serialized);
        assert(ret_serialized_size);
 
        size_t max_size = sizeof(TPM2_HANDLE) + sizeof(TPM2B_NAME) + sizeof(uint32_t) + sizeof(TPM2B_PUBLIC);
        _cleanup_free_ void *serialized = malloc(max_size);
        if (!serialized)
                return log_oom_debug();
 
        size_t serialized_size = 0;
        rc = sym_Tss2_MU_TPM2_HANDLE_Marshal(handle, serialized, max_size, &serialized_size);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to marshal tpm handle: %s", sym_Tss2_RC_Decode(rc));
 
        rc = sym_Tss2_MU_TPM2B_NAME_Marshal(name, serialized, max_size, &serialized_size);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to marshal name: %s", sym_Tss2_RC_Decode(rc));
 
        /* This is defined (non-publicly) in the tpm2-tss source as IESYSC_KEY_RSRC, to a value of "1". */
        rc = sym_Tss2_MU_UINT32_Marshal(UINT32_C(1), serialized, max_size, &serialized_size);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to marshal esys resource id: %s", sym_Tss2_RC_Decode(rc));
 
        rc = sym_Tss2_MU_TPM2B_PUBLIC_Marshal(public, serialized, max_size, &serialized_size);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to marshal public: %s", sym_Tss2_RC_Decode(rc));
 
        *ret_serialized = TAKE_PTR(serialized);
        *ret_serialized_size = serialized_size;
 
        return 0;
}
 
/* Serialize a handle. This produces a binary object that can be later deserialized (by the same TPM), even
 * across restarts of the TPM or reboots (assuming the handle is persistent). */
int tpm2_serialize(
                Tpm2Context *c,
                const Tpm2Handle *handle,
                struct iovec *ret) {
 
        TSS2_RC rc;
 
        assert(c);
        assert(handle);
        assert(ret);
 
        _cleanup_(Esys_Freep) unsigned char *serialized = NULL;
        size_t size = 0;
        rc = sym_Esys_TR_Serialize(c->esys_context, handle->esys_handle, &serialized, &size);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to serialize: %s", sym_Tss2_RC_Decode(rc));
 
        /* Make a copy since we don't want the caller to understand that ESYS allocated the pointer.
         * It would make tracking what deallocator to use for the result in which context a PITA. */
        struct iovec v;
        v.iov_base = memdup(serialized, size);
        if (!v.iov_base)
                return log_oom_debug();
        v.iov_len = size;
 
        *ret = v;
        return 0;
}
 
int tpm2_deserialize(
                Tpm2Context *c,
                const struct iovec *serialized,
                Tpm2Handle **ret_handle) {
 
        TSS2_RC rc;
        int r;
 
        assert(c);
        assert(ret_handle);
 
        if (!iovec_is_set(serialized)) {
                *ret_handle = NULL;
                return 0;
        }
 
        _cleanup_(tpm2_handle_freep) Tpm2Handle *handle = NULL;
        r = tpm2_handle_new(c, &handle);
        if (r < 0)
                return r;
 
        /* Since this is an existing handle in the TPM we should not implicitly flush it. */
        handle->flush = false;
 
        rc = sym_Esys_TR_Deserialize(c->esys_context, serialized->iov_base, serialized->iov_len, &handle->esys_handle);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to deserialize: %s", sym_Tss2_RC_Decode(rc));
 
        *ret_handle = TAKE_PTR(handle);
        return 1;
}
 
#if HAVE_OPENSSL
 
/* KDFa() as defined by the TPM spec. */
static int tpm2_kdfa(
              TPMI_ALG_HASH hash_alg,
              const void *key,
              size_t key_len,
              const char *label,
              const void *context,
              size_t context_len,
              size_t bits,
              void **ret_key,
              size_t *ret_key_len) {
 
        int r;
 
        assert(key);
        assert(label);
        assert(context || context_len == 0);
        assert(bits > 0);
        assert(bits <= SIZE_MAX - 7);
        assert(ret_key);
        assert(ret_key_len);
 
        log_debug("Calculating KDFa().");
 
        size_t len = DIV_ROUND_UP(bits, 8);
 
        const char *hash_alg_name = tpm2_hash_alg_to_string(hash_alg);
        if (!hash_alg_name)
                return -EOPNOTSUPP;
 
        _cleanup_(erase_and_freep) void *buf = NULL;
        r = kdf_kb_hmac_derive(
                        "COUNTER",
                        hash_alg_name,
                        key,
                        key_len,
                        label,
                        strlen(label),
                        context,
                        context_len,
                        /* seed= */ NULL,
                        /* seed_size= */ 0,
                        len,
                        &buf);
        if (r < 0)
                return r;
 
        /* If the number of bits results in a partial byte, the TPM spec requires we zero the unrequested
         * bits in the MSB (i.e. at index 0). From the spec Part 1 ("Architecture") section on Key
         * Derivation Function, specifically KDFa():
         *
         * "The implied return from this function is a sequence of octets with a length equal to (bits + 7) /
         * 8. If bits is not an even multiple of 8, then the returned value occupies the least significant
         * bits of the returned octet array, and the additional, high-order bits in the 0th octet are
         * CLEAR. The unused bits of the most significant octet (MSO) are masked off and not shifted." */
        size_t partial = bits % 8;
        if (partial > 0)
                ((uint8_t*) buf)[0] &= 0xffu >> (8 - partial);
 
        *ret_key = TAKE_PTR(buf);
        *ret_key_len = len;
 
        return 0;
}
 
/* KDFe() as defined by the TPM spec. */
static int tpm2_kdfe(
              TPMI_ALG_HASH hash_alg,
              const void *shared_secret,
              size_t shared_secret_len,
              const char *label,
              const void *context_u,
              size_t context_u_size,
              const void *context_v,
              size_t context_v_size,
              size_t bits,
              void **ret_key,
              size_t *ret_key_len) {
 
        int r;
 
        assert(shared_secret);
        assert(label);
        assert(context_u);
        assert(context_v);
        assert(bits > 0);
        assert(bits <= SIZE_MAX - 7);
        assert(ret_key);
        assert(ret_key_len);
 
        log_debug("Calculating KDFe().");
 
        size_t len = DIV_ROUND_UP(bits, 8);
 
        const char *hash_alg_name = tpm2_hash_alg_to_string(hash_alg);
        if (!hash_alg_name)
                return -EOPNOTSUPP;
 
        size_t info_len = strlen(label) + 1 + context_u_size + context_v_size;
        _cleanup_free_ void *info = malloc(info_len);
        if (!info)
                return log_oom_debug();
 
        _unused_ void *end = mempcpy(mempcpy(stpcpy(info, label) + 1, context_u, context_u_size),
                                     context_v, context_v_size);
        /* assert we copied exactly the right amount that we allocated */
        assert(end > info && (uintptr_t) end - (uintptr_t) info == info_len);
 
        _cleanup_(erase_and_freep) void *buf = NULL;
        r = kdf_ss_derive(
                        hash_alg_name,
                        shared_secret,
                        shared_secret_len,
                        /* salt= */ NULL,
                        /* salt_size= */ 0,
                        info,
                        info_len,
                        len,
                        &buf);
        if (r < 0)
                return r;
 
        *ret_key = TAKE_PTR(buf);
        *ret_key_len = len;
 
        return 0;
}
 
static int tpm2_calculate_seal_public(
                const TPM2B_PUBLIC *parent,
                const TPMA_OBJECT *attributes,
                const TPM2B_DIGEST *policy,
                const TPM2B_DIGEST *seed,
                const void *secret,
                size_t secret_size,
                TPM2B_PUBLIC *ret) {
 
        int r;
 
        assert(parent);
        POINTER_MAY_BE_NULL(attributes);
        POINTER_MAY_BE_NULL(policy);
        assert(seed);
        assert(secret);
        assert(ret);
 
        log_debug("Calculating public part of sealed object.");
 
        struct iovec data[] = {
                IOVEC_MAKE((void*) seed->buffer, seed->size),
                IOVEC_MAKE((void*) secret, secret_size),
        };
        TPM2B_DIGEST unique;
        r = tpm2_digest_many(
                        parent->publicArea.nameAlg,
                        &unique,
                        data,
                        ELEMENTSOF(data),
                        /* extend= */ false);
        if (r < 0)
                return r;
 
        *ret = (TPM2B_PUBLIC) {
                .size = sizeof(TPMT_PUBLIC),
                .publicArea = {
                        .type = TPM2_ALG_KEYEDHASH,
                        .nameAlg = parent->publicArea.nameAlg,
                        .objectAttributes = attributes ? *attributes : 0,
                        .authPolicy = policy ? *policy : TPM2B_DIGEST_MAKE(NULL, unique.size),
                        .parameters.keyedHashDetail.scheme.scheme = TPM2_ALG_NULL,
                        .unique.keyedHash = unique,
                },
        };
 
        return 0;
}
 
static int tpm2_calculate_seal_private(
                const TPM2B_PUBLIC *parent,
                const TPM2B_NAME *name,
                const char *pin,
                const TPM2B_DIGEST *seed,
                const void *secret,
                size_t secret_size,
                TPM2B_PRIVATE *ret) {
 
        TSS2_RC rc;
        int r;
 
        assert(parent);
        assert(name);
        assert(seed);
        assert(secret);
        assert(ret);
 
        log_debug("Calculating private part of sealed object.");
 
        _cleanup_(erase_and_freep) void *storage_key = NULL;
        size_t storage_key_size;
        r = tpm2_kdfa(parent->publicArea.nameAlg,
                      seed->buffer,
                      seed->size,
                      "STORAGE",
                      name->name,
                      name->size,
                      (size_t) parent->publicArea.parameters.asymDetail.symmetric.keyBits.sym,
                      &storage_key,
                      &storage_key_size);
        if (r < 0)
                return log_debug_errno(r, "Could not calculate storage key KDFa: %m");
 
        r = tpm2_hash_alg_to_size(parent->publicArea.nameAlg);
        if (r < 0)
                return -EOPNOTSUPP;
 
        size_t bits = (size_t) r * 8;
 
        _cleanup_(erase_and_freep) void *integrity_key = NULL;
        size_t integrity_key_size;
        r = tpm2_kdfa(parent->publicArea.nameAlg,
                      seed->buffer,
                      seed->size,
                      "INTEGRITY",
                      /* context= */ NULL,
                      /* context_len= */ 0,
                      bits,
                      &integrity_key,
                      &integrity_key_size);
        if (r < 0)
                return log_debug_errno(r, "Could not calculate integrity key KDFa: %m");
 
        TPM2B_AUTH auth = {};
        CLEANUP_ERASE(auth);
        if (pin) {
                r = tpm2_auth_value_from_pin(parent->publicArea.nameAlg, pin, &auth);
                if (r < 0)
                        return r;
        }
 
        TPM2B_SENSITIVE sensitive = {
                .size = sizeof(TPMT_SENSITIVE),
                .sensitiveArea = {
                        .sensitiveType = TPM2_ALG_KEYEDHASH,
                        .authValue = auth,
                        .seedValue = *seed,
                        .sensitive.bits = TPM2B_SENSITIVE_DATA_MAKE(secret, secret_size),
                },
        };
        CLEANUP_ERASE(sensitive);
 
        _cleanup_(erase_and_freep) void *marshalled_sensitive = malloc(sizeof(sensitive));
        if (!marshalled_sensitive)
                return log_oom_debug();
 
        size_t marshalled_sensitive_size = 0;
        rc = sym_Tss2_MU_TPM2B_SENSITIVE_Marshal(
                        &sensitive,
                        marshalled_sensitive,
                        sizeof(sensitive),
                        &marshalled_sensitive_size);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to marshal sensitive: %s", sym_Tss2_RC_Decode(rc));
 
        const char *sym_alg = tpm2_sym_alg_to_string(parent->publicArea.parameters.asymDetail.symmetric.algorithm);
        if (!sym_alg)
                return -EOPNOTSUPP;
 
        const char *sym_mode = tpm2_sym_mode_to_string(parent->publicArea.parameters.asymDetail.symmetric.mode.sym);
        if (!sym_mode)
                return -EOPNOTSUPP;
 
        _cleanup_free_ void *encrypted_sensitive = NULL;
        size_t encrypted_sensitive_size;
        r = openssl_cipher(
                        sym_alg,
                        parent->publicArea.parameters.asymDetail.symmetric.keyBits.sym,
                        sym_mode,
                        storage_key, storage_key_size,
                        /* iv= */ NULL, /* iv_size= */ 0,
                        marshalled_sensitive, marshalled_sensitive_size,
                        &encrypted_sensitive, &encrypted_sensitive_size);
        if (r < 0)
                return r;
 
        const char *hash_alg_name = tpm2_hash_alg_to_string(parent->publicArea.nameAlg);
        if (!hash_alg_name)
                return -EOPNOTSUPP;
 
        _cleanup_free_ void *hmac_buffer = NULL;
        size_t hmac_size = 0;
        struct iovec hmac_data[] = {
                IOVEC_MAKE((void*) encrypted_sensitive, encrypted_sensitive_size),
                IOVEC_MAKE((void*) name->name, name->size),
        };
        r = openssl_hmac_many(
                        hash_alg_name,
                        integrity_key,
                        integrity_key_size,
                        hmac_data,
                        ELEMENTSOF(hmac_data),
                        &hmac_buffer,
                        &hmac_size);
        if (r < 0)
                return r;
 
        TPM2B_DIGEST outer_hmac = TPM2B_DIGEST_MAKE(hmac_buffer, hmac_size);
 
        TPM2B_PRIVATE private = {};
        size_t private_size = 0;
        rc = sym_Tss2_MU_TPM2B_DIGEST_Marshal(
                        &outer_hmac,
                        private.buffer,
                        sizeof(private.buffer),
                        &private_size);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to marshal digest: %s", sym_Tss2_RC_Decode(rc));
        private.size = private_size;
 
        assert(sizeof(private.buffer) - private.size >= encrypted_sensitive_size);
        memcpy_safe(&private.buffer[private.size], encrypted_sensitive, encrypted_sensitive_size);
        private.size += encrypted_sensitive_size;
 
        *ret = private;
 
        return 0;
}
 
static int tpm2_calculate_seal_rsa_seed(
                const TPM2B_PUBLIC *parent,
                void **ret_seed,
                size_t *ret_seed_size,
                void **ret_encrypted_seed,
                size_t *ret_encrypted_seed_size) {
 
        int r;
 
        assert(parent);
        assert(ret_seed);
        assert(ret_seed_size);
        assert(ret_encrypted_seed);
        assert(ret_encrypted_seed_size);
 
        log_debug("Calculating encrypted seed for RSA sealed object.");
 
        _cleanup_(EVP_PKEY_freep) EVP_PKEY *parent_pkey = NULL;
        r = tpm2_tpm2b_public_to_openssl_pkey(parent, &parent_pkey);
        if (r < 0)
                return log_debug_errno(r, "Could not convert TPM2B_PUBLIC to OpenSSL PKEY: %m");
 
        r = tpm2_hash_alg_to_size(parent->publicArea.nameAlg);
        if (r < 0)
                return -EOPNOTSUPP;
 
        size_t seed_size = (size_t) r;
 
        _cleanup_(erase_and_freep) void *seed = malloc(seed_size);
        if (!seed)
                return log_oom_debug();
 
        r = crypto_random_bytes(seed, seed_size);
        if (r < 0)
                return log_debug_errno(r, "Failed to generate random seed: %m");
 
        const char *hash_alg_name = tpm2_hash_alg_to_string(parent->publicArea.nameAlg);
        if (!hash_alg_name)
                return -EOPNOTSUPP;
 
        _cleanup_free_ void *encrypted_seed = NULL;
        size_t encrypted_seed_size;
        r = rsa_oaep_encrypt_bytes(
                        parent_pkey,
                        hash_alg_name,
                        "DUPLICATE",
                        seed,
                        seed_size,
                        &encrypted_seed,
                        &encrypted_seed_size);
        if (r < 0)
                return log_debug_errno(r, "Could not RSA-OAEP encrypt random seed: %m");
 
        *ret_seed = TAKE_PTR(seed);
        *ret_seed_size = seed_size;
        *ret_encrypted_seed = TAKE_PTR(encrypted_seed);
        *ret_encrypted_seed_size = encrypted_seed_size;
 
        return 0;
}
 
static int tpm2_calculate_seal_ecc_seed(
                const TPM2B_PUBLIC *parent,
                void **ret_seed,
                size_t *ret_seed_size,
                void **ret_encrypted_seed,
                size_t *ret_encrypted_seed_size) {
 
        TSS2_RC rc;
        int r;
 
        assert(parent);
        assert(ret_seed);
        assert(ret_seed_size);
        assert(ret_encrypted_seed);
        assert(ret_encrypted_seed_size);
 
        log_debug("Calculating encrypted seed for ECC sealed object.");
 
        _cleanup_(EVP_PKEY_freep) EVP_PKEY *parent_pkey = NULL;
        r = tpm2_tpm2b_public_to_openssl_pkey(parent, &parent_pkey);
        if (r < 0)
                return log_debug_errno(r, "Could not convert TPM2B_PUBLIC to OpenSSL PKEY: %m");
 
        int curve_id;
        r = ecc_pkey_to_curve_x_y(
                        parent_pkey,
                        &curve_id,
                        /* ret_x= */ NULL, /* ret_x_size= */ NULL,
                        /* ret_y= */ NULL, /* ret_y_size= */ NULL);
        if (r < 0)
                return r;
 
        _cleanup_(EVP_PKEY_freep) EVP_PKEY *pkey = NULL;
        r = ecc_pkey_new(curve_id, &pkey);
        if (r < 0)
                return r;
 
        _cleanup_(erase_and_freep) void *shared_secret = NULL;
        size_t shared_secret_size;
        r = ecc_ecdh(pkey, parent_pkey, &shared_secret, &shared_secret_size);
        if (r < 0)
                return log_debug_errno(r, "Could not generate ECC shared secret: %m");
 
        _cleanup_free_ void *x = NULL, *y = NULL;
        size_t x_size, y_size;
        r = ecc_pkey_to_curve_x_y(pkey, /* ret_curve_id= */ NULL, &x, &x_size, &y, &y_size);
        if (r < 0)
                return log_debug_errno(r, "Could not get ECC get x/y: %m");
 
        r = TPM2B_ECC_PARAMETER_CHECK_SIZE(x_size);
        if (r < 0)
                return log_debug_errno(r, "ECC point x size %zu is too large: %m", x_size);
 
        r = TPM2B_ECC_PARAMETER_CHECK_SIZE(y_size);
        if (r < 0)
                return log_debug_errno(r, "ECC point y size %zu is too large: %m", y_size);
 
        TPMS_ECC_POINT point = {
                .x = TPM2B_ECC_PARAMETER_MAKE(x, x_size),
                .y = TPM2B_ECC_PARAMETER_MAKE(y, y_size),
        };
 
        _cleanup_free_ void *encrypted_seed = malloc(sizeof(point));
        if (!encrypted_seed)
                return log_oom_debug();
 
        size_t encrypted_seed_size = 0;
        rc = sym_Tss2_MU_TPMS_ECC_POINT_Marshal(&point, encrypted_seed, sizeof(point), &encrypted_seed_size);
        if (rc != TPM2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to marshal ECC point: %s", sym_Tss2_RC_Decode(rc));
 
        r = tpm2_hash_alg_to_size(parent->publicArea.nameAlg);
        if (r < 0)
                return -EOPNOTSUPP;
 
        size_t bits = (size_t) r * 8;
 
        _cleanup_(erase_and_freep) void *seed = NULL;
        size_t seed_size = 0; /* Explicit initialization to appease gcc */
        r = tpm2_kdfe(parent->publicArea.nameAlg,
                      shared_secret,
                      shared_secret_size,
                      "DUPLICATE",
                      x,
                      x_size,
                      parent->publicArea.unique.ecc.x.buffer,
                      parent->publicArea.unique.ecc.x.size,
                      bits,
                      &seed,
                      &seed_size);
        if (r < 0)
                return log_debug_errno(r, "Could not calculate KDFe: %m");
 
        *ret_seed = TAKE_PTR(seed);
        *ret_seed_size = seed_size;
        *ret_encrypted_seed = TAKE_PTR(encrypted_seed);
        *ret_encrypted_seed_size = encrypted_seed_size;
 
        return 0;
}
 
static int tpm2_calculate_seal_seed(
                const TPM2B_PUBLIC *parent,
                TPM2B_DIGEST *ret_seed,
                TPM2B_ENCRYPTED_SECRET *ret_encrypted_seed) {
 
        int r;
 
        assert(parent);
        assert(ret_seed);
        assert(ret_encrypted_seed);
 
        log_debug("Calculating encrypted seed for sealed object.");
 
        _cleanup_(erase_and_freep) void *seed = NULL;
        _cleanup_free_ void *encrypted_seed = NULL;
        size_t seed_size = 0, encrypted_seed_size = 0; /* Explicit initialization to appease gcc */
        if (parent->publicArea.type == TPM2_ALG_RSA)
                r = tpm2_calculate_seal_rsa_seed(parent, &seed, &seed_size, &encrypted_seed, &encrypted_seed_size);
        else if (parent->publicArea.type == TPM2_ALG_ECC)
                r = tpm2_calculate_seal_ecc_seed(parent, &seed, &seed_size, &encrypted_seed, &encrypted_seed_size);
        else
                return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
                                       "Unsupported parent key type 0x%" PRIx16, parent->publicArea.type);
        if (r < 0)
                return log_debug_errno(r, "Could not calculate encrypted seed: %m");
 
        *ret_seed = TPM2B_DIGEST_MAKE(seed, seed_size);
        *ret_encrypted_seed = TPM2B_ENCRYPTED_SECRET_MAKE(encrypted_seed, encrypted_seed_size);
 
        return 0;
}
 
#endif /* HAVE_OPENSSL */
 
int tpm2_calculate_seal(
                TPM2_HANDLE parent_handle,
                const TPM2B_PUBLIC *parent_public,
                const TPMA_OBJECT *attributes,
                const struct iovec *secret,
                const TPM2B_DIGEST *policy,
                const char *pin,
                struct iovec *ret_secret,
                struct iovec *ret_blob,
                struct iovec *ret_serialized_parent) {
 
#if HAVE_OPENSSL
        int r;
 
        assert(parent_public);
        assert(iovec_is_valid(secret));
        assert(secret || ret_secret);
        assert(!(secret && ret_secret)); /* Either provide a secret, or we create one, but not both */
        assert(ret_blob);
        assert(ret_serialized_parent);
 
        log_debug("Calculating sealed object.");
 
        /* Default to the SRK. */
        if (parent_handle == 0)
                parent_handle = TPM2_SRK_HANDLE;
 
        switch (TPM2_HANDLE_TYPE(parent_handle)) {
        case TPM2_HT_PERSISTENT:
        case TPM2_HT_NV_INDEX:
                break;
        case TPM2_HT_TRANSIENT:
                log_warning("Handle is transient, sealed secret may not be recoverable.");
                break;
        default:
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Handle 0x%" PRIx32 " not persistent, transient, or NV.",
                                       parent_handle);
        }
 
        _cleanup_(iovec_done_erase) struct iovec generated_secret = {};
        if (!secret) {
                /* No secret provided, generate a random secret. We use SHA256 digest length, though it can
                 * be up to TPM2_MAX_SEALED_DATA. The secret length is not limited to the nameAlg hash
                 * size. */
                r = crypto_random_bytes_allocate_iovec(TPM2_SHA256_DIGEST_SIZE, &generated_secret);
                if (r < 0)
                        return log_debug_errno(r, "Failed to generate secret key: %m");
 
                secret = &generated_secret;
        }
 
        if (secret->iov_len > TPM2_MAX_SEALED_DATA)
                return log_debug_errno(SYNTHETIC_ERRNO(EOVERFLOW),
                                       "Secret size %zu too large, limit is %d bytes.",
                                       secret->iov_len, TPM2_MAX_SEALED_DATA);
 
        TPM2B_DIGEST random_seed;
        TPM2B_ENCRYPTED_SECRET seed;
        r = tpm2_calculate_seal_seed(parent_public, &random_seed, &seed);
        if (r < 0)
                return r;
 
        TPM2B_PUBLIC public;
        r = tpm2_calculate_seal_public(parent_public, attributes, policy, &random_seed, secret->iov_base, secret->iov_len, &public);
        if (r < 0)
                return r;
 
        TPM2B_NAME name;
        r = tpm2_calculate_pubkey_name(&public.publicArea, &name);
        if (r < 0)
                return r;
 
        TPM2B_PRIVATE private;
        r = tpm2_calculate_seal_private(parent_public, &name, pin, &random_seed, secret->iov_base, secret->iov_len, &private);
        if (r < 0)
                return r;
 
        _cleanup_(iovec_done) struct iovec blob = {};
        r = tpm2_marshal_blob(&public, &private, &seed, &blob.iov_base, &blob.iov_len);
        if (r < 0)
                return log_debug_errno(r, "Could not create sealed blob: %m");
 
        TPM2B_NAME parent_name;
        r = tpm2_calculate_pubkey_name(&parent_public->publicArea, &parent_name);
        if (r < 0)
                return r;
 
        _cleanup_(iovec_done) struct iovec serialized_parent = {};
        r = tpm2_calculate_serialize(
                        parent_handle,
                        &parent_name,
                        parent_public,
                        &serialized_parent.iov_base,
                        &serialized_parent.iov_len);
        if (r < 0)
                return r;
 
        if (ret_secret)
                *ret_secret = TAKE_STRUCT(generated_secret);
        *ret_blob = TAKE_STRUCT(blob);
        *ret_serialized_parent = TAKE_STRUCT(serialized_parent);
 
        return 0;
#else /* HAVE_OPENSSL */
        return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "OpenSSL support is disabled.");
#endif
}
 
int tpm2_make_policy_authorize_tbs_data(
                const TPM2B_DIGEST *approved_digest,
                const char *policy_ref_data,
                struct iovec *ret_tbs_data) {
 
        TPM2B_NONCE policy_ref;
 
        assert(approved_digest);
        assert(ret_tbs_data);
 
        tpm2_make_policy_ref(policy_ref_data, &policy_ref);
 
        /* The data to be signed for a TPM2_PolicyAuthorize() is the concatenation of the approved policy
         * digest and the policy reference, as per TPM2 Spec Part 3, 23.16. */
        _cleanup_(iovec_done) struct iovec tbs_data = {};
 
        if (!iovec_append(&tbs_data, &IOVEC_MAKE(approved_digest->buffer, approved_digest->size)))
                return log_oom_debug();
 
        if (!iovec_append(&tbs_data, &IOVEC_MAKE(policy_ref.buffer, policy_ref.size)))
                return log_oom_debug();
 
        *ret_tbs_data = TAKE_STRUCT(tbs_data);
        return 0;
}
 
int tpm2_seal(Tpm2Context *c,
              uint32_t seal_key_handle,
              const TPM2B_DIGEST policy[],
              size_t n_policy,
              const char *pin,
              struct iovec *ret_secret,
              struct iovec **ret_blobs,
              size_t *ret_n_blobs,
              uint16_t *ret_primary_alg,
              struct iovec *ret_srk) {
 
        uint16_t primary_alg = 0;
        int r;
 
        assert(ret_secret);
        assert(ret_blobs);
        assert(ret_n_blobs);
 
        /* So here's what we do here: we connect to the TPM2 chip. It persistently contains a "seed" key that
         * is randomized when the TPM2 is first initialized or reset and remains stable across boots. We
         * generate a "primary" key pair derived from that (ECC if possible, RSA as fallback). Given the seed
         * remains fixed this will result in the same key pair whenever we specify the exact same parameters
         * for it. We then create a PCR-bound policy session, which calculates a hash on the current PCR
         * values of the indexes we specify. We then generate a randomized key on the host (which is the key
         * we actually enroll in the LUKS2 keyslots), which we upload into the TPM2, where it is encrypted
         * with the "primary" key, taking the PCR policy session into account. We then download the encrypted
         * key from the TPM2 ("sealing") and marshall it into binary form, which is ultimately placed in the
         * LUKS2 JSON header.
         *
         * The TPM2 "seed" key and "primary" keys never leave the TPM2 chip (and cannot be extracted at
         * all). The random key we enroll in LUKS2 we generate on the host using the Linux random device. It
         * is stored in the LUKS2 JSON only in encrypted form with the "primary" key of the TPM2 chip, thus
         * binding the unlocking to the TPM2 chip. */
 
        usec_t start = now(CLOCK_MONOTONIC);
 
        TPMA_OBJECT hmac_attributes =
                        TPMA_OBJECT_FIXEDTPM |
                        TPMA_OBJECT_FIXEDPARENT;