HALF ECHO LEARN / REFERENCE COLLECTION
v262.2src/home/homework-fscrypt.c
Git blob: aae9d4a196878fbbf0007b384892cb92f6ac59fc
Lines 1001–1475 of 1,475
return r;
r = fscrypt_install_master_key(h, setup, &volume_key);
if (r < 0)
return r;
/* Arm v2 master-key rollback. The duped fd captures the filesystem superblock at this exact
* point, so subsequent bind-mounts, rename(), or close+reopen on setup->root_fd don't affect
* where the rollback lands. We arm into HomeSetup (not a local) and deliberately do *not*
* disarm at the end of this function: setup completing here does not mean the home stays
* active. Only the activation path keeps the home mounted and thus legitimately owns the key
* (home_activate_directory() disarms once the mount is in place); every other caller
* (passwd/update/resize, and all error paths) tears the home back down via home_setup_done(),
* which fires this rollback and removes the transient key from the filesystem keyring. Without
* that, a passwd/update of an *inactive* v2 home would strand its master key filesystem-wide
* until the next deactivation or reboot. */
r = fscrypt_v2_key_undo_arm(&setup->fscrypt_v2_key_undo, setup->root_fd, &setup->fscrypt_key_spec);
if (r < 0)
return r;
/* We'll bind mount the image directory to a new mount point where we'll start adjusting it. Only
* once that's complete we'll move the thing to its final place eventually. */
r = home_unshare_and_mkdir();
if (r < 0)
return r;
r = mount_follow_verbose(LOG_ERR, ip, HOME_RUNTIME_WORK_DIR, NULL, MS_BIND, NULL);
if (r < 0)
return r;
setup->undo_mount = true;
/* Turn off any form of propagation for this */
r = mount_nofollow_verbose(LOG_ERR, NULL, HOME_RUNTIME_WORK_DIR, NULL, MS_PRIVATE, NULL);
if (r < 0)
return r;
/* Adjust MS_SUID and similar flags */
r = mount_nofollow_verbose(LOG_ERR, NULL, HOME_RUNTIME_WORK_DIR, NULL, MS_BIND|MS_REMOUNT|user_record_mount_flags(h), NULL);
if (r < 0)
return r;
safe_close(setup->root_fd);
setup->root_fd = open(HOME_RUNTIME_WORK_DIR, O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOFOLLOW);
if (setup->root_fd < 0)
return log_error_errno(errno, "Failed to open home directory: %m");
/* Note we intentionally leave setup->fscrypt_v2_key_undo armed here: whether the key stays
* installed is decided by the caller (kept on activation, rolled back on teardown). */
return 0;
}
static int fscrypt_slot_set(
int root_fd,
const struct iovec *volume_key,
const char *password,
uint32_t nr) {
_cleanup_free_ char *salt_base64 = NULL, *iv_base64 = NULL,
*encrypted_base64 = NULL, *tag_base64 = NULL,
*joined = NULL;
char label[STRLEN("trusted.fscrypt_slot") + DECIMAL_STR_MAX(nr) + 1];
_cleanup_(EVP_CIPHER_CTX_freep) EVP_CIPHER_CTX *context = NULL;
int r, encrypted_size_out1 = 0, encrypted_size_out2 = 0;
uint8_t salt[FSCRYPT_SLOT_SALT_SIZE], iv[FSCRYPT_SLOT_GCM_IV_SIZE],
tag[FSCRYPT_SLOT_GCM_TAG_SIZE], derived[512 / 8] = {};
_cleanup_free_ void *encrypted = NULL;
const EVP_CIPHER *cc;
size_t encrypted_size;
ssize_t ss;
assert(root_fd >= 0);
assert(iovec_is_set(volume_key));
assert(password);
r = dlopen_libcrypto(LOG_ERR);
if (r < 0)
return r;
r = crypto_random_bytes(salt, sizeof(salt));
if (r < 0)
return log_error_errno(r, "Failed to generate salt: %m");
r = crypto_random_bytes(iv, sizeof(iv));
if (r < 0)
return log_error_errno(r, "Failed to generate IV: %m");
CLEANUP_ERASE(derived);
if (sym_PKCS5_PBKDF2_HMAC(
password, strlen(password),
salt, sizeof(salt),
(int) FSCRYPT_SLOT_PBKDF2_ITERATIONS, sym_EVP_sha512(),
sizeof(derived), derived) != 1)
return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "PBKDF2 failed");
context = sym_EVP_CIPHER_CTX_new();
if (!context)
return log_oom();
/* AES-256-GCM: authenticated encryption with explicit random IV */
assert_se(cc = sym_EVP_aes_256_gcm());
/* We only use the first 256 bit of the derived key */
assert(sizeof(derived) >= (size_t) sym_EVP_CIPHER_get_key_length(cc));
if (sym_EVP_EncryptInit_ex(context, cc, /* impl= */ NULL, /* key= */ NULL, /* iv= */ NULL) != 1)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to initialize encryption context.");
if (sym_EVP_CIPHER_CTX_ctrl(context, EVP_CTRL_GCM_SET_IVLEN, (int) sizeof(iv), /* ptr= */ NULL) != 1)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to set GCM IV length.");
if (sym_EVP_EncryptInit_ex(context, /* type= */ NULL, /* impl= */ NULL, derived, iv) != 1)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to set encryption key/IV.");
if (!ADD_SAFE(&encrypted_size, volume_key->iov_len, (size_t) sym_EVP_CIPHER_get_block_size(cc)))
return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW), "Encrypted buffer size would overflow.");
encrypted = malloc(encrypted_size);
if (!encrypted)
return log_oom();
if (sym_EVP_EncryptUpdate(context, (uint8_t*) encrypted, &encrypted_size_out1, volume_key->iov_base, volume_key->iov_len) != 1)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to encrypt volume key.");
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 volume key.");
assert((size_t) encrypted_size_out1 + (size_t) encrypted_size_out2 <= encrypted_size);
encrypted_size = (size_t) encrypted_size_out1 + (size_t) encrypted_size_out2;
if (sym_EVP_CIPHER_CTX_ctrl(context, EVP_CTRL_GCM_GET_TAG, (int) sizeof(tag), tag) != 1)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to retrieve GCM tag.");
ss = base64mem(salt, sizeof(salt), &salt_base64);
if (ss < 0)
return log_oom();
ss = base64mem(iv, sizeof(iv), &iv_base64);
if (ss < 0)
return log_oom();
ss = base64mem(encrypted, encrypted_size, &encrypted_base64);
if (ss < 0)
return log_oom();
ss = base64mem(tag, sizeof(tag), &tag_base64);
if (ss < 0)
return log_oom();
if (asprintf(&joined, "$v2:%" PRIu32 ":%s:%s:%s:%s",
FSCRYPT_SLOT_PBKDF2_ITERATIONS,
salt_base64, iv_base64, encrypted_base64, tag_base64) < 0)
return log_oom();
xsprintf(label, "trusted.fscrypt_slot%" PRIu32, nr);
if (fsetxattr(root_fd, label, joined, strlen(joined), 0) < 0)
return log_error_errno(errno, "Failed to write xattr %s: %m", label);
log_info("Written key slot %s.", label);
return 0;
}
static int fscrypt_create_policy_v2(
int dir_fd,
const struct iovec *volume_key,
struct fscrypt_key_specifier *ret_spec) {
struct fscrypt_policy_v2 policy_v2 = {
.version = FSCRYPT_POLICY_V2,
.contents_encryption_mode = FSCRYPT_MODE_AES_256_XTS,
.filenames_encryption_mode = FSCRYPT_MODE_AES_256_CTS,
.flags = FSCRYPT_POLICY_FLAGS_PAD_32,
};
int r;
assert(dir_fd >= 0);
assert(iovec_is_set(volume_key));
assert(ret_spec);
/* Derive the identifier locally first so we know what to remove on failure paths below, and so
* fscrypt_v2_ioctl_add can verify the kernel agrees with us. */
r = compute_fscrypt_key_identifier_v2(volume_key, policy_v2.master_key_identifier);
if (r < 0)
return r;
r = fscrypt_v2_ioctl_add(dir_fd, policy_v2.master_key_identifier, volume_key);
if (r < 0)
return r;
if (r == 0) {
/* Kernel doesn't understand v2; caller falls back to v1. Zero-init the out param so
* the success return (>= 0) leaves it in a defined state per coding style. */
*ret_spec = (struct fscrypt_key_specifier) {};
return 0;
}
r = RET_NERRNO(ioctl(dir_fd, FS_IOC_SET_ENCRYPTION_POLICY, &policy_v2));
if (r < 0) {
(void) fscrypt_v2_ioctl_remove(dir_fd, policy_v2.master_key_identifier);
return r;
}
ret_spec->type = FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
memcpy(ret_spec->u.identifier, policy_v2.master_key_identifier, FSCRYPT_KEY_IDENTIFIER_SIZE);
return 1;
}
static int fscrypt_create_policy_v1(
int dir_fd,
const struct iovec *volume_key,
struct fscrypt_key_specifier *ret_spec) {
struct fscrypt_policy_v1 policy_v1 = {
.version = FSCRYPT_POLICY_V1,
.contents_encryption_mode = FSCRYPT_MODE_AES_256_XTS,
.filenames_encryption_mode = FSCRYPT_MODE_AES_256_CTS,
.flags = FSCRYPT_POLICY_FLAGS_PAD_32,
};
key_serial_t serial;
int r;
assert(dir_fd >= 0);
assert(iovec_is_set(volume_key));
assert(ret_spec);
compute_fscrypt_key_descriptor_v1(volume_key, policy_v1.master_key_descriptor);
r = fscrypt_v1_keyring_add(
policy_v1.master_key_descriptor,
volume_key,
KEY_SPEC_THREAD_KEYRING,
&serial);
if (r < 0)
return r;
r = RET_NERRNO(ioctl(dir_fd, FS_IOC_SET_ENCRYPTION_POLICY, &policy_v1));
if (r < 0) {
if (keyctl(KEYCTL_UNLINK, serial, KEY_SPEC_THREAD_KEYRING, 0, 0) < 0)
log_debug_errno(errno, "Failed to roll back fscrypt v1 master key from thread keyring, ignoring: %m");
return r;
}
ret_spec->type = FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR;
memcpy(ret_spec->u.descriptor, policy_v1.master_key_descriptor, FSCRYPT_KEY_DESCRIPTOR_SIZE);
return 0;
}
int home_create_fscrypt(
UserRecord *h,
HomeSetup *setup,
char **effective_passwords,
UserRecord **ret_home) {
_cleanup_(rm_rf_physical_and_freep) char *temporary = NULL;
_cleanup_(user_record_unrefp) UserRecord *new_home = NULL;
_cleanup_(iovec_done_erase) struct iovec volume_key = {};
_cleanup_(fscrypt_v2_key_undo_done) FscryptV2KeyUndo v2_key_undo = FSCRYPT_V2_KEY_UNDO_INIT;
_cleanup_close_ int mount_fd = -EBADF;
_cleanup_free_ char *d = NULL;
uint32_t nr = 0;
const char *ip;
int r;
assert(h);
assert(user_record_storage(h) == USER_FSCRYPT);
assert(setup);
assert(ret_home);
r = dlopen_libcrypto(LOG_ERR);
if (r < 0)
return r;
assert_se(ip = user_record_image_path(h));
r = tempfn_random(ip, "homework", &d);
if (r < 0)
return log_error_errno(r, "Failed to allocate temporary directory: %m");
(void) mkdir_parents(d, 0755);
if (mkdir(d, 0700) < 0)
return log_error_errno(errno, "Failed to create temporary home directory %s: %m", d);
temporary = TAKE_PTR(d); /* Needs to be destroyed now */
r = home_unshare_and_mkdir();
if (r < 0)
return r;
setup->root_fd = open(temporary, O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOFOLLOW);
if (setup->root_fd < 0)
return log_error_errno(errno, "Failed to open temporary home directory: %m");
/* Refuse if the parent directory is already encrypted (we'd inherit its policy). The v1-only
* FS_IOC_GET_ENCRYPTION_POLICY ioctl returns EINVAL on v2-encrypted dirs, so use the helper
* that understands both. */
r = fscrypt_policy_get(setup->root_fd, /* ret_spec= */ NULL);
if (r >= 0)
return log_error_errno(SYNTHETIC_ERRNO(EBUSY), "Parent of %s already encrypted, refusing.", temporary);
if (r == -ENOLINK)
return log_error_errno(r, "File system does not support fscrypt.");
if (r != -ENODATA)
return r;
volume_key.iov_len = 512 / 8;
volume_key.iov_base = malloc(volume_key.iov_len);
if (!volume_key.iov_base)
return log_oom();
r = crypto_random_bytes(volume_key.iov_base, volume_key.iov_len);
if (r < 0)
return log_error_errno(r, "Failed to acquire volume key: %m");
log_info("Generated volume key of size %zu.", volume_key.iov_len);
/* Default to v2 (Linux 5.4+), fall back to v1 only when the kernel/fs truly does not understand
* the FS_IOC_ADD_ENCRYPTION_KEY ioctl (fscrypt_create_policy_v2 returns 0 in that case). Anything
* else (e.g. -EINVAL from SET_POLICY, which can mean "directory not empty" or "conflicting flags")
* is a real failure and must propagate. See the policy version comment at the top of the file for
* why we prefer v2. */
r = fscrypt_create_policy_v2(setup->root_fd, &volume_key, &setup->fscrypt_key_spec);
if (r == 0) {
log_notice("Kernel does not support fscrypt v2 policies, falling back to v1.");
r = fscrypt_create_policy_v1(setup->root_fd, &volume_key, &setup->fscrypt_key_spec);
}
if (r < 0)
return log_error_errno(r, "Failed to set fscrypt policy on directory: %m");
/* Arm v2 master-key rollback using a dup of the temporary-dir fd. The duped fd pins the
* filesystem superblock, so rename(temporary, ip) and the close+reopen via mount_fd below
* have no effect on where the rollback removes the key from. */
r = fscrypt_v2_key_undo_arm(&v2_key_undo, setup->root_fd, &setup->fscrypt_key_spec);
if (r < 0)
return r;
log_info("Encryption policy set (v%i).",
setup->fscrypt_key_spec.type == FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER ? 2 : 1);
STRV_FOREACH(i, effective_passwords) {
r = fscrypt_slot_set(setup->root_fd, &volume_key, *i, nr);
if (r < 0)
return r;
nr++;
}
(void) home_update_quota_classic(h, setup->root_fd, temporary);
r = home_shift_uid(setup->root_fd, HOME_RUNTIME_WORK_DIR, h->uid, h->uid, &mount_fd);
if (r > 0)
setup->undo_mount = true; /* If uidmaps worked we have a mount to undo again */
if (mount_fd >= 0) {
/* If we have established a new mount, then we can use that as new root fd to our home directory. */
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, "Unable to convert mount fd into proper directory fd: %m");
mount_fd = safe_close(mount_fd);
}
r = home_populate(h, setup->root_fd);
if (r < 0)
return r;
r = home_sync_and_statfs(setup->root_fd, NULL);
if (r < 0)
return r;
r = user_record_clone(h, USER_RECORD_LOAD_MASK_SECRET|USER_RECORD_PERMISSIVE, &new_home);
if (r < 0)
return log_error_errno(r, "Failed to clone record: %m");
r = user_record_add_binding(
new_home,
USER_FSCRYPT,
ip,
SD_ID128_NULL,
SD_ID128_NULL,
SD_ID128_NULL,
NULL,
NULL,
UINT64_MAX,
NULL,
NULL,
h->uid,
(gid_t) h->uid);
if (r < 0)
return log_error_errno(r, "Failed to add binding to record: %m");
setup->root_fd = safe_close(setup->root_fd);
r = home_setup_undo_mount(setup, LOG_ERR);
if (r < 0)
return r;
if (rename(temporary, ip) < 0)
return log_error_errno(errno, "Failed to rename %s to %s: %m", temporary, ip);
temporary = mfree(temporary);
/* Note that we do *not* disarm the v2 rollback here: creation leaves the home inactive, and
* unlike v1 keys (which die with this process' keyring) a v2 key sits in the filesystem keyring
* until removed explicitly. Letting the rollback fire on return hence removes the key we only
* needed to populate the home, so that a newly created, inactive home isn't left decryptable
* until the next deactivation or reboot. Activation installs it again. */
log_info("Everything completed.");
*ret_home = TAKE_PTR(new_home);
return 0;
}
int home_passwd_fscrypt(
UserRecord *h,
HomeSetup *setup,
const PasswordCache *cache, /* the passwords acquired via PKCS#11/FIDO2 security tokens */
char **effective_passwords /* new passwords */) {
_cleanup_(iovec_done_erase) struct iovec volume_key = {};
_cleanup_free_ char *xattr_buf = NULL;
uint32_t slot = 0;
int r;
assert(h);
assert(user_record_storage(h) == USER_FSCRYPT);
assert(setup);
r = fscrypt_setup(
cache,
h->password,
setup,
&volume_key);
if (r < 0)
return r;
STRV_FOREACH(p, effective_passwords) {
r = fscrypt_slot_set(setup->root_fd, &volume_key, *p, slot);
if (r < 0)
return r;
slot++;
}
r = flistxattr_malloc(setup->root_fd, &xattr_buf);
if (r < 0)
return log_error_errno(r, "Failed to retrieve xattr list: %m");
NULSTR_FOREACH(xa, xattr_buf) {
const char *nr;
uint32_t z;
/* Check if this xattr has the format 'trusted.fscrypt_slot<nr>' where '<nr>' is a 32-bit unsigned integer */
nr = startswith(xa, "trusted.fscrypt_slot");
if (!nr)
continue;
if (safe_atou32(nr, &z) < 0)
continue;
if (z < slot)
continue;
if (fremovexattr(setup->root_fd, xa) < 0)
if (errno != ENODATA)
log_warning_errno(errno, "Failed to remove xattr %s: %m", xa);
}
return 0;
}