split dev_queue
[cor.git] / fs / crypto / keyring.c
blob040df1f5e1c8b1d1f6f0bcc766b1e4918ab6e839
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * Filesystem-level keyring for fscrypt
5 * Copyright 2019 Google LLC
6 */
8 /*
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/seq_file.h>
25 #include "fscrypt_private.h"
27 static void wipe_master_key_secret(struct fscrypt_master_key_secret *secret)
29 fscrypt_destroy_hkdf(&secret->hkdf);
30 memzero_explicit(secret, sizeof(*secret));
33 static void move_master_key_secret(struct fscrypt_master_key_secret *dst,
34 struct fscrypt_master_key_secret *src)
36 memcpy(dst, src, sizeof(*dst));
37 memzero_explicit(src, sizeof(*src));
40 static void free_master_key(struct fscrypt_master_key *mk)
42 size_t i;
44 wipe_master_key_secret(&mk->mk_secret);
46 for (i = 0; i <= __FSCRYPT_MODE_MAX; i++) {
47 crypto_free_skcipher(mk->mk_direct_tfms[i]);
48 crypto_free_skcipher(mk->mk_iv_ino_lblk_64_tfms[i]);
51 key_put(mk->mk_users);
52 kzfree(mk);
55 static inline bool valid_key_spec(const struct fscrypt_key_specifier *spec)
57 if (spec->__reserved)
58 return false;
59 return master_key_spec_len(spec) != 0;
62 static int fscrypt_key_instantiate(struct key *key,
63 struct key_preparsed_payload *prep)
65 key->payload.data[0] = (struct fscrypt_master_key *)prep->data;
66 return 0;
69 static void fscrypt_key_destroy(struct key *key)
71 free_master_key(key->payload.data[0]);
74 static void fscrypt_key_describe(const struct key *key, struct seq_file *m)
76 seq_puts(m, key->description);
78 if (key_is_positive(key)) {
79 const struct fscrypt_master_key *mk = key->payload.data[0];
81 if (!is_master_key_secret_present(&mk->mk_secret))
82 seq_puts(m, ": secret removed");
87 * Type of key in ->s_master_keys. Each key of this type represents a master
88 * key which has been added to the filesystem. Its payload is a
89 * 'struct fscrypt_master_key'. The "." prefix in the key type name prevents
90 * users from adding keys of this type via the keyrings syscalls rather than via
91 * the intended method of FS_IOC_ADD_ENCRYPTION_KEY.
93 static struct key_type key_type_fscrypt = {
94 .name = "._fscrypt",
95 .instantiate = fscrypt_key_instantiate,
96 .destroy = fscrypt_key_destroy,
97 .describe = fscrypt_key_describe,
100 static int fscrypt_user_key_instantiate(struct key *key,
101 struct key_preparsed_payload *prep)
104 * We just charge FSCRYPT_MAX_KEY_SIZE bytes to the user's key quota for
105 * each key, regardless of the exact key size. The amount of memory
106 * actually used is greater than the size of the raw key anyway.
108 return key_payload_reserve(key, FSCRYPT_MAX_KEY_SIZE);
111 static void fscrypt_user_key_describe(const struct key *key, struct seq_file *m)
113 seq_puts(m, key->description);
117 * Type of key in ->mk_users. Each key of this type represents a particular
118 * user who has added a particular master key.
120 * Note that the name of this key type really should be something like
121 * ".fscrypt-user" instead of simply ".fscrypt". But the shorter name is chosen
122 * mainly for simplicity of presentation in /proc/keys when read by a non-root
123 * user. And it is expected to be rare that a key is actually added by multiple
124 * users, since users should keep their encryption keys confidential.
126 static struct key_type key_type_fscrypt_user = {
127 .name = ".fscrypt",
128 .instantiate = fscrypt_user_key_instantiate,
129 .describe = fscrypt_user_key_describe,
132 /* Search ->s_master_keys or ->mk_users */
133 static struct key *search_fscrypt_keyring(struct key *keyring,
134 struct key_type *type,
135 const char *description)
138 * We need to mark the keyring reference as "possessed" so that we
139 * acquire permission to search it, via the KEY_POS_SEARCH permission.
141 key_ref_t keyref = make_key_ref(keyring, true /* possessed */);
143 keyref = keyring_search(keyref, type, description, false);
144 if (IS_ERR(keyref)) {
145 if (PTR_ERR(keyref) == -EAGAIN || /* not found */
146 PTR_ERR(keyref) == -EKEYREVOKED) /* recently invalidated */
147 keyref = ERR_PTR(-ENOKEY);
148 return ERR_CAST(keyref);
150 return key_ref_to_ptr(keyref);
153 #define FSCRYPT_FS_KEYRING_DESCRIPTION_SIZE \
154 (CONST_STRLEN("fscrypt-") + FIELD_SIZEOF(struct super_block, s_id))
156 #define FSCRYPT_MK_DESCRIPTION_SIZE (2 * FSCRYPT_KEY_IDENTIFIER_SIZE + 1)
158 #define FSCRYPT_MK_USERS_DESCRIPTION_SIZE \
159 (CONST_STRLEN("fscrypt-") + 2 * FSCRYPT_KEY_IDENTIFIER_SIZE + \
160 CONST_STRLEN("-users") + 1)
162 #define FSCRYPT_MK_USER_DESCRIPTION_SIZE \
163 (2 * FSCRYPT_KEY_IDENTIFIER_SIZE + CONST_STRLEN(".uid.") + 10 + 1)
165 static void format_fs_keyring_description(
166 char description[FSCRYPT_FS_KEYRING_DESCRIPTION_SIZE],
167 const struct super_block *sb)
169 sprintf(description, "fscrypt-%s", sb->s_id);
172 static void format_mk_description(
173 char description[FSCRYPT_MK_DESCRIPTION_SIZE],
174 const struct fscrypt_key_specifier *mk_spec)
176 sprintf(description, "%*phN",
177 master_key_spec_len(mk_spec), (u8 *)&mk_spec->u);
180 static void format_mk_users_keyring_description(
181 char description[FSCRYPT_MK_USERS_DESCRIPTION_SIZE],
182 const u8 mk_identifier[FSCRYPT_KEY_IDENTIFIER_SIZE])
184 sprintf(description, "fscrypt-%*phN-users",
185 FSCRYPT_KEY_IDENTIFIER_SIZE, mk_identifier);
188 static void format_mk_user_description(
189 char description[FSCRYPT_MK_USER_DESCRIPTION_SIZE],
190 const u8 mk_identifier[FSCRYPT_KEY_IDENTIFIER_SIZE])
193 sprintf(description, "%*phN.uid.%u", FSCRYPT_KEY_IDENTIFIER_SIZE,
194 mk_identifier, __kuid_val(current_fsuid()));
197 /* Create ->s_master_keys if needed. Synchronized by fscrypt_add_key_mutex. */
198 static int allocate_filesystem_keyring(struct super_block *sb)
200 char description[FSCRYPT_FS_KEYRING_DESCRIPTION_SIZE];
201 struct key *keyring;
203 if (sb->s_master_keys)
204 return 0;
206 format_fs_keyring_description(description, sb);
207 keyring = keyring_alloc(description, GLOBAL_ROOT_UID, GLOBAL_ROOT_GID,
208 current_cred(), KEY_POS_SEARCH |
209 KEY_USR_SEARCH | KEY_USR_READ | KEY_USR_VIEW,
210 KEY_ALLOC_NOT_IN_QUOTA, NULL, NULL);
211 if (IS_ERR(keyring))
212 return PTR_ERR(keyring);
214 /* Pairs with READ_ONCE() in fscrypt_find_master_key() */
215 smp_store_release(&sb->s_master_keys, keyring);
216 return 0;
219 void fscrypt_sb_free(struct super_block *sb)
221 key_put(sb->s_master_keys);
222 sb->s_master_keys = NULL;
226 * Find the specified master key in ->s_master_keys.
227 * Returns ERR_PTR(-ENOKEY) if not found.
229 struct key *fscrypt_find_master_key(struct super_block *sb,
230 const struct fscrypt_key_specifier *mk_spec)
232 struct key *keyring;
233 char description[FSCRYPT_MK_DESCRIPTION_SIZE];
235 /* pairs with smp_store_release() in allocate_filesystem_keyring() */
236 keyring = READ_ONCE(sb->s_master_keys);
237 if (keyring == NULL)
238 return ERR_PTR(-ENOKEY); /* No keyring yet, so no keys yet. */
240 format_mk_description(description, mk_spec);
241 return search_fscrypt_keyring(keyring, &key_type_fscrypt, description);
244 static int allocate_master_key_users_keyring(struct fscrypt_master_key *mk)
246 char description[FSCRYPT_MK_USERS_DESCRIPTION_SIZE];
247 struct key *keyring;
249 format_mk_users_keyring_description(description,
250 mk->mk_spec.u.identifier);
251 keyring = keyring_alloc(description, GLOBAL_ROOT_UID, GLOBAL_ROOT_GID,
252 current_cred(), KEY_POS_SEARCH |
253 KEY_USR_SEARCH | KEY_USR_READ | KEY_USR_VIEW,
254 KEY_ALLOC_NOT_IN_QUOTA, NULL, NULL);
255 if (IS_ERR(keyring))
256 return PTR_ERR(keyring);
258 mk->mk_users = keyring;
259 return 0;
263 * Find the current user's "key" in the master key's ->mk_users.
264 * Returns ERR_PTR(-ENOKEY) if not found.
266 static struct key *find_master_key_user(struct fscrypt_master_key *mk)
268 char description[FSCRYPT_MK_USER_DESCRIPTION_SIZE];
270 format_mk_user_description(description, mk->mk_spec.u.identifier);
271 return search_fscrypt_keyring(mk->mk_users, &key_type_fscrypt_user,
272 description);
276 * Give the current user a "key" in ->mk_users. This charges the user's quota
277 * and marks the master key as added by the current user, so that it cannot be
278 * removed by another user with the key. Either the master key's key->sem must
279 * be held for write, or the master key must be still undergoing initialization.
281 static int add_master_key_user(struct fscrypt_master_key *mk)
283 char description[FSCRYPT_MK_USER_DESCRIPTION_SIZE];
284 struct key *mk_user;
285 int err;
287 format_mk_user_description(description, mk->mk_spec.u.identifier);
288 mk_user = key_alloc(&key_type_fscrypt_user, description,
289 current_fsuid(), current_gid(), current_cred(),
290 KEY_POS_SEARCH | KEY_USR_VIEW, 0, NULL);
291 if (IS_ERR(mk_user))
292 return PTR_ERR(mk_user);
294 err = key_instantiate_and_link(mk_user, NULL, 0, mk->mk_users, NULL);
295 key_put(mk_user);
296 return err;
300 * Remove the current user's "key" from ->mk_users.
301 * The master key's key->sem must be held for write.
303 * Returns 0 if removed, -ENOKEY if not found, or another -errno code.
305 static int remove_master_key_user(struct fscrypt_master_key *mk)
307 struct key *mk_user;
308 int err;
310 mk_user = find_master_key_user(mk);
311 if (IS_ERR(mk_user))
312 return PTR_ERR(mk_user);
313 err = key_unlink(mk->mk_users, mk_user);
314 key_put(mk_user);
315 return err;
319 * Allocate a new fscrypt_master_key which contains the given secret, set it as
320 * the payload of a new 'struct key' of type fscrypt, and link the 'struct key'
321 * into the given keyring. Synchronized by fscrypt_add_key_mutex.
323 static int add_new_master_key(struct fscrypt_master_key_secret *secret,
324 const struct fscrypt_key_specifier *mk_spec,
325 struct key *keyring)
327 struct fscrypt_master_key *mk;
328 char description[FSCRYPT_MK_DESCRIPTION_SIZE];
329 struct key *key;
330 int err;
332 mk = kzalloc(sizeof(*mk), GFP_KERNEL);
333 if (!mk)
334 return -ENOMEM;
336 mk->mk_spec = *mk_spec;
338 move_master_key_secret(&mk->mk_secret, secret);
339 init_rwsem(&mk->mk_secret_sem);
341 refcount_set(&mk->mk_refcount, 1); /* secret is present */
342 INIT_LIST_HEAD(&mk->mk_decrypted_inodes);
343 spin_lock_init(&mk->mk_decrypted_inodes_lock);
345 if (mk_spec->type == FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER) {
346 err = allocate_master_key_users_keyring(mk);
347 if (err)
348 goto out_free_mk;
349 err = add_master_key_user(mk);
350 if (err)
351 goto out_free_mk;
355 * Note that we don't charge this key to anyone's quota, since when
356 * ->mk_users is in use those keys are charged instead, and otherwise
357 * (when ->mk_users isn't in use) only root can add these keys.
359 format_mk_description(description, mk_spec);
360 key = key_alloc(&key_type_fscrypt, description,
361 GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, current_cred(),
362 KEY_POS_SEARCH | KEY_USR_SEARCH | KEY_USR_VIEW,
363 KEY_ALLOC_NOT_IN_QUOTA, NULL);
364 if (IS_ERR(key)) {
365 err = PTR_ERR(key);
366 goto out_free_mk;
368 err = key_instantiate_and_link(key, mk, sizeof(*mk), keyring, NULL);
369 key_put(key);
370 if (err)
371 goto out_free_mk;
373 return 0;
375 out_free_mk:
376 free_master_key(mk);
377 return err;
380 #define KEY_DEAD 1
382 static int add_existing_master_key(struct fscrypt_master_key *mk,
383 struct fscrypt_master_key_secret *secret)
385 struct key *mk_user;
386 bool rekey;
387 int err;
390 * If the current user is already in ->mk_users, then there's nothing to
391 * do. (Not applicable for v1 policy keys, which have NULL ->mk_users.)
393 if (mk->mk_users) {
394 mk_user = find_master_key_user(mk);
395 if (mk_user != ERR_PTR(-ENOKEY)) {
396 if (IS_ERR(mk_user))
397 return PTR_ERR(mk_user);
398 key_put(mk_user);
399 return 0;
403 /* If we'll be re-adding ->mk_secret, try to take the reference. */
404 rekey = !is_master_key_secret_present(&mk->mk_secret);
405 if (rekey && !refcount_inc_not_zero(&mk->mk_refcount))
406 return KEY_DEAD;
408 /* Add the current user to ->mk_users, if applicable. */
409 if (mk->mk_users) {
410 err = add_master_key_user(mk);
411 if (err) {
412 if (rekey && refcount_dec_and_test(&mk->mk_refcount))
413 return KEY_DEAD;
414 return err;
418 /* Re-add the secret if needed. */
419 if (rekey) {
420 down_write(&mk->mk_secret_sem);
421 move_master_key_secret(&mk->mk_secret, secret);
422 up_write(&mk->mk_secret_sem);
424 return 0;
427 static int add_master_key(struct super_block *sb,
428 struct fscrypt_master_key_secret *secret,
429 const struct fscrypt_key_specifier *mk_spec)
431 static DEFINE_MUTEX(fscrypt_add_key_mutex);
432 struct key *key;
433 int err;
435 mutex_lock(&fscrypt_add_key_mutex); /* serialize find + link */
436 retry:
437 key = fscrypt_find_master_key(sb, mk_spec);
438 if (IS_ERR(key)) {
439 err = PTR_ERR(key);
440 if (err != -ENOKEY)
441 goto out_unlock;
442 /* Didn't find the key in ->s_master_keys. Add it. */
443 err = allocate_filesystem_keyring(sb);
444 if (err)
445 goto out_unlock;
446 err = add_new_master_key(secret, mk_spec, sb->s_master_keys);
447 } else {
449 * Found the key in ->s_master_keys. Re-add the secret if
450 * needed, and add the user to ->mk_users if needed.
452 down_write(&key->sem);
453 err = add_existing_master_key(key->payload.data[0], secret);
454 up_write(&key->sem);
455 if (err == KEY_DEAD) {
456 /* Key being removed or needs to be removed */
457 key_invalidate(key);
458 key_put(key);
459 goto retry;
461 key_put(key);
463 out_unlock:
464 mutex_unlock(&fscrypt_add_key_mutex);
465 return err;
469 * Add a master encryption key to the filesystem, causing all files which were
470 * encrypted with it to appear "unlocked" (decrypted) when accessed.
472 * When adding a key for use by v1 encryption policies, this ioctl is
473 * privileged, and userspace must provide the 'key_descriptor'.
475 * When adding a key for use by v2+ encryption policies, this ioctl is
476 * unprivileged. This is needed, in general, to allow non-root users to use
477 * encryption without encountering the visibility problems of process-subscribed
478 * keyrings and the inability to properly remove keys. This works by having
479 * each key identified by its cryptographically secure hash --- the
480 * 'key_identifier'. The cryptographic hash ensures that a malicious user
481 * cannot add the wrong key for a given identifier. Furthermore, each added key
482 * is charged to the appropriate user's quota for the keyrings service, which
483 * prevents a malicious user from adding too many keys. Finally, we forbid a
484 * user from removing a key while other users have added it too, which prevents
485 * a user who knows another user's key from causing a denial-of-service by
486 * removing it at an inopportune time. (We tolerate that a user who knows a key
487 * can prevent other users from removing it.)
489 * For more details, see the "FS_IOC_ADD_ENCRYPTION_KEY" section of
490 * Documentation/filesystems/fscrypt.rst.
492 int fscrypt_ioctl_add_key(struct file *filp, void __user *_uarg)
494 struct super_block *sb = file_inode(filp)->i_sb;
495 struct fscrypt_add_key_arg __user *uarg = _uarg;
496 struct fscrypt_add_key_arg arg;
497 struct fscrypt_master_key_secret secret;
498 int err;
500 if (copy_from_user(&arg, uarg, sizeof(arg)))
501 return -EFAULT;
503 if (!valid_key_spec(&arg.key_spec))
504 return -EINVAL;
506 if (arg.raw_size < FSCRYPT_MIN_KEY_SIZE ||
507 arg.raw_size > FSCRYPT_MAX_KEY_SIZE)
508 return -EINVAL;
510 if (memchr_inv(arg.__reserved, 0, sizeof(arg.__reserved)))
511 return -EINVAL;
513 memset(&secret, 0, sizeof(secret));
514 secret.size = arg.raw_size;
515 err = -EFAULT;
516 if (copy_from_user(secret.raw, uarg->raw, secret.size))
517 goto out_wipe_secret;
519 switch (arg.key_spec.type) {
520 case FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR:
522 * Only root can add keys that are identified by an arbitrary
523 * descriptor rather than by a cryptographic hash --- since
524 * otherwise a malicious user could add the wrong key.
526 err = -EACCES;
527 if (!capable(CAP_SYS_ADMIN))
528 goto out_wipe_secret;
529 break;
530 case FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER:
531 err = fscrypt_init_hkdf(&secret.hkdf, secret.raw, secret.size);
532 if (err)
533 goto out_wipe_secret;
536 * Now that the HKDF context is initialized, the raw key is no
537 * longer needed.
539 memzero_explicit(secret.raw, secret.size);
541 /* Calculate the key identifier and return it to userspace. */
542 err = fscrypt_hkdf_expand(&secret.hkdf,
543 HKDF_CONTEXT_KEY_IDENTIFIER,
544 NULL, 0, arg.key_spec.u.identifier,
545 FSCRYPT_KEY_IDENTIFIER_SIZE);
546 if (err)
547 goto out_wipe_secret;
548 err = -EFAULT;
549 if (copy_to_user(uarg->key_spec.u.identifier,
550 arg.key_spec.u.identifier,
551 FSCRYPT_KEY_IDENTIFIER_SIZE))
552 goto out_wipe_secret;
553 break;
554 default:
555 WARN_ON(1);
556 err = -EINVAL;
557 goto out_wipe_secret;
560 err = add_master_key(sb, &secret, &arg.key_spec);
561 out_wipe_secret:
562 wipe_master_key_secret(&secret);
563 return err;
565 EXPORT_SYMBOL_GPL(fscrypt_ioctl_add_key);
568 * Verify that the current user has added a master key with the given identifier
569 * (returns -ENOKEY if not). This is needed to prevent a user from encrypting
570 * their files using some other user's key which they don't actually know.
571 * Cryptographically this isn't much of a problem, but the semantics of this
572 * would be a bit weird, so it's best to just forbid it.
574 * The system administrator (CAP_FOWNER) can override this, which should be
575 * enough for any use cases where encryption policies are being set using keys
576 * that were chosen ahead of time but aren't available at the moment.
578 * Note that the key may have already removed by the time this returns, but
579 * that's okay; we just care whether the key was there at some point.
581 * Return: 0 if the key is added, -ENOKEY if it isn't, or another -errno code
583 int fscrypt_verify_key_added(struct super_block *sb,
584 const u8 identifier[FSCRYPT_KEY_IDENTIFIER_SIZE])
586 struct fscrypt_key_specifier mk_spec;
587 struct key *key, *mk_user;
588 struct fscrypt_master_key *mk;
589 int err;
591 mk_spec.type = FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
592 memcpy(mk_spec.u.identifier, identifier, FSCRYPT_KEY_IDENTIFIER_SIZE);
594 key = fscrypt_find_master_key(sb, &mk_spec);
595 if (IS_ERR(key)) {
596 err = PTR_ERR(key);
597 goto out;
599 mk = key->payload.data[0];
600 mk_user = find_master_key_user(mk);
601 if (IS_ERR(mk_user)) {
602 err = PTR_ERR(mk_user);
603 } else {
604 key_put(mk_user);
605 err = 0;
607 key_put(key);
608 out:
609 if (err == -ENOKEY && capable(CAP_FOWNER))
610 err = 0;
611 return err;
615 * Try to evict the inode's dentries from the dentry cache. If the inode is a
616 * directory, then it can have at most one dentry; however, that dentry may be
617 * pinned by child dentries, so first try to evict the children too.
619 static void shrink_dcache_inode(struct inode *inode)
621 struct dentry *dentry;
623 if (S_ISDIR(inode->i_mode)) {
624 dentry = d_find_any_alias(inode);
625 if (dentry) {
626 shrink_dcache_parent(dentry);
627 dput(dentry);
630 d_prune_aliases(inode);
633 static void evict_dentries_for_decrypted_inodes(struct fscrypt_master_key *mk)
635 struct fscrypt_info *ci;
636 struct inode *inode;
637 struct inode *toput_inode = NULL;
639 spin_lock(&mk->mk_decrypted_inodes_lock);
641 list_for_each_entry(ci, &mk->mk_decrypted_inodes, ci_master_key_link) {
642 inode = ci->ci_inode;
643 spin_lock(&inode->i_lock);
644 if (inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW)) {
645 spin_unlock(&inode->i_lock);
646 continue;
648 __iget(inode);
649 spin_unlock(&inode->i_lock);
650 spin_unlock(&mk->mk_decrypted_inodes_lock);
652 shrink_dcache_inode(inode);
653 iput(toput_inode);
654 toput_inode = inode;
656 spin_lock(&mk->mk_decrypted_inodes_lock);
659 spin_unlock(&mk->mk_decrypted_inodes_lock);
660 iput(toput_inode);
663 static int check_for_busy_inodes(struct super_block *sb,
664 struct fscrypt_master_key *mk)
666 struct list_head *pos;
667 size_t busy_count = 0;
668 unsigned long ino;
669 struct dentry *dentry;
670 char _path[256];
671 char *path = NULL;
673 spin_lock(&mk->mk_decrypted_inodes_lock);
675 list_for_each(pos, &mk->mk_decrypted_inodes)
676 busy_count++;
678 if (busy_count == 0) {
679 spin_unlock(&mk->mk_decrypted_inodes_lock);
680 return 0;
684 /* select an example file to show for debugging purposes */
685 struct inode *inode =
686 list_first_entry(&mk->mk_decrypted_inodes,
687 struct fscrypt_info,
688 ci_master_key_link)->ci_inode;
689 ino = inode->i_ino;
690 dentry = d_find_alias(inode);
692 spin_unlock(&mk->mk_decrypted_inodes_lock);
694 if (dentry) {
695 path = dentry_path(dentry, _path, sizeof(_path));
696 dput(dentry);
698 if (IS_ERR_OR_NULL(path))
699 path = "(unknown)";
701 fscrypt_warn(NULL,
702 "%s: %zu inode(s) still busy after removing key with %s %*phN, including ino %lu (%s)",
703 sb->s_id, busy_count, master_key_spec_type(&mk->mk_spec),
704 master_key_spec_len(&mk->mk_spec), (u8 *)&mk->mk_spec.u,
705 ino, path);
706 return -EBUSY;
709 static int try_to_lock_encrypted_files(struct super_block *sb,
710 struct fscrypt_master_key *mk)
712 int err1;
713 int err2;
716 * An inode can't be evicted while it is dirty or has dirty pages.
717 * Thus, we first have to clean the inodes in ->mk_decrypted_inodes.
719 * Just do it the easy way: call sync_filesystem(). It's overkill, but
720 * it works, and it's more important to minimize the amount of caches we
721 * drop than the amount of data we sync. Also, unprivileged users can
722 * already call sync_filesystem() via sys_syncfs() or sys_sync().
724 down_read(&sb->s_umount);
725 err1 = sync_filesystem(sb);
726 up_read(&sb->s_umount);
727 /* If a sync error occurs, still try to evict as much as possible. */
730 * Inodes are pinned by their dentries, so we have to evict their
731 * dentries. shrink_dcache_sb() would suffice, but would be overkill
732 * and inappropriate for use by unprivileged users. So instead go
733 * through the inodes' alias lists and try to evict each dentry.
735 evict_dentries_for_decrypted_inodes(mk);
738 * evict_dentries_for_decrypted_inodes() already iput() each inode in
739 * the list; any inodes for which that dropped the last reference will
740 * have been evicted due to fscrypt_drop_inode() detecting the key
741 * removal and telling the VFS to evict the inode. So to finish, we
742 * just need to check whether any inodes couldn't be evicted.
744 err2 = check_for_busy_inodes(sb, mk);
746 return err1 ?: err2;
750 * Try to remove an fscrypt master encryption key.
752 * FS_IOC_REMOVE_ENCRYPTION_KEY (all_users=false) removes the current user's
753 * claim to the key, then removes the key itself if no other users have claims.
754 * FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS (all_users=true) always removes the
755 * key itself.
757 * To "remove the key itself", first we wipe the actual master key secret, so
758 * that no more inodes can be unlocked with it. Then we try to evict all cached
759 * inodes that had been unlocked with the key.
761 * If all inodes were evicted, then we unlink the fscrypt_master_key from the
762 * keyring. Otherwise it remains in the keyring in the "incompletely removed"
763 * state (without the actual secret key) where it tracks the list of remaining
764 * inodes. Userspace can execute the ioctl again later to retry eviction, or
765 * alternatively can re-add the secret key again.
767 * For more details, see the "Removing keys" section of
768 * Documentation/filesystems/fscrypt.rst.
770 static int do_remove_key(struct file *filp, void __user *_uarg, bool all_users)
772 struct super_block *sb = file_inode(filp)->i_sb;
773 struct fscrypt_remove_key_arg __user *uarg = _uarg;
774 struct fscrypt_remove_key_arg arg;
775 struct key *key;
776 struct fscrypt_master_key *mk;
777 u32 status_flags = 0;
778 int err;
779 bool dead;
781 if (copy_from_user(&arg, uarg, sizeof(arg)))
782 return -EFAULT;
784 if (!valid_key_spec(&arg.key_spec))
785 return -EINVAL;
787 if (memchr_inv(arg.__reserved, 0, sizeof(arg.__reserved)))
788 return -EINVAL;
791 * Only root can add and remove keys that are identified by an arbitrary
792 * descriptor rather than by a cryptographic hash.
794 if (arg.key_spec.type == FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR &&
795 !capable(CAP_SYS_ADMIN))
796 return -EACCES;
798 /* Find the key being removed. */
799 key = fscrypt_find_master_key(sb, &arg.key_spec);
800 if (IS_ERR(key))
801 return PTR_ERR(key);
802 mk = key->payload.data[0];
804 down_write(&key->sem);
806 /* If relevant, remove current user's (or all users) claim to the key */
807 if (mk->mk_users && mk->mk_users->keys.nr_leaves_on_tree != 0) {
808 if (all_users)
809 err = keyring_clear(mk->mk_users);
810 else
811 err = remove_master_key_user(mk);
812 if (err) {
813 up_write(&key->sem);
814 goto out_put_key;
816 if (mk->mk_users->keys.nr_leaves_on_tree != 0) {
818 * Other users have still added the key too. We removed
819 * the current user's claim to the key, but we still
820 * can't remove the key itself.
822 status_flags |=
823 FSCRYPT_KEY_REMOVAL_STATUS_FLAG_OTHER_USERS;
824 err = 0;
825 up_write(&key->sem);
826 goto out_put_key;
830 /* No user claims remaining. Go ahead and wipe the secret. */
831 dead = false;
832 if (is_master_key_secret_present(&mk->mk_secret)) {
833 down_write(&mk->mk_secret_sem);
834 wipe_master_key_secret(&mk->mk_secret);
835 dead = refcount_dec_and_test(&mk->mk_refcount);
836 up_write(&mk->mk_secret_sem);
838 up_write(&key->sem);
839 if (dead) {
841 * No inodes reference the key, and we wiped the secret, so the
842 * key object is free to be removed from the keyring.
844 key_invalidate(key);
845 err = 0;
846 } else {
847 /* Some inodes still reference this key; try to evict them. */
848 err = try_to_lock_encrypted_files(sb, mk);
849 if (err == -EBUSY) {
850 status_flags |=
851 FSCRYPT_KEY_REMOVAL_STATUS_FLAG_FILES_BUSY;
852 err = 0;
856 * We return 0 if we successfully did something: removed a claim to the
857 * key, wiped the secret, or tried locking the files again. Users need
858 * to check the informational status flags if they care whether the key
859 * has been fully removed including all files locked.
861 out_put_key:
862 key_put(key);
863 if (err == 0)
864 err = put_user(status_flags, &uarg->removal_status_flags);
865 return err;
868 int fscrypt_ioctl_remove_key(struct file *filp, void __user *uarg)
870 return do_remove_key(filp, uarg, false);
872 EXPORT_SYMBOL_GPL(fscrypt_ioctl_remove_key);
874 int fscrypt_ioctl_remove_key_all_users(struct file *filp, void __user *uarg)
876 if (!capable(CAP_SYS_ADMIN))
877 return -EACCES;
878 return do_remove_key(filp, uarg, true);
880 EXPORT_SYMBOL_GPL(fscrypt_ioctl_remove_key_all_users);
883 * Retrieve the status of an fscrypt master encryption key.
885 * We set ->status to indicate whether the key is absent, present, or
886 * incompletely removed. "Incompletely removed" means that the master key
887 * secret has been removed, but some files which had been unlocked with it are
888 * still in use. This field allows applications to easily determine the state
889 * of an encrypted directory without using a hack such as trying to open a
890 * regular file in it (which can confuse the "incompletely removed" state with
891 * absent or present).
893 * In addition, for v2 policy keys we allow applications to determine, via
894 * ->status_flags and ->user_count, whether the key has been added by the
895 * current user, by other users, or by both. Most applications should not need
896 * this, since ordinarily only one user should know a given key. However, if a
897 * secret key is shared by multiple users, applications may wish to add an
898 * already-present key to prevent other users from removing it. This ioctl can
899 * be used to check whether that really is the case before the work is done to
900 * add the key --- which might e.g. require prompting the user for a passphrase.
902 * For more details, see the "FS_IOC_GET_ENCRYPTION_KEY_STATUS" section of
903 * Documentation/filesystems/fscrypt.rst.
905 int fscrypt_ioctl_get_key_status(struct file *filp, void __user *uarg)
907 struct super_block *sb = file_inode(filp)->i_sb;
908 struct fscrypt_get_key_status_arg arg;
909 struct key *key;
910 struct fscrypt_master_key *mk;
911 int err;
913 if (copy_from_user(&arg, uarg, sizeof(arg)))
914 return -EFAULT;
916 if (!valid_key_spec(&arg.key_spec))
917 return -EINVAL;
919 if (memchr_inv(arg.__reserved, 0, sizeof(arg.__reserved)))
920 return -EINVAL;
922 arg.status_flags = 0;
923 arg.user_count = 0;
924 memset(arg.__out_reserved, 0, sizeof(arg.__out_reserved));
926 key = fscrypt_find_master_key(sb, &arg.key_spec);
927 if (IS_ERR(key)) {
928 if (key != ERR_PTR(-ENOKEY))
929 return PTR_ERR(key);
930 arg.status = FSCRYPT_KEY_STATUS_ABSENT;
931 err = 0;
932 goto out;
934 mk = key->payload.data[0];
935 down_read(&key->sem);
937 if (!is_master_key_secret_present(&mk->mk_secret)) {
938 arg.status = FSCRYPT_KEY_STATUS_INCOMPLETELY_REMOVED;
939 err = 0;
940 goto out_release_key;
943 arg.status = FSCRYPT_KEY_STATUS_PRESENT;
944 if (mk->mk_users) {
945 struct key *mk_user;
947 arg.user_count = mk->mk_users->keys.nr_leaves_on_tree;
948 mk_user = find_master_key_user(mk);
949 if (!IS_ERR(mk_user)) {
950 arg.status_flags |=
951 FSCRYPT_KEY_STATUS_FLAG_ADDED_BY_SELF;
952 key_put(mk_user);
953 } else if (mk_user != ERR_PTR(-ENOKEY)) {
954 err = PTR_ERR(mk_user);
955 goto out_release_key;
958 err = 0;
959 out_release_key:
960 up_read(&key->sem);
961 key_put(key);
962 out:
963 if (!err && copy_to_user(uarg, &arg, sizeof(arg)))
964 err = -EFAULT;
965 return err;
967 EXPORT_SYMBOL_GPL(fscrypt_ioctl_get_key_status);
969 int __init fscrypt_init_keyring(void)
971 int err;
973 err = register_key_type(&key_type_fscrypt);
974 if (err)
975 return err;
977 err = register_key_type(&key_type_fscrypt_user);
978 if (err)
979 goto err_unregister_fscrypt;
981 return 0;
983 err_unregister_fscrypt:
984 unregister_key_type(&key_type_fscrypt);
985 return err;