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 1–1000 of 2,018

/* SPDX-License-Identifier: LGPL-2.1-or-later */
 
#include <pwd.h>
#include <sys/file.h>
#include <unistd.h>
#include "efivars.h"
#include "time-util.h"
 
#include "sd-id128.h"
#include "sd-json.h"
#include "sd-varlink.h"
 
#include "alloc-util.h"
#include "blockdev-util.h"
#include "chattr-util.h"
#include "copy.h"
#include "creds-util.h"
#include "crypto-util.h"
#include "efi-api.h"
#include "env-util.h"
#include "errno-util.h"
#include "fd-util.h"
#include "fileio.h"
#include "find-esp.h"
#include "format-util.h"
#include "fs-util.h"
#include "initrd-util.h"
#include "io-util.h"
#include "json-util.h"
#include "log.h"
#include "memory-util.h"
#include "mkdir.h"
#include "parse-util.h"
#include "path-util.h"
#include "proc-cmdline.h"
#include "random-util.h"
#include "recurse-dir.h"
#include "sparse-endian.h"
#include "stat-util.h"
#include "string-table.h"
#include "string-util.h"
#include "tmpfile-util.h"
#include "tpm2-pcr.h"
#include "tpm2-util.h"
#include "user-util.h"
 
#define PUBLIC_KEY_MAX (UINT32_C(1024) * UINT32_C(1024))
 
bool credential_name_valid(const char *s) {
        /* We want that credential names are both valid in filenames (since that's our primary way to pass
         * them around) and as fdnames (which is how we might want to pass them around eventually) */
        return filename_is_valid(s) && fdname_is_valid(s);
}
 
bool credential_glob_valid(const char *s) {
        const char *e, *a;
        size_t n;
 
        /* Checks if a credential glob expression is valid. Note that this is more restrictive than
         * fnmatch()! We only allow trailing asterisk matches for now (simply because we want some freedom
         * with automatically extending the pattern in a systematic way to cover for unit instances getting
         * per-instance credentials or similar. Moreover, credential globbing expressions are also more
         * restrictive than credential names: we don't allow *, ?, [, ] in them (except for the asterisk
         * match at the end of the string), simply to not allow ambiguity. After all, we want the flexibility
         * to one day add full globbing should the need arise.  */
 
        if (isempty(s))
                return false;
 
        /* Find first glob (or NUL byte) */
        n = strcspn(s, "*?[]");
        e = s + n;
 
        /* For now, only allow asterisk wildcards, and only at the end of the string. If it's anything else, refuse. */
        if (isempty(e))
                return credential_name_valid(s);
 
        if (!streq(e, "*")) /* only allow trailing "*", no other globs */
                return false;
 
        if (n == 0) /* Explicitly allow the complete wildcard. */
                return true;
 
        if (n > NAME_MAX + strlen(e)) /* before we make a copy on the stack, let's check this is not overly large */
                return false;
 
        /* Make a copy of the string without the '*' suffix */
        a = strndupa_safe(s, n);
 
        return credential_name_valid(a);
}
 
static int get_credentials_dir_internal(const char *envvar, const char **ret) {
        const char *e;
 
        assert(ret);
 
        e = secure_getenv(envvar);
        if (!e)
                return -ENXIO;
 
        if (!path_is_absolute(e) || !path_is_normalized(e))
                return -EINVAL;
 
        *ret = e;
        return 0;
}
 
int get_credentials_dir(const char **ret) {
        return get_credentials_dir_internal("CREDENTIALS_DIRECTORY", ret);
}
 
int get_encrypted_credentials_dir(const char **ret) {
        return get_credentials_dir_internal("ENCRYPTED_CREDENTIALS_DIRECTORY", ret);
}
 
int open_credentials_dir(void) {
        const char *d;
        int r;
 
        r = get_credentials_dir(&d);
        if (r < 0)
                return r;
 
        return RET_NERRNO(open(d, O_CLOEXEC|O_DIRECTORY));
}
 
int get_system_credentials_dir(const char **ret) {
        int r;
 
        assert(ret);
 
        /* Note that for system credentials the environment variable we honour is just for debugging purpose
         * (unlike for the per-service credential path env var where it's key part of the protocol). */
        r = get_credentials_dir_internal("SYSTEMD_SYSTEM_CREDENTIALS_DIRECTORY", ret);
        if (r >= 0 || r != -ENXIO)
                return r;
 
        *ret = SYSTEM_CREDENTIALS_DIRECTORY;
        return 0;
}
 
int get_encrypted_system_credentials_dir(const char **ret) {
        int r;
 
        assert(ret);
 
        r = get_credentials_dir_internal("SYSTEMD_ENCRYPTED_SYSTEM_CREDENTIALS_DIRECTORY", ret);
        if (r >= 0 || r != -ENXIO)
                return r;
 
        *ret = ENCRYPTED_SYSTEM_CREDENTIALS_DIRECTORY;
        return 0;
}
 
int read_credential(const char *name, void **ret, size_t *ret_size) {
        _cleanup_free_ char *fn = NULL;
        const char *d;
        int r;
 
        assert(ret);
 
        if (!credential_name_valid(name))
                return -EINVAL;
 
        r = get_credentials_dir(&d);
        if (r < 0)
                return r;
 
        fn = path_join(d, name);
        if (!fn)
                return -ENOMEM;
 
        return read_full_file_full(
                        AT_FDCWD, fn,
                        UINT64_MAX, SIZE_MAX,
                        READ_FULL_FILE_SECURE,
                        NULL,
                        (char**) ret, ret_size);
}
 
int read_credential_with_decryption(const char *name, void **ret, size_t *ret_size) {
        _cleanup_(iovec_done_erase) struct iovec decrypted = {};
        _cleanup_(erase_and_freep) void *data = NULL;
        _cleanup_free_ char *fn = NULL;
        size_t sz = 0;
        const char *d;
        int r;
 
        /* Just like read_credential() but will also look for encrypted credentials. Note that services only
         * receive decrypted credentials, hence use read_credential() for those. This helper here is for
         * generators, i.e. code that runs outside of service context, and thus has no decrypted credentials
         * yet.
         *
         * Note that read_credential_harder_and_warn() logs on its own, while read_credential() does not!
         * (It's a lot more complex and error prone given its TPM2 connectivity, and is generally called from
         * generators only where logging is OK).
         *
         * Error handling is also a bit different: if we can't find a credential we'll return 0 and NULL
         * pointers/zero size, rather than -ENXIO/-ENOENT. */
 
        if (!credential_name_valid(name))
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid credential name: %s", name);
 
        r = read_credential(name, ret, ret_size);
        if (r >= 0)
                return 1; /* found */
        if (!IN_SET(r, -ENXIO, -ENOENT))
                return log_error_errno(r, "Failed to read unencrypted credential '%s': %m", name);
 
        r = get_encrypted_credentials_dir(&d);
        if (r == -ENXIO)
                goto not_found;
        if (r < 0)
                return log_error_errno(r, "Failed to determine encrypted credentials directory: %m");
 
        fn = path_join(d, name);
        if (!fn)
                return log_oom();
 
        /* Encrypted credentials are stored as Base64, unlike the plaintext credentials checked above. */
        r = read_full_file_full(
                        AT_FDCWD, fn,
                        UINT64_MAX, CREDENTIAL_ENCRYPTED_SIZE_MAX,
                        READ_FULL_FILE_SECURE|READ_FULL_FILE_UNBASE64|READ_FULL_FILE_FAIL_WHEN_LARGER,
                        NULL,
                        (char**) &data, &sz);
        if (r == -ENOENT)
                goto not_found;
        if (r == -E2BIG)
                return log_error_errno(r, "Encrypted credential '%s' exceeds the size limit.", name);
        if (r < 0)
                return log_error_errno(
                                r, "Failed to read or Base64-decode encrypted credential '%s': %m", name);
 
        if (geteuid() != 0)
                r = ipc_decrypt_credential(
                                name,
                                now(CLOCK_REALTIME),
                                getuid(),
                                &IOVEC_MAKE(data, sz),
                                CREDENTIAL_ANY_SCOPE,
                                &decrypted);
        else
                r = decrypt_credential_and_warn(
                                name,
                                now(CLOCK_REALTIME),
                                /* tpm2_device= */ NULL,
                                /* tpm2_signature_path= */ NULL,
                                getuid(),
                                &IOVEC_MAKE(data, sz),
                                CREDENTIAL_ANY_SCOPE,
                                &decrypted);
        if (r < 0)
                return r;
 
        /* Match read_credential(): without a size output, the caller expects a string. */
        if (!ret_size && decrypted.iov_len > 0 && memchr(decrypted.iov_base, 0, decrypted.iov_len))
                return log_error_errno(
                                SYNTHETIC_ERRNO(EBADMSG),
                                "Decrypted credential '%s' contains embedded NUL bytes, refusing.", name);
 
        if (ret)
                *ret = TAKE_PTR(decrypted.iov_base);
        if (ret_size)
                *ret_size = decrypted.iov_len;
 
        return 1; /* found */
 
not_found:
        if (ret)
                *ret = NULL;
        if (ret_size)
                *ret_size = 0;
 
        return 0; /* not found */
}
 
int read_credential_strings_many_internal(
                const char *first_name, char **first_value,
                ...) {
 
        _cleanup_free_ void *b = NULL;
        bool all = true;
        int r, ret = 0;
 
        assert(first_value);
 
        /* Reads a bunch of credentials into the specified buffers. If the specified buffers are already
         * non-NULL frees them if a credential is found. Only supports string-based credentials
         * (i.e. refuses embedded NUL bytes).
         *
         * 0 is returned when some or all credentials are missing.
         */
 
        if (!first_name)
                return 0;
 
        r = read_credential(first_name, &b, NULL);
        if (r == -ENXIO) /* No creds passed at all? Bail immediately. */
                return 0;
        if (r == -ENOENT)
                all = false;
        else if (r < 0)
                RET_GATHER(ret, r);
        else
                free_and_replace(*first_value, b);
 
        va_list ap;
        va_start(ap, first_value);
 
        for (;;) {
                _cleanup_free_ void *bb = NULL;
                const char *name;
                char **value;
 
                name = va_arg(ap, const char *);
                if (!name)
                        break;
 
                value = ASSERT_PTR(va_arg(ap, char **));
 
                r = read_credential(name, &bb, NULL);
                if (r == -ENOENT)
                        all = false;
                else if (r < 0)
                        RET_GATHER(ret, r);
                else
                        free_and_replace(*value, bb);
        }
 
        va_end(ap);
        return ret < 0 ? ret : all;
}
 
int read_credential_bool(const char *name) {
        _cleanup_free_ void *data = NULL;
        int r;
 
        r = read_credential(name, &data, NULL);
        if (r < 0)
                return IN_SET(r, -ENXIO, -ENOENT) ? 0 : r;
 
        return parse_boolean(data);
}
 
int get_credential_user_password(const char *username, char **ret_password, bool *ret_is_hashed) {
        _cleanup_(erase_and_freep) char *creds_password = NULL;
        _cleanup_free_ char *cn = NULL;
        int r;
 
        assert(ret_password);
        assert(ret_is_hashed);
 
        /* Try to pick up the password for this account via the credentials logic */
        cn = strjoin("passwd.hashed-password.", username);
        if (!cn)
                return -ENOMEM;
 
        r = read_credential(cn, (void**) &creds_password, NULL);
        if (r == -ENOENT) {
                free(cn);
                cn = strjoin("passwd.plaintext-password.", username);
                if (!cn)
                        return -ENOMEM;
 
                r = read_credential(cn, (void**) &creds_password, NULL);
                if (r < 0)
                        log_debug_errno(r, "Couldn't read credential '%s', ignoring: %m", cn);
                else
                        *ret_is_hashed = false;
        } else if (r < 0)
                log_debug_errno(r, "Couldn't read credential '%s', ignoring: %m", cn);
        else
                *ret_is_hashed = true;
 
        *ret_password = TAKE_PTR(creds_password);
 
        return r;
}
 
static const char* const credential_boot_policy_table[_CRED_BOOT_POLICY_MAX] = {
        [CRED_BOOT_STRICT]  = "strict",
        [CRED_BOOT_TOFU]    = "tofu",
        [CRED_BOOT_RELAXED] = "relaxed",
        [CRED_BOOT_OFF]     = "off",
};
 
DEFINE_STRING_TABLE_LOOKUP(credential_boot_policy, CredentialBootPolicy);
 
bool credential_boot_policy_accepts_null(CredentialBootPolicy policy, bool first_boot, bool have_tpm2, bool secure_boot) {
 
        /* Decides whether a null-key encrypted credential (which offers neither confidentiality nor
         * authenticity) may be accepted, given the configured policy and the current system state. */
 
        switch (policy) {
 
        case CRED_BOOT_STRICT:
                return false;
 
        case CRED_BOOT_TOFU:
                return first_boot || !have_tpm2;
 
        case CRED_BOOT_RELAXED:
                return !secure_boot || !have_tpm2;
 
        case CRED_BOOT_OFF:
                return true;
 
        default:
                assert_not_reached();
        }
}
 
#if HAVE_OPENSSL
 
#define CREDENTIAL_HOST_SECRET_SIZE 4096
 
static const sd_id128_t credential_app_id =
        SD_ID128_MAKE(d3,ac,ec,ba,0d,ad,4c,df,b8,c9,38,15,28,93,6c,58);
 
struct credential_host_secret_format {
        /* The hashed machine ID of the machine this belongs to. Why? We want to ensure that each machine
         * gets its own secret, even if people forget to flush out this secret file. Hence we bind it to the
         * machine ID, for which there's hopefully a better chance it will be flushed out. We use a hashed
         * machine ID instead of the literal one, because it's trivial to, and it might be a good idea not
         * being able to directly associate a secret key file with a host. */
        sd_id128_t machine_id;
 
        /* The actual secret key */
        uint8_t data[CREDENTIAL_HOST_SECRET_SIZE];
} _packed_;
 
static void warn_not_encrypted(int fd, CredentialSecretFlags flags, const char *dirname, const char *filename) {
        int r;
 
        assert(fd >= 0);
        assert(dirname);
        assert(filename);
 
        if (!FLAGS_SET(flags, CREDENTIAL_SECRET_WARN_NOT_ENCRYPTED))
                return;
 
        r = fd_is_encrypted(fd);
        if (r < 0)
                log_debug_errno(r, "Failed to determine if credential secret file '%s/%s' is encrypted.",
                                dirname, filename);
        else if (r == 0)
                log_warning("Credential secret file '%s/%s' is not located on encrypted media, using anyway.",
                            dirname, filename);
}
 
static int make_credential_host_secret(
                int dfd,
                const sd_id128_t machine_id,
                CredentialSecretFlags flags,
                const char *dirname,
                const char *fn,
                struct iovec *ret) {
 
        _cleanup_free_ char *t = NULL;
        _cleanup_close_ int fd = -EBADF;
        int r;
 
        assert(dfd >= 0);
        assert(fn);
 
        fd = open_tmpfile_linkable_at(dfd, fn, O_CLOEXEC|O_WRONLY, &t);
        if (fd < 0)
                return log_debug_errno(fd, "Failed to create temporary file for credential host secret: %m");
 
        CLEANUP_TMPFILE_AT(dfd, t);
 
        r = chattr_secret(fd, 0);
        if (r < 0)
                log_debug_errno(r, "Failed to set file attributes for secrets file, ignoring: %m");
 
        struct credential_host_secret_format buf = {
                .machine_id = machine_id,
        };
 
        CLEANUP_ERASE(buf);
 
        r = crypto_random_bytes(buf.data, sizeof(buf.data));
        if (r < 0)
                return r;
 
        r = loop_write(fd, &buf, sizeof(buf));
        if (r < 0)
                return r;
 
        if (fchmod(fd, 0400) < 0)
                return -errno;
 
        warn_not_encrypted(fd, flags, dirname, fn);
 
        r = link_tmpfile_at(fd, dfd, t, fn, LINK_TMPFILE_SYNC);
        if (r < 0)
                return log_debug_errno(r, "Failed to link host key into place: %m");
 
        t = mfree(t); /* disarm CLEANUP_TMPFILE_AT() */
 
        if (ret) {
                void *copy;
 
                copy = memdup(buf.data, sizeof(buf.data));
                if (!copy)
                        return -ENOMEM;
 
                *ret = IOVEC_MAKE(copy, sizeof(buf.data));
        }
 
        return 0;
}
 
int get_credential_host_secret(CredentialSecretFlags flags, struct iovec *ret) {
        _cleanup_free_ char *_dirname = NULL, *_filename = NULL;
        _cleanup_close_ int dfd = -EBADF;
        sd_id128_t machine_id;
        const char *dirname, *filename;
        int r;
 
        r = sd_id128_get_machine_app_specific(credential_app_id, &machine_id);
        if (r < 0)
                return r;
 
        const char *e = secure_getenv("SYSTEMD_CREDENTIAL_SECRET");
        if (e) {
                if (!path_is_normalized(e))
                        return -EINVAL;
                if (!path_is_absolute(e))
                        return -EINVAL;
 
                r = path_split_prefix_filename(e, &_dirname, &_filename);
                if (r < 0)
                        return r;
                if (r == O_DIRECTORY)
                        return -EINVAL;
 
                /* We validate that the path is absolute above, hence dirname must be extractable. */
                dirname = _dirname;
                filename = _filename;
        } else {
                dirname = "/var/lib/systemd";
                filename = "credential.secret";
        }
 
        assert(dirname);
        assert(filename);
 
        (void) mkdir_parents(dirname, 0755);
 
        dfd = open_mkdir(dirname, O_CLOEXEC, 0755);
        if (dfd < 0)
                return log_debug_errno(dfd, "Failed to create or open directory '%s': %m", dirname);
 
        if (FLAGS_SET(flags, CREDENTIAL_SECRET_FAIL_ON_TEMPORARY_FS)) {
                r = fd_is_temporary_fs(dfd);
                if (r < 0)
                        return log_debug_errno(r, "Failed to check directory '%s': %m", dirname);
                if (r > 0)
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOMEDIUM),
                                               "Directory '%s' is on a temporary file system, refusing.", dirname);
        }
 
        for (unsigned attempt = 0;; attempt++) {
                _cleanup_(erase_and_freep) struct credential_host_secret_format *f = NULL;
                _cleanup_close_ int fd = -EBADF;
                size_t l = 0;
                ssize_t n = 0;
                struct stat st;
 
                if (attempt >= 3) /* Somebody is playing games with us */
                        return log_debug_errno(SYNTHETIC_ERRNO(EIO),
                                               "All attempts to create secret store in %s failed.", dirname);
 
                fd = openat(dfd, filename, O_CLOEXEC|O_RDONLY|O_NOCTTY|O_NOFOLLOW);
                if (fd < 0) {
                        if (errno != ENOENT || !FLAGS_SET(flags, CREDENTIAL_SECRET_GENERATE))
                                return log_debug_errno(errno,
                                                       "Failed to open %s/%s: %m", dirname, filename);
 
                        r = make_credential_host_secret(dfd, machine_id, flags, dirname, filename, ret);
                        if (r == -EEXIST) {
                                log_debug_errno(r, "Credential secret %s/%s appeared while we were creating it, rereading.",
                                                dirname, filename);
                                continue;
                        }
                        if (r < 0)
                                return log_debug_errno(r, "Failed to create credential secret %s/%s: %m",
                                                       dirname, filename);
                        return 0;
                }
 
                if (fstat(fd, &st) < 0)
                        return log_debug_errno(errno, "Failed to stat %s/%s: %m", dirname, filename);
 
                r = stat_verify_regular(&st);
                if (r < 0)
                        return log_debug_errno(r, "%s/%s is not a regular file: %m", dirname, filename);
                if (st.st_nlink == 0) /* Deleted by now, try again */
                        continue;
                if (st.st_nlink > 1)
                        /* Our deletion check won't work if hardlinked somewhere else */
                        return log_debug_errno(SYNTHETIC_ERRNO(EPERM),
                                               "%s/%s has too many links, refusing.",
                                               dirname, filename);
                if ((st.st_mode & 07777) != 0400)
                        /* Don't use file if not 0400 access mode */
                        return log_debug_errno(SYNTHETIC_ERRNO(EPERM),
                                               "%s/%s has permissive access mode, refusing.",
                                               dirname, filename);
                l = st.st_size;
                if (l < offsetof(struct credential_host_secret_format, data) + 1)
                        return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "%s/%s is too small, refusing.", dirname, filename);
                if (l > 16*1024*1024)
                        return log_debug_errno(SYNTHETIC_ERRNO(E2BIG),
                                               "%s/%s is too big, refusing.", dirname, filename);
 
                f = malloc(l+1);
                if (!f)
                        return log_oom_debug();
 
                n = read(fd, f, l+1);
                if (n < 0)
                        return log_debug_errno(errno,
                                               "Failed to read %s/%s: %m", dirname, filename);
                if ((size_t) n != l) /* What? The size changed? */
                        return log_debug_errno(SYNTHETIC_ERRNO(EIO),
                                               "Failed to read %s/%s.", dirname, filename);
 
                if (sd_id128_equal(machine_id, f->machine_id)) {
                        size_t sz;
 
                        warn_not_encrypted(fd, flags, dirname, filename);
 
                        sz = l - offsetof(struct credential_host_secret_format, data);
                        assert(sz > 0);
 
                        if (ret) {
                                void *copy;
 
                                assert(sz <= sizeof(f->data)); /* Ensure we don't read past f->data bounds */
 
                                copy = memdup(f->data, sz);
                                if (!copy)
                                        return log_oom_debug();
 
                                *ret = IOVEC_MAKE(copy, sz);
                        }
 
                        return 0;
                }
 
                /* Hmm, this secret is from somewhere else. Let's delete the file. Let's first acquire a lock
                 * to ensure we are the only ones accessing the file while we delete it. */
 
                log_notice("'%s/%s' comes from a different machine ID, deleting.", dirname, filename);
 
                if (flock(fd, LOCK_EX) < 0)
                        return log_debug_errno(errno,
                                               "Failed to flock %s/%s: %m", dirname, filename);
 
                /* Before we delete it check that the file is still linked into the file system */
                if (fstat(fd, &st) < 0)
                        return log_debug_errno(errno, "Failed to stat %s/%s: %m", dirname, filename);
                if (st.st_nlink == 0) /* Already deleted by now? */
                        continue;
                if (st.st_nlink != 1) /* Safety check, someone is playing games with us */
                        return log_debug_errno(SYNTHETIC_ERRNO(EPERM),
                                               "%s/%s unexpectedly has too many links.",
                                               dirname, filename);
                if (unlinkat(dfd, filename, 0) < 0)
                        return log_debug_errno(errno, "Failed to unlink %s/%s: %m", dirname, filename);
 
                /* And now try again */
        }
}
 
/* Construction is like this:
 *
 * A symmetric encryption key is derived from:
 *
 *      1. Either the "host" key (a key stored in /var/lib/credential.secret)
 *
 *      2. A key generated by letting the TPM2 calculate an HMAC hash of some nonce we pass to it, keyed
 *         by a key derived from its internal seed key.
 *
 *      3. The concatenation of the above.
 *
 *      4. Or a fixed "empty" key. This will not provide confidentiality or authenticity, of course, but is
 *         useful to encode credentials for the initrd on TPM-less systems, where we simply have no better
 *         concept to bind things to. Note that decryption of a key set up like this will be refused on
 *         systems that have a TPM and have SecureBoot enabled.
 *
 * The above is hashed with SHA256 which is then used as encryption key for AES256-GCM. The encrypted
 * credential is a short (unencrypted) header describing which of the three keys to use, the IV to use for
 * AES256-GCM and some more meta information (sizes of certain objects) that is strictly speaking redundant,
 * but kinda nice to have since we can have a more generic parser. If the TPM2 key is used this is followed
 * by another (unencrypted) header, with information about the TPM2 policy used (specifically: the PCR mask
 * to bind against, and a hash of the resulting policy — the latter being redundant, but speeding up things a
 * bit, since we can more quickly refuse PCR state), followed by a sealed/exported TPM2 HMAC key. This is
 * then followed by the encrypted data, which begins with a metadata header (which contains validity
 * timestamps as well as the credential name), followed by the actual credential payload. The file ends in
 * the AES256-GCM tag. To make things simple, the AES256-GCM AAD covers the main and the TPM2 header in
 * full. This means the whole file is either protected by AAD, or is ciphertext, or is the tag. No
 * unprotected data is included.
 */
 
struct _packed_ encrypted_credential_header {
        sd_id128_t id;
        le32_t key_size;
        le32_t block_size;
        le32_t iv_size;
        le32_t tag_size;
        uint8_t iv[];
        /* Followed by NUL bytes until next 8 byte boundary */
};
 
struct _packed_ tpm2_credential_header {
        le64_t pcr_mask;    /* Note that the spec for PC Clients only mandates 24 PCRs, and that's what systems
                             * generally have. But keep the door open for more. */
        le16_t pcr_bank;    /* For now, either TPM2_ALG_SHA256 or TPM2_ALG_SHA1 */
        le16_t primary_alg; /* Primary key algorithm (either TPM2_ALG_RSA or TPM2_ALG_ECC for now) */
        le32_t blob_size;
        le32_t policy_hash_size;
        uint8_t policy_hash_and_blob[];
        /* Followed by NUL bytes until next 8 byte boundary */
};
 
struct _packed_ tpm2_public_key_credential_header {
        le64_t pcr_mask;      /* PCRs used for the public key PCR policy (usually just PCR 11, i.e. the unified kernel) */
        le32_t size;          /* Size of DER public key */
        uint8_t data[];       /* DER public key */
        /* Followed by NUL bytes until next 8 byte boundary */
};
 
struct _packed_ tpm2_pinned_srk_credential_header {
        le32_t size;          /* Size of pinned SRK */
        uint8_t data[];       /* Pinned SRK */
        /* Followed by NUL bytes until next 8 byte boundary */
};
 
struct _packed_ scoped_credential_header {
        le64_t flags;         /* SCOPE_HASH_DATA_BASE_FLAGS for now */
};
 
/* This header is encrypted */
struct _packed_ metadata_credential_header {
        le64_t timestamp;
        le64_t not_after;
        le32_t name_size;
        char name[];
        /* Followed by NUL bytes until next 8 byte boundary */
};
 
struct _packed_ scoped_hash_data {
        le64_t flags;         /* copy of the scoped_credential_header.flags */
        le32_t uid;
        sd_id128_t machine_id;
        char username[];      /* followed by the username */
        /* Later on we might want to extend this: with a cgroup path to allow per-app secrets, and with the user's $HOME encryption key */
};
 
enum {
        /* Flags for scoped_hash_data.flags and scoped_credential_header.flags */
        SCOPE_HASH_DATA_HAS_UID      = 1 << 0,
        SCOPE_HASH_DATA_HAS_MACHINE  = 1 << 1,
        SCOPE_HASH_DATA_HAS_USERNAME = 1 << 2,
 
        SCOPE_HASH_DATA_BASE_FLAGS = SCOPE_HASH_DATA_HAS_UID | SCOPE_HASH_DATA_HAS_USERNAME | SCOPE_HASH_DATA_HAS_MACHINE,
};
 
/* Some generic limit for parts of the encrypted credential for which we don't know the right size ahead of
 * time, but where we are really sure it won't be larger than this. Should be larger than any possible IV,
 * padding, tag size and so on. This is purely used for early filtering out of invalid sizes. */
#define CREDENTIAL_FIELD_SIZE_MAX (16U*1024U)
 
static int sha256_hash_host_and_tpm2_key(
                const struct iovec *host_key,
                const struct iovec *tpm2_key,
                uint8_t ret[static SHA256_DIGEST_LENGTH]) {
 
        _cleanup_(EVP_MD_CTX_freep) EVP_MD_CTX *md = NULL;
        unsigned l;
        int r;
 
        assert(iovec_is_valid(host_key));
        assert(iovec_is_valid(tpm2_key));
        assert(ret);
 
        /* Combines the host key and the TPM2 HMAC hash into a SHA256 hash value we'll use as symmetric encryption key. */
 
        r = dlopen_libcrypto(LOG_DEBUG);
        if (r < 0)
                return r;
 
        md = sym_EVP_MD_CTX_new();
        if (!md)
                return log_oom();
 
        if (sym_EVP_DigestInit_ex(md, sym_EVP_sha256(), NULL) != 1)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to initial SHA256 context.");
 
        if (iovec_is_set(host_key) && sym_EVP_DigestUpdate(md, host_key->iov_base, host_key->iov_len) != 1)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to hash host key.");
 
        if (iovec_is_set(tpm2_key) && sym_EVP_DigestUpdate(md, tpm2_key->iov_base, tpm2_key->iov_len) != 1)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to hash TPM2 key.");
 
        assert(sym_EVP_MD_CTX_get_size(md) == SHA256_DIGEST_LENGTH);
 
        if (sym_EVP_DigestFinal_ex(md, ret, &l) != 1)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to finalize SHA256 hash.");
 
        assert(l == SHA256_DIGEST_LENGTH);
        return 0;
}
 
static int mangle_uid_into_key(
                uid_t uid,
                uint8_t md[static SHA256_DIGEST_LENGTH]) {
 
        _cleanup_free_ struct passwd *pw = NULL;
        sd_id128_t mid;
        int r;
 
        assert(uid_is_valid(uid));
        assert(md);
 
        /* If we shall encrypt for a specific user, we HMAC() a structure with the user's credentials
         * (specifically, UID, user name, machine ID) with the key we'd otherwise use for system credentials,
         * and use the resulting hash as actual encryption key. */
 
        r = getpwuid_malloc(uid, &pw);
        if (r < 0)
                return log_error_errno(r, "Failed to resolve UID "UID_FMT": %m", uid);
 
        r = sd_id128_get_machine(&mid);
        if (r < 0)
                return log_error_errno(r, "Failed to read machine ID: %m");
 
        size_t sz = offsetof(struct scoped_hash_data, username) + strlen(pw->pw_name) + 1;
        _cleanup_free_ struct scoped_hash_data *d = malloc0(sz);
        if (!d)
                return log_oom();
 
        d->flags = htole64(SCOPE_HASH_DATA_BASE_FLAGS);
        d->uid = htole32(uid);
        d->machine_id = mid;
 
        strcpy(d->username, pw->pw_name);
 
        _cleanup_(erase_and_freep) void *buf = NULL;
        size_t buf_size = 0;
        r = openssl_hmac_many(
                        "sha256",
                        md, SHA256_DIGEST_LENGTH,
                        &IOVEC_MAKE(d, sz), 1,
                        &buf, &buf_size);
        if (r < 0)
                return r;
 
        assert(buf_size == SHA256_DIGEST_LENGTH);
        memcpy(md, buf, buf_size);
 
        return 0;
}
 
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) {
 
        _cleanup_(iovec_done) struct iovec tpm2_blob = {}, tpm2_srk = {}, tpm2_policy_hash = {}, iv = {}, pubkey = {};
        _cleanup_(iovec_done_erase) struct iovec tpm2_key = {}, output = {}, host_key = {};
        _cleanup_(EVP_CIPHER_CTX_freep) EVP_CIPHER_CTX *context = NULL;
        _cleanup_free_ struct metadata_credential_header *m = NULL;
#if HAVE_TPM2
        uint16_t tpm2_pcr_bank = 0, tpm2_primary_alg = 0;
#endif
        struct encrypted_credential_header *h;
        int ksz, bsz, ivsz, tsz, added, r;
        uint8_t md[SHA256_DIGEST_LENGTH];
        const EVP_CIPHER *cc;
        sd_id128_t id;
        size_t p, ml;
 
        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);
 
        if (!CRED_KEY_IS_VALID(with_key) && !CRED_KEY_IS_AUTO(with_key))
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid key type: " SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(with_key));
 
        if (name && !credential_name_valid(name))
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid credential name: %s", name);
 
        if (not_after != USEC_INFINITY && timestamp != USEC_INFINITY && not_after <= timestamp)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Credential is invalidated before or when it becomes valid (" USEC_FMT " <= " USEC_FMT ").", not_after, timestamp);
 
        if (DEBUG_LOGGING) {
                char buf[FORMAT_TIMESTAMP_MAX];
 
                if (name)
                        log_debug("Including credential name '%s' in encrypted credential.", name);
                if (timestamp != USEC_INFINITY)
                        log_debug("Including timestamp '%s' in encrypted credential.", format_timestamp(buf, sizeof(buf), timestamp));
                if (not_after != USEC_INFINITY)
                        log_debug("Including not-after timestamp '%s' in encrypted credential.", format_timestamp(buf, sizeof(buf), not_after));
        }
 
        if (CRED_KEY_IS_SCOPED(with_key)) {
                if (!uid_is_valid(uid))
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                               "Scoped credential key type "SD_ID128_FORMAT_STR" selected, but no UID specified.", SD_ID128_FORMAT_VAL(with_key));
        } else
                uid = UID_INVALID;
 
        if (CRED_KEY_WANTS_HOST(with_key) || CRED_KEY_REQUIRES_HOST(with_key)) {
 
                r = get_credential_host_secret(
                                CREDENTIAL_SECRET_GENERATE|
                                CREDENTIAL_SECRET_WARN_NOT_ENCRYPTED|
                                (CRED_KEY_WANTS_HOST(with_key) ? CREDENTIAL_SECRET_FAIL_ON_TEMPORARY_FS : 0),
                                &host_key);
                if (r == -ENOMEDIUM && CRED_KEY_WANTS_HOST(with_key))
                        log_debug_errno(r, "Credential host secret location on temporary file system, not using.");
                else if (r < 0)
                        return log_error_errno(r, "Failed to determine local credential host secret: %m");
        }
 
        if (tpm2_hash_pcr_mask == UINT32_MAX)
                tpm2_hash_pcr_mask = 0;
        if (tpm2_pubkey_pcr_mask == UINT32_MAX)
                tpm2_pubkey_pcr_mask = UINT32_C(1) << TPM2_PCR_KERNEL_BOOT;
 
#if HAVE_TPM2
        bool try_tpm2;
        if (CRED_KEY_WANTS_TPM2(with_key)) {
                /* If automatic mode is selected lets see if a TPM2 it is present. If we are running in a
                 * container tpm2_support will detect this, and will return a different flag combination of
                 * TPM2_SUPPORT_FULL, effectively skipping the use of TPM2 when inside one. */
 
                try_tpm2 = tpm2_is_mostly_supported();
                if (!try_tpm2)
                        log_debug("System lacks TPM2 support or running in a container, not attempting to use TPM2.");
        } else
                try_tpm2 = CRED_KEY_REQUIRES_TPM2(with_key);
 
        if (try_tpm2) {
                /* If the firmware does not support TPMs, then UKI measurements are not going to work, hence
                 * PCR 11 public key stuff cannot work. Because of that, if PK is only wanted (but not
                 * required) we won't try it. */
                if ((CRED_KEY_WANTS_TPM2_PK(with_key) && tpm2_is_fully_supported()) || CRED_KEY_REQUIRES_TPM2_PK(with_key)) {
 
                        /* Load public key for PCR policies, if one is specified, or explicitly requested */
 
                        r = tpm2_load_pcr_public_key(tpm2_pubkey_path, &pubkey.iov_base, &pubkey.iov_len);
                        if (r < 0) {
                                if (r != -ENOENT || tpm2_pubkey_path || CRED_KEY_REQUIRES_TPM2_PK(with_key))
                                        return log_error_errno(r, "Failed to read TPM PCR public key: %m");
 
                                log_debug_errno(r, "Failed to read TPM2 PCR public key, proceeding without: %m");
                        }
                }
 
                if (!iovec_is_set(&pubkey))
                        tpm2_pubkey_pcr_mask = 0;
 
                _cleanup_(tpm2_context_unrefp) Tpm2Context *tpm2_context = NULL;
                r = tpm2_context_new_or_warn(tpm2_device, &tpm2_context);
                if (r < 0)
                        return r;
 
                r = tpm2_get_best_pcr_bank(tpm2_context, tpm2_hash_pcr_mask | tpm2_pubkey_pcr_mask, &tpm2_pcr_bank);
                if (r < 0)
                        return log_error_errno(r, "Could not find best pcr bank: %m");
 
                log_debug("Selected literal PCR mask: 0x%x, PK PCR mask: 0x%x", tpm2_hash_pcr_mask, tpm2_pubkey_pcr_mask);
 
                TPML_PCR_SELECTION tpm2_hash_pcr_selection;
                tpm2_tpml_pcr_selection_from_mask(tpm2_hash_pcr_mask, tpm2_pcr_bank, &tpm2_hash_pcr_selection);
 
                _cleanup_free_ Tpm2PCRValue *tpm2_hash_pcr_values = NULL;
                size_t tpm2_n_hash_pcr_values;