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 11001–12000 of 12,273

        _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
        r = sd_json_buildo(
                        &v,
                        SD_JSON_BUILD_PAIR_INTEGER("nvIndex", nv_public->nvIndex),
                        SD_JSON_BUILD_PAIR_STRING("nameAlg", tpm2_hash_alg_to_string_tss2(nv_public->nameAlg)),
                        /* tss2-fapi serializes these as an object with pretty names, but it can deserialize
                         * an integer here. */
                        SD_JSON_BUILD_PAIR_INTEGER("attributes", nv_public->attributes),
                        SD_JSON_BUILD_PAIR_HEX("authPolicy", nv_public->authPolicy.buffer, nv_public->authPolicy.size),
                        SD_JSON_BUILD_PAIR_INTEGER("dataSize", nv_public->dataSize));
        if (r < 0)
                return r;
 
        *ret = TAKE_PTR(v);
        return 0;
}
 
static const TPMT_SIG_SCHEME SIG_SCHEME_TEMPLATE_NULL = {
        .scheme = TPM2_ALG_NULL,
};
 
int tpm2_quote(
               Tpm2Context *c,
               const Tpm2Handle *sign_session,
               const Tpm2Handle *audit_session,
               const Tpm2Handle *sign_key,
               const TPM2B_DATA *qualifying_data,
               const TPML_PCR_SELECTION *pcr_select,
               TPMS_ATTEST **ret_quoted,
               TPMT_SIGNATURE **ret_signature) {
 
        TSS2_RC rc;
        int r;
 
        assert(c);
        assert(pcr_select);
 
        tpm2_log_debug_tpml_pcr_selection(pcr_select, "Fetching TPM PCR quote for selection");
 
        if (audit_session && !tpm2_is_audit_session(c, audit_session))
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Supplied session handle is not an audit session.");
 
        _cleanup_(Esys_Freep) TPM2B_ATTEST *quoted = NULL;
        _cleanup_(Esys_Freep) TPMT_SIGNATURE *signature = NULL;
        rc = sym_Esys_Quote(
                        c->esys_context,
                        sign_key ? sign_key->esys_handle : ESYS_TR_NONE,
                        sign_session ? sign_session->esys_handle : ESYS_TR_PASSWORD,
                        audit_session ? audit_session->esys_handle : ESYS_TR_NONE,
                        ESYS_TR_NONE,
                        qualifying_data,
                        &SIG_SCHEME_TEMPLATE_NULL,
                        pcr_select,
                        &quoted,
                        ret_signature ? &signature : NULL);
        if (rc == TPM2_RC_EXCLUSIVE)
                return log_debug_errno(SYNTHETIC_ERRNO(EBUSY),
                                       "Failed to obtain TPM quote: audit session required exclusivity");
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to obtain TPM quote: %s", sym_Tss2_RC_Decode(rc));
 
        if (ret_quoted) {
                _cleanup_free_ TPMS_ATTEST *quoted_decoded = new0(TPMS_ATTEST, 1);
                if (!quoted_decoded)
                        return log_oom_debug();
                r = tpm2_unmarshal_attestation(quoted->attestationData, quoted->size, quoted_decoded);
                if (r < 0)
                        return r;
 
                *ret_quoted = TAKE_PTR(quoted_decoded);
        }
        if (ret_signature)
                *ret_signature = TAKE_PTR(signature);
 
        return 0;
}
 
int tpm2_nv_certify(
                Tpm2Context *c,
                const Tpm2Handle *sign_session,
                const Tpm2Handle *auth_session,
                const Tpm2Handle *audit_session,
                const Tpm2Handle *sign_key,
                const TPMS_NV_PUBLIC *nv_public,
                const Tpm2Handle *nv_handle,
                const TPM2B_DATA *qualifying_data,
                TPMS_ATTEST **ret_certify_info,
                TPMT_SIGNATURE **ret_signature) {
 
        TSS2_RC rc;
        int r;
 
        assert(c);
        assert(nv_public);
        assert(nv_handle);
 
        log_debug("Fetching TPM attestation for NV index 0x%" PRIx32 ".", nv_public->nvIndex);
 
        if (audit_session && !tpm2_is_audit_session(c, audit_session))
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Supplied session handle is not an audit session.");
 
        TPM2_HANDLE nv_index;
        r = tpm2_index_from_handle(c, nv_handle, &nv_index);
        if (r == -EOPNOTSUPP)
                nv_index = nv_public->nvIndex;
        else if (r < 0)
                return log_debug_errno(r, "Failed to get index from TPM handle");
 
        if (nv_index != nv_public->nvIndex)
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Inconsistent TPMS_NV_PUBLIC and Tpm2Handle arguments supplied");
 
        _cleanup_(Esys_Freep) TPM2B_ATTEST *certify_info = NULL;
        _cleanup_(Esys_Freep) TPMT_SIGNATURE *signature = NULL;
        rc = sym_Esys_NV_Certify(
                        c->esys_context,
                        sign_key ? sign_key->esys_handle : ESYS_TR_NONE,
                        nv_handle->esys_handle,
                        nv_handle->esys_handle,
                        sign_session ? sign_session->esys_handle : ESYS_TR_PASSWORD,
                        auth_session ? auth_session->esys_handle : ESYS_TR_PASSWORD,
                        audit_session ? audit_session->esys_handle : ESYS_TR_NONE,
                        qualifying_data,
                        &SIG_SCHEME_TEMPLATE_NULL,
                        nv_public->dataSize, 0,
                        &certify_info,
                        ret_signature ? &signature : NULL);
        if (rc == TPM2_RC_EXCLUSIVE)
                return log_debug_errno(SYNTHETIC_ERRNO(EBUSY),
                                       "Failed to obtain TPM attestation for NV index: audit session required exclusivity");
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to obtain TPM attestation for NV index: %s", sym_Tss2_RC_Decode(rc));
 
        if (ret_certify_info) {
                _cleanup_free_ TPMS_ATTEST *certify_info_decoded = new0(TPMS_ATTEST, 1);
                if (!certify_info_decoded)
                        return log_oom_debug();
                r = tpm2_unmarshal_attestation(certify_info->attestationData, certify_info->size, certify_info_decoded);
                if (r < 0)
                        return r;
 
                *ret_certify_info = TAKE_PTR(certify_info_decoded);
        }
        if (ret_signature)
                *ret_signature = TAKE_PTR(signature);
 
        return 0;
}
 
int tpm2_get_session_audit_digest(
                Tpm2Context *c,
                const Tpm2Handle *eh_session,
                const Tpm2Handle *sign_session,
                const Tpm2Handle *audit_session,
                const Tpm2Handle *sign_key,
                const TPM2B_DATA *qualifying_data,
                TPMS_ATTEST **ret_audit_info,
                TPMT_SIGNATURE **ret_signature) {
 
        TSS2_RC rc;
        int r;
 
        assert(c);
        assert(audit_session);
 
        log_debug("Fetching TPM attestation for audit session.");
 
        _cleanup_(Esys_Freep) TPM2B_ATTEST *audit_info = NULL;
        _cleanup_(Esys_Freep) TPMT_SIGNATURE *signature = NULL;
        rc = sym_Esys_GetSessionAuditDigest(
                        c->esys_context,
                        ESYS_TR_RH_ENDORSEMENT,
                        sign_key ? sign_key->esys_handle : ESYS_TR_NONE,
                        audit_session->esys_handle,
                        eh_session ? eh_session->esys_handle : ESYS_TR_PASSWORD,
                        sign_session ? sign_session->esys_handle : ESYS_TR_PASSWORD,
                        ESYS_TR_NONE,
                        qualifying_data,
                        &SIG_SCHEME_TEMPLATE_NULL,
                        &audit_info,
                        ret_signature ? &signature : NULL);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to obtain TPM attestation for audit session: %s", sym_Tss2_RC_Decode(rc));
 
        if (ret_audit_info) {
                _cleanup_free_ TPMS_ATTEST *audit_info_decoded = new0(TPMS_ATTEST, 1);
                if (!audit_info_decoded)
                        return log_oom_debug();
                r = tpm2_unmarshal_attestation(audit_info->attestationData, audit_info->size, audit_info_decoded);
                if (r < 0)
                        return r;
 
                *ret_audit_info = TAKE_PTR(audit_info_decoded);
        }
        if (ret_signature)
                *ret_signature = TAKE_PTR(signature);
 
        return 0;
}
 
#endif
 
int tpm2_argon2id_derive_split(
                const char *pin,
                const struct iovec *salt,
                const Argon2IdParameters *argon2id_params,
                struct iovec *ret_key1,
                char **ret_b64_pin) {
 
        int r;
        _cleanup_(iovec_done_erase) struct iovec derived = {};
 
        assert(pin);
        assert(salt);
        assert(argon2id_params);
        assert(ret_key1);
        assert(ret_b64_pin);
 
        r = kdf_argon2id_derive(
                        &IOVEC_MAKE(pin, strlen(pin)),
                        salt,
                        argon2id_params,
                        /* derive_size= */ 64, &derived);
        if (r < 0)
                return r;
 
        assert(derived.iov_len == 64);
 
        const uint8_t *derived_bytes = derived.iov_base;
 
        ret_key1->iov_base = memdup(derived_bytes, 32);
        if (!ret_key1->iov_base)
                return log_oom();
        ret_key1->iov_len = 32;
 
        ssize_t n = base64mem(derived_bytes + 32, 32, ret_b64_pin);
        if (n < 0)
                return log_oom();
 
        return 0;
}
 
int tpm2_argon2id_hkdf(
                const struct iovec *key1,
                const struct iovec *unsealed,
                struct iovec *ret_volume_key) {
 
        assert(key1);
        assert(key1->iov_len > 0);
        assert(unsealed);
        assert(ret_volume_key);
 
        return kdf_hkdf_sha256(
                        key1,
                        unsealed,
                        &IOVEC_MAKE_STRING("systemd-tpm2-argon2id-lock"),
                        /* derive_size= */ 32, ret_volume_key);
}
 
char* tpm2_pcr_mask_to_string(uint32_t mask) {
        _cleanup_free_ char *s = NULL;
 
        FOREACH_PCR_IN_MASK(n, mask)
                if (strextendf_with_separator(&s, "+", "%d", n) < 0)
                        return NULL;
 
        if (!s)
                return strdup("");
 
        return TAKE_PTR(s);
}
 
int tpm2_make_pcr_json_array(uint32_t pcr_mask, sd_json_variant **ret) {
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *a = NULL;
        int r;
 
        assert(ret);
 
        for (size_t i = 0; i < TPM2_PCRS_MAX; i++) {
                _cleanup_(sd_json_variant_unrefp) sd_json_variant *e = NULL;
 
                if ((pcr_mask & (UINT32_C(1) << i)) == 0)
                        continue;
 
                r = sd_json_variant_new_integer(&e, i);
                if (r < 0)
                        return r;
 
                r = sd_json_variant_append_array(&a, e);
                if (r < 0)
                        return r;
        }
 
        if (!a)
                return sd_json_variant_new_array(ret, NULL, 0);
 
        *ret = TAKE_PTR(a);
        return 0;
}
 
int tpm2_parse_pcr_json_array(sd_json_variant *v, uint32_t *ret) {
        sd_json_variant *e;
        uint32_t mask = 0;
 
        if (!sd_json_variant_is_array(v))
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 PCR array is not a JSON array.");
 
        JSON_VARIANT_ARRAY_FOREACH(e, v) {
                uint64_t u;
 
                if (!sd_json_variant_is_unsigned(e))
                        return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 PCR is not an unsigned integer.");
 
                u = sd_json_variant_unsigned(e);
                if (u >= TPM2_PCRS_MAX)
                        return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 PCR number out of range: %" PRIu64, u);
 
                mask |= UINT32_C(1) << u;
        }
 
        if (ret)
                *ret = mask;
 
        return 0;
}
 
static int tpm2_make_shard_array(
                const struct iovec data[],
                size_t n_data,
                int (*encode_iovec)(sd_json_variant **, const void*, size_t n), /* pass sd_json_variant_new_base64() or sd_json_variant_new_hex() */
                sd_json_variant **ret) {
 
        int r;
 
        /* Turns a series of struct iovec into either an array of base64/hex strings, or a single string
         * thereof. Used for generated "tpm2-blob" or "tpm2-policy-hash" fields. */
 
        assert(data);
        assert(n_data > 0);
        assert(encode_iovec);
        assert(ret);
 
        /* Only one item? Then create only one encoded string, for compatibility with older versions which
         * didn't support the "sharding" scheme */
        if (n_data == 1)
                return encode_iovec(ret, data[0].iov_base, data[0].iov_len);
 
        /* Multiple items? Then generate an array of encoded strings */
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *j = NULL;
 
        FOREACH_ARRAY(d, data, n_data) {
                _cleanup_(sd_json_variant_unrefp) sd_json_variant *item = NULL;
 
                r = encode_iovec(&item, d->iov_base, d->iov_len);
                if (r < 0)
                        return r;
 
                r = sd_json_variant_append_array(&j, item);
                if (r < 0)
                        return r;
        }
 
        *ret = TAKE_PTR(j);
        return 0;
}
 
int tpm2_make_luks2_json(
                int keyslot,
                uint32_t hash_pcr_mask,
                uint16_t pcr_bank,
                const struct iovec *pubkey,
                const char *pubkey_policy_ref,
                uint32_t pubkey_pcr_mask,
                uint16_t primary_alg,
                const struct iovec blobs[],
                size_t n_blobs,
                const struct iovec policy_hash[],
                size_t n_policy_hash,
                const struct iovec *salt,
                const struct iovec *srk,
                const struct iovec *pcrlock_nv,
                TPM2Flags flags,
                const Argon2IdParameters *argon2id_params,
                sd_json_variant **ret) {
 
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL, *hmj = NULL, *pkmj = NULL;
        _cleanup_free_ char *keyslot_as_string = NULL;
        int r;
 
        assert(iovec_is_valid(pubkey));
        assert(!pubkey_policy_ref || iovec_is_set(pubkey));
        assert(n_blobs >= 1);
        assert(n_policy_hash >= 1);
 
        POINTER_MAY_BE_NULL(argon2id_params);
 
        if (asprintf(&keyslot_as_string, "%i", keyslot) < 0)
                return -ENOMEM;
 
        r = tpm2_make_pcr_json_array(hash_pcr_mask, &hmj);
        if (r < 0)
                return r;
 
        if (pubkey_pcr_mask != 0) {
                r = tpm2_make_pcr_json_array(pubkey_pcr_mask, &pkmj);
                if (r < 0)
                        return r;
        }
 
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *phj = NULL;
        r = tpm2_make_shard_array(policy_hash, n_policy_hash, sd_json_variant_new_hex, &phj);
        if (r < 0)
                return r;
 
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *bj = NULL;
        r = tpm2_make_shard_array(blobs, n_blobs, sd_json_variant_new_base64, &bj);
        if (r < 0)
                return r;
 
        const Argon2IdParameters argon2id_params_safe =
                FLAGS_SET(flags, TPM2_FLAGS_USE_ARGON2ID) && argon2id_params
                ? *argon2id_params
                : (Argon2IdParameters) {};
 
        /* Note: We made the mistake of using "-" in the field names, which isn't particular compatible with
         * other programming languages. Let's not make things worse though, i.e. future additions to the JSON
         * object should use "_" rather than "-" in field names. */
 
        r = sd_json_buildo(
                        &v,
                        SD_JSON_BUILD_PAIR("type", JSON_BUILD_CONST_STRING("systemd-tpm2")),
                        SD_JSON_BUILD_PAIR("keyslots", SD_JSON_BUILD_ARRAY(SD_JSON_BUILD_STRING(keyslot_as_string))),
                        SD_JSON_BUILD_PAIR_VARIANT("tpm2-blob", bj),
                        SD_JSON_BUILD_PAIR_VARIANT("tpm2-pcrs", hmj),
                        SD_JSON_BUILD_PAIR_CONDITION(pcr_bank != 0 && tpm2_hash_alg_to_string(pcr_bank), "tpm2-pcr-bank", SD_JSON_BUILD_STRING(tpm2_hash_alg_to_string(pcr_bank))),
                        SD_JSON_BUILD_PAIR_CONDITION(primary_alg != 0 && tpm2_asym_alg_to_string(primary_alg), "tpm2-primary-alg", SD_JSON_BUILD_STRING(tpm2_asym_alg_to_string(primary_alg))),
                        SD_JSON_BUILD_PAIR_VARIANT("tpm2-policy-hash", phj),
                        SD_JSON_BUILD_PAIR_CONDITION(FLAGS_SET(flags, TPM2_FLAGS_USE_PIN), "tpm2-pin", SD_JSON_BUILD_BOOLEAN(true)),
                        SD_JSON_BUILD_PAIR_CONDITION(FLAGS_SET(flags, TPM2_FLAGS_USE_PCRLOCK), "tpm2_pcrlock", SD_JSON_BUILD_BOOLEAN(true)),
                        SD_JSON_BUILD_PAIR_CONDITION(pubkey_pcr_mask != 0, "tpm2_pubkey_pcrs", SD_JSON_BUILD_VARIANT(pkmj)),
                        SD_JSON_BUILD_PAIR_CONDITION(iovec_is_set(pubkey), "tpm2_pubkey", JSON_BUILD_IOVEC_BASE64(pubkey)),
                        SD_JSON_BUILD_PAIR_CONDITION(pubkey_policy_ref != NULL, "tpm2_pubkey_ref", SD_JSON_BUILD_STRING(pubkey_policy_ref)),
                        SD_JSON_BUILD_PAIR_CONDITION(iovec_is_set(salt), "tpm2_salt", JSON_BUILD_IOVEC_BASE64(salt)),
                        SD_JSON_BUILD_PAIR_CONDITION(iovec_is_set(srk), "tpm2_srk", JSON_BUILD_IOVEC_BASE64(srk)),
                        SD_JSON_BUILD_PAIR_CONDITION(iovec_is_set(pcrlock_nv), "tpm2_pcrlock_nv", JSON_BUILD_IOVEC_BASE64(pcrlock_nv)),
                        SD_JSON_BUILD_PAIR_CONDITION(FLAGS_SET(flags, TPM2_FLAGS_USE_ARGON2ID), "tpm2_argon2id_memcost", SD_JSON_BUILD_UNSIGNED(argon2id_params_safe.memcost_bytes)),
                        SD_JSON_BUILD_PAIR_CONDITION(FLAGS_SET(flags, TPM2_FLAGS_USE_ARGON2ID), "tpm2_argon2id_iterations", SD_JSON_BUILD_UNSIGNED(argon2id_params_safe.iterations)),
                        SD_JSON_BUILD_PAIR_CONDITION(FLAGS_SET(flags, TPM2_FLAGS_USE_ARGON2ID), "tpm2_argon2id_lanes", SD_JSON_BUILD_UNSIGNED(argon2id_params_safe.lanes)));
        if (r < 0)
                return r;
 
        if (ret)
                *ret = TAKE_PTR(v);
 
        return keyslot;
}
 
static int tpm2_parse_shard_array(
                sd_json_variant *v,
                const char *name,
                int (*decode_iovec)(sd_json_variant*, struct iovec *ret), /* pass json_variant_unbase64_iovec() or json_variant_unhex_iovec() */
                struct iovec **ret_data,
                size_t *ret_n_data) {
 
        int r;
 
        assert(v);
        assert(name);
        assert(decode_iovec);
        assert(ret_data);
        assert(ret_n_data);
 
        /* Parses the "tpm2-blob" or "tpm2-policy-hash" fields of our LUKS JSON serialization. This can
         * either be an array of base64/hex strings, or a single such string. The former to allow for sharded
         * keys. The latter mostly for compatibility with older versions where we didn't support sharded
         * keys. */
 
        struct iovec *data = NULL;
        size_t n_data = 0;
        CLEANUP_ARRAY(data, n_data, iovec_array_free);
 
        if (sd_json_variant_is_array(v)) {
                if (sd_json_variant_elements(v) == 0)
                        return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 token data contains empty '%s' array.", name);
 
                data = new0(struct iovec, sd_json_variant_elements(v));
                if (!data)
                        return log_oom_debug();
 
                sd_json_variant *i;
                JSON_VARIANT_ARRAY_FOREACH(i, v) {
                        r = decode_iovec(i, data + n_data);
                        if (r < 0)
                                return log_debug_errno(r, "Invalid data in '%s' field.", name);
 
                        n_data++;
                }
        } else {
                data = new0(struct iovec, 1);
                if (!data)
                        return log_oom_debug();
 
                r = decode_iovec(v, data + 0);
                if (r < 0)
                        return log_debug_errno(r, "Invalid data in '%s' field.", name);
 
                n_data = 1;
        }
 
        *ret_data = TAKE_PTR(data);
        *ret_n_data = n_data;
        return 0;
}
 
int tpm2_parse_luks2_json(
                sd_json_variant *v,
                int *ret_keyslot,
                uint32_t *ret_hash_pcr_mask,
                uint16_t *ret_pcr_bank,
                struct iovec *ret_pubkey,
                char **ret_pubkey_policy_ref,
                uint32_t *ret_pubkey_pcr_mask,
                uint16_t *ret_primary_alg,
                struct iovec **ret_blobs,
                size_t *ret_n_blobs,
                struct iovec **ret_policy_hash,
                size_t *ret_n_policy_hash,
                struct iovec *ret_salt,
                struct iovec *ret_srk,
                struct iovec *ret_pcrlock_nv,
                TPM2Flags *ret_flags,
                Argon2IdParameters *ret_argon2id_params) {
 
        _cleanup_(iovec_done) struct iovec pubkey = {}, salt = {}, srk = {}, pcrlock_nv = {};
        _cleanup_free_ char *pubkey_ref = NULL;
        uint32_t hash_pcr_mask = 0, pubkey_pcr_mask = 0;
        uint16_t primary_alg = 0;
        uint16_t pcr_bank = UINT16_MAX; /* default: pick automatically */
        int r, keyslot = -1;
        TPM2Flags flags = 0;
        sd_json_variant *w;
 
        assert(v);
 
        if (ret_keyslot) {
                keyslot = cryptsetup_get_keyslot_from_token(v);
                if (keyslot < 0) {
                        /* Return a recognizable error when parsing this field, so that callers can handle parsing
                         * errors of the keyslots field gracefully, since it's not 'owned' by us, but by the LUKS2
                         * spec */
                        log_debug_errno(keyslot, "Failed to extract keyslot index from TPM2 JSON data token, skipping: %m");
                        return -EUCLEAN;
                }
        }
 
        w = sd_json_variant_by_key(v, "tpm2-pcrs");
        if (!w)
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 token data lacks 'tpm2-pcrs' field.");
 
        r = tpm2_parse_pcr_json_array(w, &hash_pcr_mask);
        if (r < 0)
                return log_debug_errno(r, "Failed to parse TPM2 PCR mask: %m");
 
        /* The bank field is optional, since it was added in systemd 250 only. Before the bank was hardcoded
         * to SHA256. */
        w = sd_json_variant_by_key(v, "tpm2-pcr-bank");
        if (w) {
                /* The PCR bank field is optional */
 
                if (!sd_json_variant_is_string(w))
                        return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 PCR bank is not a string.");
 
                r = tpm2_hash_alg_from_string(sd_json_variant_string(w));
                if (r < 0)
                        return log_debug_errno(r, "TPM2 PCR bank invalid or not supported: %s", sd_json_variant_string(w));
 
                pcr_bank = r;
        }
 
        /* The primary key algorithm field is optional, since it was also added in systemd 250 only. Before
         * the algorithm was hardcoded to ECC. */
        w = sd_json_variant_by_key(v, "tpm2-primary-alg");
        if (w) {
                /* The primary key algorithm is optional */
 
                if (!sd_json_variant_is_string(w))
                        return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 primary key algorithm is not a string.");
 
                r = tpm2_asym_alg_from_string(sd_json_variant_string(w));
                if (r < 0)
                        return log_debug_errno(r, "TPM2 asymmetric algorithm invalid or not supported: %s", sd_json_variant_string(w));
 
                primary_alg = r;
        }
 
        w = sd_json_variant_by_key(v, "tpm2-blob");
        if (!w)
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 token data lacks 'tpm2-blob' field.");
 
        struct iovec *blobs = NULL;
        size_t n_blobs = 0;
        CLEANUP_ARRAY(blobs, n_blobs, iovec_array_free);
 
        r = tpm2_parse_shard_array(w, "tpm2-blob", json_variant_unbase64_iovec, &blobs, &n_blobs);
        if (r < 0)
                return r;
 
        w = sd_json_variant_by_key(v, "tpm2-policy-hash");
        if (!w)
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 token data lacks 'tpm2-policy-hash' field.");
 
        struct iovec *policy_hash = NULL;
        size_t n_policy_hash = 0;
        CLEANUP_ARRAY(policy_hash, n_policy_hash, iovec_array_free);
 
        r = tpm2_parse_shard_array(w, "tpm2-policy-hash", json_variant_unhex_iovec, &policy_hash, &n_policy_hash);
        if (r < 0)
                return r;
 
        w = sd_json_variant_by_key(v, "tpm2-pin");
        if (w) {
                if (!sd_json_variant_is_boolean(w))
                        return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 PIN policy is not a boolean.");
 
                SET_FLAG(flags, TPM2_FLAGS_USE_PIN, sd_json_variant_boolean(w));
        }
 
        w = sd_json_variant_by_key(v, "tpm2_pcrlock");
        if (w) {
                if (!sd_json_variant_is_boolean(w))
                        return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 pclock policy is not a boolean.");
 
                SET_FLAG(flags, TPM2_FLAGS_USE_PCRLOCK, sd_json_variant_boolean(w));
        }
 
        w = sd_json_variant_by_key(v, "tpm2_salt");
        if (w) {
                r = json_variant_unbase64_iovec(w, &salt);
                if (r < 0)
                        return log_debug_errno(r, "Invalid base64 data in 'tpm2_salt' field.");
        }
 
        w = sd_json_variant_by_key(v, "tpm2_pubkey_pcrs");
        if (w) {
                r = tpm2_parse_pcr_json_array(w, &pubkey_pcr_mask);
                if (r < 0)
                        return r;
        }
 
        w = sd_json_variant_by_key(v, "tpm2_pubkey");
        if (w) {
                r = json_variant_unbase64_iovec(w, &pubkey);
                if (r < 0)
                        return log_debug_errno(r, "Failed to decode PCR public key.");
        } else if (pubkey_pcr_mask != 0)
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Public key PCR mask set, but not public key included in JSON data, refusing.");
 
        w = sd_json_variant_by_key(v, "tpm2_pubkey_ref");
        if (w) {
                const char *s = sd_json_variant_string(w);
                if (!s)
                        return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Public key policy reference is not a string.");
                if (!iovec_is_set(&pubkey))
                        return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Public key policy reference set, but no public key included in JSON data, refusing.");
                pubkey_ref = strdup(s);
                if (!pubkey_ref)
                        return log_oom_debug();
        }
 
        w = sd_json_variant_by_key(v, "tpm2_srk");
        if (w) {
                r = json_variant_unbase64_iovec(w, &srk);
                if (r < 0)
                        return log_debug_errno(r, "Invalid base64 data in 'tpm2_srk' field.");
        }
 
        w = sd_json_variant_by_key(v, "tpm2_pcrlock_nv");
        if (w) {
                r = json_variant_unbase64_iovec(w, &pcrlock_nv);
                if (r < 0)
                        return log_debug_errno(r, "Invalid base64 data in 'tpm2_pcrlock_nv' field.");
        }
 
        Argon2IdParameters ap = {};
 
        w = sd_json_variant_by_key(v, "tpm2_argon2id_memcost");
        if (w) {
                if (!sd_json_variant_is_unsigned(w))
                        return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "tpm2_argon2id_memcost is not an unsigned integer.");
                ap.memcost_bytes = sd_json_variant_unsigned(w);
                if (ap.memcost_bytes == 0)
                        return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN), "tpm2_argon2id_memcost must be non-zero.");
        }
 
        w = sd_json_variant_by_key(v, "tpm2_argon2id_iterations");
        if (w) {
                uint64_t raw_iterations;
 
                if (!sd_json_variant_is_unsigned(w))
                        return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "tpm2_argon2id_iterations is not an unsigned integer.");
                raw_iterations = sd_json_variant_unsigned(w);
                if (raw_iterations == 0 || raw_iterations > UINT32_MAX)
                        return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN), "tpm2_argon2id_iterations value out of range.");
                ap.iterations = (uint32_t) raw_iterations;
        }
 
        w = sd_json_variant_by_key(v, "tpm2_argon2id_lanes");
        if (w) {
                uint64_t raw_lanes;
 
                if (!sd_json_variant_is_unsigned(w))
                        return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "tpm2_argon2id_lanes is not an unsigned integer.");
                raw_lanes = sd_json_variant_unsigned(w);
                if (raw_lanes == 0 || raw_lanes > UINT32_MAX)
                        return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN), "tpm2_argon2id_lanes value out of range.");
                ap.lanes = (uint32_t) raw_lanes;
        }
 
        if (ap.memcost_bytes > 0 && ap.iterations > 0 && ap.lanes > 0) {
                if (!iovec_is_set(&salt))
                        return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Argon2id PIN requires salt in LUKS2 token.");
 
                if (ap.memcost_bytes > physical_memory())
                        return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN), "Argon2id memory cost exceeds physical memory.");
 
                SET_FLAG(flags, TPM2_FLAGS_USE_ARGON2ID, true);
        } else if (ap.memcost_bytes > 0 || ap.iterations > 0 || ap.lanes > 0)
                return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN), "Incomplete Argon2id parameters in LUKS2 token.");
 
        if (ret_keyslot)
                *ret_keyslot = keyslot;
        if (ret_hash_pcr_mask)
                *ret_hash_pcr_mask = hash_pcr_mask;
        if (ret_pcr_bank)
                *ret_pcr_bank = pcr_bank;
        if (ret_pubkey)
                *ret_pubkey = TAKE_STRUCT(pubkey);
        if (ret_pubkey_policy_ref)
                *ret_pubkey_policy_ref = TAKE_PTR(pubkey_ref);
        if (ret_pubkey_pcr_mask)
                *ret_pubkey_pcr_mask = pubkey_pcr_mask;
        if (ret_primary_alg)
                *ret_primary_alg = primary_alg;
        if (ret_blobs)
                *ret_blobs = TAKE_PTR(blobs);
        if (ret_n_blobs)
                *ret_n_blobs = n_blobs;
        if (ret_policy_hash)
                *ret_policy_hash = TAKE_PTR(policy_hash);
        if (ret_n_policy_hash)
                *ret_n_policy_hash = n_policy_hash;
        if (ret_salt)
                *ret_salt = TAKE_STRUCT(salt);
        if (ret_srk)
                *ret_srk = TAKE_STRUCT(srk);
        if (ret_pcrlock_nv)
                *ret_pcrlock_nv = TAKE_STRUCT(pcrlock_nv);
        if (ret_flags)
                *ret_flags = flags;
        if (ret_argon2id_params)
                *ret_argon2id_params = ap;
        return 0;
}
 
int tpm2_hash_alg_to_size(uint16_t alg) {
        switch (alg) {
        case TPM2_ALG_SHA1:
                return 20;
        case TPM2_ALG_SHA256:
                return 32;
        case TPM2_ALG_SHA384:
                return 48;
        case TPM2_ALG_SHA512:
                return 64;
        default:
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown hash algorithm id 0x%" PRIx16, alg);
        }
}
 
const char* tpm2_hash_alg_to_string(uint16_t alg) {
        switch (alg) {
        case TPM2_ALG_SHA1:
                return "sha1";
        case TPM2_ALG_SHA256:
                return "sha256";
        case TPM2_ALG_SHA384:
                return "sha384";
        case TPM2_ALG_SHA512:
                return "sha512";
        default:
                log_debug("Unknown hash algorithm id 0x%" PRIx16, alg);
                return NULL;
        }
}
 
int tpm2_hash_alg_from_string(const char *alg) {
        if (strcaseeq_ptr(alg, "sha1"))
                return TPM2_ALG_SHA1;
        if (strcaseeq_ptr(alg, "sha256"))
                return TPM2_ALG_SHA256;
        if (strcaseeq_ptr(alg, "sha384"))
                return TPM2_ALG_SHA384;
        if (strcaseeq_ptr(alg, "sha512"))
                return TPM2_ALG_SHA512;
        return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown hash algorithm name '%s'", alg);
}
 
const char* tpm2_asym_alg_to_string(uint16_t alg) {
        switch (alg) {
        case TPM2_ALG_ECC:
                return "ecc";
        case TPM2_ALG_RSA:
                return "rsa";
        default:
                log_debug("Unknown asymmetric algorithm id 0x%" PRIx16, alg);
                return NULL;
        }
}
 
int tpm2_asym_alg_from_string(const char *alg) {
        if (strcaseeq_ptr(alg, "ecc"))
                return TPM2_ALG_ECC;
        if (strcaseeq_ptr(alg, "rsa"))
                return TPM2_ALG_RSA;
        return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown asymmetric algorithm name '%s'", alg);
}
 
const char* tpm2_sym_alg_to_string(uint16_t alg) {
        switch (alg) {
#if HAVE_TPM2
        case TPM2_ALG_AES:
                return "aes";
#endif
        default:
                log_debug("Unknown symmetric algorithm id 0x%" PRIx16, alg);
                return NULL;
        }
}
 
const char* tpm2_sym_mode_to_string(uint16_t mode) {
        switch (mode) {
#if HAVE_TPM2
        case TPM2_ALG_CTR:
                return "ctr";
        case TPM2_ALG_OFB:
                return "ofb";
        case TPM2_ALG_CBC:
                return "cbc";
        case TPM2_ALG_CFB:
                return "cfb";
        case TPM2_ALG_ECB:
                return "ecb";
#endif
        default:
                log_debug("Unknown symmetric mode id 0x%" PRIx16, mode);
                return NULL;
        }
}
 
int tpm2_sym_mode_from_string(const char *mode) {
#if HAVE_TPM2
        if (strcaseeq_ptr(mode, "ctr"))
                return TPM2_ALG_CTR;
        if (strcaseeq_ptr(mode, "ofb"))
                return TPM2_ALG_OFB;
        if (strcaseeq_ptr(mode, "cbc"))
                return TPM2_ALG_CBC;
        if (strcaseeq_ptr(mode, "cfb"))
                return TPM2_ALG_CFB;
        if (strcaseeq_ptr(mode, "ecb"))
                return TPM2_ALG_ECB;
#endif
        return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown symmetric mode name '%s'", mode);
}
 
Tpm2Support tpm2_support_full(Tpm2Support mask) {
        Tpm2Support support = TPM2_SUPPORT_NONE;
        int r;
 
        if (((mask & (TPM2_SUPPORT_SUBSYSTEM|TPM2_SUPPORT_DRIVER)) != 0) && detect_container() <= 0) {
                /* Check if there's a /dev/tpmrm* device via sysfs. If we run in a container we likely just
                 * got the host sysfs mounted. Since devices are generally not virtualized for containers,
                 * let's assume containers never have a TPM, at least for now. */
 
                r = dir_is_empty("/sys/class/tpmrm", /* ignore_hidden_or_backup= */ false);
                if (r < 0) {
                        if (r != -ENOENT)
                                log_debug_errno(r, "Unable to test whether /sys/class/tpmrm/ exists and is populated, assuming it is not: %m");
                } else if (r == 0) /* populated! */
                        support |= TPM2_SUPPORT_SUBSYSTEM|TPM2_SUPPORT_DRIVER;
                else
                        /* If the directory exists but is empty, we know the subsystem is enabled but no
                         * driver has been loaded yet. */
                        support |= TPM2_SUPPORT_SUBSYSTEM;
        }
 
        if (FLAGS_SET(mask, TPM2_SUPPORT_FIRMWARE) && efi_has_tpm2())
                support |= TPM2_SUPPORT_FIRMWARE;
 
#if HAVE_TPM2
        support |= TPM2_SUPPORT_SYSTEM;
 
        if ((mask & (TPM2_SUPPORT_LIBRARIES|TPM2_SUPPORT_LIBTSS2_ALL)) != 0) {
                r = dlopen_tpm2_esys(LOG_DEBUG);
                if (r >= 0)
                        support |= TPM2_SUPPORT_LIBTSS2_ESYS;
 
                r = dlopen_tpm2_rc(LOG_DEBUG);
                if (r >= 0)
                        support |= TPM2_SUPPORT_LIBTSS2_RC;
 
                r = dlopen_tpm2_mu(LOG_DEBUG);
                if (r >= 0)
                        support |= TPM2_SUPPORT_LIBTSS2_MU;
 
                if (FLAGS_SET(support, TPM2_SUPPORT_LIBTSS2_ALL))
                        support |= TPM2_SUPPORT_LIBRARIES;
        }
#endif
 
        return support & mask;
}
 
static void print_field(const char *prefix, const char *s, bool supported) {
        printf("%s%s%s%s%s\n", strempty(prefix), supported ? ansi_green() : ansi_red(), plus_minus(supported), s, ansi_normal());
}
 
int verb_has_tpm2_generic(bool quiet) {
        Tpm2Support s;
 
        s = tpm2_support();
 
        if (!quiet) {
                if (s == TPM2_SUPPORT_FULL)
                        printf("%syes%s\n", ansi_green(), ansi_normal());
                else if (s == TPM2_SUPPORT_NONE)
                        printf("%sno%s\n", ansi_red(), ansi_normal());
                else
                        printf("%spartial%s\n", ansi_yellow(), ansi_normal());
 
                print_field(NULL, "firmware", FLAGS_SET(s, TPM2_SUPPORT_FIRMWARE));
                print_field(NULL, "driver", FLAGS_SET(s, TPM2_SUPPORT_DRIVER));
                print_field(NULL, "system", FLAGS_SET(s, TPM2_SUPPORT_SYSTEM));
                print_field(NULL, "subsystem", FLAGS_SET(s, TPM2_SUPPORT_SUBSYSTEM));
                print_field(NULL, "libraries", FLAGS_SET(s, TPM2_SUPPORT_LIBRARIES));
                print_field("  ", "libtss2-esys.so.0", FLAGS_SET(s, TPM2_SUPPORT_LIBTSS2_ESYS));
                print_field("  ", "libtss2-rc.so.0", FLAGS_SET(s, TPM2_SUPPORT_LIBTSS2_RC));
                print_field("  ", "libtss2-mu.so.0", FLAGS_SET(s, TPM2_SUPPORT_LIBTSS2_MU));
        }
 
        assert_cc(TPM2_SUPPORT_API <= 255); /* make sure this is safe to use as process exit status */
 
        /* Return inverted bit flags. So that TPM2_SUPPORT_FULL becomes EXIT_SUCCESS and the other values
         * become some reasonable values 1…7. i.e. the flags we return here tell what is missing rather than
         * what is there, acknowledging the fact that for process exit statuses it is customary to return
         * zero (EXIT_FAILURE) when all is good, instead of all being bad. */
        return ~s & TPM2_SUPPORT_API;
}
 
#if HAVE_TPM2
static void tpm2_pcr_values_apply_default_hash_alg(Tpm2PCRValue *pcr_values, size_t n_pcr_values) {
        TPMI_ALG_HASH default_hash = 0;
        FOREACH_ARRAY(v, pcr_values, n_pcr_values)
                if (v->hash != 0) {
                        default_hash = v->hash;
                        break;
                }
 
        if (default_hash != 0)
                FOREACH_ARRAY(v, pcr_values, n_pcr_values)
                        if (v->hash == 0)
                                v->hash = default_hash;
}
#endif
 
/* The following tpm2_parse_pcr_argument*() functions all log errors, to match the behavior of system-wide
 * parse_*_argument() functions. */
 
/* Parse the PCR selection/value arg(s) and return a corresponding array of Tpm2PCRValue objects.
 *
 * The format is the same as tpm2_pcr_values_from_string(). The first provided entry with a hash algorithm
 * set will be used as the 'default' hash algorithm. All entries with an unset hash algorithm will be updated
 * with the 'default' hash algorithm. The resulting array will be sorted and checked for validity.
 *
 * This will replace *ret_pcr_values with the new array of pcr values; to append to an existing array, use
 * tpm2_parse_pcr_argument_append(). */
int tpm2_parse_pcr_argument(const char *arg, Tpm2PCRValue **ret_pcr_values, size_t *ret_n_pcr_values) {
#if HAVE_TPM2
        int r;
 
        assert(arg);
        assert(ret_pcr_values);
        assert(ret_n_pcr_values);
 
        _cleanup_free_ Tpm2PCRValue *pcr_values = NULL;
        size_t n_pcr_values = 0;