HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/home/homework-luks.c

162,356 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: d4ce674c3601e23183894548a8204dc282786674

Lines 1–1000 of 4,048

/* SPDX-License-Identifier: LGPL-2.1-or-later */
 
#include <linux/loop.h>
#include <linux/magic.h>
#include <poll.h>
#include <sys/file.h>
#include <sys/ioctl.h>
#include <sys/xattr.h>
#include <unistd.h>
#if HAVE_VALGRIND_MEMCHECK_H
#include <valgrind/memcheck.h>
#endif
 
#include "sd-daemon.h"
#include "sd-device.h"
#include "sd-event.h"
#include "sd-gpt.h"
#include "sd-id128.h"
 
#include "blkid-util.h"
#include "blockdev-util.h"
#include "btrfs-util.h"
#include "chattr-util.h"
#include "crypto-util.h"
#include "cryptsetup-util.h"
#include "device-util.h"
#include "devnum-util.h"
#include "dissect-image.h"
#include "env-util.h"
#include "errno-util.h"
#include "fd-util.h"
#include "fdisk-util.h"
#include "fileio.h"
#include "filesystems.h"
#include "format-util.h"
#include "fs-util.h"
#include "fsck-util.h"
#include "glyph-util.h"
#include "home-util.h"
#include "homework.h"
#include "homework-blob.h"
#include "homework-luks.h"
#include "homework-mount.h"
#include "homework-password-cache.h"
#include "io-util.h"
#include "json-util.h"
#include "keyring-util.h"
#include "loop-util.h"
#include "memory-util.h"
#include "mkdir.h"
#include "mkfs-util.h"
#include "parse-util.h"
#include "path-util.h"
#include "pidref.h"
#include "process-util.h"
#include "random-util.h"
#include "reread-partition-table.h"
#include "resize-fs.h"
#include "string-util.h"
#include "strv.h"
#include "sync-util.h"
#include "time-util.h"
#include "tmpfile-util.h"
#include "udev-util.h"
#include "user-record-util.h"
#include "user-record.h"
#include "user-util.h"
 
/* Round down to the nearest 1 MiB size. Given that most tools generally align partitions to 1 MiB boundaries, let's align our
 * partitions to that too. In the worst case we'll waste 1 MiB per partition that way, but I think I can live
 * with that. */
#define DISK_SIZE_ROUND_DOWN(x) ((x) & ~(U64_MB - 1))
 
/* Rounds up to the nearest 1 MiB boundary. Returns UINT64_MAX on overflow */
#define DISK_SIZE_ROUND_UP(x)                                           \
        ({                                                              \
                uint64_t _x = (x);                                      \
                _x > UINT64_MAX - (U64_MB - 1) ? UINT64_MAX : (DISK_SIZE_ROUND_DOWN(_x + U64_MB - 1)); \
        })
 
/* How much larger will the image on disk be than the fs inside it, i.e. the space we pay for the GPT and
 * LUKS2 envelope. (As measured on cryptsetup 2.4.1) */
#define GPT_LUKS2_OVERHEAD UINT64_C(18874368)
 
static int resize_image_loop(UserRecord *h, HomeSetup *setup, uint64_t old_image_size, uint64_t new_image_size, uint64_t *ret_image_size);
 
int run_mark_dirty(int fd, bool b) {
        char x = '1';
        int r, ret;
 
        /* Sets or removes the 'user.home-dirty' xattr on the specified file. We use this to detect when a
         * home directory was not properly unmounted. */
 
        assert(fd >= 0);
 
        r = fd_verify_regular(fd);
        if (r < 0)
                return r;
 
        if (b) {
                ret = fsetxattr(fd, "user.home-dirty", &x, 1, XATTR_CREATE);
                if (ret < 0 && errno != EEXIST)
                        return log_debug_errno(errno, "Could not mark home directory as dirty: %m");
 
        } else {
                r = fsync_full(fd);
                if (r < 0)
                        return log_debug_errno(r, "Failed to synchronize image before marking it clean: %m");
 
                ret = fremovexattr(fd, "user.home-dirty");
                if (ret < 0 && !ERRNO_IS_XATTR_ABSENT(errno))
                        return log_debug_errno(errno, "Could not mark home directory as clean: %m");
        }
 
        r = fsync_full(fd);
        if (r < 0)
                return log_debug_errno(r, "Failed to synchronize dirty flag to disk: %m");
 
        return ret >= 0;
}
 
int run_mark_dirty_by_path(const char *path, bool b) {
        _cleanup_close_ int fd = -EBADF;
 
        assert(path);
 
        fd = open(path, O_RDWR|O_CLOEXEC|O_NOCTTY);
        if (fd < 0)
                return log_debug_errno(errno, "Failed to open %s to mark dirty or clean: %m", path);
 
        return run_mark_dirty(fd, b);
}
 
static int probe_file_system_by_fd(
                int fd,
                char **ret_fstype,
                sd_id128_t *ret_uuid) {
 
#if HAVE_BLKID
        _cleanup_(blkid_free_probep) blkid_probe b = NULL;
        const char *fstype = NULL;
        sd_id128_t id;
        int r;
 
        assert(fd >= 0);
        assert(ret_fstype);
        assert(ret_uuid);
 
        r = dlopen_libblkid(LOG_DEBUG);
        if (r < 0)
                return r;
 
        b = sym_blkid_new_probe();
        if (!b)
                return -ENOMEM;
 
        errno = 0;
        r = sym_blkid_probe_set_device(b, fd, 0, 0);
        if (r != 0)
                return errno_or_else(ENOMEM);
 
        (void) sym_blkid_probe_enable_superblocks(b, 1);
        (void) sym_blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE|BLKID_SUBLKS_UUID);
 
        errno = 0;
        r = sym_blkid_do_safeprobe(b);
        if (r == _BLKID_SAFEPROBE_ERROR)
                return errno_or_else(EIO);
        if (IN_SET(r, _BLKID_SAFEPROBE_AMBIGUOUS, _BLKID_SAFEPROBE_NOT_FOUND))
                return -ENOPKG;
 
        assert(r == _BLKID_SAFEPROBE_FOUND);
 
        (void) sym_blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
        if (!fstype)
                return -ENOPKG;
 
        r = blkid_probe_lookup_value_id128(b, "UUID", &id);
        if (r == -ENXIO)
                return -ENOPKG;
        if (r < 0)
                return r;
 
        r = strdup_to(ret_fstype, fstype);
        if (r < 0)
                return r;
        *ret_uuid = id;
        return 0;
#else
        return -EOPNOTSUPP;
#endif
}
 
static int probe_file_system_by_path(const char *path, char **ret_fstype, sd_id128_t *ret_uuid) {
        _cleanup_close_ int fd = -EBADF;
 
        fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NONBLOCK);
        if (fd < 0)
                return negative_errno();
 
        return probe_file_system_by_fd(fd, ret_fstype, ret_uuid);
}
 
static int block_get_size_by_fd(int fd, uint64_t *ret) {
        int r;
 
        assert(fd >= 0);
        assert(ret);
 
        r = fd_verify_block(fd);
        if (r < 0)
                return r;
 
        return blockdev_get_device_size(fd, ret);
}
 
static int block_get_size_by_path(const char *path, uint64_t *ret) {
        _cleanup_close_ int fd = -EBADF;
 
        fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NONBLOCK);
        if (fd < 0)
                return -errno;
 
        return block_get_size_by_fd(fd, ret);
}
 
static int run_fsck(const char *node, const char *fstype) {
        int r, exit_status;
 
        assert(node);
        assert(fstype);
 
        r = fsck_exists_for_fstype(fstype);
        if (r < 0)
                return log_error_errno(r, "Failed to check if fsck for file system %s exists: %m", fstype);
        if (r == 0) {
                log_warning("No fsck for file system %s installed, ignoring.", fstype);
                return 0;
        }
 
        _cleanup_(pidref_done) PidRef fsck_pidref = PIDREF_NULL;
        r = pidref_safe_fork(
                        "(fsck)",
                        FORK_RESET_SIGNALS|FORK_RLIMIT_NOFILE_SAFE|FORK_DEATHSIG_SIGTERM|FORK_LOG|FORK_STDOUT_TO_STDERR|FORK_CLOSE_ALL_FDS,
                        &fsck_pidref);
        if (r < 0)
                return r;
        if (r == 0) {
                /* Child */
                execlp("fsck", "fsck", "-aTl", node, NULL);
                log_open();
                log_error_errno(errno, "Failed to execute fsck: %m");
                _exit(FSCK_OPERATIONAL_ERROR);
        }
 
        exit_status = pidref_wait_for_terminate_and_check("fsck", &fsck_pidref, WAIT_LOG_ABNORMAL);
        if (exit_status < 0)
                return exit_status;
        if ((exit_status & ~FSCK_ERROR_CORRECTED) != 0) {
                log_warning("fsck failed with exit status %i.", exit_status);
 
                if ((exit_status & (FSCK_SYSTEM_SHOULD_REBOOT|FSCK_ERRORS_LEFT_UNCORRECTED)) != 0)
                        return log_error_errno(SYNTHETIC_ERRNO(EIO), "File system is corrupted, refusing.");
 
                log_warning("Ignoring fsck error.");
        }
 
        log_info("File system check completed.");
 
        return 1;
}
 
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(key_serial_t, keyring_unlink, -1);
 
static int upload_to_keyring(UserRecord *h, const void *vk, size_t vks, key_serial_t *ret) {
 
        _cleanup_free_ char *name = NULL;
        key_serial_t serial;
 
        assert(h);
        assert(vk);
        assert(vks > 0);
 
        /* We upload the LUKS volume key into the kernel session keyring, under the assumption that
         * systemd-homed gets its own private session keyring (i.e. the default service behavior, given
         * that KeyringMode=private is the default). That way, the key will survive between invocations
         * of systemd-homework. */
 
        name = strjoin("homework-user-", h->user_name);
        if (!name)
                return -ENOMEM;
 
        serial = add_key("user", name, vk, vks, KEY_SPEC_SESSION_KEYRING);
        if (serial == -1)
                return -errno;
 
        if (ret)
                *ret = serial;
        return 1;
}
 
static int luks_try_passwords(
                UserRecord *h,
                struct crypt_device *cd,
                char **passwords,
                void *volume_key,
                size_t *volume_key_size) {
 
        int r;
 
        assert(h);
        assert(cd);
        assert(volume_key);
        assert(volume_key_size);
 
        STRV_FOREACH(pp, passwords) {
                size_t vks = *volume_key_size;
 
                r = sym_crypt_volume_key_get(
                                cd,
                                CRYPT_ANY_SLOT,
                                volume_key,
                                &vks,
                                *pp,
                                strlen(*pp));
                if (r >= 0) {
                        *volume_key_size = vks;
                        return 0;
                }
 
                log_debug_errno(r, "Password %zu didn't work for unlocking LUKS superblock: %m", (size_t) (pp - passwords));
        }
 
        return -ENOKEY;
}
 
static int luks_get_volume_key(
                UserRecord *h,
                struct crypt_device *cd,
                const PasswordCache *cache,
                void *volume_key,
                size_t *volume_key_size,
                key_serial_t *ret_key_serial) {
 
        char **list;
        size_t vks;
        int r;
 
        assert(h);
        assert(cd);
        assert(volume_key);
        assert(volume_key_size);
 
        if (cache && cache->volume_key) {
                /* Shortcut: If volume key was loaded from the keyring then just use it */
                if (cache->volume_key_size > *volume_key_size)
                        return log_error_errno(SYNTHETIC_ERRNO(ENOBUFS),
                                               "LUKS volume key from kernel keyring too big for buffer (need %zu bytes, have %zu).",
                                               cache->volume_key_size, *volume_key_size);
                memcpy(volume_key, cache->volume_key, cache->volume_key_size);
                *volume_key_size = cache->volume_key_size;
                if (ret_key_serial)
                        *ret_key_serial = -1; /* Key came from keyring. No need to re-upload it */
                return 0;
        }
 
        vks = *volume_key_size;
 
        FOREACH_ARGUMENT(list,
                         cache ? cache->pkcs11_passwords : NULL,
                         cache ? cache->fido2_passwords : NULL,
                         h->password) {
 
                r = luks_try_passwords(h, cd, list, volume_key, &vks);
                if (r == -ENOKEY)
                        continue;
                if (r < 0)
                        return r;
 
                /* We got a volume key! */
 
                if (ret_key_serial) {
                        r = upload_to_keyring(h, volume_key, vks, ret_key_serial);
                        if (r < 0) {
                                log_warning_errno(r, "Failed to upload LUKS volume key to kernel keyring, ignoring: %m");
                                *ret_key_serial = -1;
                        }
                }
 
                *volume_key_size = vks;
                return 0;
        }
 
        return -ENOKEY;
}
 
static int luks_setup(
                UserRecord *h,
                const char *node,
                const char *dm_name,
                sd_id128_t uuid,
                const char *cipher,
                const char *cipher_mode,
                uint64_t volume_key_size,
                const PasswordCache *cache,
                bool discard,
                struct crypt_device **ret,
                sd_id128_t *ret_found_uuid,
                void **ret_volume_key,
                size_t *ret_volume_key_size,
                key_serial_t *ret_key_serial) {
 
        _cleanup_(keyring_unlinkp) key_serial_t key_serial = -1;
        _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
        _cleanup_(erase_and_freep) void *vk = NULL;
        sd_id128_t p;
        size_t vks;
        int r;
 
        assert(h);
        assert(node);
        assert(dm_name);
        assert(ret);
 
        r = sym_crypt_init(&cd, node);
        if (r < 0)
                return log_error_errno(r, "Failed to allocate libcryptsetup context: %m");
 
        cryptsetup_enable_logging(cd);
 
        r = sym_crypt_load(cd, CRYPT_LUKS2, NULL);
        if (r < 0)
                return log_error_errno(r, "Failed to load LUKS superblock: %m");
 
        r = sym_crypt_get_volume_key_size(cd);
        if (r <= 0)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to determine LUKS volume key size.");
        vks = (size_t) r;
 
        if (!sd_id128_is_null(uuid) || ret_found_uuid) {
                const char *s;
 
                s = sym_crypt_get_uuid(cd);
                if (!s)
                        return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE), "LUKS superblock has no UUID.");
 
                r = sd_id128_from_string(s, &p);
                if (r < 0)
                        return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE), "LUKS superblock has invalid UUID.");
 
                /* Check that the UUID matches, if specified */
                if (!sd_id128_is_null(uuid) &&
                    !sd_id128_equal(uuid, p))
                        return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE), "LUKS superblock has wrong UUID.");
        }
 
        if (cipher && !streq_ptr(cipher, sym_crypt_get_cipher(cd)))
                return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE), "LUKS superblock declares wrong cipher.");
 
        if (cipher_mode && !streq_ptr(cipher_mode, sym_crypt_get_cipher_mode(cd)))
                return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE), "LUKS superblock declares wrong cipher mode.");
 
        if (volume_key_size != UINT64_MAX && vks != volume_key_size)
                return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE), "LUKS superblock declares wrong volume key size.");
 
        vk = malloc(vks);
        if (!vk)
                return log_oom();
 
        r = luks_get_volume_key(h, cd, cache, vk, &vks, ret_key_serial ? &key_serial : NULL);
        if (r == -ENOKEY)
                return log_error_errno(r, "No valid password for LUKS superblock.");
        if (r < 0)
                return log_error_errno(r, "Failed to unlock LUKS superblock: %m");
 
        r = sym_crypt_activate_by_volume_key(
                        cd,
                        dm_name,
                        vk, vks,
                        discard ? CRYPT_ACTIVATE_ALLOW_DISCARDS : 0);
        if (r < 0)
                return log_error_errno(r, "Failed to unlock LUKS superblock: %m");
 
        log_info("Setting up LUKS device /dev/mapper/%s completed.", dm_name);
 
        *ret = TAKE_PTR(cd);
 
        if (ret_found_uuid) /* Return the UUID actually found if the caller wants to know */
                *ret_found_uuid = p;
        if (ret_volume_key)
                *ret_volume_key = TAKE_PTR(vk);
        if (ret_volume_key_size)
                *ret_volume_key_size = vks;
        if (ret_key_serial)
                *ret_key_serial = TAKE_KEY_SERIAL(key_serial);
 
        return 0;
}
 
static int make_dm_names(UserRecord *h, HomeSetup *setup) {
        assert(h);
        assert(h->user_name);
        assert(setup);
 
        if (!setup->dm_name) {
                setup->dm_name = strjoin("home-", h->user_name);
                if (!setup->dm_name)
                        return log_oom();
        }
 
        if (!setup->dm_node) {
                setup->dm_node = path_join("/dev/mapper/", setup->dm_name);
                if (!setup->dm_node)
                        return log_oom();
        }
 
        return 0;
}
 
static int acquire_open_luks_device(
                UserRecord *h,
                HomeSetup *setup,
                bool graceful) {
 
        _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
        int r;
 
        assert(h);
        assert(setup);
        assert(!setup->crypt_device);
 
        r = dlopen_cryptsetup(LOG_DEBUG);
        if (r < 0)
                return r;
 
        r = make_dm_names(h, setup);
        if (r < 0)
                return r;
 
        r = sym_crypt_init_by_name(&cd, setup->dm_name);
        if ((ERRNO_IS_NEG_DEVICE_ABSENT(r) || r == -EINVAL) && graceful)
                return 0;
        if (r < 0)
                return log_error_errno(r, "Failed to initialize cryptsetup context for %s: %m", setup->dm_name);
 
        cryptsetup_enable_logging(cd);
 
        setup->crypt_device = TAKE_PTR(cd);
        return 1;
}
 
static int luks_open(
                UserRecord *h,
                HomeSetup *setup,
                const PasswordCache *cache,
                sd_id128_t *ret_found_uuid,
                void **ret_volume_key,
                size_t *ret_volume_key_size) {
 
        _cleanup_(erase_and_freep) void *vk = NULL;
        sd_id128_t p;
        size_t vks;
        int r;
 
        assert(h);
        assert(setup);
        assert(!setup->crypt_device);
 
        /* Opens a LUKS device that is already set up. Re-validates the password while doing so (which also
         * provides us with the volume key, which we want). */
 
        r = acquire_open_luks_device(h, setup, /* graceful= */ false);
        if (r < 0)
                return r;
 
        r = sym_crypt_load(setup->crypt_device, CRYPT_LUKS2, NULL);
        if (r < 0)
                return log_error_errno(r, "Failed to load LUKS superblock: %m");
 
        r = sym_crypt_get_volume_key_size(setup->crypt_device);
        if (r <= 0)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to determine LUKS volume key size.");
        vks = (size_t) r;
 
        if (ret_found_uuid) {
                const char *s;
 
                s = sym_crypt_get_uuid(setup->crypt_device);
                if (!s)
                        return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE), "LUKS superblock has no UUID.");
 
                r = sd_id128_from_string(s, &p);
                if (r < 0)
                        return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE), "LUKS superblock has invalid UUID.");
        }
 
        vk = malloc(vks);
        if (!vk)
                return log_oom();
 
        r = luks_get_volume_key(h, setup->crypt_device, cache, vk, &vks, NULL);
        if (r == -ENOKEY)
                return log_error_errno(r, "No valid password for LUKS superblock.");
        if (r < 0)
                return log_error_errno(r, "Failed to unlock LUKS superblock: %m");
 
        log_info("Discovered used LUKS device /dev/mapper/%s, and validated password.", setup->dm_name);
 
        /* This is needed so that crypt_resize() can operate correctly for pre-existing LUKS devices. We need
         * to tell libcryptsetup the volume key explicitly, so that it is in the kernel keyring. */
        r = sym_crypt_activate_by_volume_key(setup->crypt_device, NULL, vk, vks, CRYPT_ACTIVATE_KEYRING_KEY);
        if (r < 0)
                return log_error_errno(r, "Failed to upload volume key again: %m");
 
        log_info("Successfully re-activated LUKS device.");
 
        if (ret_found_uuid)
                *ret_found_uuid = p;
        if (ret_volume_key)
                *ret_volume_key = TAKE_PTR(vk);
        if (ret_volume_key_size)
                *ret_volume_key_size = vks;
 
        return 0;
}
 
static int fs_validate(
                const char *dm_node,
                sd_id128_t uuid,
                char **ret_fstype,
                sd_id128_t *ret_found_uuid) {
 
        _cleanup_free_ char *fstype = NULL;
        sd_id128_t u = SD_ID128_NULL; /* avoid false maybe-uninitialized warning */
        int r;
 
        assert(dm_node);
        assert(ret_fstype);
 
        r = probe_file_system_by_path(dm_node, &fstype, &u);
        if (r < 0)
                return log_error_errno(r, "Failed to probe file system: %m");
 
        /* Limit the set of supported file systems a bit, as protection against little tested kernel file
         * systems. Also, we only support the resize ioctls for these file systems. */
        if (!supported_fstype(fstype))
                return log_error_errno(SYNTHETIC_ERRNO(EPROTONOSUPPORT), "Image contains unsupported file system: %s", strna(fstype));
 
        if (!sd_id128_is_null(uuid) &&
            !sd_id128_equal(uuid, u))
                return log_error_errno(SYNTHETIC_ERRNO(EMEDIUMTYPE), "File system has wrong UUID.");
 
        log_info("Probing file system completed (found %s).", fstype);
 
        *ret_fstype = TAKE_PTR(fstype);
 
        if (ret_found_uuid) /* Return the UUID actually found if the caller wants to know */
                *ret_found_uuid = u;
 
        return 0;
}
 
static int luks_validate(
                int fd,
                const char *label,
                sd_id128_t partition_uuid,
                uint64_t sector_size,
                sd_id128_t *ret_partition_uuid,
                uint64_t *ret_offset,
                uint64_t *ret_size) {
 
#if HAVE_BLKID
        _cleanup_(blkid_free_probep) blkid_probe b = NULL;
        sd_id128_t found_partition_uuid = SD_ID128_NULL;
        const char *fstype = NULL, *pttype = NULL;
        blkid_loff_t offset = 0, size = 0;
        blkid_partlist pl;
        bool found = false;
        int r, n;
 
        assert(fd >= 0);
        assert(label);
        assert(ret_offset);
        assert(ret_size);
        assert(sector_size > 0);
 
        r = dlopen_libblkid(LOG_DEBUG);
        if (r < 0)
                return r;
 
        b = sym_blkid_new_probe();
        if (!b)
                return -ENOMEM;
 
        errno = 0;
        r = sym_blkid_probe_set_device(b, fd, 0, 0);
        if (r != 0)
                return errno_or_else(ENOMEM);
 
        /* Set probing sector size if explicitly specified */
        if (sector_size != UINT32_MAX) {
                r = sym_blkid_probe_set_sectorsize(b, sector_size);
                if (r != 0)
                        return errno_or_else(EINVAL);
        }
        (void) sym_blkid_probe_enable_superblocks(b, 1);
        (void) sym_blkid_probe_set_superblocks_flags(b, BLKID_SUBLKS_TYPE);
        (void) sym_blkid_probe_enable_partitions(b, 1);
        (void) sym_blkid_probe_set_partitions_flags(b, BLKID_PARTS_ENTRY_DETAILS);
 
        errno = 0;
        r = sym_blkid_do_safeprobe(b);
        if (r == _BLKID_SAFEPROBE_ERROR)
                return errno_or_else(EIO);
        if (IN_SET(r, _BLKID_SAFEPROBE_AMBIGUOUS, _BLKID_SAFEPROBE_NOT_FOUND))
                return -ENOPKG;
 
        assert(r == _BLKID_SAFEPROBE_FOUND);
 
        (void) sym_blkid_probe_lookup_value(b, "TYPE", &fstype, NULL);
        if (streq_ptr(fstype, "crypto_LUKS")) {
                /* Directly a LUKS image */
                *ret_offset = 0;
                *ret_size = UINT64_MAX; /* full disk */
                *ret_partition_uuid = SD_ID128_NULL;
                return 0;
        } else if (fstype)
                return -ENOPKG;
 
        (void) sym_blkid_probe_lookup_value(b, "PTTYPE", &pttype, NULL);
        if (!streq_ptr(pttype, "gpt"))
                return -ENOPKG;
 
        errno = 0;
        pl = sym_blkid_probe_get_partitions(b);
        if (!pl)
                return errno_or_else(ENOMEM);
 
        errno = 0;
        n = sym_blkid_partlist_numof_partitions(pl);
        if (n < 0)
                return errno_or_else(EIO);
 
        for (int i = 0; i < n; i++) {
                sd_id128_t id = SD_ID128_NULL;
                blkid_partition pp;
 
                errno = 0;
                pp = sym_blkid_partlist_get_partition(pl, i);
                if (!pp)
                        return errno_or_else(EIO);
 
                if (sd_id128_string_equal(sym_blkid_partition_get_type_string(pp), SD_GPT_USER_HOME) <= 0)
                        continue;
 
                if (!streq_ptr(sym_blkid_partition_get_name(pp), label))
                        continue;
 
                r = blkid_partition_get_uuid_id128(pp, &id);
                if (r < 0)
                        log_debug_errno(r, "Failed to read partition UUID, ignoring: %m");
                else if (!sd_id128_is_null(partition_uuid) && !sd_id128_equal(id, partition_uuid))
                        continue;
 
                if (found)
                        return -ENOPKG;
 
                offset = sym_blkid_partition_get_start(pp);
                size = sym_blkid_partition_get_size(pp);
                found_partition_uuid = id;
 
                found = true;
        }
 
        if (!found)
                return -ENOPKG;
 
        if (offset < 0)
                return -EINVAL;
        if ((uint64_t) offset > UINT64_MAX / 512U)
                return -EINVAL;
        if (size <= 0)
                return -EINVAL;
        if ((uint64_t) size > UINT64_MAX / 512U)
                return -EINVAL;
 
        /* libblkid returns partitions sizes in count of 512-sectors. This does not necessarily need to match the device sector size */
        *ret_offset = offset * 512U;
        *ret_size = size * 512U;
        *ret_partition_uuid = found_partition_uuid;
 
        return 0;
#else
        return -EOPNOTSUPP;
#endif
}
 
static int crypt_device_to_evp_cipher(struct crypt_device *cd, const EVP_CIPHER **ret) {
        _cleanup_free_ char *cipher_name = NULL;
        const char *cipher, *cipher_mode, *e;
        size_t key_size, key_bits;
        const EVP_CIPHER *cc;
        int r;
 
        assert(cd);
        assert(ret);
 
        r = dlopen_libcrypto(LOG_ERR);
        if (r < 0)
                return r;
 
        /* Let's find the right OpenSSL EVP_CIPHER object that matches the encryption settings of the LUKS
         * device */
 
        cipher = sym_crypt_get_cipher(cd);
        if (!cipher)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Cannot get cipher from LUKS device.");
 
        cipher_mode = sym_crypt_get_cipher_mode(cd);
        if (!cipher_mode)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Cannot get cipher mode from LUKS device.");
 
        e = strchr(cipher_mode, '-');
        if (e)
                cipher_mode = strndupa_safe(cipher_mode, e - cipher_mode);
 
        r = sym_crypt_get_volume_key_size(cd);
        if (r <= 0)
                return log_error_errno(r < 0 ? r : SYNTHETIC_ERRNO(EINVAL), "Cannot get volume key size from LUKS device.");
 
        key_size = r;
        key_bits = key_size * 8;
        if (streq(cipher_mode, "xts"))
                key_bits /= 2;
 
        if (asprintf(&cipher_name, "%s-%zu-%s", cipher, key_bits, cipher_mode) < 0)
                return log_oom();
 
        cc = sym_EVP_get_cipherbyname(cipher_name);
        if (!cc)
                return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Selected cipher mode '%s' not supported, can't encrypt JSON record.", cipher_name);
 
        /* Verify that our key length calculations match what OpenSSL thinks */
        r = sym_EVP_CIPHER_get_key_length(cc);
        if (r < 0 || (uint64_t) r != key_size)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Key size of selected cipher doesn't meet our expectations.");
 
        *ret = cc;
        return 0;
}
 
static int luks_validate_home_record(
                struct crypt_device *cd,
                UserRecord *h,
                const void *volume_key,
                PasswordCache *cache,
                UserRecord **ret_luks_home_record) {
 
        int r;
 
        assert(cd);
        assert(h);
        assert(ret_luks_home_record);
 
        for (int token = 0; token < sym_crypt_token_max(CRYPT_LUKS2); token++) {
                _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL, *rr = NULL;
                _cleanup_(EVP_CIPHER_CTX_freep) EVP_CIPHER_CTX *context = NULL;
                _cleanup_(user_record_unrefp) UserRecord *lhr = NULL;
                _cleanup_free_ void *encrypted = NULL, *iv = NULL;
                size_t decrypted_size, encrypted_size, iv_size;
                int decrypted_size_out1, decrypted_size_out2;
                _cleanup_free_ char *decrypted = NULL;
                const char *text, *type;
                crypt_token_info state;
                sd_json_variant *jr, *jiv;
                const EVP_CIPHER *cc;
 
                state = sym_crypt_token_status(cd, token, &type);
                if (state == CRYPT_TOKEN_INACTIVE) /* First unconfigured token, give up */
                        break;
                if (IN_SET(state, CRYPT_TOKEN_INTERNAL, CRYPT_TOKEN_INTERNAL_UNKNOWN, CRYPT_TOKEN_EXTERNAL))
                        continue;
                if (state != CRYPT_TOKEN_EXTERNAL_UNKNOWN)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unexpected token state of token %i: %i", token, (int) state);
 
                if (!streq(type, "systemd-homed"))
                        continue;
 
                r = sym_crypt_token_json_get(cd, token, &text);
                if (r < 0)
                        return log_error_errno(r, "Failed to read LUKS token %i: %m", token);
 
                unsigned line = 0, column = 0;
                r = sd_json_parse(text, SD_JSON_PARSE_MUST_BE_OBJECT|SD_JSON_PARSE_SENSITIVE, &v, &line, &column);
                if (r < 0)
                        return log_error_errno(r, "Failed to parse LUKS token JSON data %u:%u: %m", line, column);
 
                jr = sd_json_variant_by_key(v, "record");
                if (!jr)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "LUKS token lacks 'record' field.");
                jiv = sd_json_variant_by_key(v, "iv");
                if (!jiv)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "LUKS token lacks 'iv' field.");
 
                r = sd_json_variant_unbase64(jr, &encrypted, &encrypted_size);
                if (r < 0)
                        return log_error_errno(r, "Failed to base64 decode record: %m");
 
                r = sd_json_variant_unbase64(jiv, &iv, &iv_size);
                if (r < 0)
                        return log_error_errno(r, "Failed to base64 decode IV: %m");
 
                r = crypt_device_to_evp_cipher(cd, &cc);
                if (r < 0)
                        return r;
                if (iv_size > INT_MAX || sym_EVP_CIPHER_get_iv_length(cc) != (int) iv_size)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "IV size doesn't match.");
 
                context = sym_EVP_CIPHER_CTX_new();
                if (!context)
                        return log_oom();
 
                if (sym_EVP_DecryptInit_ex(context, cc, NULL, volume_key, iv) != 1)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to initialize decryption context.");
 
                decrypted_size = encrypted_size + sym_EVP_CIPHER_get_key_length(cc) * 2;
                decrypted = new(char, decrypted_size);
                if (!decrypted)
                        return log_oom();
 
                if (sym_EVP_DecryptUpdate(context, (uint8_t*) decrypted, &decrypted_size_out1, encrypted, encrypted_size) != 1)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to decrypt JSON record.");
 
                assert((size_t) decrypted_size_out1 <= decrypted_size);
 
                if (sym_EVP_DecryptFinal_ex(context, (uint8_t*) decrypted + decrypted_size_out1, &decrypted_size_out2) != 1)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to finish decryption of JSON record.");
 
                assert((size_t) decrypted_size_out1 + (size_t) decrypted_size_out2 < decrypted_size);
                decrypted_size = (size_t) decrypted_size_out1 + (size_t) decrypted_size_out2;
 
                if (memchr(decrypted, 0, decrypted_size))
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Inner NUL byte in JSON record, refusing.");
 
                decrypted[decrypted_size] = 0;
 
                r = sd_json_parse(decrypted, SD_JSON_PARSE_MUST_BE_OBJECT|SD_JSON_PARSE_SENSITIVE, &rr, NULL, NULL);
                if (r < 0)
                        return log_error_errno(r, "Failed to parse decrypted JSON record, refusing.");
 
                lhr = user_record_new();
                if (!lhr)
                        return log_oom();
 
                r = user_record_load(lhr, rr, USER_RECORD_LOAD_EMBEDDED|USER_RECORD_PERMISSIVE);
                if (r < 0)
                        return log_error_errno(r, "Failed to parse user record: %m");
 
                if (!user_record_compatible(h, lhr))
                        return log_error_errno(SYNTHETIC_ERRNO(EREMCHG), "LUKS home record not compatible with host record, refusing.");
 
                r = user_record_authenticate(lhr, h, cache, /* strict_verify= */ true);
                if (r < 0)
                        return r;
                assert(r > 0); /* Insist that a password was verified */
 
                *ret_luks_home_record = TAKE_PTR(lhr);
                return 0;
        }
 
        return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Couldn't find home record in LUKS2 header, refusing.");
}
 
static int format_luks_token_text(
                struct crypt_device *cd,
                UserRecord *hr,
                const void *volume_key,
                char **ret) {
 
        int r, encrypted_size_out1 = 0, encrypted_size_out2 = 0, iv_size, key_size;
        _cleanup_(EVP_CIPHER_CTX_freep) EVP_CIPHER_CTX *context = NULL;
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
        _cleanup_free_ void *iv = NULL, *encrypted = NULL;
        size_t text_length, encrypted_size;
        _cleanup_free_ char *text = NULL;
        const EVP_CIPHER *cc;
 
        assert(cd);
        assert(hr);
        assert(volume_key);
        assert(ret);
 
        r = crypt_device_to_evp_cipher(cd, &cc);
        if (r < 0)
                return r;
 
        key_size = sym_EVP_CIPHER_get_key_length(cc);
        iv_size = sym_EVP_CIPHER_get_iv_length(cc);
 
        if (iv_size > 0) {