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 1001–2000 of 2,182

                /* Before we do anything, let's move the home mount away. */
                r = home_unshare_and_mkdir();
                if (r < 0)
                        return r;
 
                r = mount_nofollow_verbose(LOG_ERR, user_record_home_directory(h), HOME_RUNTIME_WORK_DIR, NULL, MS_BIND, NULL);
                if (r < 0)
                        return r;
 
                setup.undo_mount = true; /* remember to unmount the new bind mount from HOME_RUNTIME_WORK_DIR */
 
                /* Let's explicitly open the new root fs, using the moved path */
                setup.root_fd = open(HOME_RUNTIME_WORK_DIR, O_RDONLY|O_DIRECTORY|O_CLOEXEC);
                if (setup.root_fd < 0)
                        return log_error_errno(errno, "Failed to open moved home directory: %m");
 
                /* Now get rid of the home at its original place (we only keep the bind mount we created above) */
                r = umount_verbose(LOG_ERR, user_record_home_directory(h), UMOUNT_NOFOLLOW | (force ? MNT_FORCE|MNT_DETACH : 0));
                if (r < 0)
                        return r;
 
                if (user_record_storage(h) == USER_LUKS) {
                        /* Automatically shrink on logout if that's enabled. To be able to shrink we need the
                         * keys to the device. */
                        password_cache_load_keyring(h, &cache);
                        (void) home_trim_luks(h, &setup);
                }
 
                /* Sync explicitly, so that the drop caches logic below can work as documented */
                if (syncfs(setup.root_fd) < 0)
                        log_debug_errno(errno, "Failed to synchronize home directory, ignoring: %m");
                else
                        log_info("Syncing completed.");
 
                if (user_record_storage(h) == USER_LUKS)
                        (void) home_auto_shrink_luks(h, &setup, &cache);
 
                setup.root_fd = safe_close(setup.root_fd);
 
                /* Now get rid of the bind mount, too */
                r = umount_verbose(LOG_ERR, HOME_RUNTIME_WORK_DIR, UMOUNT_NOFOLLOW | (force ? MNT_FORCE|MNT_DETACH : 0));
                if (r < 0)
                        return r;
 
                setup.undo_mount = false; /* Remember that the bind mount doesn't need to be unmounted anymore */
 
                if (user_record_drop_caches(h))
                        setup.do_drop_caches = true;
 
                log_info("Unmounting completed.");
                done = true;
        } else
                log_info("Directory %s is already unmounted.", user_record_home_directory(h));
 
        if (user_record_storage(h) == USER_LUKS) {
                r = home_deactivate_luks(h, &setup);
                if (r < 0)
                        return r;
                if (r > 0)
                        done = true;
        }
 
        /* Explicitly flush any per-user key from the keyring */
        (void) keyring_flush(h);
 
        if (!done)
                return log_error_errno(SYNTHETIC_ERRNO(ENOEXEC), "Home is not active.");
 
        if (setup.do_drop_caches) {
                setup.do_drop_caches = false;
                drop_caches_now();
        }
 
        log_info("Everything completed.");
        return 0;
}
 
static int copy_skel(UserRecord *h, int root_fd, const char *skel) {
        _cleanup_close_ int skel_fd = -EBADF;
        int r;
 
        assert(h);
        assert(root_fd >= 0);
 
        r = chase(skel, /* root= */ NULL, CHASE_MUST_BE_DIRECTORY, /* ret_path= */ NULL, &skel_fd);
        if (r == -ENOENT) {
                log_info("Skeleton directory %s missing, ignoring.", skel);
                return 0;
        }
 
        r = copy_tree_at(
                        skel_fd, /* from= */ NULL,
                        root_fd, ".",
                        h->uid, user_record_gid(h),
                        COPY_MERGE|COPY_REPLACE,
                        /* denylist= */ NULL,
                        /* subvolumes= */ NULL);
        if (r < 0)
                return log_error_errno(r, "Failed to copy in %s: %m", skel);
 
        log_info("Copying in %s completed.", skel);
        return 0;
}
 
static int change_access_mode(int root_fd, mode_t m) {
        assert(root_fd >= 0);
 
        if (fchmod(root_fd, m) < 0)
                return log_error_errno(errno, "Failed to change access mode of top-level directory: %m");
 
        log_info("Changed top-level directory access mode to 0%o.", m);
        return 0;
}
 
int home_populate(UserRecord *h, int dir_fd) {
        int r;
 
        assert(h);
        assert(dir_fd >= 0);
 
        r = copy_skel(h, dir_fd, user_record_skeleton_directory(h));
        if (r < 0)
                return r;
 
        r = home_store_embedded_identity(h, dir_fd, NULL);
        if (r < 0)
                return r;
 
        r = home_reconcile_blob_dirs(h, dir_fd, USER_RECONCILE_HOST_WON);
        if (r < 0)
                return r;
 
        r = chown_recursive_directory(dir_fd, h->uid);
        if (r < 0)
                return r;
 
        r = change_access_mode(dir_fd, user_record_access_mode(h));
        if (r < 0)
                return r;
 
        return 0;
}
 
static int user_record_compile_effective_passwords(
                UserRecord *h,
                PasswordCache *cache,
                char ***ret_effective_passwords) {
 
        _cleanup_strv_free_erase_ char **effective = NULL;
        int r;
 
        assert(h);
        assert(cache);
 
        /* We insist on at least one classic hashed password to be defined in addition to any PKCS#11 one, as
         * a safe fallback, but also to simplify the password changing algorithm: there we require providing
         * the old literal password only (and do not care for the old PKCS#11 token) */
 
        if (strv_isempty(h->hashed_password))
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "User record has no hashed passwords, refusing.");
 
        /* Generates the list of plaintext passwords to propagate to LUKS/fscrypt devices, and checks whether
         * we have a plaintext password for each hashed one. If we are missing one we'll fail, since we
         * couldn't sync fscrypt/LUKS to the login account properly. */
 
        STRV_FOREACH(i, h->hashed_password) {
                bool found = false;
 
                log_debug("Looking for plaintext password for: %s", *i);
 
                /* Let's scan all provided plaintext passwords */
                STRV_FOREACH(j, h->password) {
                        r = test_password_one(*i, *j);
                        if (r < 0)
                                return log_error_errno(r, "Failed to test plaintext password: %m");
                        if (r > 0) {
                                if (ret_effective_passwords) {
                                        r = strv_extend(&effective, *j);
                                        if (r < 0)
                                                return log_oom();
                                }
 
                                log_debug("Found literal plaintext password.");
                                found = true;
                                break;
                        }
                }
 
                if (!found)
                        return log_error_errno(SYNTHETIC_ERRNO(ENOKEY), "Missing plaintext password for defined hashed password");
        }
 
        FOREACH_ARRAY(i, h->recovery_key, h->n_recovery_key) {
                bool found = false;
 
                log_debug("Looking for plaintext recovery key for: %s", i->hashed_password);
 
                STRV_FOREACH(j, h->password) {
                        _cleanup_(erase_and_freep) char *mangled = NULL;
                        const char *p;
 
                        if (streq(i->type, "modhex64")) {
                                r = normalize_recovery_key(*j, &mangled);
                                if (r == -EINVAL) /* Not properly formatted, probably a regular password. */
                                        continue;
                                if (r < 0)
                                        return log_error_errno(r, "Failed to normalize recovery key: %m");
 
                                p = mangled;
                        } else
                                p = *j;
 
                        r = test_password_one(i->hashed_password, p);
                        if (r < 0)
                                return log_error_errno(r, "Failed to test plaintext recovery key: %m");
                        if (r > 0) {
                                if (ret_effective_passwords) {
                                        r = strv_extend(&effective, p);
                                        if (r < 0)
                                                return log_oom();
                                }
 
                                log_debug("Found plaintext recovery key.");
                                found = true;
                                break;
                        }
                }
 
                if (!found)
                        return log_error_errno(SYNTHETIC_ERRNO(EREMOTEIO),
                                               "Missing plaintext recovery key for defined recovery key.");
        }
 
        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 = h,
                        .encrypted_key = i,
                };
 
                r = pkcs11_find_token(data.encrypted_key->uri, pkcs11_callback, &data);
                if (r == -EAGAIN)
                        return -EBADSLT;
                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), "Decrypted password from token is not correct, refusing.");
 
                if (ret_effective_passwords) {
                        r = strv_extend(&effective, data.decrypted_password);
                        if (r < 0)
                                return log_oom();
                }
 
                r = strv_extend(&cache->pkcs11_passwords, data.decrypted_password);
                if (r < 0)
                        return log_oom();
#else
                return -EBADSLT;
#endif
        }
 
        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, h, i, &decrypted_password);
                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),
                                               "Decrypted password from token is not correct, refusing.");
 
                if (ret_effective_passwords) {
                        r = strv_extend(&effective, decrypted_password);
                        if (r < 0)
                                return log_oom();
                }
 
                r = strv_extend(&cache->fido2_passwords, decrypted_password);
                if (r < 0)
                        return log_oom();
#else
                return -EBADSLT;
#endif
        }
 
        if (ret_effective_passwords)
                *ret_effective_passwords = TAKE_PTR(effective);
 
        return 0;
}
 
static int determine_default_storage(UserStorage *ret) {
        UserStorage storage = _USER_STORAGE_INVALID;
        const char *e;
        int r;
 
        assert(ret);
 
        /* homed tells us via an environment variable which default storage to use */
        e = getenv("SYSTEMD_HOME_DEFAULT_STORAGE");
        if (e) {
                storage = user_storage_from_string(e);
                if (storage < 0)
                        log_warning("$SYSTEMD_HOME_DEFAULT_STORAGE set to invalid storage type, ignoring: %s", e);
                else {
                        log_info("Using configured default storage '%s'.", user_storage_to_string(storage));
                        *ret = storage;
                        return 0;
                }
        }
 
        /* When neither user nor admin specified the storage type to use, fix it to be LUKS — unless we run
         * in a container where loopback devices and LUKS/DM are not available. Also, if /home is encrypted
         * anyway, let's avoid duplicate encryption. Note that we typically default to the assumption of
         * "classic" storage for most operations. However, if we create a new home, then let's user LUKS if
         * nothing is specified. */
 
        r = detect_container();
        if (r < 0)
                return log_error_errno(r, "Failed to determine whether we are in a container: %m");
        if (r == 0) {
                r = path_is_encrypted(get_home_root());
                if (r > 0)
                        log_info("%s is encrypted, not using '%s' storage, in order to avoid double encryption.", get_home_root(), user_storage_to_string(USER_LUKS));
                else {
                        if (r < 0)
                                log_warning_errno(r, "Failed to determine if %s is encrypted, ignoring: %m", get_home_root());
 
                        r = dlopen_cryptsetup(LOG_DEBUG);
                        if (r < 0)
                                log_info("Not using '%s' storage, since libcryptsetup could not be loaded.", user_storage_to_string(USER_LUKS));
                        else {
                                log_info("Using automatic default storage of '%s'.", user_storage_to_string(USER_LUKS));
                                *ret = USER_LUKS;
                                return 0;
                        }
                }
        } else
                log_info("Running in container, not using '%s' storage.", user_storage_to_string(USER_LUKS));
 
        r = path_is_fs_type(get_home_root(), BTRFS_SUPER_MAGIC);
        if (r < 0)
                log_warning_errno(r, "Failed to determine file system of %s, ignoring: %m", get_home_root());
        if (r > 0) {
                log_info("%s is on btrfs, using '%s' as storage.", get_home_root(), user_storage_to_string(USER_SUBVOLUME));
                *ret = USER_SUBVOLUME;
        } else {
                log_info("%s is on simple file system, using '%s' as storage.", get_home_root(), user_storage_to_string(USER_DIRECTORY));
                *ret = USER_DIRECTORY;
        }
 
        return 0;
}
 
static int home_create(UserRecord *h, Hashmap *blobs, UserRecord **ret_home) {
        _cleanup_strv_free_erase_ char **effective_passwords = NULL;
        _cleanup_(home_setup_done) HomeSetup setup = HOME_SETUP_INIT;
        _cleanup_(user_record_unrefp) UserRecord *new_home = NULL;
        _cleanup_(password_cache_free) PasswordCache cache = {};
        UserStorage new_storage = _USER_STORAGE_INVALID;
        const char *new_fs = NULL;
        int r;
 
        assert(h);
        assert(ret_home);
 
        if (!h->user_name)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "User record lacks name, refusing.");
        if (!uid_is_valid(h->uid))
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "User record lacks UID, refusing.");
 
        r = user_record_compile_effective_passwords(h, &cache, &effective_passwords);
        if (r < 0)
                return r;
 
        r = user_record_test_home_directory_and_warn(h);
        if (r < 0)
                return r;
        if (r != USER_TEST_ABSENT)
                return log_error_errno(SYNTHETIC_ERRNO(EEXIST), "Home directory %s already exists, refusing.", user_record_home_directory(h));
 
        if (h->storage < 0) {
                r = determine_default_storage(&new_storage);
                if (r < 0)
                        return r;
        }
 
        if ((h->storage == USER_LUKS ||
             (h->storage < 0 && new_storage == USER_LUKS)) &&
            !h->file_system_type)
                new_fs = getenv("SYSTEMD_HOME_DEFAULT_FILE_SYSTEM_TYPE");
 
        if (new_storage >= 0 || new_fs) {
                r = user_record_add_binding(
                                h,
                                new_storage,
                                NULL,
                                SD_ID128_NULL,
                                SD_ID128_NULL,
                                SD_ID128_NULL,
                                NULL,
                                NULL,
                                UINT64_MAX,
                                new_fs,
                                NULL,
                                UID_INVALID,
                                GID_INVALID);
                if (r < 0)
                        return log_error_errno(r, "Failed to change storage type to LUKS: %m");
        }
 
        r = user_record_test_image_path_and_warn(h);
        if (r < 0)
                return r;
        if (!IN_SET(r, USER_TEST_ABSENT, USER_TEST_UNDEFINED, USER_TEST_MAYBE))
                return log_error_errno(SYNTHETIC_ERRNO(EEXIST), "Image path %s already exists, refusing.", user_record_image_path(h));
 
        r = home_apply_new_blob_dir(h, blobs);
        if (r < 0)
                return r;
 
        switch (user_record_storage(h)) {
 
        case USER_LUKS:
                r = home_create_luks(h, &setup, &cache, effective_passwords, &new_home);
                break;
 
        case USER_DIRECTORY:
        case USER_SUBVOLUME:
                r = home_create_directory_or_subvolume(h, &setup, &new_home);
                break;
 
        case USER_FSCRYPT:
                r = home_create_fscrypt(h, &setup, effective_passwords, &new_home);
                break;
 
        case USER_CIFS:
                r = home_create_cifs(h, &setup, &new_home);
                break;
 
        default:
                return log_error_errno(SYNTHETIC_ERRNO(ENOTTY),
                                       "Creating home directories of type '%s' currently not supported.", user_storage_to_string(user_record_storage(h)));
        }
        if (r < 0)
                return r;
 
        if (user_record_equal(h, new_home)) {
                *ret_home = NULL;
                return 0;
        }
 
        *ret_home = TAKE_PTR(new_home);
        return 1;
}
 
static int home_remove(UserRecord *h) {
        bool deleted = false;
        const char *ip, *hd;
        int r;
 
        assert(h);
 
        if (!h->user_name)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "User record lacks user name, 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), "Removing home directories of type '%s' currently not supported.", user_storage_to_string(user_record_storage(h)));
 
        hd = user_record_home_directory(h);
 
        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(EBUSY), "Directory %s is still mounted, refusing.", hd);
 
        assert(hd);
 
        r = user_record_test_image_path_and_warn(h);
        if (r < 0)
                return r;
 
        ip = user_record_image_path(h);
 
        switch (user_record_storage(h)) {
 
        case USER_LUKS: {
                struct stat st;
 
                assert(ip);
 
                if (stat(ip, &st) < 0) {
                        if (errno != ENOENT)
                                return log_error_errno(errno, "Failed to stat() %s: %m", ip);
 
                } else {
                        if (S_ISREG(st.st_mode)) {
                                if (unlink(ip) < 0) {
                                        if (errno != ENOENT)
                                                return log_error_errno(errno, "Failed to remove %s: %m", ip);
                                } else {
                                        _cleanup_free_ char *parent = NULL;
 
                                        deleted = true;
 
                                        r = path_extract_directory(ip, &parent);
                                        if (r < 0)
                                                log_debug_errno(r, "Failed to determine parent directory of '%s': %m", ip);
                                        else {
                                                r = fsync_path_at(AT_FDCWD, parent);
                                                if (r < 0)
                                                        log_debug_errno(r, "Failed to synchronize disk after deleting '%s', ignoring: %m", ip);
                                        }
                                }
 
                        } else if (S_ISBLK(st.st_mode))
                                log_info("Not removing file system on block device %s.", ip);
                        else
                                return log_error_errno(SYNTHETIC_ERRNO(ENOTBLK), "Image file %s is neither block device, nor regular, refusing removal.", ip);
                }
 
                break;
        }
 
        case USER_SUBVOLUME:
        case USER_DIRECTORY:
        case USER_FSCRYPT:
                assert(ip);
 
                r = rm_rf(ip, REMOVE_ROOT|REMOVE_PHYSICAL|REMOVE_SUBVOLUME|REMOVE_SYNCFS);
                if (r < 0) {
                        if (r != -ENOENT)
                                return log_warning_errno(r, "Failed to remove %s: %m", ip);
                } else
                        deleted = true;
 
                /* If the image path and the home directory are the same invalidate the home directory, so
                 * that we don't remove it anymore */
                if (path_equal(ip, hd))
                        hd = NULL;
 
                break;
 
        case USER_CIFS:
                /* Nothing else to do here: we won't remove remote stuff. */
                log_info("Not removing home directory on remote server.");
                break;
 
        default:
                assert_not_reached();
        }
 
        if (hd) {
                if (rmdir(hd) < 0) {
                        if (errno != ENOENT)
                                return log_error_errno(errno, "Failed to remove %s, ignoring: %m", hd);
                } else
                        deleted = true;
        }
 
        if (deleted) {
                if (user_record_drop_caches(h))
                        drop_caches_now();
 
                log_info("Everything completed.");
        } else
                return log_notice_errno(SYNTHETIC_ERRNO(EALREADY),
                                        "Nothing to remove.");
 
        return 0;
}
 
static int home_basic_validate_update(UserRecord *h) {
        assert(h);
 
        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), "Processing home directories of type '%s' currently not supported.", user_storage_to_string(user_record_storage(h)));
 
        return 0;
}
 
static int home_validate_update(UserRecord *h, HomeSetup *setup, HomeSetupFlags *flags) {
        bool has_mount = false;
        int r;
 
        assert(h);
        assert(setup);
 
        r = home_basic_validate_update(h);
        if (r < 0)
                return r;
 
        r = user_record_test_home_directory_and_warn(h);
        if (r < 0)
                return r;
 
        has_mount = r == USER_TEST_MOUNTED;
 
        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 does not exist", user_record_image_path(h));
 
        switch (user_record_storage(h)) {
 
        case USER_DIRECTORY:
        case USER_SUBVOLUME:
        case USER_FSCRYPT:
        case USER_CIFS:
                break;
 
        case USER_LUKS: {
                r = home_get_state_luks(h, setup);
                if (r < 0)
                        return r;
                if ((r > 0) != has_mount)
                        return log_error_errno(SYNTHETIC_ERRNO(EBUSY), "Home mount incompletely set up.");
 
                break;
        }
 
        default:
                assert_not_reached();
        }
 
        if (flags)
                SET_FLAG(*flags, HOME_SETUP_ALREADY_ACTIVATED, has_mount);
 
        return has_mount; /* return true if the home record is already active */
}
 
static int home_update(UserRecord *h, Hashmap *blobs, UserRecord **ret) {
        _cleanup_(user_record_unrefp) UserRecord *new_home = NULL, *header_home = NULL, *embedded_home = NULL;
        _cleanup_(home_setup_done) HomeSetup setup = HOME_SETUP_INIT;
        _cleanup_(password_cache_free) PasswordCache cache = {};
        HomeSetupFlags flags = 0;
        bool offline;
        int r;
 
        assert(h);
        assert(ret);
 
        offline = getenv_bool("SYSTEMD_HOMEWORK_UPDATE_OFFLINE") > 0;
 
        if (!offline) {
                password_cache_load_keyring(h, &cache);
 
                r = user_record_authenticate(h, h, &cache, /* strict_verify= */ true);
                if (r < 0)
                        return r;
                assert(r > 0); /* Insist that a password was verified */
 
                r = home_validate_update(h, &setup, &flags);
        } else {
                /* In offline mode we skip all authentication, since we're
                 * not propagating anything into the home area. The new home
                 * records's authentication will still be checked when the user
                 * next logs in, so this is fine */
 
                r = home_basic_validate_update(h);
        }
        if (r < 0)
                return r;
 
        r = home_apply_new_blob_dir(h, blobs);
        if (r < 0)
                return r;
 
        if (offline) {
                log_info("Offline update requested. Not touching embedded records.");
                return user_record_clone(h, USER_RECORD_LOAD_MASK_SECRET|USER_RECORD_PERMISSIVE, ret);
        }
 
        r = home_setup(h, flags | HOME_SETUP_LUKS_DONT_FALLOCATE, &setup, &cache, &header_home);
        if (r < 0)
                return r;
 
        r = home_load_embedded_identity(h, setup.root_fd, header_home, USER_RECONCILE_REQUIRE_NEWER, &cache, &embedded_home, &new_home);
        if (r < 0)
                return r;
 
        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, USER_RECONCILE_HOST_WON);
        if (r < 0)
                return r;
 
        r = home_extend_embedded_identity(new_home, h, &setup);
        if (r < 0)
                return r;
 
        r = home_sync_and_statfs(setup.root_fd, NULL);
        if (r < 0)
                return r;
 
        r = home_setup_done(&setup);
        if (r < 0)
                return r;
 
        log_info("Everything completed.");
 
        *ret = TAKE_PTR(new_home);
        return 0;
}
 
static int home_resize(UserRecord *h, UserRecord **ret) {
        _cleanup_(home_setup_done) HomeSetup setup = HOME_SETUP_INIT;
        _cleanup_(password_cache_free) PasswordCache cache = {};
        HomeSetupFlags flags = 0;
        int r;
 
        assert(h);
        assert(ret);
 
        if (h->disk_size == UINT64_MAX)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No target size specified, refusing.");
 
        password_cache_load_keyring(h, &cache);
 
        r = user_record_authenticate(h, h, &cache, /* strict_verify= */ true);
        if (r < 0)
                return r;
        assert(r > 0); /* Insist that a password was verified */
 
        r = home_validate_update(h, &setup, &flags);
        if (r < 0)
                return r;
 
        switch (user_record_storage(h)) {
 
        case USER_LUKS:
                return home_resize_luks(h, flags, &setup, &cache, ret);
 
        case USER_DIRECTORY:
        case USER_SUBVOLUME:
        case USER_FSCRYPT:
                return home_resize_directory(h, flags, &setup, &cache, ret);
 
        default:
                return log_error_errno(SYNTHETIC_ERRNO(ENOTTY), "Resizing home directories of type '%s' currently not supported.", user_storage_to_string(user_record_storage(h)));
        }
}
 
static int home_passwd(UserRecord *h, UserRecord **ret_home) {
        _cleanup_(user_record_unrefp) UserRecord *header_home = NULL, *embedded_home = NULL, *new_home = NULL;
        _cleanup_strv_free_erase_ char **effective_passwords = NULL;
        _cleanup_(home_setup_done) HomeSetup setup = HOME_SETUP_INIT;
        _cleanup_(password_cache_free) PasswordCache cache = {};
        HomeSetupFlags flags = 0;
        int r, reconciled;
 
        assert(h);
        assert(ret_home);
 
        if (!IN_SET(user_record_storage(h), USER_LUKS, USER_DIRECTORY, USER_SUBVOLUME, USER_FSCRYPT))
                return log_error_errno(SYNTHETIC_ERRNO(ENOTTY), "Changing password of home directories of type '%s' currently not supported.", user_storage_to_string(user_record_storage(h)));
 
        r = user_record_compile_effective_passwords(h, &cache, &effective_passwords);
        if (r < 0)
                return r;
 
        r = home_validate_update(h, &setup, &flags);
        if (r < 0)
                return r;
 
        r = home_setup(h, flags | HOME_SETUP_LUKS_DONT_FALLOCATE, &setup, &cache, &header_home);
        if (r < 0)
                return r;
 
        reconciled = home_load_embedded_identity(h, setup.root_fd, header_home, USER_RECONCILE_REQUIRE_NEWER_OR_EQUAL, &cache, &embedded_home, &new_home);
        if (reconciled < 0)
                return reconciled;
 
        r = home_maybe_shift_uid(h, flags, &setup);
        if (r < 0)
                return r;
 
        switch (user_record_storage(h)) {
 
        case USER_LUKS:
                r = home_passwd_luks(h, flags, &setup, &cache, effective_passwords);
                if (r < 0)
                        return r;
                break;
 
        case USER_FSCRYPT:
                r = home_passwd_fscrypt(h, &setup, &cache, effective_passwords);
                if (r < 0)
                        return r;
                break;
 
        default:
                ;
        }
 
        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 = home_extend_embedded_identity(new_home, h, &setup);
        if (r < 0)
                return r;
 
        r = home_sync_and_statfs(setup.root_fd, NULL);
        if (r < 0)
                return r;
 
        r = home_setup_done(&setup);
        if (r < 0)
                return r;
 
        log_info("Everything completed.");
 
        *ret_home = TAKE_PTR(new_home);
        return 1;
}
 
static int home_inspect(UserRecord *h, UserRecord **ret_home) {
        _cleanup_(user_record_unrefp) UserRecord *header_home = NULL, *new_home = NULL;
        _cleanup_(home_setup_done) HomeSetup setup = HOME_SETUP_INIT;
        _cleanup_(password_cache_free) PasswordCache cache = {};
        HomeSetupFlags flags = 0;
        int r;
 
        assert(h);
        assert(ret_home);
 
        r = user_record_authenticate(h, h, &cache, /* strict_verify= */ false);
        if (r < 0)
                return r;
 
        r = home_validate_update(h, &setup, &flags);
        if (r < 0)
                return r;
 
        r = home_setup(h, flags | HOME_SETUP_LUKS_DONT_FALLOCATE, &setup, &cache, &header_home);
        if (r < 0)
                return r;
 
        r = home_load_embedded_identity(h, setup.root_fd, header_home, USER_RECONCILE_ANY, &cache, NULL, &new_home);
        if (r < 0)
                return r;
 
        r = home_extend_embedded_identity(new_home, h, &setup);
        if (r < 0)
                return r;
 
        r = home_setup_done(&setup);
        if (r < 0)
                return r;
 
        log_info("Everything completed.");
 
        *ret_home = TAKE_PTR(new_home);
        return 1;
}
 
static int user_session_freezer_new(uid_t uid, UnitFreezer **ret) {
        _cleanup_free_ char *unit = NULL;
        int r;
 
        assert(uid_is_valid(uid));
        assert(ret);
 
        r = getenv_bool("SYSTEMD_HOME_LOCK_FREEZE_SESSION");
        if (r < 0 && r != -ENXIO)
                log_warning_errno(r, "Cannot parse value of $SYSTEMD_HOME_LOCK_FREEZE_SESSION, ignoring: %m");
        else if (r == 0) {
                *ret = NULL;
                return 0;
        }
 
        if (asprintf(&unit, "user-" UID_FMT ".slice", uid) < 0)
                return log_oom();
 
        r = unit_freezer_new(unit, ret);
        if (r < 0)
                return r;
 
        return 1;
}
 
static int home_lock(UserRecord *h) {
        _cleanup_(home_setup_done) HomeSetup setup = HOME_SETUP_INIT;
        int r;
 
        assert(h);
 
        if (!h->user_name)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "User record incomplete, refusing.");
        if (user_record_storage(h) != USER_LUKS)
                return log_error_errno(SYNTHETIC_ERRNO(ENOTTY), "Locking 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)
                return log_error_errno(SYNTHETIC_ERRNO(ENOEXEC), "Home directory of %s is not mounted, can't lock.", h->user_name);
 
        _cleanup_(unit_freezer_freep) UnitFreezer *f = NULL;
 
        r = user_session_freezer_new(h->uid, &f);
        if (r < 0)
                return r;
        if (r > 0) {
                r = unit_freezer_freeze(f);
                if (r < 0)
                        return r;
        } else
                log_notice("Session remains unfrozen on explicit request ($SYSTEMD_HOME_LOCK_FREEZE_SESSION=0).\n"
                           "This is not recommended, and might result in unexpected behavior including data loss!");
 
        r = home_lock_luks(h, &setup);
        if (r < 0) {
                if (f)
                        (void) unit_freezer_thaw(f);
 
                return r;
        }
 
        /* Explicitly flush any per-user key from the keyring */
        (void) keyring_flush(h);
 
        log_info("Everything completed.");
        return 1;
}
 
static int home_unlock(UserRecord *h) {
        _cleanup_(home_setup_done) HomeSetup setup = HOME_SETUP_INIT;
        _cleanup_(password_cache_free) PasswordCache cache = {};
        int r;
 
        assert(h);
 
        if (!h->user_name)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "User record incomplete, refusing.");
        if (user_record_storage(h) != USER_LUKS)
                return log_error_errno(SYNTHETIC_ERRNO(ENOTTY), "Unlocking home directories of type '%s' currently not supported.", user_storage_to_string(user_record_storage(h)));
 
        /* Note that we don't check if $HOME is actually mounted, since we want to avoid disk accesses on
         * that mount until we have resumed the device. */
 
        r = user_record_authenticate(h, h, &cache, /* strict_verify= */ false);
        if (r < 0)
                return r;
 
        r = home_unlock_luks(h, &setup, &cache);
        if (r < 0)
                return r;
 
        _cleanup_(unit_freezer_freep) UnitFreezer *f = NULL;
 
        /* We want to thaw the session only after it's safe to access $HOME */
        r = user_session_freezer_new(h->uid, &f);
        if (r > 0)
                r = unit_freezer_thaw(f);
        if (r < 0)
                return r;
 
        log_info("Everything completed.");
        return 1;
}