HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/home/homework.c

85,525 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 08762a8022b92d5d0a385a5d1e46006ec7b4494c

Lines 1–1000 of 2,182

/* SPDX-License-Identifier: LGPL-2.1-or-later */
 
#include <linux/magic.h>
#include <stdlib.h>
#include <sys/mount.h>
#include <unistd.h>
 
#include "sd-daemon.h"
 
#include "blockdev-util.h"
#include "bus-unit-util.h"
#include "chase.h"
#include "chown-recursive.h"
#include "copy.h"
#include "cryptsetup-util.h"
#include "dlopen-note.h"
#include "env-util.h"
#include "errno-util.h"
#include "fd-util.h"
#include "fileio.h"
#include "filesystems.h"
#include "format-util.h"
#include "fs-util.h"
#include "hashmap.h"
#include "home-util.h"
#include "homework-fido2.h"
#include "homework-password-cache.h"
#include "homework-pkcs11.h"
#include "homework.h"
#include "homework-blob.h"
#include "homework-cifs.h"
#include "homework-directory.h"
#include "homework-fscrypt.h"
#include "homework-luks.h"
#include "homework-mount.h"
#include "json-util.h"
#include "libcrypt-util.h"
#include "loop-util.h"
#include "main-func.h"
#include "memory-util.h"
#include "mount-util.h"
#include "path-util.h"
#include "recovery-key.h"
#include "rm-rf.h"
#include "stat-util.h"
#include "string-util.h"
#include "strv.h"
#include "sync-util.h"
#include "time-util.h"
#include "tmpfile-util.h"
#include "user-record.h"
#include "user-record-util.h"
#include "user-util.h"
#include "virt.h"
 
/* Make sure a bad password always results in a 3s delay, no matter what */
#define BAD_PASSWORD_DELAY_USEC (3 * USEC_PER_SEC)
 
int user_record_authenticate(
                UserRecord *h,
                UserRecord *secret,
                PasswordCache *cache,
                bool strict_verify) {
 
        bool need_password = false, need_recovery_key = false, need_token = false, need_pin = false,
                need_protected_authentication_path_permitted = false, need_user_presence_permitted = false,
                need_user_verification_permitted = false, pin_locked = false, pin_incorrect = false,
                pin_incorrect_few_tries_left = false, pin_incorrect_one_try_left = false, token_action_timeout = false;
        int r;
 
        assert(h);
        assert(secret);
        assert(cache);
 
        /* Tries to authenticate a user record with the supplied secrets. i.e. checks whether at least one
         * supplied plaintext passwords matches a hashed password field of the user record. Or if a
         * configured PKCS#11 or FIDO2 token is around and can unlock the record.
         *
         * Note that the 'cache' parameter is both an input and output parameter: it contains lists of
         * configured, decrypted PKCS#11/FIDO2 passwords. We typically have to call this function multiple
         * times over the course of an operation (think: on login we authenticate the host user record, the
         * record embedded in the LUKS record and the one embedded in $HOME). Hence we keep a list of
         * passwords we already decrypted, so that we don't have to do the (slow and potentially interactive)
         * PKCS#11/FIDO2 dance for the relevant token again and again.
         *
         * The 'cache' parameter might also contain the LUKS volume key, loaded from the kernel keyring.
         * In this case, authentication becomes optional - if a secret section is provided it will be
         * verified, but if missing then authentication is skipped entirely. Thus, callers should
         * consider carefully whether it is safe to load the volume key into 'cache' before doing so.
         * Note that most of the time this is safe, because the home area must be active for the key
         * to exist in the keyring, and the user would have had to authenticate when activating their
         * home area; however, for some methods (i.e. ChangePassword, Authenticate) it makes more sense
         * to force re-authentication. */
 
        /* First, let's see if we already have a volume key from the keyring */
        if (cache->volume_key &&
            sd_json_variant_is_blank_object(sd_json_variant_by_key(secret->json, "secret"))) {
                log_info("LUKS volume key from keyring unlocks user record.");
                return 1;
        }
 
        /* Next, let's see if the supplied plain-text passwords work? */
        r = user_record_test_password(h, secret);
        if (r == -ENOKEY)
                need_password = true;
        else if (r == -ENXIO)
                log_debug_errno(r, "User record has no hashed passwords, plaintext passwords not tested.");
        else if (r < 0)
                return log_error_errno(r, "Failed to validate password of record: %m");
        else {
                log_info("Provided password unlocks user record.");
                return 1;
        }
 
        /* Similar, but test against the recovery keys */
        r = user_record_test_recovery_key(h, secret);
        if (r == -ENOKEY)
                need_recovery_key = true;
        else if (r == -ENXIO)
                log_debug_errno(r, "User record has no recovery keys, plaintext passwords not tested against it.");
        else if (r < 0)
                return log_error_errno(r, "Failed to validate the recovery key of the record: %m");
        else {
                log_info("Provided password is a recovery key that unlocks the user record.");
                return 1;
        }
 
        if (need_password && need_recovery_key)
                log_info("None of the supplied plaintext passwords unlock the user record's hashed passwords or recovery keys.");
        else if (need_password)
                log_info("None of the supplied plaintext passwords unlock the user record's hashed passwords.");
        else
                log_info("None of the supplied plaintext passwords unlock the user record's hashed recovery keys.");
 
        /* Next, test cached PKCS#11 passwords */
        FOREACH_ARRAY(i, h->pkcs11_encrypted_key, h->n_pkcs11_encrypted_key)
                STRV_FOREACH(pp, cache->pkcs11_passwords) {
                        r = test_password_one(i->hashed_password, *pp);
                        if (r < 0)
                                return log_error_errno(r, "Failed to check supplied PKCS#11 password: %m");
                        if (r > 0) {
                                log_info("Previously acquired PKCS#11 password unlocks user record.");
                                return 1;
                        }
                }
 
        /* Next, test cached FIDO2 passwords */
        FOREACH_ARRAY(i, h->fido2_hmac_salt, h->n_fido2_hmac_salt)
                /* See if any of the previously calculated passwords work */
                STRV_FOREACH(pp, cache->fido2_passwords) {
                        r = test_password_one(i->hashed_password, *pp);
                        if (r < 0)
                                return log_error_errno(r, "Failed to check supplied FIDO2 password: %m");
                        if (r > 0) {
                                log_info("Previously acquired FIDO2 password unlocks user record.");
                                return 1;
                        }
                }
 
        /* Next, let's see if any of the PKCS#11 security tokens are plugged in and help us */
        FOREACH_ARRAY(i, h->pkcs11_encrypted_key, h->n_pkcs11_encrypted_key) {
#if HAVE_P11KIT
                _cleanup_(pkcs11_callback_data_release) struct pkcs11_callback_data data = {
                        .user_record = h,
                        .secret = secret,
                        .encrypted_key = i,
                };
 
                r = pkcs11_find_token(data.encrypted_key->uri, pkcs11_callback, &data);
                switch (r) {
                case -EAGAIN:
                        need_token = true;
                        break;
                case -ENOANO:
                        need_pin = true;
                        break;
                case -ERFKILL:
                        need_protected_authentication_path_permitted = true;
                        break;
                case -EOWNERDEAD:
                        pin_locked = true;
                        break;
                case -ENOLCK:
                        pin_incorrect = true;
                        break;
                case -ETOOMANYREFS:
                        pin_incorrect = pin_incorrect_few_tries_left = true;
                        break;
                case -EUCLEAN:
                        pin_incorrect = pin_incorrect_few_tries_left = pin_incorrect_one_try_left = true;
                        break;
                default:
                        if (r < 0)
                                return r;
 
                        r = test_password_one(data.encrypted_key->hashed_password, data.decrypted_password);
                        if (r < 0)
                                return log_error_errno(r, "Failed to test PKCS#11 password: %m");
                        if (r == 0)
                                return log_error_errno(SYNTHETIC_ERRNO(EPERM),
                                                       "Configured PKCS#11 security token %s does not decrypt encrypted key correctly.",
                                                       data.encrypted_key->uri);
 
                        log_info("Decrypted password from PKCS#11 security token %s unlocks user record.", data.encrypted_key->uri);
 
                        r = strv_extend(&cache->pkcs11_passwords, data.decrypted_password);
                        if (r < 0)
                                return log_oom();
 
                        return 1;
                }
#else
                need_token = true;
                break;
#endif
        }
 
        /* Next, let's see if any of the FIDO2 security tokens are plugged in and help us */
        FOREACH_ARRAY(i, h->fido2_hmac_salt, h->n_fido2_hmac_salt) {
#if HAVE_LIBFIDO2
                _cleanup_(erase_and_freep) char *decrypted_password = NULL;
 
                r = fido2_use_token(h, secret, i, &decrypted_password);
                switch (r) {
                case -EAGAIN:
                        need_token = true;
                        break;
                case -ENOANO:
                        need_pin = true;
                        break;
                case -EOWNERDEAD:
                        pin_locked = true;
                        break;
                case -ENOLCK:
                        pin_incorrect = true;
                        break;
                case -EMEDIUMTYPE:
                        need_user_presence_permitted = true;
                        break;
                case -ENOCSI:
                        need_user_verification_permitted = true;
                        break;
                case -ENOSTR:
                        token_action_timeout = true;
                        break;
                default:
                        if (r < 0)
                                return r;
 
                        r = test_password_one(i->hashed_password, decrypted_password);
                        if (r < 0)
                                return log_error_errno(r, "Failed to test FIDO2 password: %m");
                        if (r == 0)
                                return log_error_errno(SYNTHETIC_ERRNO(EPERM),
                                                       "Configured FIDO2 security token does not decrypt encrypted key correctly.");
 
                        log_info("Decrypted password from FIDO2 security token unlocks user record.");
 
                        r = strv_extend(&cache->fido2_passwords, decrypted_password);
                        if (r < 0)
                                return log_oom();
 
                        return 1;
                }
#else
                need_token = true;
                break;
#endif
        }
 
        /* Ordered by "relevance", i.e. the most "important" or "interesting" error condition is returned. */
        if (pin_incorrect_one_try_left)
                return -EUCLEAN;
        if (pin_incorrect_few_tries_left)
                return -ETOOMANYREFS;
        if (pin_incorrect)
                return -ENOLCK;
        if (pin_locked)
                return -EOWNERDEAD;
        if (token_action_timeout)
                return -ENOSTR;
        if (need_protected_authentication_path_permitted)
                return -ERFKILL;
        if (need_user_presence_permitted)
                return -EMEDIUMTYPE;
        if (need_user_verification_permitted)
                return -ENOCSI;
        if (need_pin)
                return -ENOANO;
        if (need_token)
                return -EBADSLT;
        if (need_password)
                return -ENOKEY;
        if (need_recovery_key)
                return -EREMOTEIO;
 
        /* Hmm, this means neither PCKS#11/FIDO2 nor classic hashed passwords or recovery keys were supplied,
         * we cannot authenticate this reasonably */
        if (strict_verify)
                return log_debug_errno(SYNTHETIC_ERRNO(EKEYREVOKED),
                                       "No hashed passwords, no recovery keys and no PKCS#11/FIDO2 tokens defined, cannot authenticate user record, refusing.");
 
        /* If strict verification is off this means we are possibly in the case where we encountered an
         * unfixated record, i.e. a synthetic one that accordingly lacks any authentication data. In this
         * case, allow the authentication to pass for now, so that the second (or third) authentication level
         * (the ones of the user record in the LUKS header or inside the home directory) will then catch
         * invalid passwords. The second/third authentication always runs in strict verification mode. */
        log_debug("No hashed passwords, not recovery keys and no PKCS#11 tokens defined in record, cannot authenticate user record. "
                  "Deferring to embedded user record.");
        return 0;
}
 
static void drop_caches_now(void) {
        int r;
 
        /* Drop file system caches now. See https://docs.kernel.org/admin-guide/sysctl/vm.html
         * for details. We write "3" into /proc/sys/vm/drop_caches to ensure dentries/inodes are flushed, but
         * not more. */
 
        r = write_string_file("/proc/sys/vm/drop_caches", "3\n", WRITE_STRING_FILE_DISABLE_BUFFER);
        if (r < 0)
                log_warning_errno(r, "Failed to drop caches, ignoring: %m");
        else
                log_debug("Dropped caches.");
}
 
int home_setup_undo_mount(HomeSetup *setup, int level) {
        int r;
 
        assert(setup);
 
        if (!setup->undo_mount)
                return 0;
 
        r = umount_recursive(HOME_RUNTIME_WORK_DIR, 0);
        if (r < 0) {
                if (level >= LOG_DEBUG) /* umount_recursive() does debug level logging anyway, no need to
                                         * repeat that here */
                        return r;
 
                /* If a higher log level is requested, the generate a non-debug message here too. */
                return log_full_errno(level, r, "Failed to unmount mount tree below %s: %m", HOME_RUNTIME_WORK_DIR);
        }
 
        setup->undo_mount = false;
        return 1;
}
 
int home_setup_undo_dm(HomeSetup *setup, int level) {
        int r, ret;
 
        assert(setup);
 
        if (setup->undo_dm) {
                assert(setup->crypt_device);
                assert(setup->dm_name);
 
                r = sym_crypt_deactivate_by_name(setup->crypt_device, setup->dm_name, 0);
                if (r < 0)
                        return log_full_errno(level, r, "Failed to deactivate LUKS device: %m");
 
                /* In case the device was already remove asynchronously by an early unmount via the deferred
                 * remove logic, let's wait for it */
                (void) wait_for_block_device_gone(setup, USEC_PER_SEC * 30);
 
                setup->undo_dm = false;
                ret = 1;
        } else
                ret = 0;
 
        if (setup->crypt_device) {
                sym_crypt_free(setup->crypt_device);
                setup->crypt_device = NULL;
        }
 
        return ret;
}
 
int keyring_unlink(key_serial_t k) {
 
        if (k == -1) /* already invalidated? */
                return -1;
 
        if (keyctl(KEYCTL_UNLINK, k, KEY_SPEC_SESSION_KEYRING, 0, 0) < 0)
                log_debug_errno(errno, "Failed to unlink key from session kernel keyring, ignoring: %m");
 
        return -1; /* Always return the key_serial_t value for "invalid" */
}
 
static int keyring_flush(UserRecord *h) {
        _cleanup_free_ char *name = NULL;
        long serial;
 
        assert(h);
 
        if (user_record_storage(h) == USER_FSCRYPT)
                (void) home_flush_keyring_fscrypt(h);
 
        name = strjoin("homework-user-", h->user_name);
        if (!name)
                return log_oom();
 
        serial = keyctl(KEYCTL_SEARCH, (unsigned long) KEY_SPEC_SESSION_KEYRING, (unsigned long) "user", (unsigned long) name, 0);
        if (serial == -1)
                return log_debug_errno(errno, "Failed to find kernel keyring entry for user, ignoring: %m");
 
        return keyring_unlink(serial);
}
 
int home_setup_done(HomeSetup *setup) {
        int r = 0, q;
 
        assert(setup);
 
        if (setup->root_fd >= 0) {
                if (setup->do_offline_fitrim) {
                        q = run_fitrim(setup->root_fd);
                        if (q < 0)
                                r = q;
                }
 
                if (syncfs(setup->root_fd) < 0)
                        log_debug_errno(errno, "Failed to synchronize home directory, ignoring: %m");
 
                setup->root_fd = safe_close(setup->root_fd);
        }
 
        q = home_setup_undo_mount(setup, LOG_DEBUG);
        if (q < 0)
                r = q;
 
        q = home_setup_undo_dm(setup, LOG_DEBUG);
        if (q < 0)
                r = q;
 
        if (setup->image_fd >= 0) {
                if (setup->do_offline_fallocate) {
                        q = run_fallocate(setup->image_fd, NULL);
                        if (setup->tolerate_offline_fallocate_enospc &&
                            ERRNO_IS_NEG_DISK_SPACE(q))
                                log_warning_errno(q, "Failed to allocate backing file, ignoring: %m");
                        else if (q < 0)
                                r = q;
                }
 
                if (setup->do_mark_clean) {
                        q = run_mark_dirty(setup->image_fd, false);
                        if (q < 0)
                                r = q;
                }
 
                setup->image_fd = safe_close(setup->image_fd);
        }
 
        if (setup->temporary_image_path) {
                if (unlink(setup->temporary_image_path) < 0)
                        log_debug_errno(errno, "Failed to remove temporary image file '%s', ignoring: %m",
                                        setup->temporary_image_path);
 
                setup->temporary_image_path = mfree(setup->temporary_image_path);
        }
 
        setup->key_serial = keyring_unlink(setup->key_serial);
 
        /* Roll back a v2 fscrypt master key that home_setup_fscrypt() installed but that no activated
         * home ended up owning (passwd/update/resize of an inactive home, or any error path). On the
         * activation path home_activate_directory() disarms this first, so the live home keeps its key. */
        fscrypt_v2_key_undo_done(&setup->fscrypt_v2_key_undo);
 
        setup->undo_mount = false;
        setup->undo_dm = false;
        setup->do_offline_fitrim = false;
        setup->do_offline_fallocate = false;
        setup->tolerate_offline_fallocate_enospc = false;
        setup->do_mark_clean = false;
 
        setup->dm_name = mfree(setup->dm_name);
        setup->dm_node = mfree(setup->dm_node);
 
        setup->loop = loop_device_unref(setup->loop);
 
        setup->volume_key = erase_and_free(setup->volume_key);
        setup->volume_key_size = 0;
 
        if (setup->do_drop_caches)
                drop_caches_now();
 
        setup->mount_suffix = mfree(setup->mount_suffix);
 
        return r;
}
 
int home_setup(
                UserRecord *h,
                HomeSetupFlags flags,
                HomeSetup *setup,
                PasswordCache *cache,
                UserRecord **ret_header_home) {
 
        int r;
 
        assert(h);
        assert(setup);
        assert(!setup->loop);
        assert(!setup->crypt_device);
        assert(setup->root_fd < 0);
        assert(!setup->undo_dm);
        assert(!setup->undo_mount);
 
        /* Makes a home directory accessible (through the root_fd file descriptor, not by path!). */
 
        if (!FLAGS_SET(flags, HOME_SETUP_ALREADY_ACTIVATED)) /* If we set up the directory, we should also drop caches once we are done */
                setup->do_drop_caches = setup->do_drop_caches || user_record_drop_caches(h);
 
        switch (user_record_storage(h)) {
 
        case USER_LUKS:
                return home_setup_luks(h, flags, NULL, setup, cache, ret_header_home);
 
        case USER_SUBVOLUME:
        case USER_DIRECTORY:
                r = home_setup_directory(h, setup);
                break;
 
        case USER_FSCRYPT:
                r = home_setup_fscrypt(h, flags, setup, cache);
                break;
 
        case USER_CIFS:
                r = home_setup_cifs(h, flags, setup);
                break;
 
        default:
                return log_error_errno(SYNTHETIC_ERRNO(ENOLINK), "Processing home directories of type '%s' currently not supported.", user_storage_to_string(user_record_storage(h)));
        }
 
        if (r < 0)
                return r;
 
        if (ret_header_home)
                *ret_header_home = NULL;
 
        return r;
}
 
int home_sync_and_statfs(int root_fd, struct statfs *ret) {
        assert(root_fd >= 0);
 
        /* Let's sync this to disk, so that the disk space reported by fstatfs() below is accurate (for file
         * systems such as btrfs where this is determined lazily). */
 
        if (syncfs(root_fd) < 0)
                return log_error_errno(errno, "Failed to synchronize file system: %m");
 
        if (ret)
                if (fstatfs(root_fd, ret) < 0)
                        return log_error_errno(errno, "Failed to statfs() file system: %m");
 
        log_info("Synchronized disk.");
 
        return 0;
}
 
static int read_identity_file(int root_fd, sd_json_variant **ret) {
        int r;
 
        assert(root_fd >= 0);
        assert(ret);
 
        _cleanup_close_ int identity_fd = xopenat_full(root_fd, ".identity", O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW|O_NONBLOCK, XO_REGULAR, MODE_INVALID);
        if (identity_fd < 0)
                return log_error_errno(identity_fd, "Failed to open .identity file in home directory: %m");
 
        unsigned line = 0, column = 0;
        r = sd_json_parse_fd(
                        ".identity",
                        TAKE_FD(identity_fd),
                        SD_JSON_PARSE_MUST_BE_OBJECT|SD_JSON_PARSE_SENSITIVE|SD_JSON_PARSE_DONATE_FD,
                        ret,
                        &line,
                        &column);
        if (r < 0)
                return log_error_errno(r, "[.identity:%u:%u] Failed to parse JSON data: %m", line, column);
 
        log_info("Read embedded .identity file.");
 
        return 0;
}
 
static int write_identity_file(int root_fd, sd_json_variant *v, uid_t uid) {
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *normalized = NULL;
        _cleanup_fclose_ FILE *identity_file = NULL;
        _cleanup_close_ int identity_fd = -EBADF;
        _cleanup_free_ char *fn = NULL;
        int r;
 
        assert(root_fd >= 0);
        assert(v);
 
        normalized = sd_json_variant_ref(v);
 
        r = sd_json_variant_normalize(&normalized);
        if (r < 0)
                log_warning_errno(r, "Failed to normalize user record, ignoring: %m");
 
        r = tempfn_random(".identity", NULL, &fn);
        if (r < 0)
                return r;
 
        identity_fd = openat(root_fd, fn, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
        if (identity_fd < 0)
                return log_error_errno(errno, "Failed to create .identity file in home directory: %m");
 
        identity_file = take_fdopen(&identity_fd, "w");
        if (!identity_file) {
                r = log_oom();
                goto fail;
        }
 
        sd_json_variant_dump(normalized, SD_JSON_FORMAT_PRETTY, identity_file, NULL);
 
        r = fflush_and_check(identity_file);
        if (r < 0) {
                log_error_errno(r, "Failed to write .identity file: %m");
                goto fail;
        }
 
        if (fchown(fileno(identity_file), uid, uid) < 0) {
                r = log_error_errno(errno, "Failed to change ownership of identity file: %m");
                goto fail;
        }
 
        if (renameat(root_fd, fn, root_fd, ".identity") < 0) {
                r = log_error_errno(errno, "Failed to move identity file into place: %m");
                goto fail;
        }
 
        log_info("Wrote embedded .identity file.");
 
        return 0;
 
fail:
        (void) unlinkat(root_fd, fn, 0);
        return r;
}
 
int home_load_embedded_identity(
                UserRecord *h,
                int root_fd,
                UserRecord *header_home,
                UserReconcileMode mode,
                PasswordCache *cache,
                UserRecord **ret_embedded_home,
                UserRecord **ret_new_home) {
 
        _cleanup_(user_record_unrefp) UserRecord *embedded_home = NULL, *intermediate_home = NULL, *new_home = NULL;
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
        int r;
 
        assert(h);
        assert(root_fd >= 0);
 
        r = read_identity_file(root_fd, &v);
        if (r < 0)
                return r;
 
        embedded_home = user_record_new();
        if (!embedded_home)
                return log_oom();
 
        r = user_record_load(embedded_home, v, USER_RECORD_LOAD_EMBEDDED|USER_RECORD_PERMISSIVE);
        if (r < 0)
                return r;
 
        if (!user_record_compatible(h, embedded_home))
                return log_error_errno(SYNTHETIC_ERRNO(EREMCHG), "Embedded home record not compatible with host record, refusing.");
 
        /* Insist that credentials the user supplies also unlocks any embedded records. */
        r = user_record_authenticate(embedded_home, h, cache, /* strict_verify= */ true);
        if (r < 0)
                return r;
        assert(r > 0); /* Insist that a password was verified */
 
        /* At this point we have three records to deal with:
         *
         *      · The record we got passed from the host
         *      · The record included in the LUKS header (only if LUKS is used)
         *      · The record in the home directory itself (~/.identity)
         *
         *  Now we have to reconcile all three, and let the newest one win. */
 
        if (header_home) {
                /* Note we relax the requirements here. Instead of insisting that the host record is strictly
                 * newer, let's also be OK if its equally new. If it is, we'll however insist that the
                 * embedded record must be newer, so that we update at least one of the two. */
 
                r = user_record_reconcile(h, header_home, mode == USER_RECONCILE_REQUIRE_NEWER ? USER_RECONCILE_REQUIRE_NEWER_OR_EQUAL : mode, &intermediate_home);
                if (r == -EREMCHG) /* this was supposed to be checked earlier already, but let's check this again */
                        return log_error_errno(r, "Identity stored on host and in header don't match, refusing.");
                if (r == -ESTALE)
                        return log_error_errno(r, "Embedded identity record is newer than supplied record, refusing.");
                if (r < 0)
                        return log_error_errno(r, "Failed to reconcile host and header identities: %m");
                if (r == USER_RECONCILE_EMBEDDED_WON)
                        log_info("Reconciling header user identity completed (header version was newer).");
                else if (r == USER_RECONCILE_HOST_WON) {
                        log_info("Reconciling header user identity completed (host version was newer).");
 
                        if (mode == USER_RECONCILE_REQUIRE_NEWER) /* Host version is newer than the header
                                                                   * version, hence we'll update
                                                                   * something. This means we can relax the
                                                                   * requirements on the embedded
                                                                   * identity. */
                                mode = USER_RECONCILE_REQUIRE_NEWER_OR_EQUAL;
                } else {
                        assert(r == USER_RECONCILE_IDENTICAL);
                        log_info("Reconciling user identities completed (host and header version were identical).");
                }
 
                h = intermediate_home;
        }
 
        r = user_record_reconcile(h, embedded_home, mode, &new_home);
        if (r == -EREMCHG)
                return log_error_errno(r, "Identity stored on host and in home don't match, refusing.");
        if (r == -ESTALE)
                return log_error_errno(r, "Embedded identity record is equally new or newer than supplied record, refusing.");
        if (r < 0)
                return log_error_errno(r, "Failed to reconcile host and embedded identities: %m");
        if (r == USER_RECONCILE_EMBEDDED_WON)
                log_info("Reconciling embedded user identity completed (embedded version was newer).");
        else if (r == USER_RECONCILE_HOST_WON)
                log_info("Reconciling embedded user identity completed (host version was newer).");
        else {
                assert(r == USER_RECONCILE_IDENTICAL);
                log_info("Reconciling embedded user identity completed (host and embedded version were identical).");
        }
 
        if (ret_embedded_home)
                *ret_embedded_home = TAKE_PTR(embedded_home);
 
        if (ret_new_home)
                *ret_new_home = TAKE_PTR(new_home);
 
        return r; /* We pass along who won the reconciliation */
}
 
int home_store_embedded_identity(UserRecord *h, int root_fd, UserRecord *old_home) {
        _cleanup_(user_record_unrefp) UserRecord *embedded = NULL;
        int r;
 
        assert(h);
        assert(root_fd >= 0);
 
        r = user_record_clone(h, USER_RECORD_EXTRACT_EMBEDDED|USER_RECORD_PERMISSIVE, &embedded);
        if (r < 0)
                return log_error_errno(r, "Failed to determine new embedded record: %m");
 
        if (old_home && user_record_equal(old_home, embedded)) {
                log_debug("Not updating embedded home record.");
                return 0;
        }
 
        /* The identity has changed, let's update it in the image */
        r = write_identity_file(root_fd, embedded->json, h->uid);
        if (r < 0)
                return r;
 
        return 1;
}
 
static const char *file_system_type_fd(int fd) {
        struct statfs sfs;
 
        assert(fd >= 0);
 
        if (fstatfs(fd, &sfs) < 0) {
                log_debug_errno(errno, "Failed to statfs(): %m");
                return NULL;
        }
 
        return fs_type_to_string(sfs.f_type);
}
 
int home_extend_embedded_identity(UserRecord *h, UserRecord *used, HomeSetup *setup) {
        int r;
 
        assert(h);
        assert(used);
        assert(setup);
 
        r = user_record_add_binding(
                        h,
                        user_record_storage(used),
                        user_record_image_path(used),
                        setup->found_partition_uuid,
                        setup->found_luks_uuid,
                        setup->found_fs_uuid,
                        setup->crypt_device ? sym_crypt_get_cipher(setup->crypt_device) : NULL,
                        setup->crypt_device ? sym_crypt_get_cipher_mode(setup->crypt_device) : NULL,
                        setup->crypt_device ? luks_volume_key_size_convert(setup->crypt_device) : UINT64_MAX,
                        file_system_type_fd(setup->root_fd),
                        user_record_home_directory(used),
                        used->uid,
                        (gid_t) used->uid);
        if (r < 0)
                return log_error_errno(r, "Failed to update binding in record: %m");
 
        return 0;
}
 
static int chown_recursive_directory(int root_fd, uid_t uid) {
        int r;
 
        assert(root_fd >= 0);
        assert(uid_is_valid(uid));
 
        r = fd_chown_recursive(root_fd, uid, (gid_t) uid, 0777);
        if (r < 0)
                return log_error_errno(r, "Failed to change ownership of files and directories: %m");
        if (r == 0)
                log_info("Recursive changing of ownership not necessary, skipped.");
        else
                log_info("Recursive changing of ownership completed.");
 
        return 0;
}
 
int home_maybe_shift_uid(
                UserRecord *h,
                HomeSetupFlags flags,
                HomeSetup *setup) {
 
        _cleanup_close_ int mount_fd = -EBADF;
        struct stat st;
 
        assert(h);
        assert(setup);
        assert(setup->root_fd >= 0);
 
        /* If the home dir is already activated, then the UID shift is already applied. */
        if (FLAGS_SET(flags, HOME_SETUP_ALREADY_ACTIVATED))
                return 0;
 
        if (fstat(setup->root_fd, &st) < 0)
                return log_error_errno(errno, "Failed to stat() home directory: %m");
 
        /* Let's shift UIDs of this mount. Hopefully this makes the later chowning unnecessary. (Note that we
         * also prefer to do UID mapping even if the UID already matches our goal UID. That's because we want
         * to leave UIDs in the homed managed range unmapped.) */
        (void) home_shift_uid(setup->root_fd, NULL, st.st_uid, h->uid, &mount_fd);
 
        /* If this worked, then we'll have a reference to the mount now, which we can also use like an O_PATH
         * fd to the new dir. Let's convert it into a proper O_DIRECTORY fd. */
        if (mount_fd >= 0) {
                safe_close(setup->root_fd);
 
                setup->root_fd = fd_reopen(mount_fd, O_RDONLY|O_CLOEXEC|O_DIRECTORY);
                if (setup->root_fd < 0)
                        return log_error_errno(setup->root_fd, "Failed to convert mount fd into regular directory fd: %m");
        }
 
        return 0;
}
 
int home_refresh(
                UserRecord *h,
                HomeSetupFlags flags,
                HomeSetup *setup,
                UserRecord *header_home,
                PasswordCache *cache,
                struct statfs *ret_statfs,
                UserRecord **ret_new_home) {
 
        _cleanup_(user_record_unrefp) UserRecord *embedded_home = NULL, *new_home = NULL;
        int r, reconciled;
 
        assert(h);
        assert(setup);
        assert(ret_new_home);
 
        /* When activating a home directory, does the identity work: loads the identity from the $HOME
         * directory, reconciles it with our idea, chown()s everything. */
 
        reconciled = home_load_embedded_identity(h, setup->root_fd, header_home, USER_RECONCILE_ANY, cache, &embedded_home, &new_home);
        if (reconciled < 0)
                return reconciled;
 
        r = home_maybe_shift_uid(h, flags, setup);
        if (r < 0)
                return r;
 
        r = home_store_header_identity_luks(new_home, setup, header_home);
        if (r < 0)
                return r;
 
        r = home_store_embedded_identity(new_home, setup->root_fd, embedded_home);
        if (r < 0)
                return r;
 
        r = home_reconcile_blob_dirs(new_home, setup->root_fd, reconciled);
        if (r < 0)
                return r;
 
        r = chown_recursive_directory(setup->root_fd, h->uid);
        if (r < 0)
                return r;
 
        r = home_sync_and_statfs(setup->root_fd, ret_statfs);
        if (r < 0)
                return r;
 
        *ret_new_home = TAKE_PTR(new_home);
        return 0;
}
 
static int home_activate(UserRecord *h, UserRecord **ret_home) {
        _cleanup_(home_setup_done) HomeSetup setup = HOME_SETUP_INIT;
        _cleanup_(user_record_unrefp) UserRecord *new_home = NULL;
        _cleanup_(password_cache_free) PasswordCache cache = {};
        HomeSetupFlags flags = 0;
        int r;
 
        assert(h);
        assert(ret_home);
 
        if (!h->user_name)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "User record lacks user name, refusing.");
        if (!uid_is_valid(h->uid))
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "User record lacks UID, refusing.");
        if (!IN_SET(user_record_storage(h), USER_LUKS, USER_DIRECTORY, USER_SUBVOLUME, USER_FSCRYPT, USER_CIFS))
                return log_error_errno(SYNTHETIC_ERRNO(ENOTTY), "Activating home directories of type '%s' currently not supported.", user_storage_to_string(user_record_storage(h)));
 
        r = user_record_authenticate(h, h, &cache, /* strict_verify= */ false);
        if (r < 0)
                return r;
 
        r = user_record_test_home_directory_and_warn(h);
        if (r < 0)
                return r;
        if (r == USER_TEST_MOUNTED)
                return log_error_errno(SYNTHETIC_ERRNO(EALREADY), "Home directory %s is already mounted, refusing.", user_record_home_directory(h));
 
        r = user_record_test_image_path_and_warn(h);
        if (r < 0)
                return r;
        if (r == USER_TEST_ABSENT)
                return log_error_errno(SYNTHETIC_ERRNO(ENETUNREACH), "Image path %s is missing, refusing.", user_record_image_path(h));
 
        switch (user_record_storage(h)) {
 
        case USER_LUKS:
                r = home_activate_luks(h, flags, &setup, &cache, &new_home);
                break;
 
        case USER_SUBVOLUME:
        case USER_DIRECTORY:
        case USER_FSCRYPT:
                r = home_activate_directory(h, flags, &setup, &cache, &new_home);
                break;
 
        case USER_CIFS:
                r = home_activate_cifs(h, flags, &setup, &cache, &new_home);
                break;
 
        default:
                assert_not_reached();
        }
        if (r < 0)
                return r;
 
        /* Note that the returned object might either be a reference to an updated version of the existing
         * home object, or a reference to a newly allocated home object. The caller has to be able to deal
         * with both, and consider the old object out-of-date. */
        if (user_record_equal(h, new_home)) {
                *ret_home = NULL;
                return 0; /* no identity change */
        }
 
        *ret_home = TAKE_PTR(new_home);
        return 1; /* identity updated */
}
 
static int home_deactivate(UserRecord *h, bool force) {
        _cleanup_(home_setup_done) HomeSetup setup = HOME_SETUP_INIT;
        _cleanup_(password_cache_free) PasswordCache cache = {};
        bool done = false;
        int r;
 
        assert(h);
 
        if (!h->user_name)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "User record incomplete, refusing.");
        if (!IN_SET(user_record_storage(h), USER_LUKS, USER_DIRECTORY, USER_SUBVOLUME, USER_FSCRYPT, USER_CIFS))
                return log_error_errno(SYNTHETIC_ERRNO(ENOTTY), "Deactivating home directories of type '%s' currently not supported.", user_storage_to_string(user_record_storage(h)));
 
        r = user_record_test_home_directory_and_warn(h);
        if (r < 0)
                return r;
        if (r == USER_TEST_MOUNTED) {