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 1001–2000 of 4,048

                iv = malloc(iv_size);
                if (!iv)
                        return log_oom();
 
                r = crypto_random_bytes(iv, iv_size);
                if (r < 0)
                        return log_error_errno(r, "Failed to generate IV: %m");
        }
 
        context = sym_EVP_CIPHER_CTX_new();
        if (!context)
                return log_oom();
 
        if (sym_EVP_EncryptInit_ex(context, cc, NULL, volume_key, iv) != 1)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to initialize encryption context.");
 
        r = sd_json_variant_format(hr->json, 0, &text);
        if (r < 0)
                return log_error_errno(r, "Failed to format user record for LUKS: %m");
 
        text_length = strlen(text);
        encrypted_size = text_length + 2*key_size - 1;
 
        encrypted = malloc(encrypted_size);
        if (!encrypted)
                return log_oom();
 
        if (sym_EVP_EncryptUpdate(context, encrypted, &encrypted_size_out1, (uint8_t*) text, text_length) != 1)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to encrypt JSON record.");
 
        assert((size_t) encrypted_size_out1 <= encrypted_size);
 
        if (sym_EVP_EncryptFinal_ex(context, (uint8_t*) encrypted + encrypted_size_out1, &encrypted_size_out2) != 1)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to finish encryption of JSON record.");
 
        assert((size_t) encrypted_size_out1 + (size_t) encrypted_size_out2 <= encrypted_size);
 
        r = sd_json_buildo(
                        &v,
                        SD_JSON_BUILD_PAIR("type", JSON_BUILD_CONST_STRING("systemd-homed")),
                        SD_JSON_BUILD_PAIR("keyslots", SD_JSON_BUILD_EMPTY_ARRAY),
                        SD_JSON_BUILD_PAIR("record", SD_JSON_BUILD_BASE64(encrypted, encrypted_size_out1 + encrypted_size_out2)),
                        SD_JSON_BUILD_PAIR("iv", SD_JSON_BUILD_BASE64(iv, iv_size)));
        if (r < 0)
                return log_error_errno(r, "Failed to prepare LUKS JSON token object: %m");
 
        r = sd_json_variant_format(v, 0, ret);
        if (r < 0)
                return log_error_errno(r, "Failed to format encrypted user record for LUKS: %m");
 
        return 0;
}
 
int home_store_header_identity_luks(
                UserRecord *h,
                HomeSetup *setup,
                UserRecord *old_home) {
 
        _cleanup_(user_record_unrefp) UserRecord *header_home = NULL;
        _cleanup_free_ char *text = NULL;
        int r;
 
        assert(h);
 
        if (!setup->crypt_device)
                return 0;
 
        assert(setup->volume_key);
 
        /* Let's store the user's identity record in the LUKS2 "token" header data fields, in an encrypted
         * fashion. Why that? If we'd rely on the record being embedded in the payload file system itself we
         * would have to mount the file system before we can validate the JSON record, its signatures and
         * whether it matches what we are looking for. However, kernel file system implementations are
         * generally not ready to be used on untrusted media. Hence let's store the record independently of
         * the file system, so that we can validate it first, and only then mount the file system. To keep
         * things simple we use the same encryption settings for this record as for the file system itself. */
 
        r = user_record_clone(h, USER_RECORD_EXTRACT_EMBEDDED|USER_RECORD_PERMISSIVE, &header_home);
        if (r < 0)
                return log_error_errno(r, "Failed to determine new header record: %m");
 
        if (old_home && user_record_equal(old_home, header_home)) {
                log_debug("Not updating header home record.");
                return 0;
        }
 
        r = format_luks_token_text(setup->crypt_device, header_home, setup->volume_key, &text);
        if (r < 0)
                return r;
 
        for (int token = 0; token < sym_crypt_token_max(CRYPT_LUKS2); token++) {
                crypt_token_info state;
                const char *type;
 
                state = sym_crypt_token_status(setup->crypt_device, token, &type);
                if (state == CRYPT_TOKEN_INACTIVE) /* First unconfigured token, we are done */
                        break;
                if (IN_SET(state, CRYPT_TOKEN_INTERNAL, CRYPT_TOKEN_INTERNAL_UNKNOWN, CRYPT_TOKEN_EXTERNAL))
                        continue; /* Not ours */
                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_set(setup->crypt_device, token, text);
                if (r < 0)
                        return log_error_errno(r, "Failed to set JSON token for slot %i: %m", token);
 
                /* Now, let's free the text so that for all further matching tokens we all crypt_json_token_set()
                 * with a NULL text in order to invalidate the tokens. */
                text = mfree(text);
        }
 
        if (text)
                return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Didn't find any record token to update.");
 
        log_info("Wrote LUKS header user record.");
 
        return 1;
}
 
int run_fitrim(int root_fd) {
        struct fstrim_range range = {
                .len = UINT64_MAX,
        };
 
        /* If discarding is on, discard everything right after mounting, so that the discard setting takes
         * effect on activation. (Also, optionally, trim on logout) */
 
        assert(root_fd >= 0);
 
        if (ioctl(root_fd, FITRIM, &range) < 0) {
                if (ERRNO_IS_NOT_SUPPORTED(errno) || errno == EBADF) {
                        log_debug_errno(errno, "File system does not support FITRIM, not trimming.");
                        return 0;
                }
 
                return log_warning_errno(errno, "Failed to invoke FITRIM, ignoring: %m");
        }
 
        log_info("Discarded unused %s.", FORMAT_BYTES(range.len));
        return 1;
}
 
int run_fallocate(int backing_fd, const struct stat *st) {
        struct stat stbuf;
 
        assert(backing_fd >= 0);
 
        /* If discarding is off, let's allocate the whole image before mounting, so that the setting takes
         * effect on activation */
 
        if (!st) {
                if (fstat(backing_fd, &stbuf) < 0)
                        return log_error_errno(errno, "Failed to fstat(): %m");
 
                st = &stbuf;
        }
 
        if (!S_ISREG(st->st_mode))
                return 0;
 
        if (st->st_blocks >= DIV_ROUND_UP(st->st_size, 512)) {
                log_info("Backing file is fully allocated already.");
                return 0;
        }
 
        if (fallocate(backing_fd, FALLOC_FL_KEEP_SIZE, 0, st->st_size) < 0) {
 
                if (ERRNO_IS_NOT_SUPPORTED(errno)) {
                        log_debug_errno(errno, "fallocate() not supported on file system, ignoring.");
                        return 0;
                }
 
                if (ERRNO_IS_DISK_SPACE(errno)) {
                        log_debug_errno(errno, "Not enough disk space to fully allocate home.");
                        return -ENOSPC; /* make recognizable */
                }
 
                return log_error_errno(errno, "Failed to allocate backing file blocks: %m");
        }
 
        log_info("Allocated additional %s.",
                 FORMAT_BYTES((DIV_ROUND_UP(st->st_size, 512) - st->st_blocks) * 512));
        return 1;
}
 
int run_fallocate_by_path(const char *backing_path) {
        _cleanup_close_ int backing_fd = -EBADF;
 
        backing_fd = open(backing_path, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK);
        if (backing_fd < 0)
                return log_error_errno(errno, "Failed to open '%s' for fallocate(): %m", backing_path);
 
        return run_fallocate(backing_fd, NULL);
}
 
static int lock_image_fd(int image_fd, const char *ip) {
        int r;
 
        /* If the $SYSTEMD_LUKS_LOCK environment variable is set we'll take an exclusive BSD lock on the
         * image file, and send it to our parent. homed will keep it open to ensure no other instance of
         * homed (across the network or such) will also mount the file. */
 
        assert(image_fd >= 0);
        assert(ip);
 
        r = getenv_bool("SYSTEMD_LUKS_LOCK");
        if (r == -ENXIO)
                return 0;
        if (r < 0)
                return log_error_errno(r, "Failed to parse $SYSTEMD_LUKS_LOCK environment variable: %m");
        if (r == 0)
                return 0;
 
        if (flock(image_fd, LOCK_EX|LOCK_NB) < 0) {
 
                if (errno == EAGAIN)
                        log_error_errno(errno, "Image file '%s' already locked, can't use.", ip);
                else
                        log_error_errno(errno, "Failed to lock image file '%s': %m", ip);
 
                return errno != EAGAIN ? -errno : -EADDRINUSE; /* Make error recognizable */
        }
 
        log_info("Successfully locked image file '%s'.", ip);
 
        /* Now send it to our parent to keep safe while the home dir is active */
        r = sd_pid_notify_with_fds(0, false, "SYSTEMD_LUKS_LOCK_FD=1", &image_fd, 1);
        if (r < 0)
                log_warning_errno(r, "Failed to send LUKS lock fd to parent, ignoring: %m");
 
        return 0;
}
 
static int open_image_file(
                UserRecord *h,
                const char *force_image_path,
                struct stat *ret_stat) {
 
        _cleanup_close_ int image_fd = -EBADF;
        struct stat st;
        const char *ip;
        int r;
 
        assert(h || force_image_path);
 
        ip = force_image_path ?: user_record_image_path(h);
 
        image_fd = open(ip, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK);
        if (image_fd < 0)
                return log_error_errno(errno, "Failed to open image file %s: %m", ip);
 
        if (fstat(image_fd, &st) < 0)
                return log_error_errno(errno, "Failed to fstat() image file: %m");
        r = stat_verify_regular_or_block(&st);
        if (r < 0)
                return log_error_errno(r, "Image file '%s' is not a regular file or block device.", ip);
 
        /* Locking block devices doesn't really make sense, as this might interfere with
         * udev's workings, and these locks aren't network propagated anyway, hence not what
         * we are after here. */
        if (S_ISREG(st.st_mode)) {
                r = lock_image_fd(image_fd, ip);
                if (r < 0)
                        return r;
        }
 
        if (ret_stat)
                *ret_stat = st;
 
        return TAKE_FD(image_fd);
}
 
int home_setup_luks(
                UserRecord *h,
                HomeSetupFlags flags,
                const char *force_image_path,
                HomeSetup *setup,
                PasswordCache *cache,
                UserRecord **ret_luks_home) {
 
        sd_id128_t found_partition_uuid, found_fs_uuid = SD_ID128_NULL, found_luks_uuid = SD_ID128_NULL;
        _cleanup_(user_record_unrefp) UserRecord *luks_home = NULL;
        _cleanup_(erase_and_freep) void *volume_key = NULL;
        size_t volume_key_size = 0;
        uint64_t offset, size;
        struct stat st;
        int r;
 
        assert(h);
        assert(setup);
        assert(user_record_storage(h) == USER_LUKS);
 
        r = dlopen_cryptsetup(LOG_DEBUG);
        if (r < 0)
                return r;
 
        r = make_dm_names(h, setup);
        if (r < 0)
                return r;
 
        /* Reuse the image fd if it has already been opened by an earlier step */
        if (setup->image_fd < 0) {
                setup->image_fd = open_image_file(h, force_image_path, &st);
                if (setup->image_fd < 0)
                        return setup->image_fd;
        } else if (fstat(setup->image_fd, &st) < 0)
                return log_error_errno(errno, "Failed to stat image: %m");
 
        if (FLAGS_SET(flags, HOME_SETUP_ALREADY_ACTIVATED)) {
                struct loop_info64 info;
                const char *n;
 
                if (!setup->crypt_device) {
                        r = luks_open(h,
                                      setup,
                                      cache,
                                      &found_luks_uuid,
                                      &volume_key,
                                      &volume_key_size);
                        if (r < 0)
                                return r;
                }
 
                if (ret_luks_home) {
                        r = luks_validate_home_record(setup->crypt_device, h, volume_key, cache, &luks_home);
                        if (r < 0)
                                return r;
                }
 
                n = sym_crypt_get_device_name(setup->crypt_device);
                if (!n)
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to determine backing device for DM %s.", setup->dm_name);
 
                if (!setup->loop) {
                        r = loop_device_open_from_path(n, O_RDWR, LOCK_UN, &setup->loop);
                        if (r < 0)
                                return log_error_errno(r, "Failed to open loopback device %s: %m", n);
                }
 
                if (ioctl(setup->loop->fd, LOOP_GET_STATUS64, &info) < 0) {
                        _cleanup_free_ char *sysfs = NULL;
 
                        if (!IN_SET(errno, ENOTTY, EINVAL))
                                return log_error_errno(errno, "Failed to get block device metrics of %s: %m", n);
 
                        if (fstat(setup->loop->fd, &st) < 0)
                                return log_error_errno(errno, "Failed to stat block device %s: %m", n);
                        assert(S_ISBLK(st.st_mode));
 
                        if (asprintf(&sysfs, "/sys/dev/block/" DEVNUM_FORMAT_STR "/partition", DEVNUM_FORMAT_VAL(st.st_rdev)) < 0)
                                return log_oom();
 
                        if (access(sysfs, F_OK) < 0) {
                                if (errno != ENOENT)
                                        return log_error_errno(errno, "Failed to determine whether %s exists: %m", sysfs);
 
                                offset = 0;
                        } else {
                                _cleanup_free_ char *buffer = NULL;
 
                                if (asprintf(&sysfs, "/sys/dev/block/" DEVNUM_FORMAT_STR "/start", DEVNUM_FORMAT_VAL(st.st_rdev)) < 0)
                                        return log_oom();
 
                                r = read_one_line_file(sysfs, &buffer);
                                if (r < 0)
                                        return log_error_errno(r, "Failed to read partition start offset: %m");
 
                                r = safe_atou64(buffer, &offset);
                                if (r < 0)
                                        return log_error_errno(r, "Failed to parse partition start offset: %m");
 
                                if (offset > UINT64_MAX / 512U)
                                        return log_error_errno(SYNTHETIC_ERRNO(E2BIG), "Offset too large for 64 byte range, refusing.");
 
                                offset *= 512U;
                        }
 
                        size = setup->loop->device_size;
                } else {
#if HAVE_VALGRIND_MEMCHECK_H
                        VALGRIND_MAKE_MEM_DEFINED(&info, sizeof(info));
#endif
 
                        offset = info.lo_offset;
                        size = info.lo_sizelimit;
                }
 
                found_partition_uuid = found_fs_uuid = SD_ID128_NULL;
 
                log_info("Discovered used loopback device %s.", setup->loop->node);
 
                if (setup->root_fd < 0) {
                        setup->root_fd = open(user_record_home_directory(h), O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOFOLLOW);
                        if (setup->root_fd < 0)
                                return log_error_errno(errno, "Failed to open home directory: %m");
                }
        } else {
                _cleanup_free_ char *fstype = NULL, *subdir = NULL;
                const char *ip;
 
                /* When we aren't reopening the home directory we are allocating it fresh, hence the relevant
                 * objects can't be allocated yet. */
                assert(setup->root_fd < 0);
                assert(!setup->crypt_device);
                assert(!setup->loop);
 
                ip = force_image_path ?: user_record_image_path(h);
 
                subdir = path_join(HOME_RUNTIME_WORK_DIR, user_record_user_name_and_realm(h));
                if (!subdir)
                        return log_oom();
 
                r = luks_validate(
                                setup->image_fd,
                                user_record_user_name_and_realm(h),
                                h->partition_uuid,
                                /* if sector size is not specified, select UINT32_MAX, i.e. auto-probe */
                                h->luks_sector_size == UINT64_MAX ? UINT32_MAX : user_record_luks_sector_size(h),
                                &found_partition_uuid,
                                &offset,
                                &size);
                if (r < 0)
                        return log_error_errno(r, "Failed to validate disk label: %m");
 
                /* Everything before this point left the image untouched. We are now starting to make
                 * changes, hence mark the image dirty */
                if (run_mark_dirty(setup->image_fd, true) > 0)
                        setup->do_mark_clean = true;
 
                if (!FLAGS_SET(flags, HOME_SETUP_LUKS_DONT_FALLOCATE) && !user_record_luks_discard(h)) {
                        r = run_fallocate(setup->image_fd, &st);
                        if (r < 0)
                                return r;
                }
 
                /* Before we make the loop device, make sure offset is zero & we are using the full partition
                 * If our offset is not zero, loop_device_make will create a loop device on top of the block device */
                if (S_ISBLK(st.st_mode))
                        assert(offset == 0 && size == UINT64_MAX);
 
                r = loop_device_make(
                                setup->image_fd,
                                O_RDWR,
                                offset,
                                size,
                                h->luks_sector_size == UINT64_MAX ? UINT32_MAX : user_record_luks_sector_size(h), /* if sector size is not specified, select UINT32_MAX, i.e. auto-probe */
                                /* loop_flags= */ 0,
                                LOCK_UN,
                                &setup->loop);
                if (r == -ENOENT) {
                        log_error_errno(r, "Loopback block device support is not available on this system.");
                        return -ENOLINK; /* make recognizable */
                }
                if (r < 0)
                        return log_error_errno(r, "Failed to allocate loopback context: %m");
 
                log_info("Setting up loopback device %s completed.", setup->loop->node ?: ip);
 
                r = luks_setup(h,
                               setup->loop->node ?: ip,
                               setup->dm_name,
                               h->luks_uuid,
                               h->luks_cipher,
                               h->luks_cipher_mode,
                               h->luks_volume_key_size,
                               cache,
                               user_record_luks_discard(h) || user_record_luks_offline_discard(h),
                               &setup->crypt_device,
                               &found_luks_uuid,
                               &volume_key,
                               &volume_key_size,
                               &setup->key_serial);
                if (r < 0)
                        return r;
 
                setup->undo_dm = true;
 
                if (ret_luks_home) {
                        r = luks_validate_home_record(setup->crypt_device, h, volume_key, cache, &luks_home);
                        if (r < 0)
                                return r;
                }
 
                r = fs_validate(setup->dm_node, h->file_system_uuid, &fstype, &found_fs_uuid);
                if (r < 0)
                        return r;
 
                r = run_fsck(setup->dm_node, fstype);
                if (r < 0)
                        return r;
 
                r = home_unshare_and_mount(setup->dm_node, fstype, user_record_luks_discard(h), user_record_mount_flags(h), h->luks_extra_mount_options);
                if (r < 0)
                        return r;
 
                setup->undo_mount = true;
 
                setup->root_fd = open(subdir, O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOFOLLOW);
                if (setup->root_fd < 0)
                        return log_error_errno(errno, "Failed to open home directory: %m");
 
                if (user_record_luks_discard(h))
                        (void) run_fitrim(setup->root_fd);
 
                setup->do_offline_fitrim = user_record_luks_offline_discard(h);
                setup->do_offline_fallocate = !setup->do_offline_fitrim;
                setup->tolerate_offline_fallocate_enospc = FLAGS_SET(flags, HOME_SETUP_LUKS_DONT_FALLOCATE);
        }
 
        if (!sd_id128_is_null(found_partition_uuid))
                setup->found_partition_uuid = found_partition_uuid;
        if (!sd_id128_is_null(found_luks_uuid))
                setup->found_luks_uuid = found_luks_uuid;
        if (!sd_id128_is_null(found_fs_uuid))
                setup->found_fs_uuid = found_fs_uuid;
 
        setup->partition_offset = offset;
        setup->partition_size = size;
 
        if (volume_key) {
                erase_and_free(setup->volume_key);
                setup->volume_key = TAKE_PTR(volume_key);
                setup->volume_key_size = volume_key_size;
        }
 
        if (ret_luks_home)
                *ret_luks_home = TAKE_PTR(luks_home);
 
        return 0;
}
 
static void print_size_summary(uint64_t host_size, uint64_t encrypted_size, const struct statfs *sfs) {
        assert(sfs);
 
        log_info("Image size is %s, file system size is %s, file system payload size is %s, file system free is %s.",
                 FORMAT_BYTES(host_size),
                 FORMAT_BYTES(encrypted_size),
                 FORMAT_BYTES((uint64_t) sfs->f_blocks * (uint64_t) sfs->f_frsize),
                 FORMAT_BYTES((uint64_t) sfs->f_bfree * (uint64_t) sfs->f_frsize));
}
 
static int home_auto_grow_luks(
                UserRecord *h,
                HomeSetup *setup,
                PasswordCache *cache) {
 
        struct statfs sfs;
 
        assert(h);
        assert(setup);
 
        if (!IN_SET(user_record_auto_resize_mode(h), AUTO_RESIZE_GROW, AUTO_RESIZE_SHRINK_AND_GROW))
                return 0;
 
        assert(setup->root_fd >= 0);
 
        if (fstatfs(setup->root_fd, &sfs) < 0)
                return log_error_errno(errno, "Failed to statfs home directory: %m");
 
        if (!fs_can_online_shrink_and_grow(sfs.f_type)) {
                log_debug("Not auto-grow file system, since selected file system cannot do both online shrink and grow.");
                return 0;
        }
 
        log_debug("Initiating auto-grow...");
 
        return home_resize_luks(
                        h,
                        HOME_SETUP_ALREADY_ACTIVATED|
                        HOME_SETUP_RESIZE_DONT_SYNC_IDENTITIES|
                        HOME_SETUP_RESIZE_DONT_SHRINK|
                        HOME_SETUP_RESIZE_DONT_UNDO,
                        setup,
                        cache,
                        NULL);
}
 
int home_activate_luks(
                UserRecord *h,
                HomeSetupFlags flags,
                HomeSetup *setup,
                PasswordCache *cache,
                UserRecord **ret_home) {
 
        _cleanup_(user_record_unrefp) UserRecord *new_home = NULL, *luks_home_record = NULL;
        uint64_t host_size, encrypted_size;
        const char *hdo, *hd;
        struct statfs sfs;
        int r;
 
        assert(h);
        assert(user_record_storage(h) == USER_LUKS);
        assert(setup);
        assert(ret_home);
 
        r = dlopen_cryptsetup(LOG_DEBUG);
        if (r < 0)
                return r;
 
        assert_se(hdo = user_record_home_directory(h));
        hd = strdupa_safe(hdo); /* copy the string out, since it might change later in the home record object */
 
        r = home_get_state_luks(h, setup);
        if (r < 0)
                return r;
        if (r > 0)
                return log_error_errno(SYNTHETIC_ERRNO(EEXIST), "Device mapper device %s already exists, refusing.", setup->dm_node);
 
        r = home_setup_luks(
                        h,
                        flags,
                        NULL,
                        setup,
                        cache,
                        &luks_home_record);
        if (r < 0)
                return r;
 
        r = home_auto_grow_luks(h, setup, cache);
        if (r < 0)
                return r;
 
        r = block_get_size_by_fd(setup->loop->fd, &host_size);
        if (r < 0)
                return log_error_errno(r, "Failed to get loopback block device size: %m");
 
        r = block_get_size_by_path(setup->dm_node, &encrypted_size);
        if (r < 0)
                return log_error_errno(r, "Failed to get LUKS block device size: %m");
 
        r = home_refresh(
                        h,
                        flags,
                        setup,
                        luks_home_record,
                        cache,
                        &sfs,
                        &new_home);
        if (r < 0)
                return r;
 
        r = home_extend_embedded_identity(new_home, h, setup);
        if (r < 0)
                return r;
 
        setup->root_fd = safe_close(setup->root_fd);
 
        r = home_move_mount(user_record_user_name_and_realm(h), hd);
        if (r < 0)
                return r;
 
        setup->undo_mount = false;
        setup->do_offline_fitrim = false;
 
        loop_device_relinquish(setup->loop);
 
        r = sym_crypt_deactivate_by_name(NULL, setup->dm_name, CRYPT_DEACTIVATE_DEFERRED);
        if (r < 0)
                log_warning_errno(r, "Failed to relinquish DM device, ignoring: %m");
 
        setup->undo_dm = false;
        setup->do_offline_fallocate = false;
        setup->do_mark_clean = false;
        setup->do_drop_caches = false;
        TAKE_KEY_SERIAL(setup->key_serial); /* Leave key in kernel keyring */
 
        log_info("Activation completed.");
 
        print_size_summary(host_size, encrypted_size, &sfs);
 
        *ret_home = TAKE_PTR(new_home);
        return 1;
}
 
int home_deactivate_luks(UserRecord *h, HomeSetup *setup) {
        bool we_detached = false;
        int r;
 
        assert(h);
        assert(setup);
 
        /* Note that the DM device and loopback device are set to auto-detach, hence strictly speaking we
         * don't have to explicitly have to detach them. However, we do that nonetheless (in case of the DM
         * device), to avoid races: by explicitly detaching them we know when the detaching is complete. We
         * don't bother about the loopback device because unlike the DM device it doesn't have a fixed
         * name. */
 
        if (!setup->crypt_device) {
                r = acquire_open_luks_device(h, setup, /* graceful= */ true);
                if (r < 0)
                        return log_error_errno(r, "Failed to initialize cryptsetup context for %s: %m", setup->dm_name);
                if (r == 0)
                        log_debug("LUKS device %s has already been detached.", setup->dm_name);
        }
 
        if (setup->crypt_device) {
                log_info("Discovered used LUKS device %s.", setup->dm_node);
 
                cryptsetup_enable_logging(setup->crypt_device);
 
                r = sym_crypt_deactivate_by_name(setup->crypt_device, setup->dm_name, 0);
                if (ERRNO_IS_NEG_DEVICE_ABSENT(r) || r == -EINVAL)
                        log_debug_errno(r, "LUKS device %s is already detached.", setup->dm_node);
                else if (r < 0)
                        return log_info_errno(r, "LUKS device %s couldn't be deactivated: %m", setup->dm_node);
                else {
                        log_info("LUKS device detaching completed.");
                        we_detached = true;
                }
        }
 
        (void) wait_for_block_device_gone(setup, USEC_PER_SEC * 30);
        setup->undo_dm = false;
 
        if (user_record_luks_offline_discard(h))
                log_debug("Not allocating on logout.");
        else
                (void) run_fallocate_by_path(user_record_image_path(h));
 
        run_mark_dirty_by_path(user_record_image_path(h), false);
        return we_detached;
}
 
int home_trim_luks(UserRecord *h, HomeSetup *setup) {
        assert(h);
        assert(setup);
        assert(setup->root_fd >= 0);
 
        if (!user_record_luks_offline_discard(h)) {
                log_debug("Not trimming on logout.");
                return 0;
        }
 
        (void) run_fitrim(setup->root_fd);
        return 0;
}
 
static struct crypt_pbkdf_type* build_good_pbkdf(struct crypt_pbkdf_type *buffer, UserRecord *hr) {
        assert(buffer);
        assert(hr);
 
        bool benchmark = user_record_luks_pbkdf_force_iterations(hr) == UINT64_MAX;
 
        *buffer = (struct crypt_pbkdf_type) {
                .hash = user_record_luks_pbkdf_hash_algorithm(hr),
                .type = user_record_luks_pbkdf_type(hr),
                .time_ms = benchmark ? user_record_luks_pbkdf_time_cost_usec(hr) / USEC_PER_MSEC : 0,
                .iterations = benchmark ? 0 : user_record_luks_pbkdf_force_iterations(hr),
                .max_memory_kb = user_record_luks_pbkdf_memory_cost(hr) / 1024,
                .parallel_threads = user_record_luks_pbkdf_parallel_threads(hr),
                .flags = benchmark ? 0 : CRYPT_PBKDF_NO_BENCHMARK,
        };
 
        return buffer;
}
 
static struct crypt_pbkdf_type* build_minimal_pbkdf(struct crypt_pbkdf_type *buffer, UserRecord *hr) {
        assert(buffer);
        assert(hr);
 
        /* For PKCS#11 derived keys (which are generated randomly and are of high quality already) we use a
         * minimal PBKDF and CRYPT_PBKDF_NO_BENCHMARK flag to skip benchmark. */
        *buffer = (struct crypt_pbkdf_type) {
                .hash = user_record_luks_pbkdf_hash_algorithm(hr),
                .type = CRYPT_KDF_PBKDF2,
                .iterations = 1000, /* recommended minimum count for pbkdf2
                                     * according to NIST SP 800-132, ch. 5.2 */
                .flags = CRYPT_PBKDF_NO_BENCHMARK
        };
 
        return buffer;
}
 
static int luks_format(
                const char *node,
                const char *dm_name,
                sd_id128_t uuid,
                const char *label,
                const PasswordCache *cache,
                char **effective_passwords,
                bool discard,
                uint64_t sector_size,
                UserRecord *hr,
                struct crypt_device **ret) {
 
        _cleanup_(user_record_unrefp) UserRecord *reduced = NULL;
        _cleanup_(crypt_freep) struct crypt_device *cd = NULL;
        _cleanup_(erase_and_freep) void *volume_key = NULL;
        struct crypt_pbkdf_type good_pbkdf, minimal_pbkdf;
        _cleanup_free_ char *text = NULL;
        size_t volume_key_size;
        int slot = 0, r;
 
        assert(node);
        assert(dm_name);
        assert(hr);
        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);
 
        /* Normally we'd, just leave volume key generation to libcryptsetup. However, we can't, since we
         * can't extract the volume key from the library again, but we need it in order to encrypt the JSON
         * record. Hence, let's generate it on our own, so that we can keep track of it. */
 
        volume_key_size = user_record_luks_volume_key_size(hr);
        volume_key = malloc(volume_key_size);
        if (!volume_key)
                return log_oom();
 
        r = crypto_random_bytes(volume_key, volume_key_size);
        if (r < 0)
                return log_error_errno(r, "Failed to generate volume key: %m");
 
        /* Increase the metadata space to 4M, the largest LUKS2 supports */
        r = sym_crypt_set_metadata_size(cd, 4096U*1024U, 0);
        if (r < 0)
                return log_error_errno(r, "Failed to change LUKS2 metadata size: %m");
 
        build_good_pbkdf(&good_pbkdf, hr);
        build_minimal_pbkdf(&minimal_pbkdf, hr);
 
        r = sym_crypt_format(
                        cd,
                        CRYPT_LUKS2,
                        user_record_luks_cipher(hr),
                        user_record_luks_cipher_mode(hr),
                        SD_ID128_TO_UUID_STRING(uuid),
                        volume_key,
                        volume_key_size,
                        &(struct crypt_params_luks2) {
                                .label = label,
                                .subsystem = "systemd-home",
                                .sector_size = sector_size, /* sector-size of 0 is auto for libcryptsetup */
                                .pbkdf = &good_pbkdf,
                        });
        if (r < 0)
                return log_error_errno(r, "Failed to format LUKS image: %m");
 
        log_info("LUKS formatting completed.");
 
        STRV_FOREACH(pp, effective_passwords) {
 
                if (password_cache_contains(cache, *pp)) { /* is this a fido2 or pkcs11 password? */
                        log_debug("Using minimal PBKDF for slot %i", slot);
                        r = sym_crypt_set_pbkdf_type(cd, &minimal_pbkdf);
                } else {
                        log_debug("Using good PBKDF for slot %i", slot);
                        r = sym_crypt_set_pbkdf_type(cd, &good_pbkdf);
                }
                if (r < 0)
                        return log_error_errno(r, "Failed to tweak PBKDF for slot %i: %m", slot);
 
                r = sym_crypt_keyslot_add_by_volume_key(
                                cd,
                                slot,
                                volume_key,
                                volume_key_size,
                                *pp,
                                strlen(*pp));
                if (r < 0)
                        return log_error_errno(r, "Failed to set up LUKS password for slot %i: %m", slot);
 
                log_info("Writing password to LUKS keyslot %i completed.", slot);
                slot++;
        }
 
        r = sym_crypt_activate_by_volume_key(
                        cd,
                        dm_name,
                        volume_key,
                        volume_key_size,
                        discard ? CRYPT_ACTIVATE_ALLOW_DISCARDS : 0);
        if (r < 0)
                return log_error_errno(r, "Failed to activate LUKS superblock: %m");
 
        log_info("LUKS activation by volume key succeeded.");
 
        r = user_record_clone(hr, USER_RECORD_EXTRACT_EMBEDDED|USER_RECORD_PERMISSIVE, &reduced);
        if (r < 0)
                return log_error_errno(r, "Failed to prepare home record for LUKS: %m");
 
        r = format_luks_token_text(cd, reduced, volume_key, &text);
        if (r < 0)
                return r;
 
        r = sym_crypt_token_json_set(cd, CRYPT_ANY_TOKEN, text);
        if (r < 0)
                return log_error_errno(r, "Failed to set LUKS JSON token: %m");
 
        log_info("Writing user record as LUKS token completed.");
 
        if (ret)
                *ret = TAKE_PTR(cd);
 
        return 0;
}
 
static int make_partition_table(
                int fd,
                uint32_t sector_size,
                const char *label,
                sd_id128_t uuid,
                uint64_t *ret_offset,
                uint64_t *ret_size,
                sd_id128_t *ret_disk_uuid) {
 
        _cleanup_(fdisk_unref_partitionp) struct fdisk_partition *p = NULL, *q = NULL;
        _cleanup_(fdisk_unref_parttypep) struct fdisk_parttype *t = NULL;
        _cleanup_(fdisk_unref_contextp) struct fdisk_context *c = NULL;
        uint64_t offset, size, first_lba, start, last_lba, end, fdisk_sector_size;
        sd_id128_t disk_uuid;
        int r;
 
        assert(fd >= 0);
        assert(label);
        assert(ret_offset);
        assert(ret_size);
        assert(ret_disk_uuid);
 
        t = sym_fdisk_new_parttype();
        if (!t)
                return log_oom();
 
        r = sym_fdisk_parttype_set_typestr(t, SD_GPT_USER_HOME_STR);
        if (r < 0)
                return log_error_errno(r, "Failed to initialize partition type: %m");
 
        r = fdisk_new_context_at(fd, /* path= */ NULL, /* read_only= */ false, sector_size, &c);
        if (r < 0)
                return log_error_errno(r, "Failed to open device: %m");
 
        r = sym_fdisk_create_disklabel(c, "gpt");
        if (r < 0)
                return log_error_errno(r, "Failed to create GPT disk label: %m");
 
        p = sym_fdisk_new_partition();
        if (!p)
                return log_oom();
 
        r = sym_fdisk_partition_set_type(p, t);
        if (r < 0)
                return log_error_errno(r, "Failed to set partition type: %m");
 
        r = sym_fdisk_partition_partno_follow_default(p, 1);
        if (r < 0)
                return log_error_errno(r, "Failed to place partition at first free partition index: %m");
 
        /* Use same sector size as the fdisk context when converting to bytes */
        fdisk_sector_size = sym_fdisk_get_sector_size(c);
        assert(fdisk_sector_size > 0);
 
        first_lba = sym_fdisk_get_first_lba(c); /* Boundary where usable space starts */
        assert(first_lba <= UINT64_MAX / fdisk_sector_size);
        start = DISK_SIZE_ROUND_UP(first_lba * fdisk_sector_size);
 
        log_debug("Starting partition at offset %" PRIu64, start);
 
        if (start == UINT64_MAX)
                return log_error_errno(SYNTHETIC_ERRNO(ERANGE), "Overflow while rounding up start LBA.");
 
        last_lba = sym_fdisk_get_last_lba(c); /* One sector before boundary where usable space ends */
        assert(last_lba < UINT64_MAX / fdisk_sector_size);
        end = DISK_SIZE_ROUND_DOWN((last_lba + 1) * fdisk_sector_size);
 
        if (end <= start)
                return log_error_errno(SYNTHETIC_ERRNO(ERANGE), "Resulting partition size zero or negative.");
 
        r = sym_fdisk_partition_set_start(p, start / fdisk_sector_size);
        if (r < 0)
                return log_error_errno(r, "Failed to place partition at offset %" PRIu64 ": %m", start);
 
        r = sym_fdisk_partition_set_size(p, (end - start) / fdisk_sector_size);
        if (r < 0)
                return log_error_errno(r, "Failed to end partition at offset %" PRIu64 ": %m", end);
 
        r = sym_fdisk_partition_set_name(p, label);
        if (r < 0)
                return log_error_errno(r, "Failed to set partition name: %m");
 
        r = sym_fdisk_partition_set_uuid(p, SD_ID128_TO_UUID_STRING(uuid));
        if (r < 0)
                return log_error_errno(r, "Failed to set partition UUID: %m");
 
        r = sym_fdisk_add_partition(c, p, NULL);
        if (r < 0)
                return log_error_errno(r, "Failed to add partition: %m");
 
        r = sym_fdisk_write_disklabel(c);
        if (r < 0)
                return log_error_errno(r, "Failed to write disk label: %m");
 
        r = fdisk_get_disklabel_id_as_id128(c, &disk_uuid);
        if (r < 0)