HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/shared/creds-util.c

91,977 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: cb5d92f6a45f4041b7c1a566e4b7dd27ae58fa89

Lines 1001–2000 of 2,018

                r = tpm2_pcr_read(tpm2_context, &tpm2_hash_pcr_selection, &tpm2_hash_pcr_values, &tpm2_n_hash_pcr_values);
                if (r < 0)
                        return log_error_errno(r, "Could not read PCR values: %m");
 
                TPM2B_PUBLIC public;
                if (iovec_is_set(&pubkey)) {
                        r = tpm2_tpm2b_public_from_pem(pubkey.iov_base, pubkey.iov_len, &public);
                        if (r < 0)
                                return log_error_errno(r, "Could not convert public key to TPM2B_PUBLIC: %m");
                }
 
                TPM2B_DIGEST tpm2_policy = TPM2B_DIGEST_MAKE(NULL, TPM2_SHA256_DIGEST_SIZE);
                r = tpm2_calculate_sealing_policy(
                                tpm2_hash_pcr_values,
                                tpm2_n_hash_pcr_values,
                                iovec_is_set(&pubkey) ? &public : NULL,
                                /* pubkey_policy_ref= */ NULL,
                                /* use_pin= */ false,
                                /* pcrlock_policy= */ NULL,
                                &tpm2_policy);
                if (r < 0)
                        return log_error_errno(r, "Could not calculate sealing policy digest: %m");
 
                struct iovec *blobs = NULL;
                size_t n_blobs = 0;
                CLEANUP_ARRAY(blobs, n_blobs, iovec_array_free);
 
                r = tpm2_seal(tpm2_context,
                              /* seal_key_handle= */ 0,
                              &tpm2_policy,
                              /* n_policy= */ 1,
                              /* pin= */ NULL,
                              &tpm2_key,
                              &blobs,
                              &n_blobs,
                              &tpm2_primary_alg,
                              CRED_KEY_WANTS_TPM2_PINNED_SRK(with_key) || CRED_KEY_REQUIRES_TPM2_PINNED_SRK(with_key) ? &tpm2_srk : NULL);
                if (r < 0) {
                        if (sd_id128_equal(with_key, _CRED_AUTO_INITRD))
                                log_warning("TPM2 present and used, but we didn't manage to talk to it. Credential will be refused if SecureBoot is enabled.");
                        else if (!sd_id128_in_set(with_key, _CRED_AUTO, _CRED_AUTO_SCOPED))
                                return log_error_errno(r, "Failed to seal to TPM2: %m");
 
                        log_notice_errno(r, "TPM2 sealing didn't work, continuing without TPM2: %m");
                } else {
                        if (!iovec_memdup(&IOVEC_MAKE(tpm2_policy.buffer, tpm2_policy.size), &tpm2_policy_hash))
                                return log_oom();
 
                        assert(n_blobs == 1);
                        tpm2_blob = TAKE_STRUCT(blobs[0]);
 
                        assert(tpm2_blob.iov_len <= CREDENTIAL_FIELD_SIZE_MAX);
                        assert(tpm2_policy_hash.iov_len <= CREDENTIAL_FIELD_SIZE_MAX);
                        assert(tpm2_srk.iov_len <= CREDENTIAL_FIELD_SIZE_MAX);
                }
        }
#endif
 
        if (CRED_KEY_IS_AUTO(with_key)) {
                /* Let's settle the key type in auto mode now. */
                assert(!iovec_is_set(&tpm2_key) || iovec_is_set(&tpm2_srk));
 
                if (iovec_is_set(&host_key) && iovec_is_set(&tpm2_key))
                        id = iovec_is_set(&pubkey) ? (sd_id128_equal(with_key, _CRED_AUTO_SCOPED) ?
                                                      CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC_WITH_PK_SCOPED_PINNED_SRK : CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC_WITH_PK_PINNED_SRK)
                                                   : (sd_id128_equal(with_key, _CRED_AUTO_SCOPED) ?
                                                      CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC_SCOPED_PINNED_SRK : CRED_AES256_GCM_BY_HOST_AND_TPM2_HMAC_PINNED_SRK);
                else if (iovec_is_set(&tpm2_key) && !sd_id128_equal(with_key, _CRED_AUTO_SCOPED))
                        id = iovec_is_set(&pubkey) ? CRED_AES256_GCM_BY_TPM2_HMAC_WITH_PK_PINNED_SRK : CRED_AES256_GCM_BY_TPM2_HMAC_PINNED_SRK;
                else if (iovec_is_set(&host_key))
                        id = sd_id128_equal(with_key, _CRED_AUTO_SCOPED) ? CRED_AES256_GCM_BY_HOST_SCOPED : CRED_AES256_GCM_BY_HOST;
                else if (sd_id128_equal(with_key, _CRED_AUTO_INITRD))
                        id = CRED_AES256_GCM_BY_NULL;
                else
                        return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE),
                                               "TPM2 not available and host key located on temporary file system, no encryption key available.");
        } else
                id = with_key;
 
        if (sd_id128_equal(id, CRED_AES256_GCM_BY_NULL)) {
                if (FLAGS_SET(flags, CREDENTIAL_REFUSE_NULL))
                        return log_error_errno(SYNTHETIC_ERRNO(EHWPOISON), "Attempted to encrypt with null key, but this is disallowed.");
                if (!FLAGS_SET(flags, CREDENTIAL_ALLOW_NULL))
                        log_warning("Using a null key for encryption and signing. Confidentiality or authenticity will not be provided.");
        }
 
        /* Let's now take the host key and the TPM2 key and hash it together, to use as encryption key for the data */
        r = sha256_hash_host_and_tpm2_key(&host_key, &tpm2_key, md);
        if (r < 0)
                return r;
 
        if (uid_is_valid(uid)) {
                r = mangle_uid_into_key(uid, md);
                if (r < 0)
                        return r;
        }
 
        r = dlopen_libcrypto(LOG_DEBUG);
        if (r < 0)
                return r;
 
        assert_se(cc = sym_EVP_aes_256_gcm());
 
        ksz = sym_EVP_CIPHER_get_key_length(cc);
        assert(ksz == sizeof(md));
 
        bsz = sym_EVP_CIPHER_get_block_size(cc);
        assert(bsz > 0);
        assert((size_t) bsz <= CREDENTIAL_FIELD_SIZE_MAX);
 
        ivsz = sym_EVP_CIPHER_get_iv_length(cc);
        if (ivsz > 0) {
                assert((size_t) ivsz <= CREDENTIAL_FIELD_SIZE_MAX);
 
                r = crypto_random_bytes_allocate_iovec(ivsz, &iv);
                if (r < 0)
                        return log_error_errno(r, "Failed to acquired randomized IV: %m");
        }
 
        context = sym_EVP_CIPHER_CTX_new();
        if (!context)
                return log_openssl_errors(LOG_ERR, "Failed to allocate encryption object");
 
        if (sym_EVP_EncryptInit_ex(context, cc, NULL, md, iv.iov_base) != 1)
                return log_openssl_errors(LOG_ERR, "Failed to initialize encryption context");
 
        tsz = sym_EVP_CIPHER_CTX_get_tag_length(context);
        if (tsz <= 0 || (size_t) tsz > CREDENTIAL_FIELD_SIZE_MAX)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid tag size reported by OpenSSL.");
 
        /* Just an upper estimate */
        output.iov_len =
                ALIGN8(offsetof(struct encrypted_credential_header, iv) + ivsz) +
                ALIGN8(iovec_is_set(&tpm2_key) ? offsetof(struct tpm2_credential_header, policy_hash_and_blob) + tpm2_blob.iov_len + tpm2_policy_hash.iov_len : 0) +
                ALIGN8(iovec_is_set(&pubkey) ? offsetof(struct tpm2_public_key_credential_header, data) + pubkey.iov_len : 0) +
                ALIGN8(iovec_is_set(&tpm2_srk) ? offsetof(struct tpm2_pinned_srk_credential_header, data) + tpm2_srk.iov_len : 0) +
                ALIGN8(uid_is_valid(uid) ? sizeof(struct scoped_credential_header) : 0) +
                ALIGN8(offsetof(struct metadata_credential_header, name) + strlen_ptr(name)) +
                input->iov_len + 2U * (size_t) bsz +
                tsz;
        /* Silence static analyzers */
        assert(output.iov_len >= input->iov_len);
 
        output.iov_base = malloc0(output.iov_len);
        if (!output.iov_base)
                return log_oom();
 
        h = (struct encrypted_credential_header*) output.iov_base;
        h->id = id;
        h->block_size = htole32(bsz);
        h->key_size = htole32(ksz);
        h->tag_size = htole32(tsz);
        h->iv_size = htole32(ivsz);
        memcpy(h->iv, iv.iov_base, ivsz);
 
        p = ALIGN8(offsetof(struct encrypted_credential_header, iv) + ivsz);
 
#if HAVE_TPM2
        if (iovec_is_set(&tpm2_key)) {
                struct tpm2_credential_header *t;
 
                t = (struct tpm2_credential_header*) ((uint8_t*) output.iov_base + p);
                t->pcr_mask = htole64(tpm2_hash_pcr_mask);
                t->pcr_bank = htole16(tpm2_pcr_bank);
                t->primary_alg = htole16(tpm2_primary_alg);
                t->blob_size = htole32(tpm2_blob.iov_len);
                t->policy_hash_size = htole32(tpm2_policy_hash.iov_len);
                memcpy(t->policy_hash_and_blob, tpm2_blob.iov_base, tpm2_blob.iov_len);
                memcpy(t->policy_hash_and_blob + tpm2_blob.iov_len, tpm2_policy_hash.iov_base, tpm2_policy_hash.iov_len);
 
                p += ALIGN8(offsetof(struct tpm2_credential_header, policy_hash_and_blob) + tpm2_blob.iov_len + tpm2_policy_hash.iov_len);
        }
#endif
        if (iovec_is_set(&pubkey)) {
                struct tpm2_public_key_credential_header *z;
 
                z = (struct tpm2_public_key_credential_header*) ((uint8_t*) output.iov_base + p);
                z->pcr_mask = htole64(tpm2_pubkey_pcr_mask);
                z->size = htole32(pubkey.iov_len);
                memcpy(z->data, pubkey.iov_base, pubkey.iov_len);
 
                p += ALIGN8(offsetof(struct tpm2_public_key_credential_header, data) + pubkey.iov_len);
        }
 
        if (iovec_is_set(&tpm2_srk)) {
                struct tpm2_pinned_srk_credential_header *z;
 
                z = (struct tpm2_pinned_srk_credential_header*) ((uint8_t*) output.iov_base + p);
                z->size = htole32(tpm2_srk.iov_len);
                memcpy(z->data, tpm2_srk.iov_base, tpm2_srk.iov_len);
 
                p += ALIGN8(offsetof(struct tpm2_pinned_srk_credential_header, data) + tpm2_srk.iov_len);
        }
 
        if (uid_is_valid(uid)) {
                struct scoped_credential_header *w;
 
                w = (struct scoped_credential_header*) ((uint8_t*) output.iov_base + p);
                w->flags = htole64(SCOPE_HASH_DATA_BASE_FLAGS);
 
                p += ALIGN8(sizeof(struct scoped_credential_header));
        }
 
        /* Pass the encrypted + TPM2 header + scoped header as AAD */
        if (sym_EVP_EncryptUpdate(context, NULL, &added, output.iov_base, p) != 1)
                return log_openssl_errors(LOG_ERR, "Failed to write AAD data");
 
        /* Now construct the metadata header */
        ml = strlen_ptr(name);
        m = malloc0(ALIGN8(offsetof(struct metadata_credential_header, name) + ml));
        if (!m)
                return log_oom();
 
        m->timestamp = htole64(timestamp);
        m->not_after = htole64(not_after);
        m->name_size = htole32(ml);
        memcpy_safe(m->name, name, ml);
 
        /* And encrypt the metadata header */
        if (sym_EVP_EncryptUpdate(context, (uint8_t*) output.iov_base + p, &added, (const unsigned char*) m, ALIGN8(offsetof(struct metadata_credential_header, name) + ml)) != 1)
                return log_openssl_errors(LOG_ERR, "Failed to encrypt metadata header");
 
        assert(added >= 0);
        assert((size_t) added <= output.iov_len - p);
        p += added;
 
        /* Then encrypt the plaintext */
        if (sym_EVP_EncryptUpdate(context, (uint8_t*) output.iov_base + p, &added, input->iov_base, input->iov_len) != 1)
                return log_openssl_errors(LOG_ERR, "Failed to encrypt data");
 
        assert(added >= 0);
        assert((size_t) added <= output.iov_len - p);
        p += added;
 
        /* Finalize */
        if (sym_EVP_EncryptFinal_ex(context, (uint8_t*) output.iov_base + p, &added) != 1)
                return log_openssl_errors(LOG_ERR, "Failed to finalize data encryption");
 
        assert(added >= 0);
        assert((size_t) added <= output.iov_len - p);
        p += added;
 
        assert(p <= output.iov_len - tsz);
 
        /* Append tag */
        if (sym_EVP_CIPHER_CTX_ctrl(context, EVP_CTRL_GCM_GET_TAG, tsz, (uint8_t*) output.iov_base + p) != 1)
                return log_openssl_errors(LOG_ERR, "Failed to get tag");
 
        p += tsz;
        assert(p <= output.iov_len);
        output.iov_len = p;
 
        if (DEBUG_LOGGING && input->iov_len > 0) {
                size_t base64_size;
 
                base64_size = DIV_ROUND_UP(output.iov_len * 4, 3); /* Include base64 size increase in debug output */
                assert(base64_size >= input->iov_len);
                log_debug("Input of %zu bytes grew to output of %zu bytes (+%2zu%%).", input->iov_len, base64_size, base64_size * 100 / input->iov_len - 100);
        }
 
        *ret = TAKE_STRUCT(output);
        return 0;
}
 
static CredentialBootPolicy query_credential_boot_policy(void) {
        static CredentialBootPolicy cached = _CRED_BOOT_POLICY_INVALID;
        _cleanup_free_ char *value = NULL;
        int r;
 
        if (cached >= 0)
                return cached;
 
        /* default to RELAXED if invalid or unset */
        cached = CRED_BOOT_RELAXED;
        r = proc_cmdline_get_key("systemd.credentials_boot_policy", PROC_CMDLINE_STRIP_RD_PREFIX, &value);
        if (r < 0)
                log_debug_errno(r, "Failed to read systemd.credentials_boot_policy= from kernel command line, ignoring: %m");
        else if (r > 0) {
                CredentialBootPolicy p = credential_boot_policy_from_string(value);
                if (p < 0)
                        log_warning("Invalid systemd.credentials_boot_policy= value '%s', ignoring.", value);
                else
                        cached = p;
        }
 
        return cached;
}
 
static int check_null_key_policy(CredentialFlags flags) {
        if (FLAGS_SET(flags, CREDENTIAL_REFUSE_NULL))
                return log_error_errno(SYNTHETIC_ERRNO(EHWPOISON),
                                       "Credential uses null key, but that's not allowed, refusing.");
 
        if (FLAGS_SET(flags, CREDENTIAL_ALLOW_NULL))
                return 0;
 
        /* So this is a credential encrypted with a zero length key. We support this to cover for the
         * case where neither a host key not a TPM2 are available (specifically: initrd environments
         * where the host key is not yet accessible and no TPM2 chip exists at all), to minimize
         * different codeflow for TPM2 and non-TPM2 codepaths. Of course, credentials encoded this
         * way offer no confidentiality nor authenticity. Because of that it's important we refuse to
         * use them on systems that actually *do* have a TPM2 chip – if we are in SecureBoot
         * mode. Otherwise an attacker could hand us credentials like this and we'd use them thinking
         * they are trusted, even though they are not.
         *
         * Which conditions actually lead us to accept a null-key credential is configurable via
         * systemd.credentials_boot_policy=, which also covers the first boot case (before any key
         * exists yet); the decision itself is made in credential_boot_policy_accepts_null(). */
 
        CredentialBootPolicy policy = query_credential_boot_policy();
 
        bool have_tpm2 = efi_has_tpm2(), secure_boot = is_efi_secure_boot();
        /* in_first_boot() can return <0 on error: use the safe default in this case (not-first-boot). */
        bool first_boot = in_first_boot() > 0;
 
        if (!credential_boot_policy_accepts_null(policy, first_boot, have_tpm2, secure_boot))
                return log_error_errno(SYNTHETIC_ERRNO(EHWPOISON),
                                       "Credential uses null key, but systemd.credentials_boot_policy=%s refuses it here (TPM2=%s, SecureBoot=%s, first boot=%s).",
                                       credential_boot_policy_to_string(policy),
                                       yes_no(have_tpm2), yes_no(secure_boot), yes_no(first_boot));
 
        /* Accepting a null-key credential on a tpm2 host is undesired so keep it auditable */
        if (have_tpm2 && !first_boot)
                log_warning("Credential uses null key intended for use when TPM2 is absent, but TPM2 is present! "
                            "Accepting anyway, under systemd.credentials_boot_policy=%s.",
                            credential_boot_policy_to_string(policy));
        else
                log_debug("Credential uses null key, accepted under systemd.credentials_boot_policy=%s.",
                          credential_boot_policy_to_string(policy));
 
        return 0;
}
 
int decrypt_credential_and_warn(
                const char *validate_name,
                usec_t validate_timestamp,
                const char *tpm2_device,
                const char *tpm2_signature_path,
                uid_t uid,
                const struct iovec *input,
                CredentialFlags flags,
                struct iovec *ret) {
 
        _cleanup_(iovec_done_erase) struct iovec host_key = {}, plaintext = {}, tpm2_key = {};
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *signature_json = NULL;
        _cleanup_(EVP_CIPHER_CTX_freep) EVP_CIPHER_CTX *context = NULL;
        struct encrypted_credential_header *h;
        struct metadata_credential_header *m;
        uint8_t md[SHA256_DIGEST_LENGTH];
        const EVP_CIPHER *cc;
        uint32_t tag_size;
        size_t p, hs;
        int r, added, tsz;
 
        assert(iovec_is_valid(input));
        assert(ret);
 
        /* Only one of these two flags may be set at the same time */
        assert(!FLAGS_SET(flags, CREDENTIAL_ALLOW_NULL) || !FLAGS_SET(flags, CREDENTIAL_REFUSE_NULL));
 
        CLEANUP_ERASE(md);
 
        /* Relevant error codes:
         *
         *   -EBADMSG      → Corrupted file, or unparsable PCR signature file
         *   -EOPNOTSUPP   → Unsupported file type (could be: requires TPM but we have no TPM)
         *   -EHOSTDOWN    → Need PCR signature file, but couldn't find it
         *   -EHWPOISON    → Attempt to unlock with NULL key and either CREDENTIAL_ALLOW_REFUSE is on, or CREDENTIAL_ALLOW_NULL is off, but the system has a TPM and SecureBoot is on
         *   -EMEDIUMTYPE  → File has unexpected scope, i.e. user-scoped credential is attempted to be unlocked in system scope, or vice versa
         *   -EDESTADDRREQ → Credential is incorrectly named (i.e. the authenticated name does not match the actual name)
         *   -ESTALE       → Credential's validity has passed
         *   -ESRCH        → User specified for scope does not exist on this system
         *
         *   (plus the various error codes tpm2_unseal() returns) */
 
        h = (struct encrypted_credential_header*) input->iov_base;
 
        /* The ID must fit in, for the current and all future formats */
        if (input->iov_len < sizeof(h->id))
                return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Encrypted file too short.");
 
        if (!CRED_KEY_IS_VALID(h->id))
                return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Unknown encryption format, or corrupted data.");
 
        if (CRED_KEY_REQUIRES_TPM2_PK(h->id)) {
                r = tpm2_load_pcr_signature(tpm2_signature_path, &signature_json);
                if (r == -ENOENT)
                        return log_error_errno(SYNTHETIC_ERRNO(EHOSTDOWN), "Couldn't find PCR signature file: %m");
                if (r == -EBADMSG)
                        return log_error_errno(r, "PCR signature file is malformed.");
                if (r < 0)
                        return log_error_errno(r, "Failed to load PCR signature: %m");
        }
 
        if (sd_id128_equal(h->id, CRED_AES256_GCM_BY_NULL)) {
                r = check_null_key_policy(flags);
                if (r < 0)
                        return r;
        }
 
        if (CRED_KEY_IS_SCOPED(h->id)) {
                if (!uid_is_valid(uid))
                        return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE), "Encrypted file is scoped to a user, but no user selected.");
        } else {
                /* Refuse to unlock system credentials if user scope is requested. */
                if (uid_is_valid(uid) && !FLAGS_SET(flags, CREDENTIAL_ANY_SCOPE))
                        return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE), "Encrypted file is scoped to the system, but user scope selected.");
 
                uid = UID_INVALID;
        }
 
        /* Now we know the minimum header size */
        if (input->iov_len < offsetof(struct encrypted_credential_header, iv))
                return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Encrypted file too short.");
 
        /* Verify some basic header values */
        if (le32toh(h->key_size) != sizeof(md))
                return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Unexpected key size in header.");
        if (le32toh(h->block_size) <= 0 || le32toh(h->block_size) > CREDENTIAL_FIELD_SIZE_MAX)
                return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Unexpected block size in header.");
        if (le32toh(h->iv_size) > CREDENTIAL_FIELD_SIZE_MAX)
                return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "IV size too large.");
 
        tag_size = le32toh(h->tag_size);
        if (tag_size == 0 || tag_size > CREDENTIAL_FIELD_SIZE_MAX)
                return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Unexpected tag size in header.");
 
        /* Ensure we have space for the full header now (we don't know the size of the name hence this is a
         * lower limit only) */
        if (input->iov_len <
            ALIGN8(offsetof(struct encrypted_credential_header, iv) + le32toh(h->iv_size)) +
            ALIGN8(CRED_KEY_REQUIRES_TPM2(h->id) ? offsetof(struct tpm2_credential_header, policy_hash_and_blob) : 0) +
            ALIGN8(CRED_KEY_REQUIRES_TPM2_PK(h->id) ? offsetof(struct tpm2_public_key_credential_header, data) : 0) +
            ALIGN8(CRED_KEY_REQUIRES_TPM2_PINNED_SRK(h->id) ? offsetof(struct tpm2_pinned_srk_credential_header, data) : 0) +
            ALIGN8(CRED_KEY_IS_SCOPED(h->id) ? sizeof(struct scoped_credential_header) : 0) +
            ALIGN8(offsetof(struct metadata_credential_header, name)) +
            tag_size)
                return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Encrypted file too short.");
 
        p = ALIGN8(offsetof(struct encrypted_credential_header, iv) + le32toh(h->iv_size));
 
        if (CRED_KEY_REQUIRES_TPM2(h->id)) {
#if HAVE_TPM2
                struct tpm2_credential_header* t = (struct tpm2_credential_header*) ((uint8_t*) input->iov_base + p);
                struct tpm2_public_key_credential_header *z_pubkey = NULL;
                struct tpm2_pinned_srk_credential_header *z_srk = NULL;
 
                if (!TPM2_PCR_MASK_VALID(le64toh(t->pcr_mask)))
                        return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "TPM2 PCR mask out of range.");
                if (!tpm2_hash_alg_to_string(le16toh(t->pcr_bank)))
                        return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "TPM2 PCR bank invalid or not supported");
                if (!tpm2_asym_alg_to_string(le16toh(t->primary_alg)))
                        return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "TPM2 primary key algorithm invalid or not supported.");
                if (le32toh(t->blob_size) > CREDENTIAL_FIELD_SIZE_MAX)
                        return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Unexpected TPM2 blob size.");
                if (le32toh(t->policy_hash_size) > CREDENTIAL_FIELD_SIZE_MAX)
                        return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Unexpected TPM2 policy hash size.");
 
                /* Ensure we have space for the full TPM2 header now (still don't know the name, and its size
                 * though, hence still just a lower limit test only) */
                if (input->iov_len <
                    p +
                    ALIGN8(offsetof(struct tpm2_credential_header, policy_hash_and_blob) + le32toh(t->blob_size) + le32toh(t->policy_hash_size)) +
                    ALIGN8(CRED_KEY_REQUIRES_TPM2_PK(h->id) ? offsetof(struct tpm2_public_key_credential_header, data) : 0) +
                    ALIGN8(CRED_KEY_REQUIRES_TPM2_PINNED_SRK(h->id) ? offsetof(struct tpm2_pinned_srk_credential_header, data) : 0) +
                    ALIGN8(CRED_KEY_IS_SCOPED(h->id) ? sizeof(struct scoped_credential_header) : 0) +
                    ALIGN8(offsetof(struct metadata_credential_header, name)) +
                    tag_size)
                        return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Encrypted file too short.");
 
                p += ALIGN8(offsetof(struct tpm2_credential_header, policy_hash_and_blob) +
                            le32toh(t->blob_size) +
                            le32toh(t->policy_hash_size));
 
                if (CRED_KEY_REQUIRES_TPM2_PK(h->id)) {
                        z_pubkey = (struct tpm2_public_key_credential_header*) ((uint8_t*) input->iov_base + p);
 
                        if (!TPM2_PCR_MASK_VALID(le64toh(z_pubkey->pcr_mask)) || le64toh(z_pubkey->pcr_mask) == 0)
                                return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "TPM2 PCR mask out of range.");
                        if (le32toh(z_pubkey->size) > PUBLIC_KEY_MAX)
                                return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Unexpected public key size.");
 
                        if (input->iov_len <
                            p +
                            ALIGN8(offsetof(struct tpm2_public_key_credential_header, data) + le32toh(z_pubkey->size)) +
                            ALIGN8(CRED_KEY_REQUIRES_TPM2_PINNED_SRK(h->id) ? offsetof(struct tpm2_pinned_srk_credential_header, data) : 0) +
                            ALIGN8(CRED_KEY_IS_SCOPED(h->id) ? sizeof(struct scoped_credential_header) : 0) +
                            ALIGN8(offsetof(struct metadata_credential_header, name)) +
                            tag_size)
                                return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Encrypted file too short.");
 
                        p += ALIGN8(offsetof(struct tpm2_public_key_credential_header, data) +
                                    le32toh(z_pubkey->size));
                }
 
                if (CRED_KEY_REQUIRES_TPM2_PINNED_SRK(h->id)) {
                        z_srk = (struct tpm2_pinned_srk_credential_header*) ((uint8_t*) input->iov_base + p);
 
                        if (le32toh(z_srk->size) > CREDENTIAL_FIELD_SIZE_MAX)
                                return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Unexpected pinned SRK size.");
 
                        if (input->iov_len <
                            p +
                            ALIGN8(offsetof(struct tpm2_pinned_srk_credential_header, data) + le32toh(z_srk->size)) +
                            ALIGN8(CRED_KEY_IS_SCOPED(h->id) ? sizeof(struct scoped_credential_header) : 0) +
                            ALIGN8(offsetof(struct metadata_credential_header, name)) +
                            tag_size)
                                return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Encrypted file too short.");
 
                        p += ALIGN8(offsetof(struct tpm2_pinned_srk_credential_header, data) +
                                    le32toh(z_srk->size));
                }
 
                _cleanup_(tpm2_context_unrefp) Tpm2Context *tpm2_context = NULL;
                r = tpm2_context_new(tpm2_device, &tpm2_context);
                if (r < 0)
                        return r;
 
                r = tpm2_unseal(tpm2_context,
                                le64toh(t->pcr_mask),
                                le16toh(t->pcr_bank),
                                z_pubkey ? &IOVEC_MAKE(z_pubkey->data, le32toh(z_pubkey->size)) : NULL,
                                /* pubkey_policy_ref= */ NULL,
                                z_pubkey ? le64toh(z_pubkey->pcr_mask) : 0,
                                signature_json,
                                /* pin= */ NULL,
                                /* pcrlock_policy= */ NULL,
                                le16toh(t->primary_alg),
                                &IOVEC_MAKE(t->policy_hash_and_blob, le32toh(t->blob_size)),
                                /* n_blobs= */ 1,
                                &IOVEC_MAKE(t->policy_hash_and_blob + le32toh(t->blob_size), le32toh(t->policy_hash_size)),
                                /* n_known_policy_hash= */ 1,
                                z_srk ? &IOVEC_MAKE(z_srk->data, le32toh(z_srk->size)) : NULL,
                                &tpm2_key);
                if (r == -EREMOTE)
                        return log_error_errno(r, "TPM key integrity check failed. Key most likely does not belong to this TPM.");
                if (r == -EADDRNOTAVAIL)
                        return log_error_errno(r, "NV index referenced by key is missing, unwritten, or unusable, it could be for another system.");
                if (r == -EUCLEAN)
                        return log_error_errno(r, "PCR values kept changing while unsealing the TPM2 secret, giving up. Something on this system extends a PCR continuously.");
                if (ERRNO_IS_NEG_TPM2_UNSEAL_BAD_PCR(r))
                        return log_error_errno(r, "TPM policy does not match current system state. Either system has been tampered with or policy out-of-date: %m");
                if (r < 0)
                        return log_error_errno(r, "Failed to unseal secret using TPM2: %m");
#else
                return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Credential requires TPM2 support, but TPM2 support not available.");
#endif
        }
 
        if (CRED_KEY_IS_SCOPED(h->id)) {
                struct scoped_credential_header* sh = (struct scoped_credential_header*) ((uint8_t*) input->iov_base + p);
 
                if (le64toh(sh->flags) != SCOPE_HASH_DATA_BASE_FLAGS)
                        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Scoped credential with unsupported flags.");
 
                if (input->iov_len <
                    p +
                    sizeof(struct scoped_credential_header) +
                    ALIGN8(offsetof(struct metadata_credential_header, name)) +
                    tag_size)
                        return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Encrypted file too short.");
 
                p += sizeof(struct scoped_credential_header);
        }
 
        if (CRED_KEY_REQUIRES_HOST(h->id)) {
                r = get_credential_host_secret(/* flags= */ 0, &host_key);
                if (r < 0)
                        return log_error_errno(r, "Failed to determine local credential key: %m");
        }
 
        if (sd_id128_equal(h->id, CRED_AES256_GCM_BY_NULL) && !FLAGS_SET(flags, CREDENTIAL_ALLOW_NULL))
                log_warning("Warning: using a null key for decryption and authentication. Confidentiality or authenticity are not provided.");
 
        r = sha256_hash_host_and_tpm2_key(&host_key, &tpm2_key, md);
        if (r < 0)
                return r;
 
        if (CRED_KEY_IS_SCOPED(h->id)) {
                r = mangle_uid_into_key(uid, md);
                if (r < 0)
                        return r;
        }
 
        r = dlopen_libcrypto(LOG_DEBUG);
        if (r < 0)
                return r;
 
        assert_se(cc = sym_EVP_aes_256_gcm());
 
        /* Make sure cipher expectations match the header */
        if (sym_EVP_CIPHER_get_key_length(cc) != (int) le32toh(h->key_size))
                return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Unexpected key size in header.");
        if (sym_EVP_CIPHER_get_block_size(cc) != (int) le32toh(h->block_size))
                return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Unexpected block size in header.");
 
        context = sym_EVP_CIPHER_CTX_new();
        if (!context)
                return log_openssl_errors(LOG_ERR, "Failed to allocate decryption object");
 
        if (sym_EVP_DecryptInit_ex(context, cc, NULL, NULL, NULL) != 1)
                return log_openssl_errors(LOG_ERR, "Failed to initialize decryption context");
 
        tsz = sym_EVP_CIPHER_CTX_get_tag_length(context);
        if (tsz <= 0 || (size_t) tsz > CREDENTIAL_FIELD_SIZE_MAX)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid tag size reported by OpenSSL.");
        if (tag_size != (uint32_t) tsz)
                return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Unexpected tag size in header.");
 
        if (sym_EVP_CIPHER_CTX_ctrl(context, EVP_CTRL_GCM_SET_IVLEN, le32toh(h->iv_size), NULL) != 1)
                return log_openssl_errors(LOG_ERR, "Failed to set IV size on decryption context");
 
        if (sym_EVP_DecryptInit_ex(context, NULL, NULL, md, h->iv) != 1)
                return log_openssl_errors(LOG_ERR, "Failed to set IV and key");
 
        if (sym_EVP_DecryptUpdate(context, NULL, &added, input->iov_base, p) != 1)
                return log_openssl_errors(LOG_ERR, "Failed to write AAD data");
 
        plaintext.iov_base = malloc(input->iov_len - p - tag_size);
        if (!plaintext.iov_base)
                return -ENOMEM;
 
        if (sym_EVP_DecryptUpdate(
                            context,
                            plaintext.iov_base,
                            &added,
                            (uint8_t*) input->iov_base + p,
                            input->iov_len - p - tag_size) != 1)
                return log_openssl_errors(LOG_ERR, "Failed to decrypt data");
 
        assert(added >= 0);
        assert((size_t) added <= input->iov_len - p - tag_size);
        plaintext.iov_len = added;
 
        if (sym_EVP_CIPHER_CTX_ctrl(context, EVP_CTRL_GCM_SET_TAG, tag_size, (uint8_t*) input->iov_base + input->iov_len - tag_size) != 1)
                return log_openssl_errors(LOG_ERR, "Failed to set tag");
 
        if (sym_EVP_DecryptFinal_ex(context, (uint8_t*) plaintext.iov_base + plaintext.iov_len, &added) != 1) {
                log_openssl_errors(LOG_ERR, "Decryption failed (incorrect key?)");
                /* A GCM tag/authentication mismatch (wrong key or corrupted blob) is the common case here
                 * and typically leaves the OpenSSL error queue empty, so we can't rely on the translated
                 * errno. Return -EBADMSG unconditionally: it's this function's documented "corrupted file"
                 * code, and credentials_varlink_error_table[] maps it to io.systemd.Credentials.BadFormat. */
                return -EBADMSG;
        }
 
        plaintext.iov_len += added;
 
        if (plaintext.iov_len < ALIGN8(offsetof(struct metadata_credential_header, name)))
                return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Metadata header incomplete.");
 
        m = plaintext.iov_base;
 
        if (le64toh(m->timestamp) != USEC_INFINITY &&
            le64toh(m->not_after) != USEC_INFINITY &&
            le64toh(m->timestamp) >= le64toh(m->not_after))
                return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Timestamps of credential are not in order, refusing.");
 
        if (le32toh(m->name_size) > CREDENTIAL_NAME_MAX)
                return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Embedded credential name too long, refusing.");
 
        hs = ALIGN8(offsetof(struct metadata_credential_header, name) + le32toh(m->name_size));
        if (plaintext.iov_len < hs)
                return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Metadata header incomplete.");
 
        if (le32toh(m->name_size) > 0) {
                _cleanup_free_ char *embedded_name = NULL;
 
                r = make_cstring(m->name, le32toh(m->name_size), MAKE_CSTRING_REFUSE_TRAILING_NUL, &embedded_name);
                if (r < 0)
                        return log_error_errno(r, "Unable to convert embedded credential name to C string: %m");
 
                if (!credential_name_valid(embedded_name))
                        return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Embedded credential name is not valid, refusing.");
 
                if (validate_name && !streq(embedded_name, validate_name)) {
 
                        r = secure_getenv_bool("SYSTEMD_CREDENTIAL_VALIDATE_NAME");
                        if (r < 0 && r != -ENXIO)
                                log_debug_errno(r, "Failed to parse $SYSTEMD_CREDENTIAL_VALIDATE_NAME: %m");
                        if (r != 0)
                                return log_error_errno(SYNTHETIC_ERRNO(EDESTADDRREQ), "Embedded credential name '%s' does not match filename '%s', refusing.", embedded_name, validate_name);
 
                        log_debug("Embedded credential name '%s' does not match expected name '%s', but configured to use credential anyway.", embedded_name, validate_name);
                }
        }
 
        if (validate_timestamp != USEC_INFINITY) {
                if (le64toh(m->timestamp) != USEC_INFINITY && le64toh(m->timestamp) > validate_timestamp)
                        log_debug("Credential timestamp is from the future, assuming clock skew.");
 
                if (le64toh(m->not_after) != USEC_INFINITY && le64toh(m->not_after) < validate_timestamp) {
 
                        r = secure_getenv_bool("SYSTEMD_CREDENTIAL_VALIDATE_NOT_AFTER");
                        if (r < 0 && r != -ENXIO)
                                log_debug_errno(r, "Failed to parse $SYSTEMD_CREDENTIAL_VALIDATE_NOT_AFTER: %m");
                        if (r != 0)
                                return log_error_errno(SYNTHETIC_ERRNO(ESTALE), "Credential's time passed, refusing to use.");
 
                        log_debug("Credential not-after timestamp has passed, but configured to use credential anyway.");
                }
        }
 
        if (ret) {
                _cleanup_(iovec_done_erase) struct iovec without_metadata = {};
 
                without_metadata.iov_len = plaintext.iov_len - hs;
                without_metadata.iov_base = memdup_suffix0((uint8_t*) plaintext.iov_base + hs, without_metadata.iov_len);
                if (!without_metadata.iov_base)
                        return log_oom();
 
                *ret = TAKE_STRUCT(without_metadata);
        }
 
        return 0;
}
 
#else
 
int get_credential_host_secret(CredentialSecretFlags flags, struct iovec *ret) {
        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Support for encrypted credentials not available.");
}
 
int encrypt_credential_and_warn(sd_id128_t with_key, const char *name, usec_t timestamp, usec_t not_after, const char *tpm2_device, uint32_t tpm2_hash_pcr_mask, const char *tpm2_pubkey_path, uint32_t tpm2_pubkey_pcr_mask, uid_t uid, const struct iovec *input, CredentialFlags flags, struct iovec *ret) {
        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Support for encrypted credentials not available.");
}
 
int decrypt_credential_and_warn(const char *validate_name, usec_t validate_timestamp, const char *tpm2_device, const char *tpm2_signature_path, uid_t uid, const struct iovec *input, CredentialFlags flags, struct iovec *ret) {
        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Support for encrypted credentials not available.");
}
 
#endif
 
int ipc_encrypt_credential(const char *name, usec_t timestamp, usec_t not_after, uid_t uid, const struct iovec *input, CredentialFlags flags, struct iovec *ret) {
        _cleanup_(sd_varlink_unrefp) sd_varlink *vl = NULL;
        int r;
 
        assert(input && iovec_is_valid(input));
        assert(ret);
 
        r = sd_varlink_connect_address(&vl, "/run/systemd/io.systemd.Credentials");
        if (r < 0)
                return log_error_errno(r, "Failed to connect to io.systemd.Credentials: %m");
 
        /* Mark anything we get from the service as sensitive, given that it might use a NULL cypher, at least in theory */
        r = sd_varlink_set_input_sensitive(vl);
        if (r < 0)
                return log_error_errno(r, "Failed to enable sensitive Varlink input: %m");
 
        /* Create the input data blob object separately, so that we can mark it as sensitive */
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *jinput = NULL;
        r = sd_json_build(&jinput, JSON_BUILD_IOVEC_BASE64(input));
        if (r < 0)
                return log_error_errno(r, "Failed to create input object: %m");
 
        sd_json_variant_sensitive(jinput);
 
        sd_json_variant *reply = NULL;
        const char *error_id = NULL;
        r = sd_varlink_callbo(
                        vl,
                        "io.systemd.Credentials.Encrypt",
                        &reply,
                        &error_id,
                        SD_JSON_BUILD_PAIR_CONDITION(!!name, "name", SD_JSON_BUILD_STRING(name)),
                        SD_JSON_BUILD_PAIR_VARIANT("data", jinput),
                        SD_JSON_BUILD_PAIR_CONDITION(timestamp != USEC_INFINITY, "timestamp", SD_JSON_BUILD_UNSIGNED(timestamp)),
                        SD_JSON_BUILD_PAIR_CONDITION(not_after != USEC_INFINITY, "notAfter",  SD_JSON_BUILD_UNSIGNED(not_after)),
                        SD_JSON_BUILD_PAIR_CONDITION(!FLAGS_SET(flags, CREDENTIAL_ANY_SCOPE), "scope", SD_JSON_BUILD_STRING(uid_is_valid(uid) ? "user" : "system")),
                        SD_JSON_BUILD_PAIR_CONDITION(uid_is_valid(uid), "uid", SD_JSON_BUILD_UNSIGNED(uid)),
                        SD_JSON_BUILD_PAIR_CONDITION((flags & (CREDENTIAL_ALLOW_NULL|CREDENTIAL_REFUSE_NULL)) != 0, "allowNull", SD_JSON_BUILD_BOOLEAN(flags & CREDENTIAL_ALLOW_NULL)),
                        SD_JSON_BUILD_PAIR_BOOLEAN("allowInteractiveAuthentication", FLAGS_SET(flags, CREDENTIAL_IPC_ALLOW_INTERACTIVE)));
        if (r < 0)
                return log_error_errno(r, "Failed to call Encrypt() varlink call.");
        if (!isempty(error_id)) {
                if (streq(error_id, "io.systemd.Credentials.NoSuchUser"))
                        return log_error_errno(SYNTHETIC_ERRNO(ESRCH), "No such user.");
 
                return log_error_errno(sd_varlink_error_to_errno(error_id, reply), "Failed to encrypt: %s", error_id);
        }
 
        static const sd_json_dispatch_field dispatch_table[] = {
                { "blob", SD_JSON_VARIANT_STRING, json_dispatch_unbase64_iovec, 0, SD_JSON_MANDATORY },
                {},
        };
 
        r = sd_json_dispatch(reply, dispatch_table, SD_JSON_LOG|SD_JSON_ALLOW_EXTENSIONS, ret);
        if (r < 0)
                return r;
 
        return 0;
}
 
int ipc_decrypt_credential(const char *validate_name, usec_t validate_timestamp, uid_t uid, const struct iovec *input, CredentialFlags flags, struct iovec *ret) {
        _cleanup_(sd_varlink_unrefp) sd_varlink *vl = NULL;
        int r;
 
        assert(input && iovec_is_valid(input));
        assert(ret);
 
        r = sd_varlink_connect_address(&vl, "/run/systemd/io.systemd.Credentials");
        if (r < 0)
                return log_error_errno(r, "Failed to connect to io.systemd.Credentials: %m");
 
        r = sd_varlink_set_input_sensitive(vl);
        if (r < 0)
                return log_error_errno(r, "Failed to enable sensitive Varlink input: %m");
 
        /* Create the input data blob object separately, so that we can mark it as sensitive (it's supposed
         * to be encrypted, but who knows maybe it uses the NULL cypher). */
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *jinput = NULL;
        r = sd_json_build(&jinput, JSON_BUILD_IOVEC_BASE64(input));
        if (r < 0)
                return log_error_errno(r, "Failed to create input object: %m");
 
        sd_json_variant_sensitive(jinput);
 
        sd_json_variant *reply = NULL;
        const char *error_id = NULL;
        r = sd_varlink_callbo(
                        vl,
                        "io.systemd.Credentials.Decrypt",
                        &reply,
                        &error_id,
                        SD_JSON_BUILD_PAIR_CONDITION(!!validate_name, "name", SD_JSON_BUILD_STRING(validate_name)),
                        SD_JSON_BUILD_PAIR_VARIANT("blob", jinput),
                        SD_JSON_BUILD_PAIR_CONDITION(validate_timestamp != USEC_INFINITY, "timestamp", SD_JSON_BUILD_UNSIGNED(validate_timestamp)),
                        SD_JSON_BUILD_PAIR_CONDITION(!FLAGS_SET(flags, CREDENTIAL_ANY_SCOPE), "scope", SD_JSON_BUILD_STRING(uid_is_valid(uid) ? "user" : "system")),
                        SD_JSON_BUILD_PAIR_CONDITION(uid_is_valid(uid), "uid", SD_JSON_BUILD_UNSIGNED(uid)),
                        SD_JSON_BUILD_PAIR_BOOLEAN("allowInteractiveAuthentication", FLAGS_SET(flags, CREDENTIAL_IPC_ALLOW_INTERACTIVE)));
        if (r < 0)
                return log_error_errno(r, "Failed to call Decrypt() varlink call.");
        if (!isempty(error_id))  {
                const CredentialsVarlinkError *e = credentials_varlink_error_by_id(error_id);
                if (e)
                        return log_error_errno(SYNTHETIC_ERRNO(e->errnum), "%s", e->msg);
 
                return log_error_errno(sd_varlink_error_to_errno(error_id, reply), "Failed to decrypt: %s", error_id);
        }
 
        static const sd_json_dispatch_field dispatch_table[] = {
                { "data", SD_JSON_VARIANT_STRING, json_dispatch_unbase64_iovec, 0, SD_JSON_MANDATORY },
                {},
        };
 
        r = sd_json_dispatch(reply, dispatch_table, SD_JSON_LOG|SD_JSON_ALLOW_EXTENSIONS, ret);
        if (r < 0)
                return r;
 
        return 0;
}
 
int get_global_boot_credentials_path(char **ret) {
        _cleanup_free_ char *path = NULL;
        int r;
 
        assert(ret);
 
        /* Determines where to put global boot credentials in. Returns the path to the "/loader/credentials/"
         * directory below the XBOOTLDR or ESP partition. Any credentials placed in this directory can be
         * picked up later in the initrd. */
 
        r = find_xbootldr_and_warn(
                        /* root= */ NULL,
                        /* path= */ NULL,
                        /* unprivileged_mode= */ false,
                        &path,
                        /* ret_fd= */ NULL);
        if (r < 0) {
                if (r != -ENOKEY)
                        return log_error_errno(r, "Failed to find XBOOTLDR partition: %m");
 
                r = find_esp_and_warn(
                                /* root= */ NULL,
                                /* path= */ NULL,
                                /* unprivileged_mode= */ false,
                                &path,
                                /* ret_fd= */ NULL);
                if (r < 0) {
                        if (r != -ENOKEY)
                                return log_error_errno(r, "Failed to find ESP partition: %m");
 
                        *ret = NULL;
                        return 0; /* not found! */
                }
        }
 
        _cleanup_free_ char *joined = path_join(path, "loader/credentials");
        if (!joined)
                return log_oom();
 
        log_debug("Determined global boot credentials path as: %s", joined);
 
        *ret = TAKE_PTR(joined);
        return 1; /* found! */
}
 
static int pick_up_credential_one(
                int credential_dir_fd,
                const char *credential_name,
                const PickUpCredential *table_entry) {
 
        _cleanup_free_ char *fn = NULL, *target_path = NULL;
        const char *e;
        int r;
 
        assert(credential_dir_fd >= 0);
        assert(credential_name);
        assert(table_entry);
 
        e = startswith(credential_name, table_entry->credential_prefix);
        if (!e)
                return 0; /* unmatched */
 
        fn = strjoin(e, table_entry->filename_suffix);
        if (!fn)
                return log_oom();
 
        if (!filename_is_valid(fn))
                return log_warning_errno(SYNTHETIC_ERRNO(EINVAL),
                                         "Passed credential '%s' would result in invalid filename '%s'.",
                                         credential_name, fn);
 
        r = mkdir_p_label(table_entry->target_dir, 0755);
        if (r < 0)
                return log_warning_errno(r, "Failed to create '%s': %m", table_entry->target_dir);
 
        target_path = path_join(table_entry->target_dir, fn);
        if (!target_path)
                return log_oom();
 
        r = copy_file_at(
                        credential_dir_fd, credential_name,
                        AT_FDCWD, target_path,
                        /* open_flags= */ 0,
                        0644,
                        /* copy_flags= */ 0);
        if (r < 0)
                return log_warning_errno(r, "Failed to copy credential %s → file %s: %m",
                                         credential_name, target_path);
 
        log_info("Installed %s from credential.", target_path);
        return 1; /* done */
}
 
int pick_up_credentials(const PickUpCredential *table, size_t n_table_entry) {
        _cleanup_close_ int credential_dir_fd = -EBADF;
        int r, ret = 0;
 
        assert(table);
        assert(n_table_entry > 0);
 
        credential_dir_fd = open_credentials_dir();
        if (IN_SET(credential_dir_fd, -ENXIO, -ENOENT)) {
                /* Credential env var not set, or dir doesn't exist. */
                log_debug("No credentials found.");
                return 0;
        }
        if (credential_dir_fd < 0)
                return log_error_errno(credential_dir_fd, "Failed to open credentials directory: %m");
 
        _cleanup_free_ DirectoryEntries *des = NULL;
        r = readdir_all(credential_dir_fd, RECURSE_DIR_SORT|RECURSE_DIR_IGNORE_DOT|RECURSE_DIR_MUST_BE_REGULAR, &des);
        if (r < 0)
                return log_error_errno(r, "Failed to enumerate credentials: %m");
 
        FOREACH_ARRAY(i, des->entries, des->n_entries) {
                struct dirent *de = *i;
 
                FOREACH_ARRAY(t, table, n_table_entry) {
                        r = pick_up_credential_one(credential_dir_fd, de->d_name, t);
                        if (r != 0) {
                                RET_GATHER(ret, r);
                                break; /* Done, or failed. Let's move to the next credential. */
                        }
                }
        }
 
        return ret;
}
 
static const CredentialsVarlinkError credentials_varlink_error_table[] = {
        { "io.systemd.Credentials.BadFormat",              EBADMSG,      "Bad credential format." },
        { "io.systemd.Credentials.NameMismatch",           EDESTADDRREQ, "Name in credential doesn't match expectations." },
        { "io.systemd.Credentials.TimeMismatch",           ESTALE,       "Outside of credential validity time window." },
        { "io.systemd.Credentials.NoSuchUser",             ESRCH,        "No such user." },
        { "io.systemd.Credentials.BadScope",               EMEDIUMTYPE,  "Scope mismatch." },
        { "io.systemd.Credentials.CantFindPCRSignature",   EHOSTDOWN,    "PCR signature required for decryption, but could not be found." },
        { "io.systemd.Credentials.NullKeyNotAllowed",      EHWPOISON,    "The key was encrypted with a null key, but that's not allowed during decryption." },
        { "io.systemd.Credentials.KeyBelongsToOtherTPM",   EREMOTE,      "The TPM integrity check for this key failed, key probably belongs to another TPM, or was corrupted." },
        { "io.systemd.Credentials.TPMInDictionaryLockout", ENOLCK,       "The TPM is in dictionary lockout mode, cannot operate." },
        { "io.systemd.Credentials.UnexpectedPCRState",     EPERM,        "Unexpected TPM PCR state of the system." },
        { "io.systemd.Credentials.PCRsKeptChanging",       EUCLEAN,      "PCR values kept changing while unsealing the TPM2 secret, something on this system extends a PCR continuously." },
        { "io.systemd.Credentials.NVIndexUnusable",        EADDRNOTAVAIL, "The NV index referenced by the key is missing, unwritten, or unusable, it could be for another system." },
};
 
const CredentialsVarlinkError* credentials_varlink_error_by_id(const char *id) {
        assert(id);
 
        FOREACH_ELEMENT(i, credentials_varlink_error_table)