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 <asm/unaligned.h>
22 #include <crypto/skcipher.h>
23 #include <linux/key-type.h>
24 #include <linux/random.h>
25 #include <linux/seq_file.h>
27 #include "fscrypt_private.h"
29 /* The master encryption keys for a filesystem (->s_master_keys) */
30 struct fscrypt_keyring {
32 * Lock that protects ->key_hashtable. It does *not* protect the
33 * fscrypt_master_key structs themselves.
37 /* Hash table that maps fscrypt_key_specifier to fscrypt_master_key */
38 struct hlist_head key_hashtable[128];
41 static void wipe_master_key_secret(struct fscrypt_master_key_secret *secret)
43 fscrypt_destroy_hkdf(&secret->hkdf);
44 memzero_explicit(secret, sizeof(*secret));
47 static void move_master_key_secret(struct fscrypt_master_key_secret *dst,
48 struct fscrypt_master_key_secret *src)
50 memcpy(dst, src, sizeof(*dst));
51 memzero_explicit(src, sizeof(*src));
54 static void fscrypt_free_master_key(struct rcu_head *head)
56 struct fscrypt_master_key *mk =
57 container_of(head, struct fscrypt_master_key, mk_rcu_head);
59 * The master key secret and any embedded subkeys should have already
60 * been wiped when the last active reference to the fscrypt_master_key
61 * struct was dropped; doing it here would be unnecessarily late.
62 * Nevertheless, use kfree_sensitive() in case anything was missed.
67 void fscrypt_put_master_key(struct fscrypt_master_key *mk)
69 if (!refcount_dec_and_test(&mk->mk_struct_refs))
72 * No structural references left, so free ->mk_users, and also free the
73 * fscrypt_master_key struct itself after an RCU grace period ensures
74 * that concurrent keyring lookups can no longer find it.
76 WARN_ON(refcount_read(&mk->mk_active_refs) != 0);
77 key_put(mk->mk_users);
79 call_rcu(&mk->mk_rcu_head, fscrypt_free_master_key);
82 void fscrypt_put_master_key_activeref(struct fscrypt_master_key *mk)
84 struct super_block *sb = mk->mk_sb;
85 struct fscrypt_keyring *keyring = sb->s_master_keys;
88 if (!refcount_dec_and_test(&mk->mk_active_refs))
91 * No active references left, so complete the full removal of this
92 * fscrypt_master_key struct by removing it from the keyring and
93 * destroying any subkeys embedded in it.
96 spin_lock(&keyring->lock);
97 hlist_del_rcu(&mk->mk_node);
98 spin_unlock(&keyring->lock);
101 * ->mk_active_refs == 0 implies that ->mk_secret is not present and
102 * that ->mk_decrypted_inodes is empty.
104 WARN_ON(is_master_key_secret_present(&mk->mk_secret));
105 WARN_ON(!list_empty(&mk->mk_decrypted_inodes));
107 for (i = 0; i <= FSCRYPT_MODE_MAX; i++) {
108 fscrypt_destroy_prepared_key(&mk->mk_direct_keys[i]);
109 fscrypt_destroy_prepared_key(&mk->mk_iv_ino_lblk_64_keys[i]);
110 fscrypt_destroy_prepared_key(&mk->mk_iv_ino_lblk_32_keys[i]);
112 memzero_explicit(&mk->mk_ino_hash_key,
113 sizeof(mk->mk_ino_hash_key));
114 mk->mk_ino_hash_key_initialized = false;
116 /* Drop the structural ref associated with the active refs. */
117 fscrypt_put_master_key(mk);
120 static inline bool valid_key_spec(const struct fscrypt_key_specifier *spec)
122 if (spec->__reserved)
124 return master_key_spec_len(spec) != 0;
127 static int fscrypt_user_key_instantiate(struct key *key,
128 struct key_preparsed_payload *prep)
131 * We just charge FSCRYPT_MAX_KEY_SIZE bytes to the user's key quota for
132 * each key, regardless of the exact key size. The amount of memory
133 * actually used is greater than the size of the raw key anyway.
135 return key_payload_reserve(key, FSCRYPT_MAX_KEY_SIZE);
138 static void fscrypt_user_key_describe(const struct key *key, struct seq_file *m)
140 seq_puts(m, key->description);
144 * Type of key in ->mk_users. Each key of this type represents a particular
145 * user who has added a particular master key.
147 * Note that the name of this key type really should be something like
148 * ".fscrypt-user" instead of simply ".fscrypt". But the shorter name is chosen
149 * mainly for simplicity of presentation in /proc/keys when read by a non-root
150 * user. And it is expected to be rare that a key is actually added by multiple
151 * users, since users should keep their encryption keys confidential.
153 static struct key_type key_type_fscrypt_user = {
155 .instantiate = fscrypt_user_key_instantiate,
156 .describe = fscrypt_user_key_describe,
159 #define FSCRYPT_MK_USERS_DESCRIPTION_SIZE \
160 (CONST_STRLEN("fscrypt-") + 2 * FSCRYPT_KEY_IDENTIFIER_SIZE + \
161 CONST_STRLEN("-users") + 1)
163 #define FSCRYPT_MK_USER_DESCRIPTION_SIZE \
164 (2 * FSCRYPT_KEY_IDENTIFIER_SIZE + CONST_STRLEN(".uid.") + 10 + 1)
166 static void format_mk_users_keyring_description(
167 char description[FSCRYPT_MK_USERS_DESCRIPTION_SIZE],
168 const u8 mk_identifier[FSCRYPT_KEY_IDENTIFIER_SIZE])
170 sprintf(description, "fscrypt-%*phN-users",
171 FSCRYPT_KEY_IDENTIFIER_SIZE, mk_identifier);
174 static void format_mk_user_description(
175 char description[FSCRYPT_MK_USER_DESCRIPTION_SIZE],
176 const u8 mk_identifier[FSCRYPT_KEY_IDENTIFIER_SIZE])
179 sprintf(description, "%*phN.uid.%u", FSCRYPT_KEY_IDENTIFIER_SIZE,
180 mk_identifier, __kuid_val(current_fsuid()));
183 /* Create ->s_master_keys if needed. Synchronized by fscrypt_add_key_mutex. */
184 static int allocate_filesystem_keyring(struct super_block *sb)
186 struct fscrypt_keyring *keyring;
188 if (sb->s_master_keys)
191 keyring = kzalloc(sizeof(*keyring), GFP_KERNEL);
194 spin_lock_init(&keyring->lock);
196 * Pairs with the smp_load_acquire() in fscrypt_find_master_key().
197 * I.e., here we publish ->s_master_keys with a RELEASE barrier so that
198 * concurrent tasks can ACQUIRE it.
200 smp_store_release(&sb->s_master_keys, keyring);
205 * Release all encryption keys that have been added to the filesystem, along
206 * with the keyring that contains them.
208 * This is called at unmount time. The filesystem's underlying block device(s)
209 * are still available at this time; this is important because after user file
210 * accesses have been allowed, this function may need to evict keys from the
211 * keyslots of an inline crypto engine, which requires the block device(s).
213 * This is also called when the super_block is being freed. This is needed to
214 * avoid a memory leak if mounting fails after the "test_dummy_encryption"
215 * option was processed, as in that case the unmount-time call isn't made.
217 void fscrypt_destroy_keyring(struct super_block *sb)
219 struct fscrypt_keyring *keyring = sb->s_master_keys;
225 for (i = 0; i < ARRAY_SIZE(keyring->key_hashtable); i++) {
226 struct hlist_head *bucket = &keyring->key_hashtable[i];
227 struct fscrypt_master_key *mk;
228 struct hlist_node *tmp;
230 hlist_for_each_entry_safe(mk, tmp, bucket, mk_node) {
232 * Since all inodes were already evicted, every key
233 * remaining in the keyring should have an empty inode
234 * list, and should only still be in the keyring due to
235 * the single active ref associated with ->mk_secret.
236 * There should be no structural refs beyond the one
237 * associated with the active ref.
239 WARN_ON(refcount_read(&mk->mk_active_refs) != 1);
240 WARN_ON(refcount_read(&mk->mk_struct_refs) != 1);
241 WARN_ON(!is_master_key_secret_present(&mk->mk_secret));
242 wipe_master_key_secret(&mk->mk_secret);
243 fscrypt_put_master_key_activeref(mk);
246 kfree_sensitive(keyring);
247 sb->s_master_keys = NULL;
250 static struct hlist_head *
251 fscrypt_mk_hash_bucket(struct fscrypt_keyring *keyring,
252 const struct fscrypt_key_specifier *mk_spec)
255 * Since key specifiers should be "random" values, it is sufficient to
256 * use a trivial hash function that just takes the first several bits of
259 unsigned long i = get_unaligned((unsigned long *)&mk_spec->u);
261 return &keyring->key_hashtable[i % ARRAY_SIZE(keyring->key_hashtable)];
265 * Find the specified master key struct in ->s_master_keys and take a structural
266 * ref to it. The structural ref guarantees that the key struct continues to
267 * exist, but it does *not* guarantee that ->s_master_keys continues to contain
268 * the key struct. The structural ref needs to be dropped by
269 * fscrypt_put_master_key(). Returns NULL if the key struct is not found.
271 struct fscrypt_master_key *
272 fscrypt_find_master_key(struct super_block *sb,
273 const struct fscrypt_key_specifier *mk_spec)
275 struct fscrypt_keyring *keyring;
276 struct hlist_head *bucket;
277 struct fscrypt_master_key *mk;
280 * Pairs with the smp_store_release() in allocate_filesystem_keyring().
281 * I.e., another task can publish ->s_master_keys concurrently,
282 * executing a RELEASE barrier. We need to use smp_load_acquire() here
283 * to safely ACQUIRE the memory the other task published.
285 keyring = smp_load_acquire(&sb->s_master_keys);
287 return NULL; /* No keyring yet, so no keys yet. */
289 bucket = fscrypt_mk_hash_bucket(keyring, mk_spec);
291 switch (mk_spec->type) {
292 case FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR:
293 hlist_for_each_entry_rcu(mk, bucket, mk_node) {
294 if (mk->mk_spec.type ==
295 FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR &&
296 memcmp(mk->mk_spec.u.descriptor,
297 mk_spec->u.descriptor,
298 FSCRYPT_KEY_DESCRIPTOR_SIZE) == 0 &&
299 refcount_inc_not_zero(&mk->mk_struct_refs))
303 case FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER:
304 hlist_for_each_entry_rcu(mk, bucket, mk_node) {
305 if (mk->mk_spec.type ==
306 FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER &&
307 memcmp(mk->mk_spec.u.identifier,
308 mk_spec->u.identifier,
309 FSCRYPT_KEY_IDENTIFIER_SIZE) == 0 &&
310 refcount_inc_not_zero(&mk->mk_struct_refs))
321 static int allocate_master_key_users_keyring(struct fscrypt_master_key *mk)
323 char description[FSCRYPT_MK_USERS_DESCRIPTION_SIZE];
326 format_mk_users_keyring_description(description,
327 mk->mk_spec.u.identifier);
328 keyring = keyring_alloc(description, GLOBAL_ROOT_UID, GLOBAL_ROOT_GID,
329 current_cred(), KEY_POS_SEARCH |
330 KEY_USR_SEARCH | KEY_USR_READ | KEY_USR_VIEW,
331 KEY_ALLOC_NOT_IN_QUOTA, NULL, NULL);
333 return PTR_ERR(keyring);
335 mk->mk_users = keyring;
340 * Find the current user's "key" in the master key's ->mk_users.
341 * Returns ERR_PTR(-ENOKEY) if not found.
343 static struct key *find_master_key_user(struct fscrypt_master_key *mk)
345 char description[FSCRYPT_MK_USER_DESCRIPTION_SIZE];
348 format_mk_user_description(description, mk->mk_spec.u.identifier);
351 * We need to mark the keyring reference as "possessed" so that we
352 * acquire permission to search it, via the KEY_POS_SEARCH permission.
354 keyref = keyring_search(make_key_ref(mk->mk_users, true /*possessed*/),
355 &key_type_fscrypt_user, description, false);
356 if (IS_ERR(keyref)) {
357 if (PTR_ERR(keyref) == -EAGAIN || /* not found */
358 PTR_ERR(keyref) == -EKEYREVOKED) /* recently invalidated */
359 keyref = ERR_PTR(-ENOKEY);
360 return ERR_CAST(keyref);
362 return key_ref_to_ptr(keyref);
366 * Give the current user a "key" in ->mk_users. This charges the user's quota
367 * and marks the master key as added by the current user, so that it cannot be
368 * removed by another user with the key. Either ->mk_sem must be held for
369 * write, or the master key must be still undergoing initialization.
371 static int add_master_key_user(struct fscrypt_master_key *mk)
373 char description[FSCRYPT_MK_USER_DESCRIPTION_SIZE];
377 format_mk_user_description(description, mk->mk_spec.u.identifier);
378 mk_user = key_alloc(&key_type_fscrypt_user, description,
379 current_fsuid(), current_gid(), current_cred(),
380 KEY_POS_SEARCH | KEY_USR_VIEW, 0, NULL);
382 return PTR_ERR(mk_user);
384 err = key_instantiate_and_link(mk_user, NULL, 0, mk->mk_users, NULL);
390 * Remove the current user's "key" from ->mk_users.
391 * ->mk_sem must be held for write.
393 * Returns 0 if removed, -ENOKEY if not found, or another -errno code.
395 static int remove_master_key_user(struct fscrypt_master_key *mk)
400 mk_user = find_master_key_user(mk);
402 return PTR_ERR(mk_user);
403 err = key_unlink(mk->mk_users, mk_user);
409 * Allocate a new fscrypt_master_key, transfer the given secret over to it, and
410 * insert it into sb->s_master_keys.
412 static int add_new_master_key(struct super_block *sb,
413 struct fscrypt_master_key_secret *secret,
414 const struct fscrypt_key_specifier *mk_spec)
416 struct fscrypt_keyring *keyring = sb->s_master_keys;
417 struct fscrypt_master_key *mk;
420 mk = kzalloc(sizeof(*mk), GFP_KERNEL);
425 init_rwsem(&mk->mk_sem);
426 refcount_set(&mk->mk_struct_refs, 1);
427 mk->mk_spec = *mk_spec;
429 INIT_LIST_HEAD(&mk->mk_decrypted_inodes);
430 spin_lock_init(&mk->mk_decrypted_inodes_lock);
432 if (mk_spec->type == FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER) {
433 err = allocate_master_key_users_keyring(mk);
436 err = add_master_key_user(mk);
441 move_master_key_secret(&mk->mk_secret, secret);
442 refcount_set(&mk->mk_active_refs, 1); /* ->mk_secret is present */
444 spin_lock(&keyring->lock);
445 hlist_add_head_rcu(&mk->mk_node,
446 fscrypt_mk_hash_bucket(keyring, mk_spec));
447 spin_unlock(&keyring->lock);
451 fscrypt_put_master_key(mk);
457 static int add_existing_master_key(struct fscrypt_master_key *mk,
458 struct fscrypt_master_key_secret *secret)
463 * If the current user is already in ->mk_users, then there's nothing to
464 * do. Otherwise, we need to add the user to ->mk_users. (Neither is
465 * applicable for v1 policy keys, which have NULL ->mk_users.)
468 struct key *mk_user = find_master_key_user(mk);
470 if (mk_user != ERR_PTR(-ENOKEY)) {
472 return PTR_ERR(mk_user);
476 err = add_master_key_user(mk);
481 /* Re-add the secret if needed. */
482 if (!is_master_key_secret_present(&mk->mk_secret)) {
483 if (!refcount_inc_not_zero(&mk->mk_active_refs))
485 move_master_key_secret(&mk->mk_secret, secret);
491 static int do_add_master_key(struct super_block *sb,
492 struct fscrypt_master_key_secret *secret,
493 const struct fscrypt_key_specifier *mk_spec)
495 static DEFINE_MUTEX(fscrypt_add_key_mutex);
496 struct fscrypt_master_key *mk;
499 mutex_lock(&fscrypt_add_key_mutex); /* serialize find + link */
501 mk = fscrypt_find_master_key(sb, mk_spec);
503 /* Didn't find the key in ->s_master_keys. Add it. */
504 err = allocate_filesystem_keyring(sb);
506 err = add_new_master_key(sb, secret, mk_spec);
509 * Found the key in ->s_master_keys. Re-add the secret if
510 * needed, and add the user to ->mk_users if needed.
512 down_write(&mk->mk_sem);
513 err = add_existing_master_key(mk, secret);
514 up_write(&mk->mk_sem);
515 if (err == KEY_DEAD) {
517 * We found a key struct, but it's already been fully
518 * removed. Ignore the old struct and add a new one.
519 * fscrypt_add_key_mutex means we don't need to worry
520 * about concurrent adds.
522 err = add_new_master_key(sb, secret, mk_spec);
524 fscrypt_put_master_key(mk);
526 mutex_unlock(&fscrypt_add_key_mutex);
530 static int add_master_key(struct super_block *sb,
531 struct fscrypt_master_key_secret *secret,
532 struct fscrypt_key_specifier *key_spec)
536 if (key_spec->type == FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER) {
537 err = fscrypt_init_hkdf(&secret->hkdf, secret->raw,
543 * Now that the HKDF context is initialized, the raw key is no
546 memzero_explicit(secret->raw, secret->size);
548 /* Calculate the key identifier */
549 err = fscrypt_hkdf_expand(&secret->hkdf,
550 HKDF_CONTEXT_KEY_IDENTIFIER, NULL, 0,
551 key_spec->u.identifier,
552 FSCRYPT_KEY_IDENTIFIER_SIZE);
556 return do_add_master_key(sb, secret, key_spec);
559 static int fscrypt_provisioning_key_preparse(struct key_preparsed_payload *prep)
561 const struct fscrypt_provisioning_key_payload *payload = prep->data;
563 if (prep->datalen < sizeof(*payload) + FSCRYPT_MIN_KEY_SIZE ||
564 prep->datalen > sizeof(*payload) + FSCRYPT_MAX_KEY_SIZE)
567 if (payload->type != FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR &&
568 payload->type != FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER)
571 if (payload->__reserved)
574 prep->payload.data[0] = kmemdup(payload, prep->datalen, GFP_KERNEL);
575 if (!prep->payload.data[0])
578 prep->quotalen = prep->datalen;
582 static void fscrypt_provisioning_key_free_preparse(
583 struct key_preparsed_payload *prep)
585 kfree_sensitive(prep->payload.data[0]);
588 static void fscrypt_provisioning_key_describe(const struct key *key,
591 seq_puts(m, key->description);
592 if (key_is_positive(key)) {
593 const struct fscrypt_provisioning_key_payload *payload =
594 key->payload.data[0];
596 seq_printf(m, ": %u [%u]", key->datalen, payload->type);
600 static void fscrypt_provisioning_key_destroy(struct key *key)
602 kfree_sensitive(key->payload.data[0]);
605 static struct key_type key_type_fscrypt_provisioning = {
606 .name = "fscrypt-provisioning",
607 .preparse = fscrypt_provisioning_key_preparse,
608 .free_preparse = fscrypt_provisioning_key_free_preparse,
609 .instantiate = generic_key_instantiate,
610 .describe = fscrypt_provisioning_key_describe,
611 .destroy = fscrypt_provisioning_key_destroy,
615 * Retrieve the raw key from the Linux keyring key specified by 'key_id', and
616 * store it into 'secret'.
618 * The key must be of type "fscrypt-provisioning" and must have the field
619 * fscrypt_provisioning_key_payload::type set to 'type', indicating that it's
620 * only usable with fscrypt with the particular KDF version identified by
621 * 'type'. We don't use the "logon" key type because there's no way to
622 * completely restrict the use of such keys; they can be used by any kernel API
623 * that accepts "logon" keys and doesn't require a specific service prefix.
625 * The ability to specify the key via Linux keyring key is intended for cases
626 * where userspace needs to re-add keys after the filesystem is unmounted and
627 * re-mounted. Most users should just provide the raw key directly instead.
629 static int get_keyring_key(u32 key_id, u32 type,
630 struct fscrypt_master_key_secret *secret)
634 const struct fscrypt_provisioning_key_payload *payload;
637 ref = lookup_user_key(key_id, 0, KEY_NEED_SEARCH);
640 key = key_ref_to_ptr(ref);
642 if (key->type != &key_type_fscrypt_provisioning)
644 payload = key->payload.data[0];
646 /* Don't allow fscrypt v1 keys to be used as v2 keys and vice versa. */
647 if (payload->type != type)
650 secret->size = key->datalen - sizeof(*payload);
651 memcpy(secret->raw, payload->raw, secret->size);
663 * Add a master encryption key to the filesystem, causing all files which were
664 * encrypted with it to appear "unlocked" (decrypted) when accessed.
666 * When adding a key for use by v1 encryption policies, this ioctl is
667 * privileged, and userspace must provide the 'key_descriptor'.
669 * When adding a key for use by v2+ encryption policies, this ioctl is
670 * unprivileged. This is needed, in general, to allow non-root users to use
671 * encryption without encountering the visibility problems of process-subscribed
672 * keyrings and the inability to properly remove keys. This works by having
673 * each key identified by its cryptographically secure hash --- the
674 * 'key_identifier'. The cryptographic hash ensures that a malicious user
675 * cannot add the wrong key for a given identifier. Furthermore, each added key
676 * is charged to the appropriate user's quota for the keyrings service, which
677 * prevents a malicious user from adding too many keys. Finally, we forbid a
678 * user from removing a key while other users have added it too, which prevents
679 * a user who knows another user's key from causing a denial-of-service by
680 * removing it at an inopportune time. (We tolerate that a user who knows a key
681 * can prevent other users from removing it.)
683 * For more details, see the "FS_IOC_ADD_ENCRYPTION_KEY" section of
684 * Documentation/filesystems/fscrypt.rst.
686 int fscrypt_ioctl_add_key(struct file *filp, void __user *_uarg)
688 struct super_block *sb = file_inode(filp)->i_sb;
689 struct fscrypt_add_key_arg __user *uarg = _uarg;
690 struct fscrypt_add_key_arg arg;
691 struct fscrypt_master_key_secret secret;
694 if (copy_from_user(&arg, uarg, sizeof(arg)))
697 if (!valid_key_spec(&arg.key_spec))
700 if (memchr_inv(arg.__reserved, 0, sizeof(arg.__reserved)))
704 * Only root can add keys that are identified by an arbitrary descriptor
705 * rather than by a cryptographic hash --- since otherwise a malicious
706 * user could add the wrong key.
708 if (arg.key_spec.type == FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR &&
709 !capable(CAP_SYS_ADMIN))
712 memset(&secret, 0, sizeof(secret));
714 if (arg.raw_size != 0)
716 err = get_keyring_key(arg.key_id, arg.key_spec.type, &secret);
718 goto out_wipe_secret;
720 if (arg.raw_size < FSCRYPT_MIN_KEY_SIZE ||
721 arg.raw_size > FSCRYPT_MAX_KEY_SIZE)
723 secret.size = arg.raw_size;
725 if (copy_from_user(secret.raw, uarg->raw, secret.size))
726 goto out_wipe_secret;
729 err = add_master_key(sb, &secret, &arg.key_spec);
731 goto out_wipe_secret;
733 /* Return the key identifier to userspace, if applicable */
735 if (arg.key_spec.type == FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER &&
736 copy_to_user(uarg->key_spec.u.identifier, arg.key_spec.u.identifier,
737 FSCRYPT_KEY_IDENTIFIER_SIZE))
738 goto out_wipe_secret;
741 wipe_master_key_secret(&secret);
744 EXPORT_SYMBOL_GPL(fscrypt_ioctl_add_key);
747 * Add the key for '-o test_dummy_encryption' to the filesystem keyring.
749 * Use a per-boot random key to prevent people from misusing this option.
751 int fscrypt_add_test_dummy_key(struct super_block *sb,
752 struct fscrypt_key_specifier *key_spec)
754 static u8 test_key[FSCRYPT_MAX_KEY_SIZE];
755 struct fscrypt_master_key_secret secret;
758 get_random_once(test_key, FSCRYPT_MAX_KEY_SIZE);
760 memset(&secret, 0, sizeof(secret));
761 secret.size = FSCRYPT_MAX_KEY_SIZE;
762 memcpy(secret.raw, test_key, FSCRYPT_MAX_KEY_SIZE);
764 err = add_master_key(sb, &secret, key_spec);
765 wipe_master_key_secret(&secret);
770 * Verify that the current user has added a master key with the given identifier
771 * (returns -ENOKEY if not). This is needed to prevent a user from encrypting
772 * their files using some other user's key which they don't actually know.
773 * Cryptographically this isn't much of a problem, but the semantics of this
774 * would be a bit weird, so it's best to just forbid it.
776 * The system administrator (CAP_FOWNER) can override this, which should be
777 * enough for any use cases where encryption policies are being set using keys
778 * that were chosen ahead of time but aren't available at the moment.
780 * Note that the key may have already removed by the time this returns, but
781 * that's okay; we just care whether the key was there at some point.
783 * Return: 0 if the key is added, -ENOKEY if it isn't, or another -errno code
785 int fscrypt_verify_key_added(struct super_block *sb,
786 const u8 identifier[FSCRYPT_KEY_IDENTIFIER_SIZE])
788 struct fscrypt_key_specifier mk_spec;
789 struct fscrypt_master_key *mk;
793 mk_spec.type = FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
794 memcpy(mk_spec.u.identifier, identifier, FSCRYPT_KEY_IDENTIFIER_SIZE);
796 mk = fscrypt_find_master_key(sb, &mk_spec);
801 down_read(&mk->mk_sem);
802 mk_user = find_master_key_user(mk);
803 if (IS_ERR(mk_user)) {
804 err = PTR_ERR(mk_user);
809 up_read(&mk->mk_sem);
810 fscrypt_put_master_key(mk);
812 if (err == -ENOKEY && capable(CAP_FOWNER))
818 * Try to evict the inode's dentries from the dentry cache. If the inode is a
819 * directory, then it can have at most one dentry; however, that dentry may be
820 * pinned by child dentries, so first try to evict the children too.
822 static void shrink_dcache_inode(struct inode *inode)
824 struct dentry *dentry;
826 if (S_ISDIR(inode->i_mode)) {
827 dentry = d_find_any_alias(inode);
829 shrink_dcache_parent(dentry);
833 d_prune_aliases(inode);
836 static void evict_dentries_for_decrypted_inodes(struct fscrypt_master_key *mk)
838 struct fscrypt_info *ci;
840 struct inode *toput_inode = NULL;
842 spin_lock(&mk->mk_decrypted_inodes_lock);
844 list_for_each_entry(ci, &mk->mk_decrypted_inodes, ci_master_key_link) {
845 inode = ci->ci_inode;
846 spin_lock(&inode->i_lock);
847 if (inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW)) {
848 spin_unlock(&inode->i_lock);
852 spin_unlock(&inode->i_lock);
853 spin_unlock(&mk->mk_decrypted_inodes_lock);
855 shrink_dcache_inode(inode);
859 spin_lock(&mk->mk_decrypted_inodes_lock);
862 spin_unlock(&mk->mk_decrypted_inodes_lock);
866 static int check_for_busy_inodes(struct super_block *sb,
867 struct fscrypt_master_key *mk)
869 struct list_head *pos;
870 size_t busy_count = 0;
872 char ino_str[50] = "";
874 spin_lock(&mk->mk_decrypted_inodes_lock);
876 list_for_each(pos, &mk->mk_decrypted_inodes)
879 if (busy_count == 0) {
880 spin_unlock(&mk->mk_decrypted_inodes_lock);
885 /* select an example file to show for debugging purposes */
886 struct inode *inode =
887 list_first_entry(&mk->mk_decrypted_inodes,
889 ci_master_key_link)->ci_inode;
892 spin_unlock(&mk->mk_decrypted_inodes_lock);
894 /* If the inode is currently being created, ino may still be 0. */
896 snprintf(ino_str, sizeof(ino_str), ", including ino %lu", ino);
899 "%s: %zu inode(s) still busy after removing key with %s %*phN%s",
900 sb->s_id, busy_count, master_key_spec_type(&mk->mk_spec),
901 master_key_spec_len(&mk->mk_spec), (u8 *)&mk->mk_spec.u,
906 static int try_to_lock_encrypted_files(struct super_block *sb,
907 struct fscrypt_master_key *mk)
913 * An inode can't be evicted while it is dirty or has dirty pages.
914 * Thus, we first have to clean the inodes in ->mk_decrypted_inodes.
916 * Just do it the easy way: call sync_filesystem(). It's overkill, but
917 * it works, and it's more important to minimize the amount of caches we
918 * drop than the amount of data we sync. Also, unprivileged users can
919 * already call sync_filesystem() via sys_syncfs() or sys_sync().
921 down_read(&sb->s_umount);
922 err1 = sync_filesystem(sb);
923 up_read(&sb->s_umount);
924 /* If a sync error occurs, still try to evict as much as possible. */
927 * Inodes are pinned by their dentries, so we have to evict their
928 * dentries. shrink_dcache_sb() would suffice, but would be overkill
929 * and inappropriate for use by unprivileged users. So instead go
930 * through the inodes' alias lists and try to evict each dentry.
932 evict_dentries_for_decrypted_inodes(mk);
935 * evict_dentries_for_decrypted_inodes() already iput() each inode in
936 * the list; any inodes for which that dropped the last reference will
937 * have been evicted due to fscrypt_drop_inode() detecting the key
938 * removal and telling the VFS to evict the inode. So to finish, we
939 * just need to check whether any inodes couldn't be evicted.
941 err2 = check_for_busy_inodes(sb, mk);
947 * Try to remove an fscrypt master encryption key.
949 * FS_IOC_REMOVE_ENCRYPTION_KEY (all_users=false) removes the current user's
950 * claim to the key, then removes the key itself if no other users have claims.
951 * FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS (all_users=true) always removes the
954 * To "remove the key itself", first we wipe the actual master key secret, so
955 * that no more inodes can be unlocked with it. Then we try to evict all cached
956 * inodes that had been unlocked with the key.
958 * If all inodes were evicted, then we unlink the fscrypt_master_key from the
959 * keyring. Otherwise it remains in the keyring in the "incompletely removed"
960 * state (without the actual secret key) where it tracks the list of remaining
961 * inodes. Userspace can execute the ioctl again later to retry eviction, or
962 * alternatively can re-add the secret key again.
964 * For more details, see the "Removing keys" section of
965 * Documentation/filesystems/fscrypt.rst.
967 static int do_remove_key(struct file *filp, void __user *_uarg, bool all_users)
969 struct super_block *sb = file_inode(filp)->i_sb;
970 struct fscrypt_remove_key_arg __user *uarg = _uarg;
971 struct fscrypt_remove_key_arg arg;
972 struct fscrypt_master_key *mk;
973 u32 status_flags = 0;
977 if (copy_from_user(&arg, uarg, sizeof(arg)))
980 if (!valid_key_spec(&arg.key_spec))
983 if (memchr_inv(arg.__reserved, 0, sizeof(arg.__reserved)))
987 * Only root can add and remove keys that are identified by an arbitrary
988 * descriptor rather than by a cryptographic hash.
990 if (arg.key_spec.type == FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR &&
991 !capable(CAP_SYS_ADMIN))
994 /* Find the key being removed. */
995 mk = fscrypt_find_master_key(sb, &arg.key_spec);
998 down_write(&mk->mk_sem);
1000 /* If relevant, remove current user's (or all users) claim to the key */
1001 if (mk->mk_users && mk->mk_users->keys.nr_leaves_on_tree != 0) {
1003 err = keyring_clear(mk->mk_users);
1005 err = remove_master_key_user(mk);
1007 up_write(&mk->mk_sem);
1010 if (mk->mk_users->keys.nr_leaves_on_tree != 0) {
1012 * Other users have still added the key too. We removed
1013 * the current user's claim to the key, but we still
1014 * can't remove the key itself.
1017 FSCRYPT_KEY_REMOVAL_STATUS_FLAG_OTHER_USERS;
1019 up_write(&mk->mk_sem);
1024 /* No user claims remaining. Go ahead and wipe the secret. */
1026 if (is_master_key_secret_present(&mk->mk_secret)) {
1027 wipe_master_key_secret(&mk->mk_secret);
1028 fscrypt_put_master_key_activeref(mk);
1031 inodes_remain = refcount_read(&mk->mk_active_refs) > 0;
1032 up_write(&mk->mk_sem);
1034 if (inodes_remain) {
1035 /* Some inodes still reference this key; try to evict them. */
1036 err = try_to_lock_encrypted_files(sb, mk);
1037 if (err == -EBUSY) {
1039 FSCRYPT_KEY_REMOVAL_STATUS_FLAG_FILES_BUSY;
1044 * We return 0 if we successfully did something: removed a claim to the
1045 * key, wiped the secret, or tried locking the files again. Users need
1046 * to check the informational status flags if they care whether the key
1047 * has been fully removed including all files locked.
1050 fscrypt_put_master_key(mk);
1052 err = put_user(status_flags, &uarg->removal_status_flags);
1056 int fscrypt_ioctl_remove_key(struct file *filp, void __user *uarg)
1058 return do_remove_key(filp, uarg, false);
1060 EXPORT_SYMBOL_GPL(fscrypt_ioctl_remove_key);
1062 int fscrypt_ioctl_remove_key_all_users(struct file *filp, void __user *uarg)
1064 if (!capable(CAP_SYS_ADMIN))
1066 return do_remove_key(filp, uarg, true);
1068 EXPORT_SYMBOL_GPL(fscrypt_ioctl_remove_key_all_users);
1071 * Retrieve the status of an fscrypt master encryption key.
1073 * We set ->status to indicate whether the key is absent, present, or
1074 * incompletely removed. "Incompletely removed" means that the master key
1075 * secret has been removed, but some files which had been unlocked with it are
1076 * still in use. This field allows applications to easily determine the state
1077 * of an encrypted directory without using a hack such as trying to open a
1078 * regular file in it (which can confuse the "incompletely removed" state with
1079 * absent or present).
1081 * In addition, for v2 policy keys we allow applications to determine, via
1082 * ->status_flags and ->user_count, whether the key has been added by the
1083 * current user, by other users, or by both. Most applications should not need
1084 * this, since ordinarily only one user should know a given key. However, if a
1085 * secret key is shared by multiple users, applications may wish to add an
1086 * already-present key to prevent other users from removing it. This ioctl can
1087 * be used to check whether that really is the case before the work is done to
1088 * add the key --- which might e.g. require prompting the user for a passphrase.
1090 * For more details, see the "FS_IOC_GET_ENCRYPTION_KEY_STATUS" section of
1091 * Documentation/filesystems/fscrypt.rst.
1093 int fscrypt_ioctl_get_key_status(struct file *filp, void __user *uarg)
1095 struct super_block *sb = file_inode(filp)->i_sb;
1096 struct fscrypt_get_key_status_arg arg;
1097 struct fscrypt_master_key *mk;
1100 if (copy_from_user(&arg, uarg, sizeof(arg)))
1103 if (!valid_key_spec(&arg.key_spec))
1106 if (memchr_inv(arg.__reserved, 0, sizeof(arg.__reserved)))
1109 arg.status_flags = 0;
1111 memset(arg.__out_reserved, 0, sizeof(arg.__out_reserved));
1113 mk = fscrypt_find_master_key(sb, &arg.key_spec);
1115 arg.status = FSCRYPT_KEY_STATUS_ABSENT;
1119 down_read(&mk->mk_sem);
1121 if (!is_master_key_secret_present(&mk->mk_secret)) {
1122 arg.status = refcount_read(&mk->mk_active_refs) > 0 ?
1123 FSCRYPT_KEY_STATUS_INCOMPLETELY_REMOVED :
1124 FSCRYPT_KEY_STATUS_ABSENT /* raced with full removal */;
1126 goto out_release_key;
1129 arg.status = FSCRYPT_KEY_STATUS_PRESENT;
1131 struct key *mk_user;
1133 arg.user_count = mk->mk_users->keys.nr_leaves_on_tree;
1134 mk_user = find_master_key_user(mk);
1135 if (!IS_ERR(mk_user)) {
1137 FSCRYPT_KEY_STATUS_FLAG_ADDED_BY_SELF;
1139 } else if (mk_user != ERR_PTR(-ENOKEY)) {
1140 err = PTR_ERR(mk_user);
1141 goto out_release_key;
1146 up_read(&mk->mk_sem);
1147 fscrypt_put_master_key(mk);
1149 if (!err && copy_to_user(uarg, &arg, sizeof(arg)))
1153 EXPORT_SYMBOL_GPL(fscrypt_ioctl_get_key_status);
1155 int __init fscrypt_init_keyring(void)
1159 err = register_key_type(&key_type_fscrypt_user);
1163 err = register_key_type(&key_type_fscrypt_provisioning);
1165 goto err_unregister_fscrypt_user;
1169 err_unregister_fscrypt_user:
1170 unregister_key_type(&key_type_fscrypt_user);