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 10001–11000 of 12,273

                                                        pcr,
                                                        algorithm,
                                                        *hash),
                                        /* n_pcr_values= */ 1,
                                        &pcr_policy_digest);
                        if (r < 0)
                                return log_error_errno(r, "Failed to calculate PolicyPCR: %m");
 
                        branches[i++] = pcr_policy_digest;
                }
 
                assert_se(i == n_branches);
 
                current_policy_digest = mfree(current_policy_digest);
                r = tpm2_policy_or(
                                c,
                                session,
                                branches,
                                n_branches,
                                &current_policy_digest);
                if (r == -ENOANO)
                        return log_error_errno(r, "None of the alternative values for PCR %" PRIu32 " encoded in policy match the current TPM state. Either the system has been tampered with or the provided policy is incorrect.", pcr);
                if (r < 0)
                        return log_error_errno(r, "Failed to submit OR policy to TPM: %m");
 
                previous_policy_digest = *current_policy_digest;
        }
 
        return 0;
}
 
void tpm2_pcrlock_policy_done(Tpm2PCRLockPolicy *data) {
        assert(data);
 
        data->prediction_json = sd_json_variant_unref(data->prediction_json);
        tpm2_pcr_prediction_done(&data->prediction);
        iovec_done(&data->nv_handle);
        iovec_done(&data->nv_public);
        iovec_done(&data->srk_handle);
        iovec_done(&data->pin_public);
        iovec_done(&data->pin_private);
}
 
int tpm2_pcrlock_search_file(const char *path, FILE **ret_file, char **ret_path) {
        static const char search[] =
                "/run/systemd\0"
                "/var/lib/systemd\0";
 
        int r;
 
        if (!path)
                path = "pcrlock.json";
 
        r = search_and_fopen_nulstr(path, ret_file ? "re" : NULL, NULL, search, ret_file, ret_path);
        if (r < 0)
                return log_debug_errno(r, "Failed to find TPM2 pcrlock policy file '%s': %m", path);
 
        return 0;
}
 
int tpm2_pcrlock_policy_from_json(
                sd_json_variant *v,
                Tpm2PCRLockPolicy *ret_policy) {
 
        /* We use a type check of _JSON_VARIANT_TYPE_INVALID for the integer fields to allow
         * json_dispatch_uint32() to parse strings as integers to work around the integer type weakness of
         * JSON's design. */
        static const sd_json_dispatch_field policy_dispatch[] = {
                { "pcrBank",    SD_JSON_VARIANT_STRING,        json_dispatch_tpm2_algorithm, offsetof(Tpm2PCRLockPolicy, algorithm),       SD_JSON_MANDATORY },
                { "pcrValues",  SD_JSON_VARIANT_ARRAY,         sd_json_dispatch_variant,     offsetof(Tpm2PCRLockPolicy, prediction_json), SD_JSON_MANDATORY },
                { "nvIndex",    _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint32,      offsetof(Tpm2PCRLockPolicy, nv_index),        SD_JSON_MANDATORY },
                { "nvHandle",   SD_JSON_VARIANT_STRING,        json_dispatch_unbase64_iovec, offsetof(Tpm2PCRLockPolicy, nv_handle),       SD_JSON_MANDATORY },
                { "nvPublic",   SD_JSON_VARIANT_STRING,        json_dispatch_unbase64_iovec, offsetof(Tpm2PCRLockPolicy, nv_public),       SD_JSON_MANDATORY },
                { "srkHandle",  SD_JSON_VARIANT_STRING,        json_dispatch_unbase64_iovec, offsetof(Tpm2PCRLockPolicy, srk_handle),      SD_JSON_MANDATORY },
                { "pinPublic",  SD_JSON_VARIANT_STRING,        json_dispatch_unbase64_iovec, offsetof(Tpm2PCRLockPolicy, pin_public),      SD_JSON_MANDATORY },
                { "pinPrivate", SD_JSON_VARIANT_STRING,        json_dispatch_unbase64_iovec, offsetof(Tpm2PCRLockPolicy, pin_private),     SD_JSON_MANDATORY },
                {}
        };
 
        _cleanup_(tpm2_pcrlock_policy_done) Tpm2PCRLockPolicy policy = {};
        int r;
 
        assert(v);
        assert(ret_policy);
 
        r = sd_json_dispatch(v, policy_dispatch, SD_JSON_LOG, &policy);
        if (r < 0)
                return r;
 
        r = tpm2_pcr_prediction_from_json(&policy.prediction, policy.algorithm, policy.prediction_json);
        if (r < 0)
                return r;
 
        *ret_policy = TAKE_STRUCT(policy);
        return 1;
}
 
int tpm2_pcrlock_policy_load(
                const char *path,
                Tpm2PCRLockPolicy *ret_policy) {
 
        _cleanup_free_ char *discovered_path = NULL;
        _cleanup_fclose_ FILE *f = NULL;
        int r;
 
        assert(ret_policy);
 
        r = tpm2_pcrlock_search_file(path, &f, &discovered_path);
        if (r == -ENOENT) {
                *ret_policy = (Tpm2PCRLockPolicy) {};
                return 0;
        }
        if (r < 0)
                return log_error_errno(r, "Failed to load TPM2 pcrlock policy file: %m");
 
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
        r = sd_json_parse_file(
                        f,
                        discovered_path,
                        /* flags= */ 0,
                        &v,
                        /* reterr_line= */ NULL,
                        /* ret_column= */ NULL);
        if (r < 0)
                return log_error_errno(r, "Failed to parse existing pcrlock policy file '%s': %m", discovered_path);
 
        return tpm2_pcrlock_policy_from_json(v, ret_policy);
}
 
static int pcrlock_policy_load_credential(
                const char *name,
                const struct iovec *data,
                Tpm2PCRLockPolicy *ret) {
 
        _cleanup_free_ char *c = NULL;
        int r;
 
        assert(name);
 
        c = strdup(name);
        if (!c)
                return log_oom();
 
        ascii_strlower(c); /* Lowercase, to match what we did at encryption time */
 
        _cleanup_(iovec_done) struct iovec decoded = {};
        r = decrypt_credential_and_warn(
                        c,
                        now(CLOCK_REALTIME),
                        /* tpm2_device= */ NULL,
                        /* tpm2_signature_path= */ NULL,
                        UID_INVALID,
                        data,
                        CREDENTIAL_ALLOW_NULL,
                        &decoded);
        if (r < 0)
                return r;
 
        if (memchr(decoded.iov_base, 0, decoded.iov_len))
                return log_error_errno(r, "Credential '%s' contains embedded NUL byte, refusing.", name);
 
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
        r = sd_json_parse(decoded.iov_base,
                       /* flags= */ 0,
                       &v,
                       /* reterr_line= */ NULL,
                       /* ret_column= */ NULL);
        if (r < 0)
                return log_error_errno(r, "Failed to parse pcrlock policy: %m");
 
        r = tpm2_pcrlock_policy_from_json(v, ret);
        if (r < 0)
                return r;
 
        return 0;
}
 
int tpm2_pcrlock_policy_from_credentials(
                const struct iovec *srk,
                const struct iovec *nv,
                Tpm2PCRLockPolicy *ret) {
 
        _cleanup_close_ int dfd = -EBADF;
        int r;
 
        assert(ret);
 
        /* During boot we'll not have access to the pcrlock.json file in /var/. In order to support
         * pcrlock-bound root file systems we'll store a copy of the JSON data, wrapped in an (plaintext)
         * credential in the ESP or XBOOTLDR partition. There might be multiple of those however (because of
         * multi-boot), hence we use the SRK and NV data from the LUKS2 header as search key, and parse all
         * such JSON policies until we find a matching one. */
 
        const char *dp;
        r = get_encrypted_system_credentials_dir(&dp);
        if (r < 0)
                return log_error_errno(r, "Failed to get encrypted system credentials directory: %m");
 
        dfd = open(dp, O_CLOEXEC|O_DIRECTORY);
        if (dfd < 0) {
                if (errno == ENOENT) {
                        log_debug("No encrypted system credentials passed.");
                        return 0;
                }
 
                return log_error_errno(errno, "Failed to open system credentials directory.");
        }
 
        _cleanup_free_ DirectoryEntries *de = NULL;
        r = readdir_all(dfd, RECURSE_DIR_IGNORE_DOT, &de);
        if (r < 0)
                return log_error_errno(r, "Failed to enumerate system credentials: %m");
 
        FOREACH_ARRAY(i, de->entries, de->n_entries) {
                _cleanup_(iovec_done) struct iovec data = {};
                struct dirent *d = *i;
 
                if (!startswith_no_case(d->d_name, "pcrlock.")) /* VFAT is case-insensitive, hence don't be too strict here */
                        continue;
 
                r = read_full_file_full(
                                dfd, d->d_name,
                                /* offset= */ UINT64_MAX,
                                /* size= */ CREDENTIAL_ENCRYPTED_SIZE_MAX,
                                READ_FULL_FILE_UNBASE64|READ_FULL_FILE_FAIL_WHEN_LARGER,
                                /* bind_name= */ NULL,
                                (char**) &data.iov_base,
                                &data.iov_len);
                if (r == -ENOENT)
                        continue;
                if (r < 0) {
                        log_warning_errno(r, "Failed to read credentials file %s/%s, skipping: %m", dp, d->d_name);
                        continue;
                }
 
                _cleanup_(tpm2_pcrlock_policy_done) Tpm2PCRLockPolicy loaded_policy = {};
                r = pcrlock_policy_load_credential(
                                d->d_name,
                                &data,
                                &loaded_policy);
                if (r < 0) {
                        log_warning_errno(r, "Loading of pcrlock policy from credential '%s/%s' failed, skipping.", ENCRYPTED_SYSTEM_CREDENTIALS_DIRECTORY, d->d_name);
                        continue;
                }
 
                if ((!srk || iovec_equal(srk, &loaded_policy.srk_handle)) &&
                    (!nv || iovec_equal(nv, &loaded_policy.nv_handle))) {
                        *ret = TAKE_STRUCT(loaded_policy);
                        return 1;
                }
        }
 
        log_info("No pcrlock policy found among system credentials.");
        *ret = (Tpm2PCRLockPolicy) {};
        return 0;
}
 
int tpm2_load_public_key_file(const char *path, TPM2B_PUBLIC *ret) {
        _cleanup_free_ char *device_key_buffer = NULL;
        TPM2B_PUBLIC device_key_public = {};
        size_t device_key_buffer_size;
        TSS2_RC rc;
        int r;
 
        assert(path);
        assert(ret);
 
        r = dlopen_tpm2(LOG_DEBUG);
        if (r < 0)
                return r;
 
        r = read_full_file(path, &device_key_buffer, &device_key_buffer_size);
        if (r < 0)
                return log_error_errno(r, "Failed to read device key from file '%s': %m", path);
 
        size_t offset = 0;
        rc = sym_Tss2_MU_TPM2B_PUBLIC_Unmarshal(
                        (uint8_t*) device_key_buffer,
                        device_key_buffer_size,
                        &offset,
                        &device_key_public);
        if (rc != TSS2_RC_SUCCESS)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Could not unmarshal public key from file.");
 
        assert(offset <= device_key_buffer_size);
        if (offset != device_key_buffer_size)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Found %zu bytes of trailing garbage in public key file.",
                                       device_key_buffer_size - offset);
 
        *ret = device_key_public;
        return 0;
}
 
int tpm2_hmac_key_from_pin(Tpm2Context *c, const Tpm2Handle *session, const TPM2B_AUTH *pin, Tpm2Handle **ret) {
        int r;
 
        assert(c);
        assert(pin);
        assert(ret);
 
        log_debug("Converting PIN into TPM2 HMAC-SHA256 object.");
 
        /* Load the PIN (which we have stored in the "auth" TPM2B_AUTH) into the TPM as an HMAC key so that
         * we can use it in a TPM2_PolicySigned() to write to the nvindex. For that we'll prep a pair of
         * TPM2B_PUBLIC and TPM2B_SENSITIVE that defines an HMAC-SHA256 keyed hash function, and initialize
         * it based on the provided PIN data. */
 
        TPM2B_PUBLIC auth_hmac_public = {
                .publicArea = {
                        .type = TPM2_ALG_KEYEDHASH,
                        .nameAlg = TPM2_ALG_SHA256,
                        .objectAttributes = TPMA_OBJECT_SIGN_ENCRYPT,
                        .parameters.keyedHashDetail.scheme = {
                                .scheme = TPM2_ALG_HMAC,
                                .details.hmac.hashAlg = TPM2_ALG_SHA256,
                        },
                        .unique.keyedHash.size = SHA256_DIGEST_SIZE,
                },
        };
 
        TPM2B_SENSITIVE auth_hmac_private = {
                .sensitiveArea = {
                        .sensitiveType = TPM2_ALG_KEYEDHASH,
                        .sensitive.bits.size = pin->size,
                        .seedValue.size = SHA256_DIGEST_SIZE,
                },
        };
 
        /* Copy in the key data */
        memcpy_safe(auth_hmac_private.sensitiveArea.sensitive.bits.buffer, pin->buffer, pin->size);
 
        /* NB: We initialize the seed of the TPMT_SENSITIVE structure to all zeroes, since we want a stable
         * "name" of the PIN object */
 
        /* Now calculate the "unique" field for the public area, based on the sensitive data, according to
         * the algorithm in the TPM2 spec, part 1, Section 27.5.3.2 */
        struct iovec sensitive_data[] = {
                IOVEC_MAKE(auth_hmac_private.sensitiveArea.seedValue.buffer, auth_hmac_private.sensitiveArea.seedValue.size),
                IOVEC_MAKE(auth_hmac_private.sensitiveArea.sensitive.bits.buffer, auth_hmac_private.sensitiveArea.sensitive.bits.size),
        };
        r = tpm2_digest_many(
                        auth_hmac_public.publicArea.nameAlg,
                        &auth_hmac_public.publicArea.unique.keyedHash,
                        sensitive_data,
                        ELEMENTSOF(sensitive_data),
                        /* extend= */ false);
        if (r < 0)
                return r;
 
        /* And now load the public/private parts into the TPM and get a handle back */
        r = tpm2_load_external(
                        c,
                        session,
                        &auth_hmac_public,
                        &auth_hmac_private,
                        ret);
        if (r < 0)
                return log_error_errno(r, "Failed to load PIN into TPM2: %m");
 
        return 0;
}
 
static int tpm2_unmarshal_attestation(const void *data, size_t size, TPMS_ATTEST *ret) {
        size_t offset = 0;
        TPMS_ATTEST attest = {};
        TSS2_RC rc;
        int r;
 
        assert(data);
        assert(ret);
 
        r = dlopen_tpm2(LOG_DEBUG);
        if (r < 0)
                return r;
 
        rc = sym_Tss2_MU_TPMS_ATTEST_Unmarshal(data, size, &offset, &attest);
        if (rc != TSS2_RC_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Failed to unmarshal attestation structure: %s", sym_Tss2_RC_Decode(rc));
        if (offset != size)
                return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                       "Garbage at end of attestation structure data.");
 
        *ret = attest;
        return 0;
}
 
/* Convert a TPM signature to PEM. This only supports RSASSA, RSAPSS and ECDSA signatures. */
int tpm2_tpmt_signature_to_pem(const TPMT_SIGNATURE *signature, char **ret) {
#if HAVE_OPENSSL
        int r;
 
        assert(signature);
        assert(ret);
 
        r = dlopen_libcrypto(LOG_DEBUG);
        if (r < 0)
                return r;
 
        const char *label = NULL;
        _cleanup_free_ void *sig = NULL;
        size_t sig_len = 0;
        switch (signature->sigAlg) {
        case TPM2_ALG_RSASSA:
                label = "RSA SIGNATURE";
                sig_len = signature->signature.rsassa.sig.size;
                sig = memdup(signature->signature.rsassa.sig.buffer, sig_len);
                if (!sig)
                        return log_oom_debug();
                break;
        case TPM2_ALG_RSAPSS:
                label = "RSA SIGNATURE";
                sig_len = signature->signature.rsapss.sig.size;
                sig = memdup(signature->signature.rsapss.sig.buffer, sig_len);
                if (!sig)
                        return log_oom_debug();
                break;
        case TPM2_ALG_ECDSA: {
                label = "ECDSA SIGNATURE";
                _cleanup_(BN_freep) BIGNUM *bn_r = sym_BN_bin2bn(
                                signature->signature.ecdsa.signatureR.buffer,
                                signature->signature.ecdsa.signatureR.size, NULL);
                if (!bn_r)
                        return log_openssl_errors(LOG_DEBUG, "Failed to convert ECDSA signature r to BIGNUM");
 
                _cleanup_(BN_freep) BIGNUM *bn_s = sym_BN_bin2bn(
                                signature->signature.ecdsa.signatureS.buffer,
                                signature->signature.ecdsa.signatureS.size, NULL);
                if (!bn_s)
                        return log_openssl_errors(LOG_DEBUG, "Failed to convert ECDSA signature s to BIGNUM");
 
                _cleanup_(ECDSA_SIG_freep) ECDSA_SIG *ecdsaSig = sym_ECDSA_SIG_new();
                if (!ecdsaSig)
                        return log_oom_debug();
 
                if (sym_ECDSA_SIG_set0(ecdsaSig, bn_r, bn_s) <= 0)
                        return log_openssl_errors(LOG_DEBUG, "Failed to set ECDSA signature");
                TAKE_PTR(bn_r);
                TAKE_PTR(bn_s);
 
                /* We want to allocate our own buffer so we can have a common cleanup path for this
                 * and RSA signatures. */
                r = sym_i2d_ECDSA_SIG(ecdsaSig, NULL);
                if (r <= 0)
                        return log_openssl_errors(LOG_DEBUG, "Failed to determine ECDSA signature size");
                sig_len = r;
 
                sig = malloc(sig_len);
                if (!sig)
                        return log_oom_debug();
 
                unsigned char *p = sig;
                r = sym_i2d_ECDSA_SIG(ecdsaSig, &p);
                if (r <= 0)
                        return log_openssl_errors(LOG_DEBUG, "Failed to DER encode ECDSA signature");
 
                break;
        }
        case TPM2_ALG_NULL:
                *ret = NULL;
                return 0;
        default:
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Unknown signature algorithm id 0x%" PRIx16, signature->sigAlg);
        }
 
        _cleanup_(memstream_done) MemStream m = {};
        FILE *f = memstream_init(&m);
        if (!f)
                return -ENOMEM;
 
        if (sym_PEM_write(f, label, /* header= */ NULL, sig, sig_len) <= 0)
                return log_openssl_errors(LOG_DEBUG, "Failed to write signature in PEM format");
 
        return memstream_finalize(&m, ret, /* ret_size= */ NULL);
#else
        return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "OpenSSL support is disabled.");
#endif
}
 
/* Convert a TPM public key to a SubjectPublicKeyInfo PEM sequence. */
int tpm2_tpmt_public_to_pem(const TPMT_PUBLIC *public, char **ret) {
#if HAVE_OPENSSL
        int r;
 
        assert(public);
        assert(ret);
 
        TPM2B_PUBLIC public2b = {
                .size = sizeof(TPMT_PUBLIC),
                .publicArea = *public,
        };
 
        _cleanup_(EVP_PKEY_freep) EVP_PKEY *pkey = NULL;
        r = tpm2_tpm2b_public_to_openssl_pkey(&public2b, &pkey);
        if (r < 0)
                return r;
 
        return openssl_pubkey_to_pem(pkey, ret);
#else
        return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "OpenSSL support is disabled.");
#endif
}
 
static const char* tpm2_hash_alg_to_string_tss2(TPMI_ALG_HASH alg) {
        /* Note that this is different to tpm2_hash_alg_to_string because it
         * returns a string that aligns with those produced by TSS2 and compatible
         * with the TCG TSS2 JSON format. The JSON format is actually not case
         * sensitive, but this is here just to be consistent with the signature
         * algorithm. */
        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;
        }
}
 
static const char* tpm2_sig_alg_to_string(TPMI_ALG_SIG_SCHEME alg) {
        switch (alg) {
        case TPM2_ALG_RSASSA:
                return "RSASSA";
        case TPM2_ALG_RSAPSS:
                return "RSAPSS";
        case TPM2_ALG_ECDSA:
                return "ECDSA";
        case TPM2_ALG_NULL:
                return "NULL";
        default:
                log_debug("Unknown signature algorithm id 0x%" PRIx16, alg);
                return NULL;
        }
}
 
/* Convert a TPM signature to JSON, in a format compatible with the TCG TSS2 JSON data format,
 * and which is compatible with the TSS2 implementation. This only supports RSASSA, RSAPSS and ECDSA
 * signatures.
 *
 * See https://trustedcomputinggroup.org/wp-content/uploads/TSS_JSON_Policy_v0p7_r08_pub.pdf */
int tpm2_tpmt_signature_to_json(const TPMT_SIGNATURE *signature, sd_json_variant **ret) {
        int r = 0;
 
        assert(signature);
        assert(ret);
 
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *siginnerj = NULL;
        switch (signature->sigAlg) {
        case TPM2_ALG_RSASSA:
                r = sd_json_buildo(
                                &siginnerj,
                                SD_JSON_BUILD_PAIR_STRING("hash", tpm2_hash_alg_to_string_tss2(signature->signature.rsassa.hash)),
                                SD_JSON_BUILD_PAIR_HEX("sig", signature->signature.rsassa.sig.buffer, signature->signature.rsassa.sig.size));
                break;
        case TPM2_ALG_RSAPSS:
                r = sd_json_buildo(
                                &siginnerj,
                                SD_JSON_BUILD_PAIR_STRING("hash", tpm2_hash_alg_to_string_tss2(signature->signature.rsapss.hash)),
                                SD_JSON_BUILD_PAIR_HEX("sig", signature->signature.rsapss.sig.buffer, signature->signature.rsapss.sig.size));
                break;
        case TPM2_ALG_ECDSA:
                r = sd_json_buildo(
                                &siginnerj,
                                SD_JSON_BUILD_PAIR_STRING("hash", tpm2_hash_alg_to_string_tss2(signature->signature.ecdsa.hash)),
                                SD_JSON_BUILD_PAIR_HEX("signatureR", signature->signature.ecdsa.signatureR.buffer, signature->signature.ecdsa.signatureR.size),
                                SD_JSON_BUILD_PAIR_HEX("signatureS", signature->signature.ecdsa.signatureS.buffer, signature->signature.ecdsa.signatureS.size));
                break;
        case TPM2_ALG_NULL:
                break;
        default:
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Unknown signature algorithm id 0x%" PRIx16, signature->sigAlg);
        }
        if (r < 0)
                return r;
 
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *sigj = NULL;
        r = sd_json_buildo(
                        &sigj,
                        SD_JSON_BUILD_PAIR_STRING("sigAlg", tpm2_sig_alg_to_string(signature->sigAlg)),
                        JSON_BUILD_PAIR_VARIANT_NON_NULL("signature", siginnerj));
        if (r < 0)
                return r;
 
        *ret = TAKE_PTR(sigj);
        return 0;
}
 
static const char* tpm2_st_attest_to_string(TPMI_ST_ATTEST attest) {
        switch (attest) {
        case TPM2_ST_ATTEST_NV:
                return "ATTEST_NV";
        case TPM2_ST_ATTEST_SESSION_AUDIT:
                return "ATTEST_SESSION_AUDIT";
        case TPM2_ST_ATTEST_QUOTE:
                return "ATTEST_QUOTE";
        default:
                log_debug("Unknown attestation type 0x%" PRIx16, attest);
                return NULL;
        }
}
 
/* Convert a TPMS_CLOCK_INFO to JSON, in a format compatible with the TCG TSS2 JSON data format,
 * and which is compatible with the TSS2 implementation.
 *
 * See https://trustedcomputinggroup.org/wp-content/uploads/TSS_JSON_Policy_v0p7_r08_pub.pdf */
static int tpm2_tpms_clock_info_to_json(const TPMS_CLOCK_INFO *clock_info, sd_json_variant **ret) {
        int r;
 
        assert(clock_info);
        assert(ret);
 
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
        r = sd_json_buildo(
                        &v,
                        /* tss2-fapi serializes a uint64_t that doesn't fit into a signed 54-bits as an
                         * array of 2 integers, but the deserialize path handles decoding this just fine. */
                        SD_JSON_BUILD_PAIR_UNSIGNED("clock", clock_info->clock),
                        SD_JSON_BUILD_PAIR_UNSIGNED("resetCount", clock_info->resetCount),
                        SD_JSON_BUILD_PAIR_UNSIGNED("restartCount", clock_info->restartCount),
                        /* tss2-fapi doesn't handle this being a boolean when deserializing. */
                        SD_JSON_BUILD_PAIR_STRING("safe", clock_info->safe == TPM2_YES ? "YES" : "NO"));
        if (r < 0)
                return r;
 
        *ret = TAKE_PTR(v);
        return 0;
}
 
/* Convert TPML_PCR_SELECTION to JSON, in a format compatible with the TCG TSS2 JSON data format,
 * and which is compatible with the TSS2 implementation.
 *
 * See https://trustedcomputinggroup.org/wp-content/uploads/TSS_JSON_Policy_v0p7_r08_pub.pdf */
static int tpm2_tpml_pcr_selection_to_json(const TPML_PCR_SELECTION *pcrs, sd_json_variant **ret) {
        int r;
 
        assert(pcrs);
        assert(ret);
 
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
        FOREACH_TPMS_PCR_SELECTION_IN_TPML_PCR_SELECTION(s, pcrs) {
                _cleanup_(sd_json_variant_unrefp) sd_json_variant *sv = NULL;
                FOREACH_PCR_IN_TPMS_PCR_SELECTION(pcr, s) {
                        r = sd_json_variant_append_arrayb(&sv, SD_JSON_BUILD_INTEGER(pcr));
                        if (r < 0)
                                return r;
                }
 
                r = sd_json_variant_append_arraybo(
                                &v,
                                /* As documented in the TCG TSS2 JSON data format spec, the sizeOfSelect
                                 * field isn't represented in the encoding. */
                                SD_JSON_BUILD_PAIR_STRING("hash", tpm2_hash_alg_to_string_tss2(s->hash)),
                                SD_JSON_BUILD_PAIR_VARIANT("pcrSelect", sv));
                if (r < 0)
                        return r;
        }
 
        *ret = TAKE_PTR(v);
        return 0;
}
 
/* Convert TPMS_ATTEST to JSON, in a format compatible with the TCG TSS2 JSON data format, and which is
 * compatible with the TSS2 implementation.
 *
 * See https://trustedcomputinggroup.org/wp-content/uploads/TSS_JSON_Policy_v0p7_r08_pub.pdf */
static int tpm2_tpms_attest_to_json(const TPMS_ATTEST *attest, sd_json_variant **ret) {
        int r;
 
        assert(attest);
        assert(ret);
 
        if (attest->magic != TPM2_GENERATED_VALUE)
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Invalid magic value %" PRIu32, attest->magic);
 
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *cv = NULL;
        r = tpm2_tpms_clock_info_to_json(&attest->clockInfo, &cv);
        if (r < 0)
                return r;
 
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *av = NULL;
        switch (attest->type) {
        case TPM2_ST_ATTEST_NV:
                r = sd_json_buildo(
                                &av,
                                SD_JSON_BUILD_PAIR_HEX("indexName", attest->attested.nv.indexName.name, attest->attested.nv.indexName.size),
                                SD_JSON_BUILD_PAIR_UNSIGNED("offset", attest->attested.nv.offset),
                                SD_JSON_BUILD_PAIR_HEX("nvContents", attest->attested.nv.nvContents.buffer, attest->attested.nv.nvContents.size));
                break;
        case TPM2_ST_ATTEST_SESSION_AUDIT:
                r = sd_json_buildo(
                                &av,
                                /* tss2-fapi doesn't handle this being a boolean when deserializing. */
                                SD_JSON_BUILD_PAIR_STRING("exclusiveSession", attest->attested.sessionAudit.exclusiveSession == TPM2_YES ? "YES" : "NO"),
                                SD_JSON_BUILD_PAIR_HEX("sessionDigest", attest->attested.sessionAudit.sessionDigest.buffer, attest->attested.sessionAudit.sessionDigest.size));
                break;
        case TPM2_ST_ATTEST_QUOTE: {
                _cleanup_(sd_json_variant_unrefp) sd_json_variant *sv = NULL;
                r = tpm2_tpml_pcr_selection_to_json(&attest->attested.quote.pcrSelect, &sv);
                if (r < 0)
                        return r;
                r = sd_json_buildo(
                                &av,
                                SD_JSON_BUILD_PAIR_VARIANT("pcrSelect", sv),
                                SD_JSON_BUILD_PAIR_HEX("pcrDigest", attest->attested.quote.pcrDigest.buffer, attest->attested.quote.pcrDigest.size));
                break;
        }
        default:
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Unknown attestation type id 0x%" PRIx16, attest->type);
        }
        if (r < 0)
                return r;
 
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
        r = sd_json_buildo(
                        &v,
                        SD_JSON_BUILD_PAIR_STRING("magic", "VALUE"),
                        SD_JSON_BUILD_PAIR_STRING("type", tpm2_st_attest_to_string(attest->type)),
                        SD_JSON_BUILD_PAIR_HEX("qualifiedSigner", attest->qualifiedSigner.name, attest->qualifiedSigner.size),
                        SD_JSON_BUILD_PAIR_HEX("extraData", attest->extraData.buffer, attest->extraData.size),
                        SD_JSON_BUILD_PAIR_VARIANT("clockInfo", cv),
                        /* tss2-fapi serializes a uint64_t that doesn't fit into a signed 54-bits as an
                         * array of 2 integers, but the deserialize path handles decoding this just fine. */
                        SD_JSON_BUILD_PAIR_UNSIGNED("firmwareVersion", attest->firmwareVersion),
                        SD_JSON_BUILD_PAIR_VARIANT("attested", av));
        if (r < 0)
                return r;
 
        *ret = TAKE_PTR(v);
        return 0;
}
 
/* Convert a signature scheme to JSON, in a format compatible with the TCG TSS2 JSON data format,
 * and which is compatible with the TSS2 implementation. This only supports RSASSA, RSAPSS and ECDSA
 * signatures.
 *
 * See https://trustedcomputinggroup.org/wp-content/uploads/TSS_JSON_Policy_v0p7_r08_pub.pdf */
static int tpm2_tpmt_sig_scheme_to_json(const TPMT_SIG_SCHEME *scheme, sd_json_variant **ret) {
        int r;
 
        assert(scheme);
        assert(ret);
 
        TPMI_ALG_SIG_SCHEME alg = scheme->scheme;
 
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *dv = NULL;
        if (IN_SET(alg, TPM2_ALG_RSASSA, TPM2_ALG_RSAPSS, TPM2_ALG_ECDSA)) {
                r = sd_json_buildo(
                                &dv,
                                SD_JSON_BUILD_PAIR_STRING("hashAlg", tpm2_hash_alg_to_string_tss2(scheme->details.any.hashAlg)));
                if (r < 0)
                        return r;
        } else if (alg != TPM2_ALG_NULL)
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Unknown signature algorithm id 0x%" PRIx16, alg);
 
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
        r = sd_json_buildo(
                        &v,
                        SD_JSON_BUILD_PAIR_STRING("scheme", tpm2_sig_alg_to_string(alg)),
                        JSON_BUILD_PAIR_VARIANT_NON_NULL("details", dv));
        if (r < 0)
                return r;
 
        *ret = TAKE_PTR(v);
        return 0;
}
 
/* Convert a signature scheme and attestation structure to JSON in a format that is compatible with the
 * "QuoteInfo encoding" described in the TCG FAPI spec and which matches the TSS2 FAPI implementation. Note
 * that this is generic - supporting also the result from NV_Certify and GetSessionAuditDigest. Note that
 * only RSASSA, RSAPSS and ECDSA signature schemes are supported.
 *
 * See https://trustedcomputinggroup.org/wp-content/uploads/TSS_JSON_Policy_v0p7_r08_pub.pdf and
 * https://trustedcomputinggroup.org/wp-content/uploads/TSS_FAPI_v0p94_r09_pub.pdf */
int tpm2_attest_info_to_json(const TPMT_SIG_SCHEME *scheme, const TPMS_ATTEST *attest, sd_json_variant **ret) {
        int r;
 
        assert(attest);
        assert(ret);
 
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *sv = NULL;
        r = tpm2_tpmt_sig_scheme_to_json(scheme, &sv);
        if (r < 0)
                return r;
 
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *av = NULL;
        r = tpm2_tpms_attest_to_json(attest, &av);
        if (r < 0)
                return r;
 
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
        r = sd_json_buildo(
                        &v,
                        SD_JSON_BUILD_PAIR_VARIANT("sig_scheme", sv),
                        SD_JSON_BUILD_PAIR_VARIANT("attest", av));
        if (r < 0)
                return r;
 
        *ret = TAKE_PTR(v);
        return 0;
}
 
static const char* tpm2_public_alg_to_string(TPMI_ALG_PUBLIC alg) {
        switch (alg) {
        case TPM2_ALG_RSA:
                return "RSA";
        case TPM2_ALG_ECC:
                return "ECC";
        case TPM2_ALG_SYMCIPHER:
                return "SYMCIPHER";
        case TPM2_ALG_KEYEDHASH:
                return "KEYEDHASH";
        default:
                log_debug("Unknown public object type 0x%" PRIx16, alg);
                return NULL;
        }
}
 
static const char* tpm2_ecc_curve_to_string(TPMI_ECC_CURVE curve) {
        switch (curve) {
        case TPM2_ECC_NIST_P192:
                return "NIST_P192";
        case TPM2_ECC_NIST_P224:
                return "NIST_P224";
        case TPM2_ECC_NIST_P256:
                return "NIST_P256";
        case TPM2_ECC_NIST_P384:
                return "NIST_P384";
        case TPM2_ECC_NIST_P521:
                return "NIST_P521";
        case TPM2_ECC_BN_P256:
                return "BN_P256";
        case TPM2_ECC_BN_P638:
                return "BN_P638";
        case TPM2_ECC_SM2_P256:
                return "SM2_P256";
        default:
                log_debug("Unknown ECC curve ID 0x%" PRIx16, curve);
                return NULL;
        }
}
 
/* Convert an asymmetric scheme to JSON, in a format compatible with the TCG TSS2 JSON data format,
 * and which is compatible with the TSS2 implementation. This only supports the signature schemes RSASSA,
 * RSAPSS and ECDSA.
 *
 * See https://trustedcomputinggroup.org/wp-content/uploads/TSS_JSON_Policy_v0p7_r08_pub.pdf */
static int tpm2_tpmt_asym_scheme_to_json(const TPMT_ASYM_SCHEME *scheme, sd_json_variant **ret) {
        int r;
 
        assert(scheme);
        assert(ret);
 
        TPMI_ALG_ASYM_SCHEME alg = scheme->scheme;
 
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *dv = NULL;
        if (IN_SET(alg, TPM2_ALG_RSASSA, TPM2_ALG_RSAPSS, TPM2_ALG_ECDSA)) {
                r = sd_json_buildo(
                                &dv,
                                SD_JSON_BUILD_PAIR_STRING("hashAlg", tpm2_hash_alg_to_string_tss2(scheme->details.anySig.hashAlg)));
                if (r < 0)
                        return r;
        } else if (alg != TPM2_ALG_NULL)
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Unknown asymmetric scheme id 0x%" PRIx16, alg);
 
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
        r = sd_json_buildo(
                        &v,
                        SD_JSON_BUILD_PAIR_STRING("scheme", tpm2_sig_alg_to_string(alg)),
                        SD_JSON_BUILD_PAIR_VARIANT("details", dv));
        if (r < 0)
                return r;
 
        *ret = TAKE_PTR(v);
        return 0;
}
 
/* Convert a TPM public key to JSON, in a format compatible with the TCG TSS2 JSON data format, and which
 * is compatible with the TSS2 implementation. This only supports restricted asymmetric signing keys with
 * the signing scheme RSASSA, RSAPSS or ECDSA.
 *
 * See https://trustedcomputinggroup.org/wp-content/uploads/TSS_JSON_Policy_v0p7_r08_pub.pdf */
int tpm2_tpmt_public_to_json(const TPMT_PUBLIC *public, sd_json_variant **ret) {
        int r;
 
        assert(public);
        assert(ret);
 
        if (!IN_SET(public->type, TPM2_ALG_RSA, TPM2_ALG_ECC))
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Unsupported object type 0x%" PRIx16, public->type);
 
        /* We're currently only serializing restricted signing keys which never have a symmetric algorithm,
         * so to avoid implementing the JSON encoding for this, just reject anything with a symmetric
         * algorithm. */
        if (public->parameters.asymDetail.symmetric.algorithm != TPM2_ALG_NULL)
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Unsupported object symmetric algorithm 0x%" PRIx16,
                                       public->parameters.asymDetail.symmetric.algorithm);
 
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *sv = NULL;
        r = tpm2_tpmt_asym_scheme_to_json(&public->parameters.asymDetail.scheme, &sv);
        if (r < 0)
                return r;
 
        /* Marshal the public parameters. */
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *pv = NULL;
        switch (public->type) {
        case TPM2_ALG_RSA:
                r = sd_json_buildo(
                                &pv,
                                SD_JSON_BUILD_PAIR_OBJECT("symmetric",
                                                          SD_JSON_BUILD_PAIR_STRING("algorithm", "NULL")),
                                SD_JSON_BUILD_PAIR_VARIANT("scheme", sv),
                                SD_JSON_BUILD_PAIR_UNSIGNED("keyBits", public->parameters.rsaDetail.keyBits),
                                SD_JSON_BUILD_PAIR_UNSIGNED("exponent", public->parameters.rsaDetail.exponent));
                break;
        case TPM2_ALG_ECC:
                /* No valid key has anything other than NULL here, so reject anything else to avoid
                 * having to implement the JSON encoding. */
                if (public->parameters.eccDetail.kdf.scheme != TPM2_ALG_NULL)
                        return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "Unsupported ECC object KDF algorithm 0x%" PRIx16,
                                               public->parameters.eccDetail.kdf.scheme);
 
                r = sd_json_buildo(
                                &pv,
                                SD_JSON_BUILD_PAIR_OBJECT("symmetric",
                                                          SD_JSON_BUILD_PAIR_STRING("algorithm", "NULL")),
                                SD_JSON_BUILD_PAIR_VARIANT("scheme", sv),
                                SD_JSON_BUILD_PAIR_STRING("curveID", tpm2_ecc_curve_to_string(public->parameters.eccDetail.curveID)),
                                SD_JSON_BUILD_PAIR_OBJECT("kdf",
                                                          SD_JSON_BUILD_PAIR_STRING("scheme", "NULL")));
                break;
        default:
                /* We've already checked the type. */
                assert_not_reached();
        }
        if (r < 0)
                return r;
 
        /* Marshal the public key. */
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *uv = NULL;
        switch (public->type) {
        case TPM2_ALG_RSA:
                r = sd_json_variant_new_hex(&uv, public->unique.rsa.buffer, public->unique.rsa.size);
                break;
        case TPM2_ALG_ECC:
                r = sd_json_buildo(
                                &uv,
                                SD_JSON_BUILD_PAIR_HEX("x", public->unique.ecc.x.buffer, public->unique.ecc.x.size),
                                SD_JSON_BUILD_PAIR_HEX("y", public->unique.ecc.y.buffer, public->unique.ecc.y.size));
                break;
        default:
                /* We've already checked the type. */
                assert_not_reached();
        }
        if (r < 0)
                return r;
 
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
        r = sd_json_buildo(
                        &v,
                        SD_JSON_BUILD_PAIR_STRING("type", tpm2_public_alg_to_string(public->type)),
                        SD_JSON_BUILD_PAIR_STRING("nameAlg", tpm2_hash_alg_to_string_tss2(public->nameAlg)),
                        /* tss2-fapi serializes these as an object with pretty names, but it can deserialize
                         * an integer here. */
                        SD_JSON_BUILD_PAIR_INTEGER("objectAttributes", public->objectAttributes),
                        SD_JSON_BUILD_PAIR_HEX("authPolicy", public->authPolicy.buffer, public->authPolicy.size),
                        SD_JSON_BUILD_PAIR_VARIANT("parameters", pv),
                        SD_JSON_BUILD_PAIR_VARIANT("unique", uv));
        if (r < 0)
                return r;
 
        *ret = TAKE_PTR(v);
        return 0;
}
 
/* Convert a NV public area to JSON, in a format compatible with the TCG TSS2 JSON data format, and which
 * is compatible with the TSS2 implementation.
 *
 * See https://trustedcomputinggroup.org/wp-content/uploads/TSS_JSON_Policy_v0p7_r08_pub.pdf */
int tpm2_tpms_nv_public_to_json(const TPMS_NV_PUBLIC *nv_public, sd_json_variant **ret) {
        int r;
 
        assert(nv_public);
        assert(ret);