1 // SPDX-License-Identifier: GPL-2.0
3 * Filesystem-level keyring for fscrypt
5 * Copyright 2019 Google LLC
9 * This file implements management of fscrypt master keys in the
10 * filesystem-level keyring, including the ioctls:
12 * - FS_IOC_ADD_ENCRYPTION_KEY
13 * - FS_IOC_REMOVE_ENCRYPTION_KEY
14 * - FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS
15 * - FS_IOC_GET_ENCRYPTION_KEY_STATUS
17 * See the "User API" section of Documentation/filesystems/fscrypt.rst for more
18 * information about these ioctls.
21 #include <crypto/skcipher.h>
22 #include <linux/key-type.h>
23 #include <linux/random.h>
24 #include <linux/seq_file.h>
26 #include "fscrypt_private.h"
28 static void wipe_master_key_secret(struct fscrypt_master_key_secret *secret)
30 fscrypt_destroy_hkdf(&secret->hkdf);
31 memzero_explicit(secret, sizeof(*secret));
34 static void move_master_key_secret(struct fscrypt_master_key_secret *dst,
35 struct fscrypt_master_key_secret *src)
37 memcpy(dst, src, sizeof(*dst));
38 memzero_explicit(src, sizeof(*src));
41 static void free_master_key(struct fscrypt_master_key *mk)
45 wipe_master_key_secret(&mk->mk_secret);
47 for (i = 0; i <= __FSCRYPT_MODE_MAX; i++) {
48 crypto_free_skcipher(mk->mk_direct_keys[i]);
49 crypto_free_skcipher(mk->mk_iv_ino_lblk_64_keys[i]);
50 crypto_free_skcipher(mk->mk_iv_ino_lblk_32_keys[i]);
53 key_put(mk->mk_users);
57 static inline bool valid_key_spec(const struct fscrypt_key_specifier *spec)
61 return master_key_spec_len(spec) != 0;
64 static int fscrypt_key_instantiate(struct key *key,
65 struct key_preparsed_payload *prep)
67 key->payload.data[0] = (struct fscrypt_master_key *)prep->data;
71 static void fscrypt_key_destroy(struct key *key)
73 free_master_key(key->payload.data[0]);
76 static void fscrypt_key_describe(const struct key *key, struct seq_file *m)
78 seq_puts(m, key->description);
80 if (key_is_positive(key)) {
81 const struct fscrypt_master_key *mk = key->payload.data[0];
83 if (!is_master_key_secret_present(&mk->mk_secret))
84 seq_puts(m, ": secret removed");
89 * Type of key in ->s_master_keys. Each key of this type represents a master
90 * key which has been added to the filesystem. Its payload is a
91 * 'struct fscrypt_master_key'. The "." prefix in the key type name prevents
92 * users from adding keys of this type via the keyrings syscalls rather than via
93 * the intended method of FS_IOC_ADD_ENCRYPTION_KEY.
95 static struct key_type key_type_fscrypt = {
97 .instantiate = fscrypt_key_instantiate,
98 .destroy = fscrypt_key_destroy,
99 .describe = fscrypt_key_describe,
102 static int fscrypt_user_key_instantiate(struct key *key,
103 struct key_preparsed_payload *prep)
106 * We just charge FSCRYPT_MAX_KEY_SIZE bytes to the user's key quota for
107 * each key, regardless of the exact key size. The amount of memory
108 * actually used is greater than the size of the raw key anyway.
110 return key_payload_reserve(key, FSCRYPT_MAX_KEY_SIZE);
113 static void fscrypt_user_key_describe(const struct key *key, struct seq_file *m)
115 seq_puts(m, key->description);
119 * Type of key in ->mk_users. Each key of this type represents a particular
120 * user who has added a particular master key.
122 * Note that the name of this key type really should be something like
123 * ".fscrypt-user" instead of simply ".fscrypt". But the shorter name is chosen
124 * mainly for simplicity of presentation in /proc/keys when read by a non-root
125 * user. And it is expected to be rare that a key is actually added by multiple
126 * users, since users should keep their encryption keys confidential.
128 static struct key_type key_type_fscrypt_user = {
130 .instantiate = fscrypt_user_key_instantiate,
131 .describe = fscrypt_user_key_describe,
134 /* Search ->s_master_keys or ->mk_users */
135 static struct key *search_fscrypt_keyring(struct key *keyring,
136 struct key_type *type,
137 const char *description)
140 * We need to mark the keyring reference as "possessed" so that we
141 * acquire permission to search it, via the KEY_POS_SEARCH permission.
143 key_ref_t keyref = make_key_ref(keyring, true /* possessed */);
145 keyref = keyring_search(keyref, type, description, false);
146 if (IS_ERR(keyref)) {
147 if (PTR_ERR(keyref) == -EAGAIN || /* not found */
148 PTR_ERR(keyref) == -EKEYREVOKED) /* recently invalidated */
149 keyref = ERR_PTR(-ENOKEY);
150 return ERR_CAST(keyref);
152 return key_ref_to_ptr(keyref);
155 #define FSCRYPT_FS_KEYRING_DESCRIPTION_SIZE \
156 (CONST_STRLEN("fscrypt-") + sizeof_field(struct super_block, s_id))
158 #define FSCRYPT_MK_DESCRIPTION_SIZE (2 * FSCRYPT_KEY_IDENTIFIER_SIZE + 1)
160 #define FSCRYPT_MK_USERS_DESCRIPTION_SIZE \
161 (CONST_STRLEN("fscrypt-") + 2 * FSCRYPT_KEY_IDENTIFIER_SIZE + \
162 CONST_STRLEN("-users") + 1)
164 #define FSCRYPT_MK_USER_DESCRIPTION_SIZE \
165 (2 * FSCRYPT_KEY_IDENTIFIER_SIZE + CONST_STRLEN(".uid.") + 10 + 1)
167 static void format_fs_keyring_description(
168 char description[FSCRYPT_FS_KEYRING_DESCRIPTION_SIZE],
169 const struct super_block *sb)
171 sprintf(description, "fscrypt-%s", sb->s_id);
174 static void format_mk_description(
175 char description[FSCRYPT_MK_DESCRIPTION_SIZE],
176 const struct fscrypt_key_specifier *mk_spec)
178 sprintf(description, "%*phN",
179 master_key_spec_len(mk_spec), (u8 *)&mk_spec->u);
182 static void format_mk_users_keyring_description(
183 char description[FSCRYPT_MK_USERS_DESCRIPTION_SIZE],
184 const u8 mk_identifier[FSCRYPT_KEY_IDENTIFIER_SIZE])
186 sprintf(description, "fscrypt-%*phN-users",
187 FSCRYPT_KEY_IDENTIFIER_SIZE, mk_identifier);
190 static void format_mk_user_description(
191 char description[FSCRYPT_MK_USER_DESCRIPTION_SIZE],
192 const u8 mk_identifier[FSCRYPT_KEY_IDENTIFIER_SIZE])
195 sprintf(description, "%*phN.uid.%u", FSCRYPT_KEY_IDENTIFIER_SIZE,
196 mk_identifier, __kuid_val(current_fsuid()));
199 /* Create ->s_master_keys if needed. Synchronized by fscrypt_add_key_mutex. */
200 static int allocate_filesystem_keyring(struct super_block *sb)
202 char description[FSCRYPT_FS_KEYRING_DESCRIPTION_SIZE];
205 if (sb->s_master_keys)
208 format_fs_keyring_description(description, sb);
209 keyring = keyring_alloc(description, GLOBAL_ROOT_UID, GLOBAL_ROOT_GID,
210 current_cred(), KEY_POS_SEARCH |
211 KEY_USR_SEARCH | KEY_USR_READ | KEY_USR_VIEW,
212 KEY_ALLOC_NOT_IN_QUOTA, NULL, NULL);
214 return PTR_ERR(keyring);
216 /* Pairs with READ_ONCE() in fscrypt_find_master_key() */
217 smp_store_release(&sb->s_master_keys, keyring);
221 void fscrypt_sb_free(struct super_block *sb)
223 key_put(sb->s_master_keys);
224 sb->s_master_keys = NULL;
228 * Find the specified master key in ->s_master_keys.
229 * Returns ERR_PTR(-ENOKEY) if not found.
231 struct key *fscrypt_find_master_key(struct super_block *sb,
232 const struct fscrypt_key_specifier *mk_spec)
235 char description[FSCRYPT_MK_DESCRIPTION_SIZE];
237 /* pairs with smp_store_release() in allocate_filesystem_keyring() */
238 keyring = READ_ONCE(sb->s_master_keys);
240 return ERR_PTR(-ENOKEY); /* No keyring yet, so no keys yet. */
242 format_mk_description(description, mk_spec);
243 return search_fscrypt_keyring(keyring, &key_type_fscrypt, description);
246 static int allocate_master_key_users_keyring(struct fscrypt_master_key *mk)
248 char description[FSCRYPT_MK_USERS_DESCRIPTION_SIZE];
251 format_mk_users_keyring_description(description,
252 mk->mk_spec.u.identifier);
253 keyring = keyring_alloc(description, GLOBAL_ROOT_UID, GLOBAL_ROOT_GID,
254 current_cred(), KEY_POS_SEARCH |
255 KEY_USR_SEARCH | KEY_USR_READ | KEY_USR_VIEW,
256 KEY_ALLOC_NOT_IN_QUOTA, NULL, NULL);
258 return PTR_ERR(keyring);
260 mk->mk_users = keyring;
265 * Find the current user's "key" in the master key's ->mk_users.
266 * Returns ERR_PTR(-ENOKEY) if not found.
268 static struct key *find_master_key_user(struct fscrypt_master_key *mk)
270 char description[FSCRYPT_MK_USER_DESCRIPTION_SIZE];
272 format_mk_user_description(description, mk->mk_spec.u.identifier);
273 return search_fscrypt_keyring(mk->mk_users, &key_type_fscrypt_user,
278 * Give the current user a "key" in ->mk_users. This charges the user's quota
279 * and marks the master key as added by the current user, so that it cannot be
280 * removed by another user with the key. Either the master key's key->sem must
281 * be held for write, or the master key must be still undergoing initialization.
283 static int add_master_key_user(struct fscrypt_master_key *mk)
285 char description[FSCRYPT_MK_USER_DESCRIPTION_SIZE];
289 format_mk_user_description(description, mk->mk_spec.u.identifier);
290 mk_user = key_alloc(&key_type_fscrypt_user, description,
291 current_fsuid(), current_gid(), current_cred(),
292 KEY_POS_SEARCH | KEY_USR_VIEW, 0, NULL);
294 return PTR_ERR(mk_user);
296 err = key_instantiate_and_link(mk_user, NULL, 0, mk->mk_users, NULL);
302 * Remove the current user's "key" from ->mk_users.
303 * The master key's key->sem must be held for write.
305 * Returns 0 if removed, -ENOKEY if not found, or another -errno code.
307 static int remove_master_key_user(struct fscrypt_master_key *mk)
312 mk_user = find_master_key_user(mk);
314 return PTR_ERR(mk_user);
315 err = key_unlink(mk->mk_users, mk_user);
321 * Allocate a new fscrypt_master_key which contains the given secret, set it as
322 * the payload of a new 'struct key' of type fscrypt, and link the 'struct key'
323 * into the given keyring. Synchronized by fscrypt_add_key_mutex.
325 static int add_new_master_key(struct fscrypt_master_key_secret *secret,
326 const struct fscrypt_key_specifier *mk_spec,
329 struct fscrypt_master_key *mk;
330 char description[FSCRYPT_MK_DESCRIPTION_SIZE];
334 mk = kzalloc(sizeof(*mk), GFP_KERNEL);
338 mk->mk_spec = *mk_spec;
340 move_master_key_secret(&mk->mk_secret, secret);
341 init_rwsem(&mk->mk_secret_sem);
343 refcount_set(&mk->mk_refcount, 1); /* secret is present */
344 INIT_LIST_HEAD(&mk->mk_decrypted_inodes);
345 spin_lock_init(&mk->mk_decrypted_inodes_lock);
347 if (mk_spec->type == FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER) {
348 err = allocate_master_key_users_keyring(mk);
351 err = add_master_key_user(mk);
357 * Note that we don't charge this key to anyone's quota, since when
358 * ->mk_users is in use those keys are charged instead, and otherwise
359 * (when ->mk_users isn't in use) only root can add these keys.
361 format_mk_description(description, mk_spec);
362 key = key_alloc(&key_type_fscrypt, description,
363 GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, current_cred(),
364 KEY_POS_SEARCH | KEY_USR_SEARCH | KEY_USR_VIEW,
365 KEY_ALLOC_NOT_IN_QUOTA, NULL);
370 err = key_instantiate_and_link(key, mk, sizeof(*mk), keyring, NULL);
384 static int add_existing_master_key(struct fscrypt_master_key *mk,
385 struct fscrypt_master_key_secret *secret)
392 * If the current user is already in ->mk_users, then there's nothing to
393 * do. (Not applicable for v1 policy keys, which have NULL ->mk_users.)
396 mk_user = find_master_key_user(mk);
397 if (mk_user != ERR_PTR(-ENOKEY)) {
399 return PTR_ERR(mk_user);
405 /* If we'll be re-adding ->mk_secret, try to take the reference. */
406 rekey = !is_master_key_secret_present(&mk->mk_secret);
407 if (rekey && !refcount_inc_not_zero(&mk->mk_refcount))
410 /* Add the current user to ->mk_users, if applicable. */
412 err = add_master_key_user(mk);
414 if (rekey && refcount_dec_and_test(&mk->mk_refcount))
420 /* Re-add the secret if needed. */
422 down_write(&mk->mk_secret_sem);
423 move_master_key_secret(&mk->mk_secret, secret);
424 up_write(&mk->mk_secret_sem);
429 static int do_add_master_key(struct super_block *sb,
430 struct fscrypt_master_key_secret *secret,
431 const struct fscrypt_key_specifier *mk_spec)
433 static DEFINE_MUTEX(fscrypt_add_key_mutex);
437 mutex_lock(&fscrypt_add_key_mutex); /* serialize find + link */
439 key = fscrypt_find_master_key(sb, mk_spec);
444 /* Didn't find the key in ->s_master_keys. Add it. */
445 err = allocate_filesystem_keyring(sb);
448 err = add_new_master_key(secret, mk_spec, sb->s_master_keys);
451 * Found the key in ->s_master_keys. Re-add the secret if
452 * needed, and add the user to ->mk_users if needed.
454 down_write(&key->sem);
455 err = add_existing_master_key(key->payload.data[0], secret);
457 if (err == KEY_DEAD) {
458 /* Key being removed or needs to be removed */
466 mutex_unlock(&fscrypt_add_key_mutex);
470 static int add_master_key(struct super_block *sb,
471 struct fscrypt_master_key_secret *secret,
472 struct fscrypt_key_specifier *key_spec)
476 if (key_spec->type == FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER) {
477 err = fscrypt_init_hkdf(&secret->hkdf, secret->raw,
483 * Now that the HKDF context is initialized, the raw key is no
486 memzero_explicit(secret->raw, secret->size);
488 /* Calculate the key identifier */
489 err = fscrypt_hkdf_expand(&secret->hkdf,
490 HKDF_CONTEXT_KEY_IDENTIFIER, NULL, 0,
491 key_spec->u.identifier,
492 FSCRYPT_KEY_IDENTIFIER_SIZE);
496 return do_add_master_key(sb, secret, key_spec);
499 static int fscrypt_provisioning_key_preparse(struct key_preparsed_payload *prep)
501 const struct fscrypt_provisioning_key_payload *payload = prep->data;
503 if (prep->datalen < sizeof(*payload) + FSCRYPT_MIN_KEY_SIZE ||
504 prep->datalen > sizeof(*payload) + FSCRYPT_MAX_KEY_SIZE)
507 if (payload->type != FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR &&
508 payload->type != FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER)
511 if (payload->__reserved)
514 prep->payload.data[0] = kmemdup(payload, prep->datalen, GFP_KERNEL);
515 if (!prep->payload.data[0])
518 prep->quotalen = prep->datalen;
522 static void fscrypt_provisioning_key_free_preparse(
523 struct key_preparsed_payload *prep)
525 kzfree(prep->payload.data[0]);
528 static void fscrypt_provisioning_key_describe(const struct key *key,
531 seq_puts(m, key->description);
532 if (key_is_positive(key)) {
533 const struct fscrypt_provisioning_key_payload *payload =
534 key->payload.data[0];
536 seq_printf(m, ": %u [%u]", key->datalen, payload->type);
540 static void fscrypt_provisioning_key_destroy(struct key *key)
542 kzfree(key->payload.data[0]);
545 static struct key_type key_type_fscrypt_provisioning = {
546 .name = "fscrypt-provisioning",
547 .preparse = fscrypt_provisioning_key_preparse,
548 .free_preparse = fscrypt_provisioning_key_free_preparse,
549 .instantiate = generic_key_instantiate,
550 .describe = fscrypt_provisioning_key_describe,
551 .destroy = fscrypt_provisioning_key_destroy,
555 * Retrieve the raw key from the Linux keyring key specified by 'key_id', and
556 * store it into 'secret'.
558 * The key must be of type "fscrypt-provisioning" and must have the field
559 * fscrypt_provisioning_key_payload::type set to 'type', indicating that it's
560 * only usable with fscrypt with the particular KDF version identified by
561 * 'type'. We don't use the "logon" key type because there's no way to
562 * completely restrict the use of such keys; they can be used by any kernel API
563 * that accepts "logon" keys and doesn't require a specific service prefix.
565 * The ability to specify the key via Linux keyring key is intended for cases
566 * where userspace needs to re-add keys after the filesystem is unmounted and
567 * re-mounted. Most users should just provide the raw key directly instead.
569 static int get_keyring_key(u32 key_id, u32 type,
570 struct fscrypt_master_key_secret *secret)
574 const struct fscrypt_provisioning_key_payload *payload;
577 ref = lookup_user_key(key_id, 0, KEY_NEED_SEARCH);
580 key = key_ref_to_ptr(ref);
582 if (key->type != &key_type_fscrypt_provisioning)
584 payload = key->payload.data[0];
586 /* Don't allow fscrypt v1 keys to be used as v2 keys and vice versa. */
587 if (payload->type != type)
590 secret->size = key->datalen - sizeof(*payload);
591 memcpy(secret->raw, payload->raw, secret->size);
603 * Add a master encryption key to the filesystem, causing all files which were
604 * encrypted with it to appear "unlocked" (decrypted) when accessed.
606 * When adding a key for use by v1 encryption policies, this ioctl is
607 * privileged, and userspace must provide the 'key_descriptor'.
609 * When adding a key for use by v2+ encryption policies, this ioctl is
610 * unprivileged. This is needed, in general, to allow non-root users to use
611 * encryption without encountering the visibility problems of process-subscribed
612 * keyrings and the inability to properly remove keys. This works by having
613 * each key identified by its cryptographically secure hash --- the
614 * 'key_identifier'. The cryptographic hash ensures that a malicious user
615 * cannot add the wrong key for a given identifier. Furthermore, each added key
616 * is charged to the appropriate user's quota for the keyrings service, which
617 * prevents a malicious user from adding too many keys. Finally, we forbid a
618 * user from removing a key while other users have added it too, which prevents
619 * a user who knows another user's key from causing a denial-of-service by
620 * removing it at an inopportune time. (We tolerate that a user who knows a key
621 * can prevent other users from removing it.)
623 * For more details, see the "FS_IOC_ADD_ENCRYPTION_KEY" section of
624 * Documentation/filesystems/fscrypt.rst.
626 int fscrypt_ioctl_add_key(struct file *filp, void __user *_uarg)
628 struct super_block *sb = file_inode(filp)->i_sb;
629 struct fscrypt_add_key_arg __user *uarg = _uarg;
630 struct fscrypt_add_key_arg arg;
631 struct fscrypt_master_key_secret secret;
634 if (copy_from_user(&arg, uarg, sizeof(arg)))
637 if (!valid_key_spec(&arg.key_spec))
640 if (memchr_inv(arg.__reserved, 0, sizeof(arg.__reserved)))
644 * Only root can add keys that are identified by an arbitrary descriptor
645 * rather than by a cryptographic hash --- since otherwise a malicious
646 * user could add the wrong key.
648 if (arg.key_spec.type == FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR &&
649 !capable(CAP_SYS_ADMIN))
652 memset(&secret, 0, sizeof(secret));
654 if (arg.raw_size != 0)
656 err = get_keyring_key(arg.key_id, arg.key_spec.type, &secret);
658 goto out_wipe_secret;
660 if (arg.raw_size < FSCRYPT_MIN_KEY_SIZE ||
661 arg.raw_size > FSCRYPT_MAX_KEY_SIZE)
663 secret.size = arg.raw_size;
665 if (copy_from_user(secret.raw, uarg->raw, secret.size))
666 goto out_wipe_secret;
669 err = add_master_key(sb, &secret, &arg.key_spec);
671 goto out_wipe_secret;
673 /* Return the key identifier to userspace, if applicable */
675 if (arg.key_spec.type == FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER &&
676 copy_to_user(uarg->key_spec.u.identifier, arg.key_spec.u.identifier,
677 FSCRYPT_KEY_IDENTIFIER_SIZE))
678 goto out_wipe_secret;
681 wipe_master_key_secret(&secret);
684 EXPORT_SYMBOL_GPL(fscrypt_ioctl_add_key);
687 * Add the key for '-o test_dummy_encryption' to the filesystem keyring.
689 * Use a per-boot random key to prevent people from misusing this option.
691 int fscrypt_add_test_dummy_key(struct super_block *sb,
692 struct fscrypt_key_specifier *key_spec)
694 static u8 test_key[FSCRYPT_MAX_KEY_SIZE];
695 struct fscrypt_master_key_secret secret;
698 get_random_once(test_key, FSCRYPT_MAX_KEY_SIZE);
700 memset(&secret, 0, sizeof(secret));
701 secret.size = FSCRYPT_MAX_KEY_SIZE;
702 memcpy(secret.raw, test_key, FSCRYPT_MAX_KEY_SIZE);
704 err = add_master_key(sb, &secret, key_spec);
705 wipe_master_key_secret(&secret);
710 * Verify that the current user has added a master key with the given identifier
711 * (returns -ENOKEY if not). This is needed to prevent a user from encrypting
712 * their files using some other user's key which they don't actually know.
713 * Cryptographically this isn't much of a problem, but the semantics of this
714 * would be a bit weird, so it's best to just forbid it.
716 * The system administrator (CAP_FOWNER) can override this, which should be
717 * enough for any use cases where encryption policies are being set using keys
718 * that were chosen ahead of time but aren't available at the moment.
720 * Note that the key may have already removed by the time this returns, but
721 * that's okay; we just care whether the key was there at some point.
723 * Return: 0 if the key is added, -ENOKEY if it isn't, or another -errno code
725 int fscrypt_verify_key_added(struct super_block *sb,
726 const u8 identifier[FSCRYPT_KEY_IDENTIFIER_SIZE])
728 struct fscrypt_key_specifier mk_spec;
729 struct key *key, *mk_user;
730 struct fscrypt_master_key *mk;
733 mk_spec.type = FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
734 memcpy(mk_spec.u.identifier, identifier, FSCRYPT_KEY_IDENTIFIER_SIZE);
736 key = fscrypt_find_master_key(sb, &mk_spec);
741 mk = key->payload.data[0];
742 mk_user = find_master_key_user(mk);
743 if (IS_ERR(mk_user)) {
744 err = PTR_ERR(mk_user);
751 if (err == -ENOKEY && capable(CAP_FOWNER))
757 * Try to evict the inode's dentries from the dentry cache. If the inode is a
758 * directory, then it can have at most one dentry; however, that dentry may be
759 * pinned by child dentries, so first try to evict the children too.
761 static void shrink_dcache_inode(struct inode *inode)
763 struct dentry *dentry;
765 if (S_ISDIR(inode->i_mode)) {
766 dentry = d_find_any_alias(inode);
768 shrink_dcache_parent(dentry);
772 d_prune_aliases(inode);
775 static void evict_dentries_for_decrypted_inodes(struct fscrypt_master_key *mk)
777 struct fscrypt_info *ci;
779 struct inode *toput_inode = NULL;
781 spin_lock(&mk->mk_decrypted_inodes_lock);
783 list_for_each_entry(ci, &mk->mk_decrypted_inodes, ci_master_key_link) {
784 inode = ci->ci_inode;
785 spin_lock(&inode->i_lock);
786 if (inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW)) {
787 spin_unlock(&inode->i_lock);
791 spin_unlock(&inode->i_lock);
792 spin_unlock(&mk->mk_decrypted_inodes_lock);
794 shrink_dcache_inode(inode);
798 spin_lock(&mk->mk_decrypted_inodes_lock);
801 spin_unlock(&mk->mk_decrypted_inodes_lock);
805 static int check_for_busy_inodes(struct super_block *sb,
806 struct fscrypt_master_key *mk)
808 struct list_head *pos;
809 size_t busy_count = 0;
812 spin_lock(&mk->mk_decrypted_inodes_lock);
814 list_for_each(pos, &mk->mk_decrypted_inodes)
817 if (busy_count == 0) {
818 spin_unlock(&mk->mk_decrypted_inodes_lock);
823 /* select an example file to show for debugging purposes */
824 struct inode *inode =
825 list_first_entry(&mk->mk_decrypted_inodes,
827 ci_master_key_link)->ci_inode;
830 spin_unlock(&mk->mk_decrypted_inodes_lock);
833 "%s: %zu inode(s) still busy after removing key with %s %*phN, including ino %lu",
834 sb->s_id, busy_count, master_key_spec_type(&mk->mk_spec),
835 master_key_spec_len(&mk->mk_spec), (u8 *)&mk->mk_spec.u,
840 static int try_to_lock_encrypted_files(struct super_block *sb,
841 struct fscrypt_master_key *mk)
847 * An inode can't be evicted while it is dirty or has dirty pages.
848 * Thus, we first have to clean the inodes in ->mk_decrypted_inodes.
850 * Just do it the easy way: call sync_filesystem(). It's overkill, but
851 * it works, and it's more important to minimize the amount of caches we
852 * drop than the amount of data we sync. Also, unprivileged users can
853 * already call sync_filesystem() via sys_syncfs() or sys_sync().
855 down_read(&sb->s_umount);
856 err1 = sync_filesystem(sb);
857 up_read(&sb->s_umount);
858 /* If a sync error occurs, still try to evict as much as possible. */
861 * Inodes are pinned by their dentries, so we have to evict their
862 * dentries. shrink_dcache_sb() would suffice, but would be overkill
863 * and inappropriate for use by unprivileged users. So instead go
864 * through the inodes' alias lists and try to evict each dentry.
866 evict_dentries_for_decrypted_inodes(mk);
869 * evict_dentries_for_decrypted_inodes() already iput() each inode in
870 * the list; any inodes for which that dropped the last reference will
871 * have been evicted due to fscrypt_drop_inode() detecting the key
872 * removal and telling the VFS to evict the inode. So to finish, we
873 * just need to check whether any inodes couldn't be evicted.
875 err2 = check_for_busy_inodes(sb, mk);
881 * Try to remove an fscrypt master encryption key.
883 * FS_IOC_REMOVE_ENCRYPTION_KEY (all_users=false) removes the current user's
884 * claim to the key, then removes the key itself if no other users have claims.
885 * FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS (all_users=true) always removes the
888 * To "remove the key itself", first we wipe the actual master key secret, so
889 * that no more inodes can be unlocked with it. Then we try to evict all cached
890 * inodes that had been unlocked with the key.
892 * If all inodes were evicted, then we unlink the fscrypt_master_key from the
893 * keyring. Otherwise it remains in the keyring in the "incompletely removed"
894 * state (without the actual secret key) where it tracks the list of remaining
895 * inodes. Userspace can execute the ioctl again later to retry eviction, or
896 * alternatively can re-add the secret key again.
898 * For more details, see the "Removing keys" section of
899 * Documentation/filesystems/fscrypt.rst.
901 static int do_remove_key(struct file *filp, void __user *_uarg, bool all_users)
903 struct super_block *sb = file_inode(filp)->i_sb;
904 struct fscrypt_remove_key_arg __user *uarg = _uarg;
905 struct fscrypt_remove_key_arg arg;
907 struct fscrypt_master_key *mk;
908 u32 status_flags = 0;
912 if (copy_from_user(&arg, uarg, sizeof(arg)))
915 if (!valid_key_spec(&arg.key_spec))
918 if (memchr_inv(arg.__reserved, 0, sizeof(arg.__reserved)))
922 * Only root can add and remove keys that are identified by an arbitrary
923 * descriptor rather than by a cryptographic hash.
925 if (arg.key_spec.type == FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR &&
926 !capable(CAP_SYS_ADMIN))
929 /* Find the key being removed. */
930 key = fscrypt_find_master_key(sb, &arg.key_spec);
933 mk = key->payload.data[0];
935 down_write(&key->sem);
937 /* If relevant, remove current user's (or all users) claim to the key */
938 if (mk->mk_users && mk->mk_users->keys.nr_leaves_on_tree != 0) {
940 err = keyring_clear(mk->mk_users);
942 err = remove_master_key_user(mk);
947 if (mk->mk_users->keys.nr_leaves_on_tree != 0) {
949 * Other users have still added the key too. We removed
950 * the current user's claim to the key, but we still
951 * can't remove the key itself.
954 FSCRYPT_KEY_REMOVAL_STATUS_FLAG_OTHER_USERS;
961 /* No user claims remaining. Go ahead and wipe the secret. */
963 if (is_master_key_secret_present(&mk->mk_secret)) {
964 down_write(&mk->mk_secret_sem);
965 wipe_master_key_secret(&mk->mk_secret);
966 dead = refcount_dec_and_test(&mk->mk_refcount);
967 up_write(&mk->mk_secret_sem);
972 * No inodes reference the key, and we wiped the secret, so the
973 * key object is free to be removed from the keyring.
978 /* Some inodes still reference this key; try to evict them. */
979 err = try_to_lock_encrypted_files(sb, mk);
982 FSCRYPT_KEY_REMOVAL_STATUS_FLAG_FILES_BUSY;
987 * We return 0 if we successfully did something: removed a claim to the
988 * key, wiped the secret, or tried locking the files again. Users need
989 * to check the informational status flags if they care whether the key
990 * has been fully removed including all files locked.
995 err = put_user(status_flags, &uarg->removal_status_flags);
999 int fscrypt_ioctl_remove_key(struct file *filp, void __user *uarg)
1001 return do_remove_key(filp, uarg, false);
1003 EXPORT_SYMBOL_GPL(fscrypt_ioctl_remove_key);
1005 int fscrypt_ioctl_remove_key_all_users(struct file *filp, void __user *uarg)
1007 if (!capable(CAP_SYS_ADMIN))
1009 return do_remove_key(filp, uarg, true);
1011 EXPORT_SYMBOL_GPL(fscrypt_ioctl_remove_key_all_users);
1014 * Retrieve the status of an fscrypt master encryption key.
1016 * We set ->status to indicate whether the key is absent, present, or
1017 * incompletely removed. "Incompletely removed" means that the master key
1018 * secret has been removed, but some files which had been unlocked with it are
1019 * still in use. This field allows applications to easily determine the state
1020 * of an encrypted directory without using a hack such as trying to open a
1021 * regular file in it (which can confuse the "incompletely removed" state with
1022 * absent or present).
1024 * In addition, for v2 policy keys we allow applications to determine, via
1025 * ->status_flags and ->user_count, whether the key has been added by the
1026 * current user, by other users, or by both. Most applications should not need
1027 * this, since ordinarily only one user should know a given key. However, if a
1028 * secret key is shared by multiple users, applications may wish to add an
1029 * already-present key to prevent other users from removing it. This ioctl can
1030 * be used to check whether that really is the case before the work is done to
1031 * add the key --- which might e.g. require prompting the user for a passphrase.
1033 * For more details, see the "FS_IOC_GET_ENCRYPTION_KEY_STATUS" section of
1034 * Documentation/filesystems/fscrypt.rst.
1036 int fscrypt_ioctl_get_key_status(struct file *filp, void __user *uarg)
1038 struct super_block *sb = file_inode(filp)->i_sb;
1039 struct fscrypt_get_key_status_arg arg;
1041 struct fscrypt_master_key *mk;
1044 if (copy_from_user(&arg, uarg, sizeof(arg)))
1047 if (!valid_key_spec(&arg.key_spec))
1050 if (memchr_inv(arg.__reserved, 0, sizeof(arg.__reserved)))
1053 arg.status_flags = 0;
1055 memset(arg.__out_reserved, 0, sizeof(arg.__out_reserved));
1057 key = fscrypt_find_master_key(sb, &arg.key_spec);
1059 if (key != ERR_PTR(-ENOKEY))
1060 return PTR_ERR(key);
1061 arg.status = FSCRYPT_KEY_STATUS_ABSENT;
1065 mk = key->payload.data[0];
1066 down_read(&key->sem);
1068 if (!is_master_key_secret_present(&mk->mk_secret)) {
1069 arg.status = FSCRYPT_KEY_STATUS_INCOMPLETELY_REMOVED;
1071 goto out_release_key;
1074 arg.status = FSCRYPT_KEY_STATUS_PRESENT;
1076 struct key *mk_user;
1078 arg.user_count = mk->mk_users->keys.nr_leaves_on_tree;
1079 mk_user = find_master_key_user(mk);
1080 if (!IS_ERR(mk_user)) {
1082 FSCRYPT_KEY_STATUS_FLAG_ADDED_BY_SELF;
1084 } else if (mk_user != ERR_PTR(-ENOKEY)) {
1085 err = PTR_ERR(mk_user);
1086 goto out_release_key;
1094 if (!err && copy_to_user(uarg, &arg, sizeof(arg)))
1098 EXPORT_SYMBOL_GPL(fscrypt_ioctl_get_key_status);
1100 int __init fscrypt_init_keyring(void)
1104 err = register_key_type(&key_type_fscrypt);
1108 err = register_key_type(&key_type_fscrypt_user);
1110 goto err_unregister_fscrypt;
1112 err = register_key_type(&key_type_fscrypt_provisioning);
1114 goto err_unregister_fscrypt_user;
1118 err_unregister_fscrypt_user:
1119 unregister_key_type(&key_type_fscrypt_user);
1120 err_unregister_fscrypt:
1121 unregister_key_type(&key_type_fscrypt);