1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
4 #include <openssl/evp.h>
5 #include <openssl/sha.h>
9 #include "errno-util.h"
11 #include "hexdecoct.h"
12 #include "homework-fscrypt.h"
13 #include "homework-mount.h"
14 #include "homework-quota.h"
15 #include "memory-util.h"
16 #include "missing_keyctl.h"
17 #include "missing_syscall.h"
19 #include "mount-util.h"
20 #include "nulstr-util.h"
21 #include "openssl-util.h"
22 #include "parse-util.h"
23 #include "process-util.h"
24 #include "random-util.h"
26 #include "stdio-util.h"
28 #include "tmpfile-util.h"
29 #include "user-util.h"
30 #include "xattr-util.h"
32 static int fscrypt_upload_volume_key(
33 const uint8_t key_descriptor
[static FS_KEY_DESCRIPTOR_SIZE
],
34 const void *volume_key
,
35 size_t volume_key_size
,
38 _cleanup_free_
char *hex
= NULL
;
39 const char *description
;
40 struct fscrypt_key key
;
43 assert(key_descriptor
);
45 assert(volume_key_size
> 0);
47 if (volume_key_size
> sizeof(key
.raw
))
48 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Volume key too long.");
50 hex
= hexmem(key_descriptor
, FS_KEY_DESCRIPTOR_SIZE
);
54 description
= strjoina("fscrypt:", hex
);
56 key
= (struct fscrypt_key
) {
57 .size
= volume_key_size
,
59 memcpy(key
.raw
, volume_key
, volume_key_size
);
63 /* Upload to the kernel */
64 serial
= add_key("logon", description
, &key
, sizeof(key
), where
);
66 return log_error_errno(errno
, "Failed to install master key in keyring: %m");
68 log_info("Uploaded encryption key to kernel.");
73 static void calculate_key_descriptor(
76 uint8_t ret_key_descriptor
[static FS_KEY_DESCRIPTOR_SIZE
]) {
78 uint8_t hashed
[512 / 8] = {}, hashed2
[512 / 8] = {};
80 /* Derive the key descriptor from the volume key via double SHA512, in order to be compatible with e4crypt */
82 assert_se(SHA512(key
, key_size
, hashed
) == hashed
);
83 assert_se(SHA512(hashed
, sizeof(hashed
), hashed2
) == hashed2
);
85 assert_cc(sizeof(hashed2
) >= FS_KEY_DESCRIPTOR_SIZE
);
87 memcpy(ret_key_descriptor
, hashed2
, FS_KEY_DESCRIPTOR_SIZE
);
90 static int fscrypt_slot_try_one(
92 const void *salt
, size_t salt_size
,
93 const void *encrypted
, size_t encrypted_size
,
94 const uint8_t match_key_descriptor
[static FS_KEY_DESCRIPTOR_SIZE
],
95 void **ret_decrypted
, size_t *ret_decrypted_size
) {
98 _cleanup_(EVP_CIPHER_CTX_freep
) EVP_CIPHER_CTX
*context
= NULL
;
99 _cleanup_(erase_and_freep
) void *decrypted
= NULL
;
100 uint8_t key_descriptor
[FS_KEY_DESCRIPTOR_SIZE
];
101 int decrypted_size_out1
, decrypted_size_out2
;
102 uint8_t derived
[512 / 8] = {};
103 size_t decrypted_size
;
104 const EVP_CIPHER
*cc
;
109 assert(salt_size
> 0);
111 assert(encrypted_size
> 0);
112 assert(match_key_descriptor
);
114 /* Our construction is like this:
116 * 1. In each key slot we store a salt value plus the encrypted volume key
118 * 2. Unlocking is via calculating PBKDF2-HMAC-SHA512 of the supplied password (in combination with
119 * the salt), then using the first 256 bit of the hash as key for decrypting the encrypted
120 * volume key in AES256 counter mode.
122 * 3. Writing a password is similar: calculate PBKDF2-HMAC-SHA512 of the supplied password (in
123 * combination with the salt), then encrypt the volume key in AES256 counter mode with the
127 CLEANUP_ERASE(derived
);
129 if (PKCS5_PBKDF2_HMAC(
130 password
, strlen(password
),
132 0xFFFF, EVP_sha512(),
133 sizeof(derived
), derived
) != 1)
134 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
), "PBKDF2 failed");
136 context
= EVP_CIPHER_CTX_new();
140 /* We use AES256 in counter mode */
141 assert_se(cc
= EVP_aes_256_ctr());
143 /* We only use the first half of the derived key */
144 assert(sizeof(derived
) >= (size_t) EVP_CIPHER_key_length(cc
));
146 if (EVP_DecryptInit_ex(context
, cc
, NULL
, derived
, NULL
) != 1)
147 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to initialize decryption context.");
149 decrypted_size
= encrypted_size
+ EVP_CIPHER_key_length(cc
) * 2;
150 decrypted
= malloc(decrypted_size
);
154 if (EVP_DecryptUpdate(context
, (uint8_t*) decrypted
, &decrypted_size_out1
, encrypted
, encrypted_size
) != 1)
155 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to decrypt volume key.");
157 assert((size_t) decrypted_size_out1
<= decrypted_size
);
159 if (EVP_DecryptFinal_ex(context
, (uint8_t*) decrypted_size
+ decrypted_size_out1
, &decrypted_size_out2
) != 1)
160 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to finish decryption of volume key.");
162 assert((size_t) decrypted_size_out1
+ (size_t) decrypted_size_out2
< decrypted_size
);
163 decrypted_size
= (size_t) decrypted_size_out1
+ (size_t) decrypted_size_out2
;
165 calculate_key_descriptor(decrypted
, decrypted_size
, key_descriptor
);
167 if (memcmp(key_descriptor
, match_key_descriptor
, FS_KEY_DESCRIPTOR_SIZE
) != 0)
168 return -ENOANO
; /* don't log here */
170 r
= fscrypt_upload_volume_key(key_descriptor
, decrypted
, decrypted_size
, KEY_SPEC_THREAD_KEYRING
);
175 *ret_decrypted
= TAKE_PTR(decrypted
);
176 if (ret_decrypted_size
)
177 *ret_decrypted_size
= decrypted_size
;
182 static int fscrypt_slot_try_many(
184 const void *salt
, size_t salt_size
,
185 const void *encrypted
, size_t encrypted_size
,
186 const uint8_t match_key_descriptor
[static FS_KEY_DESCRIPTOR_SIZE
],
187 void **ret_decrypted
, size_t *ret_decrypted_size
) {
191 STRV_FOREACH(i
, passwords
) {
192 r
= fscrypt_slot_try_one(*i
, salt
, salt_size
, encrypted
, encrypted_size
, match_key_descriptor
, ret_decrypted
, ret_decrypted_size
);
200 static int fscrypt_setup(
201 const PasswordCache
*cache
,
204 void **ret_volume_key
,
205 size_t *ret_volume_key_size
) {
207 _cleanup_free_
char *xattr_buf
= NULL
;
211 assert(setup
->root_fd
>= 0);
213 r
= flistxattr_malloc(setup
->root_fd
, &xattr_buf
);
215 return log_error_errno(errno
, "Failed to retrieve xattr list: %m");
217 NULSTR_FOREACH(xa
, xattr_buf
) {
218 _cleanup_free_
void *salt
= NULL
, *encrypted
= NULL
;
219 _cleanup_free_
char *value
= NULL
;
220 size_t salt_size
, encrypted_size
;
225 /* Check if this xattr has the format 'trusted.fscrypt_slot<nr>' where '<nr>' is a 32-bit unsigned integer */
226 nr
= startswith(xa
, "trusted.fscrypt_slot");
229 if (safe_atou32(nr
, NULL
) < 0)
232 n
= fgetxattr_malloc(setup
->root_fd
, xa
, &value
);
233 if (n
== -ENODATA
) /* deleted by now? */
236 return log_error_errno(n
, "Failed to read %s xattr: %m", xa
);
238 e
= memchr(value
, ':', n
);
240 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "xattr %s lacks ':' separator: %m", xa
);
242 r
= unbase64mem(value
, e
- value
, &salt
, &salt_size
);
244 return log_error_errno(r
, "Failed to decode salt of %s: %m", xa
);
245 r
= unbase64mem(e
+1, n
- (e
- value
) - 1, &encrypted
, &encrypted_size
);
247 return log_error_errno(r
, "Failed to decode encrypted key of %s: %m", xa
);
250 FOREACH_POINTER(list
, cache
->pkcs11_passwords
, cache
->fido2_passwords
, password
) {
251 r
= fscrypt_slot_try_many(
254 encrypted
, encrypted_size
,
255 setup
->fscrypt_key_descriptor
,
256 ret_volume_key
, ret_volume_key_size
);
267 return log_error_errno(SYNTHETIC_ERRNO(ENOKEY
), "Failed to set up home directory with provided passwords.");
270 int home_setup_fscrypt(
273 const PasswordCache
*cache
) {
275 _cleanup_(erase_and_freep
) void *volume_key
= NULL
;
276 struct fscrypt_policy policy
= {};
277 size_t volume_key_size
= 0;
282 assert(user_record_storage(h
) == USER_FSCRYPT
);
284 assert(setup
->root_fd
< 0);
286 assert_se(ip
= user_record_image_path(h
));
288 setup
->root_fd
= open(ip
, O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
);
289 if (setup
->root_fd
< 0)
290 return log_error_errno(errno
, "Failed to open home directory: %m");
292 if (ioctl(setup
->root_fd
, FS_IOC_GET_ENCRYPTION_POLICY
, &policy
) < 0) {
293 if (errno
== ENODATA
)
294 return log_error_errno(errno
, "Home directory %s is not encrypted.", ip
);
295 if (ERRNO_IS_NOT_SUPPORTED(errno
)) {
296 log_error_errno(errno
, "File system does not support fscrypt: %m");
297 return -ENOLINK
; /* make recognizable */
299 return log_error_errno(errno
, "Failed to acquire encryption policy of %s: %m", ip
);
302 memcpy(setup
->fscrypt_key_descriptor
, policy
.master_key_descriptor
, FS_KEY_DESCRIPTOR_SIZE
);
313 /* Also install the access key in the user's own keyring */
315 if (uid_is_valid(h
->uid
)) {
316 r
= safe_fork("(sd-addkey)",
317 FORK_RESET_SIGNALS
|FORK_CLOSE_ALL_FDS
|FORK_DEATHSIG_SIGTERM
|FORK_LOG
|FORK_WAIT
|FORK_REOPEN_LOG
,
320 return log_error_errno(r
, "Failed install encryption key in user's keyring: %m");
326 gid
= user_record_gid(h
);
327 if (setresgid(gid
, gid
, gid
) < 0) {
328 log_error_errno(errno
, "Failed to change GID to " GID_FMT
": %m", gid
);
332 if (setgroups(0, NULL
) < 0) {
333 log_error_errno(errno
, "Failed to reset auxiliary groups list: %m");
337 if (setresuid(h
->uid
, h
->uid
, h
->uid
) < 0) {
338 log_error_errno(errno
, "Failed to change UID to " UID_FMT
": %m", h
->uid
);
342 r
= fscrypt_upload_volume_key(
343 setup
->fscrypt_key_descriptor
,
346 KEY_SPEC_USER_KEYRING
);
354 /* We'll bind mount the image directory to a new mount point where we'll start adjusting it. Only
355 * once that's complete we'll move the thing to its final place eventually. */
356 r
= home_unshare_and_mkdir();
360 r
= mount_follow_verbose(LOG_ERR
, ip
, HOME_RUNTIME_WORK_DIR
, NULL
, MS_BIND
, NULL
);
364 setup
->undo_mount
= true;
366 /* Turn off any form of propagation for this */
367 r
= mount_nofollow_verbose(LOG_ERR
, NULL
, HOME_RUNTIME_WORK_DIR
, NULL
, MS_PRIVATE
, NULL
);
371 /* Adjust MS_SUID and similar flags */
372 r
= mount_nofollow_verbose(LOG_ERR
, NULL
, HOME_RUNTIME_WORK_DIR
, NULL
, MS_BIND
|MS_REMOUNT
|user_record_mount_flags(h
), NULL
);
376 safe_close(setup
->root_fd
);
377 setup
->root_fd
= open(HOME_RUNTIME_WORK_DIR
, O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
|O_NOFOLLOW
);
378 if (setup
->root_fd
< 0)
379 return log_error_errno(errno
, "Failed to open home directory: %m");
384 static int fscrypt_slot_set(
386 const void *volume_key
,
387 size_t volume_key_size
,
388 const char *password
,
391 _cleanup_free_
char *salt_base64
= NULL
, *encrypted_base64
= NULL
, *joined
= NULL
;
392 char label
[STRLEN("trusted.fscrypt_slot") + DECIMAL_STR_MAX(nr
) + 1];
393 _cleanup_(EVP_CIPHER_CTX_freep
) EVP_CIPHER_CTX
*context
= NULL
;
394 int r
, encrypted_size_out1
, encrypted_size_out2
;
395 uint8_t salt
[64], derived
[512 / 8] = {};
396 _cleanup_free_
void *encrypted
= NULL
;
397 const EVP_CIPHER
*cc
;
398 size_t encrypted_size
;
401 r
= crypto_random_bytes(salt
, sizeof(salt
));
403 return log_error_errno(r
, "Failed to generate salt: %m");
405 CLEANUP_ERASE(derived
);
407 if (PKCS5_PBKDF2_HMAC(
408 password
, strlen(password
),
410 0xFFFF, EVP_sha512(),
411 sizeof(derived
), derived
) != 1)
412 return log_error_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE
), "PBKDF2 failed");
414 context
= EVP_CIPHER_CTX_new();
418 /* We use AES256 in counter mode */
419 cc
= EVP_aes_256_ctr();
421 /* We only use the first half of the derived key */
422 assert(sizeof(derived
) >= (size_t) EVP_CIPHER_key_length(cc
));
424 if (EVP_EncryptInit_ex(context
, cc
, NULL
, derived
, NULL
) != 1)
425 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to initialize encryption context.");
427 encrypted_size
= volume_key_size
+ EVP_CIPHER_key_length(cc
) * 2;
428 encrypted
= malloc(encrypted_size
);
432 if (EVP_EncryptUpdate(context
, (uint8_t*) encrypted
, &encrypted_size_out1
, volume_key
, volume_key_size
) != 1)
433 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to encrypt volume key.");
435 assert((size_t) encrypted_size_out1
<= encrypted_size
);
437 if (EVP_EncryptFinal_ex(context
, (uint8_t*) encrypted_size
+ encrypted_size_out1
, &encrypted_size_out2
) != 1)
438 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to finish encryption of volume key.");
440 assert((size_t) encrypted_size_out1
+ (size_t) encrypted_size_out2
< encrypted_size
);
441 encrypted_size
= (size_t) encrypted_size_out1
+ (size_t) encrypted_size_out2
;
443 ss
= base64mem(salt
, sizeof(salt
), &salt_base64
);
447 ss
= base64mem(encrypted
, encrypted_size
, &encrypted_base64
);
451 joined
= strjoin(salt_base64
, ":", encrypted_base64
);
455 xsprintf(label
, "trusted.fscrypt_slot%" PRIu32
, nr
);
456 if (fsetxattr(root_fd
, label
, joined
, strlen(joined
), 0) < 0)
457 return log_error_errno(errno
, "Failed to write xattr %s: %m", label
);
459 log_info("Written key slot %s.", label
);
464 int home_create_fscrypt(
467 char **effective_passwords
,
468 UserRecord
**ret_home
) {
470 _cleanup_(rm_rf_physical_and_freep
) char *temporary
= NULL
;
471 _cleanup_(user_record_unrefp
) UserRecord
*new_home
= NULL
;
472 _cleanup_(erase_and_freep
) void *volume_key
= NULL
;
473 _cleanup_close_
int mount_fd
= -EBADF
;
474 struct fscrypt_policy policy
= {};
475 size_t volume_key_size
= 512 / 8;
476 _cleanup_free_
char *d
= NULL
;
482 assert(user_record_storage(h
) == USER_FSCRYPT
);
486 assert_se(ip
= user_record_image_path(h
));
488 r
= tempfn_random(ip
, "homework", &d
);
490 return log_error_errno(r
, "Failed to allocate temporary directory: %m");
492 (void) mkdir_parents(d
, 0755);
494 if (mkdir(d
, 0700) < 0)
495 return log_error_errno(errno
, "Failed to create temporary home directory %s: %m", d
);
497 temporary
= TAKE_PTR(d
); /* Needs to be destroyed now */
499 r
= home_unshare_and_mkdir();
503 setup
->root_fd
= open(temporary
, O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
|O_NOFOLLOW
);
504 if (setup
->root_fd
< 0)
505 return log_error_errno(errno
, "Failed to open temporary home directory: %m");
507 if (ioctl(setup
->root_fd
, FS_IOC_GET_ENCRYPTION_POLICY
, &policy
) < 0) {
508 if (ERRNO_IS_NOT_SUPPORTED(errno
)) {
509 log_error_errno(errno
, "File system does not support fscrypt: %m");
510 return -ENOLINK
; /* make recognizable */
512 if (errno
!= ENODATA
)
513 return log_error_errno(errno
, "Failed to get fscrypt policy of directory: %m");
515 return log_error_errno(SYNTHETIC_ERRNO(EBUSY
), "Parent of %s already encrypted, refusing.", d
);
517 volume_key
= malloc(volume_key_size
);
521 r
= crypto_random_bytes(volume_key
, volume_key_size
);
523 return log_error_errno(r
, "Failed to acquire volume key: %m");
525 log_info("Generated volume key of size %zu.", volume_key_size
);
527 policy
= (struct fscrypt_policy
) {
528 .contents_encryption_mode
= FS_ENCRYPTION_MODE_AES_256_XTS
,
529 .filenames_encryption_mode
= FS_ENCRYPTION_MODE_AES_256_CTS
,
530 .flags
= FS_POLICY_FLAGS_PAD_32
,
533 calculate_key_descriptor(volume_key
, volume_key_size
, policy
.master_key_descriptor
);
535 r
= fscrypt_upload_volume_key(policy
.master_key_descriptor
, volume_key
, volume_key_size
, KEY_SPEC_THREAD_KEYRING
);
539 log_info("Uploaded volume key to kernel.");
541 if (ioctl(setup
->root_fd
, FS_IOC_SET_ENCRYPTION_POLICY
, &policy
) < 0)
542 return log_error_errno(errno
, "Failed to set fscrypt policy on directory: %m");
544 log_info("Encryption policy set.");
546 STRV_FOREACH(i
, effective_passwords
) {
547 r
= fscrypt_slot_set(setup
->root_fd
, volume_key
, volume_key_size
, *i
, nr
);
554 (void) home_update_quota_classic(h
, temporary
);
556 r
= home_shift_uid(setup
->root_fd
, HOME_RUNTIME_WORK_DIR
, h
->uid
, h
->uid
, &mount_fd
);
558 setup
->undo_mount
= true; /* If uidmaps worked we have a mount to undo again */
561 /* If we have established a new mount, then we can use that as new root fd to our home directory. */
562 safe_close(setup
->root_fd
);
564 setup
->root_fd
= fd_reopen(mount_fd
, O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
);
565 if (setup
->root_fd
< 0)
566 return log_error_errno(setup
->root_fd
, "Unable to convert mount fd into proper directory fd: %m");
568 mount_fd
= safe_close(mount_fd
);
571 r
= home_populate(h
, setup
->root_fd
);
575 r
= home_sync_and_statfs(setup
->root_fd
, NULL
);
579 r
= user_record_clone(h
, USER_RECORD_LOAD_MASK_SECRET
|USER_RECORD_PERMISSIVE
, &new_home
);
581 return log_error_errno(r
, "Failed to clone record: %m");
583 r
= user_record_add_binding(
598 return log_error_errno(r
, "Failed to add binding to record: %m");
600 setup
->root_fd
= safe_close(setup
->root_fd
);
602 r
= home_setup_undo_mount(setup
, LOG_ERR
);
606 if (rename(temporary
, ip
) < 0)
607 return log_error_errno(errno
, "Failed to rename %s to %s: %m", temporary
, ip
);
609 temporary
= mfree(temporary
);
611 log_info("Everything completed.");
613 *ret_home
= TAKE_PTR(new_home
);
617 int home_passwd_fscrypt(
620 const PasswordCache
*cache
, /* the passwords acquired via PKCS#11/FIDO2 security tokens */
621 char **effective_passwords
/* new passwords */) {
623 _cleanup_(erase_and_freep
) void *volume_key
= NULL
;
624 _cleanup_free_
char *xattr_buf
= NULL
;
625 size_t volume_key_size
= 0;
630 assert(user_record_storage(h
) == USER_FSCRYPT
);
642 STRV_FOREACH(p
, effective_passwords
) {
643 r
= fscrypt_slot_set(setup
->root_fd
, volume_key
, volume_key_size
, *p
, slot
);
650 r
= flistxattr_malloc(setup
->root_fd
, &xattr_buf
);
652 return log_error_errno(errno
, "Failed to retrieve xattr list: %m");
654 NULSTR_FOREACH(xa
, xattr_buf
) {
658 /* Check if this xattr has the format 'trusted.fscrypt_slot<nr>' where '<nr>' is a 32-bit unsigned integer */
659 nr
= startswith(xa
, "trusted.fscrypt_slot");
662 if (safe_atou32(nr
, &z
) < 0)
668 if (fremovexattr(setup
->root_fd
, xa
) < 0)
669 if (errno
!= ENODATA
)
670 log_warning_errno(errno
, "Failed to remove xattr %s: %m", xa
);