1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Filesystem-level keyring for fscrypt
4  *
5  * Copyright 2019 Google LLC
6  */
7 
8 /*
9  * This file implements management of fscrypt master keys in the
10  * filesystem-level keyring, including the ioctls:
11  *
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
16  *
17  * See the "User API" section of Documentation/filesystems/fscrypt.rst for more
18  * information about these ioctls.
19  */
20 
21 #include <linux/unaligned.h>
22 #include <crypto/skcipher.h>
23 #include <linux/key-type.h>
24 #include <linux/random.h>
25 #include <linux/once.h>
26 #include <linux/seq_file.h>
27 
28 #include "fscrypt_private.h"
29 
30 /* The master encryption keys for a filesystem (->s_master_keys) */
31 struct fscrypt_keyring {
32 	/*
33 	 * Lock that protects ->key_hashtable.  It does *not* protect the
34 	 * fscrypt_master_key structs themselves.
35 	 */
36 	spinlock_t lock;
37 
38 	/* Hash table that maps fscrypt_key_specifier to fscrypt_master_key */
39 	struct hlist_head key_hashtable[128];
40 };
41 
42 static void wipe_master_key_secret(struct fscrypt_master_key_secret *secret)
43 {
44 	fscrypt_destroy_hkdf(&secret->hkdf);
45 	memzero_explicit(secret, sizeof(*secret));
46 }
47 
48 static void move_master_key_secret(struct fscrypt_master_key_secret *dst,
49 				   struct fscrypt_master_key_secret *src)
50 {
51 	memcpy(dst, src, sizeof(*dst));
52 	memzero_explicit(src, sizeof(*src));
53 }
54 
55 static void fscrypt_free_master_key(struct rcu_head *head)
56 {
57 	struct fscrypt_master_key *mk =
58 		container_of(head, struct fscrypt_master_key, mk_rcu_head);
59 	/*
60 	 * The master key secret and any embedded subkeys should have already
61 	 * been wiped when the last active reference to the fscrypt_master_key
62 	 * struct was dropped; doing it here would be unnecessarily late.
63 	 * Nevertheless, use kfree_sensitive() in case anything was missed.
64 	 */
65 	kfree_sensitive(mk);
66 }
67 
68 void fscrypt_put_master_key(struct fscrypt_master_key *mk)
69 {
70 	if (!refcount_dec_and_test(&mk->mk_struct_refs))
71 		return;
72 	/*
73 	 * No structural references left, so free ->mk_users, and also free the
74 	 * fscrypt_master_key struct itself after an RCU grace period ensures
75 	 * that concurrent keyring lookups can no longer find it.
76 	 */
77 	WARN_ON_ONCE(refcount_read(&mk->mk_active_refs) != 0);
78 	if (mk->mk_users) {
79 		/* Clear the keyring so the quota gets released right away. */
80 		keyring_clear(mk->mk_users);
81 		key_put(mk->mk_users);
82 		mk->mk_users = NULL;
83 	}
84 	call_rcu(&mk->mk_rcu_head, fscrypt_free_master_key);
85 }
86 
87 void fscrypt_put_master_key_activeref(struct super_block *sb,
88 				      struct fscrypt_master_key *mk)
89 {
90 	size_t i;
91 
92 	if (!refcount_dec_and_test(&mk->mk_active_refs))
93 		return;
94 	/*
95 	 * No active references left, so complete the full removal of this
96 	 * fscrypt_master_key struct by removing it from the keyring and
97 	 * destroying any subkeys embedded in it.
98 	 */
99 
100 	if (WARN_ON_ONCE(!sb->s_master_keys))
101 		return;
102 	spin_lock(&sb->s_master_keys->lock);
103 	hlist_del_rcu(&mk->mk_node);
104 	spin_unlock(&sb->s_master_keys->lock);
105 
106 	/*
107 	 * ->mk_active_refs == 0 implies that ->mk_present is false and
108 	 * ->mk_decrypted_inodes is empty.
109 	 */
110 	WARN_ON_ONCE(mk->mk_present);
111 	WARN_ON_ONCE(!list_empty(&mk->mk_decrypted_inodes));
112 
113 	for (i = 0; i <= FSCRYPT_MODE_MAX; i++) {
114 		fscrypt_destroy_prepared_key(
115 				sb, &mk->mk_direct_keys[i]);
116 		fscrypt_destroy_prepared_key(
117 				sb, &mk->mk_iv_ino_lblk_64_keys[i]);
118 		fscrypt_destroy_prepared_key(
119 				sb, &mk->mk_iv_ino_lblk_32_keys[i]);
120 	}
121 	memzero_explicit(&mk->mk_ino_hash_key,
122 			 sizeof(mk->mk_ino_hash_key));
123 	mk->mk_ino_hash_key_initialized = false;
124 
125 	/* Drop the structural ref associated with the active refs. */
126 	fscrypt_put_master_key(mk);
127 }
128 
129 /*
130  * This transitions the key state from present to incompletely removed, and then
131  * potentially to absent (depending on whether inodes remain).
132  */
133 static void fscrypt_initiate_key_removal(struct super_block *sb,
134 					 struct fscrypt_master_key *mk)
135 {
136 	WRITE_ONCE(mk->mk_present, false);
137 	wipe_master_key_secret(&mk->mk_secret);
138 	fscrypt_put_master_key_activeref(sb, mk);
139 }
140 
141 static inline bool valid_key_spec(const struct fscrypt_key_specifier *spec)
142 {
143 	if (spec->__reserved)
144 		return false;
145 	return master_key_spec_len(spec) != 0;
146 }
147 
148 static int fscrypt_user_key_instantiate(struct key *key,
149 					struct key_preparsed_payload *prep)
150 {
151 	/*
152 	 * We just charge FSCRYPT_MAX_RAW_KEY_SIZE bytes to the user's key quota
153 	 * for each key, regardless of the exact key size.  The amount of memory
154 	 * actually used is greater than the size of the raw key anyway.
155 	 */
156 	return key_payload_reserve(key, FSCRYPT_MAX_RAW_KEY_SIZE);
157 }
158 
159 static void fscrypt_user_key_describe(const struct key *key, struct seq_file *m)
160 {
161 	seq_puts(m, key->description);
162 }
163 
164 /*
165  * Type of key in ->mk_users.  Each key of this type represents a particular
166  * user who has added a particular master key.
167  *
168  * Note that the name of this key type really should be something like
169  * ".fscrypt-user" instead of simply ".fscrypt".  But the shorter name is chosen
170  * mainly for simplicity of presentation in /proc/keys when read by a non-root
171  * user.  And it is expected to be rare that a key is actually added by multiple
172  * users, since users should keep their encryption keys confidential.
173  */
174 static struct key_type key_type_fscrypt_user = {
175 	.name			= ".fscrypt",
176 	.instantiate		= fscrypt_user_key_instantiate,
177 	.describe		= fscrypt_user_key_describe,
178 };
179 
180 #define FSCRYPT_MK_USERS_DESCRIPTION_SIZE	\
181 	(CONST_STRLEN("fscrypt-") + 2 * FSCRYPT_KEY_IDENTIFIER_SIZE + \
182 	 CONST_STRLEN("-users") + 1)
183 
184 #define FSCRYPT_MK_USER_DESCRIPTION_SIZE	\
185 	(2 * FSCRYPT_KEY_IDENTIFIER_SIZE + CONST_STRLEN(".uid.") + 10 + 1)
186 
187 static void format_mk_users_keyring_description(
188 			char description[FSCRYPT_MK_USERS_DESCRIPTION_SIZE],
189 			const u8 mk_identifier[FSCRYPT_KEY_IDENTIFIER_SIZE])
190 {
191 	sprintf(description, "fscrypt-%*phN-users",
192 		FSCRYPT_KEY_IDENTIFIER_SIZE, mk_identifier);
193 }
194 
195 static void format_mk_user_description(
196 			char description[FSCRYPT_MK_USER_DESCRIPTION_SIZE],
197 			const u8 mk_identifier[FSCRYPT_KEY_IDENTIFIER_SIZE])
198 {
199 
200 	sprintf(description, "%*phN.uid.%u", FSCRYPT_KEY_IDENTIFIER_SIZE,
201 		mk_identifier, __kuid_val(current_fsuid()));
202 }
203 
204 /* Create ->s_master_keys if needed.  Synchronized by fscrypt_add_key_mutex. */
205 static int allocate_filesystem_keyring(struct super_block *sb)
206 {
207 	struct fscrypt_keyring *keyring;
208 
209 	if (sb->s_master_keys)
210 		return 0;
211 
212 	keyring = kzalloc(sizeof(*keyring), GFP_KERNEL);
213 	if (!keyring)
214 		return -ENOMEM;
215 	spin_lock_init(&keyring->lock);
216 	/*
217 	 * Pairs with the smp_load_acquire() in fscrypt_find_master_key().
218 	 * I.e., here we publish ->s_master_keys with a RELEASE barrier so that
219 	 * concurrent tasks can ACQUIRE it.
220 	 */
221 	smp_store_release(&sb->s_master_keys, keyring);
222 	return 0;
223 }
224 
225 /*
226  * Release all encryption keys that have been added to the filesystem, along
227  * with the keyring that contains them.
228  *
229  * This is called at unmount time, after all potentially-encrypted inodes have
230  * been evicted.  The filesystem's underlying block device(s) are still
231  * available at this time; this is important because after user file accesses
232  * have been allowed, this function may need to evict keys from the keyslots of
233  * an inline crypto engine, which requires the block device(s).
234  */
235 void fscrypt_destroy_keyring(struct super_block *sb)
236 {
237 	struct fscrypt_keyring *keyring = sb->s_master_keys;
238 	size_t i;
239 
240 	if (!keyring)
241 		return;
242 
243 	for (i = 0; i < ARRAY_SIZE(keyring->key_hashtable); i++) {
244 		struct hlist_head *bucket = &keyring->key_hashtable[i];
245 		struct fscrypt_master_key *mk;
246 		struct hlist_node *tmp;
247 
248 		hlist_for_each_entry_safe(mk, tmp, bucket, mk_node) {
249 			/*
250 			 * Since all potentially-encrypted inodes were already
251 			 * evicted, every key remaining in the keyring should
252 			 * have an empty inode list, and should only still be in
253 			 * the keyring due to the single active ref associated
254 			 * with ->mk_present.  There should be no structural
255 			 * refs beyond the one associated with the active ref.
256 			 */
257 			WARN_ON_ONCE(refcount_read(&mk->mk_active_refs) != 1);
258 			WARN_ON_ONCE(refcount_read(&mk->mk_struct_refs) != 1);
259 			WARN_ON_ONCE(!mk->mk_present);
260 			fscrypt_initiate_key_removal(sb, mk);
261 		}
262 	}
263 	kfree_sensitive(keyring);
264 	sb->s_master_keys = NULL;
265 }
266 
267 static struct hlist_head *
268 fscrypt_mk_hash_bucket(struct fscrypt_keyring *keyring,
269 		       const struct fscrypt_key_specifier *mk_spec)
270 {
271 	/*
272 	 * Since key specifiers should be "random" values, it is sufficient to
273 	 * use a trivial hash function that just takes the first several bits of
274 	 * the key specifier.
275 	 */
276 	unsigned long i = get_unaligned((unsigned long *)&mk_spec->u);
277 
278 	return &keyring->key_hashtable[i % ARRAY_SIZE(keyring->key_hashtable)];
279 }
280 
281 /*
282  * Find the specified master key struct in ->s_master_keys and take a structural
283  * ref to it.  The structural ref guarantees that the key struct continues to
284  * exist, but it does *not* guarantee that ->s_master_keys continues to contain
285  * the key struct.  The structural ref needs to be dropped by
286  * fscrypt_put_master_key().  Returns NULL if the key struct is not found.
287  */
288 struct fscrypt_master_key *
289 fscrypt_find_master_key(struct super_block *sb,
290 			const struct fscrypt_key_specifier *mk_spec)
291 {
292 	struct fscrypt_keyring *keyring;
293 	struct hlist_head *bucket;
294 	struct fscrypt_master_key *mk;
295 
296 	/*
297 	 * Pairs with the smp_store_release() in allocate_filesystem_keyring().
298 	 * I.e., another task can publish ->s_master_keys concurrently,
299 	 * executing a RELEASE barrier.  We need to use smp_load_acquire() here
300 	 * to safely ACQUIRE the memory the other task published.
301 	 */
302 	keyring = smp_load_acquire(&sb->s_master_keys);
303 	if (keyring == NULL)
304 		return NULL; /* No keyring yet, so no keys yet. */
305 
306 	bucket = fscrypt_mk_hash_bucket(keyring, mk_spec);
307 	rcu_read_lock();
308 	switch (mk_spec->type) {
309 	case FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR:
310 		hlist_for_each_entry_rcu(mk, bucket, mk_node) {
311 			if (mk->mk_spec.type ==
312 				FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR &&
313 			    memcmp(mk->mk_spec.u.descriptor,
314 				   mk_spec->u.descriptor,
315 				   FSCRYPT_KEY_DESCRIPTOR_SIZE) == 0 &&
316 			    refcount_inc_not_zero(&mk->mk_struct_refs))
317 				goto out;
318 		}
319 		break;
320 	case FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER:
321 		hlist_for_each_entry_rcu(mk, bucket, mk_node) {
322 			if (mk->mk_spec.type ==
323 				FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER &&
324 			    memcmp(mk->mk_spec.u.identifier,
325 				   mk_spec->u.identifier,
326 				   FSCRYPT_KEY_IDENTIFIER_SIZE) == 0 &&
327 			    refcount_inc_not_zero(&mk->mk_struct_refs))
328 				goto out;
329 		}
330 		break;
331 	}
332 	mk = NULL;
333 out:
334 	rcu_read_unlock();
335 	return mk;
336 }
337 
338 static int allocate_master_key_users_keyring(struct fscrypt_master_key *mk)
339 {
340 	char description[FSCRYPT_MK_USERS_DESCRIPTION_SIZE];
341 	struct key *keyring;
342 
343 	format_mk_users_keyring_description(description,
344 					    mk->mk_spec.u.identifier);
345 	keyring = keyring_alloc(description, GLOBAL_ROOT_UID, GLOBAL_ROOT_GID,
346 				current_cred(), KEY_POS_SEARCH |
347 				  KEY_USR_SEARCH | KEY_USR_READ | KEY_USR_VIEW,
348 				KEY_ALLOC_NOT_IN_QUOTA, NULL, NULL);
349 	if (IS_ERR(keyring))
350 		return PTR_ERR(keyring);
351 
352 	mk->mk_users = keyring;
353 	return 0;
354 }
355 
356 /*
357  * Find the current user's "key" in the master key's ->mk_users.
358  * Returns ERR_PTR(-ENOKEY) if not found.
359  */
360 static struct key *find_master_key_user(struct fscrypt_master_key *mk)
361 {
362 	char description[FSCRYPT_MK_USER_DESCRIPTION_SIZE];
363 	key_ref_t keyref;
364 
365 	format_mk_user_description(description, mk->mk_spec.u.identifier);
366 
367 	/*
368 	 * We need to mark the keyring reference as "possessed" so that we
369 	 * acquire permission to search it, via the KEY_POS_SEARCH permission.
370 	 */
371 	keyref = keyring_search(make_key_ref(mk->mk_users, true /*possessed*/),
372 				&key_type_fscrypt_user, description, false);
373 	if (IS_ERR(keyref)) {
374 		if (PTR_ERR(keyref) == -EAGAIN || /* not found */
375 		    PTR_ERR(keyref) == -EKEYREVOKED) /* recently invalidated */
376 			keyref = ERR_PTR(-ENOKEY);
377 		return ERR_CAST(keyref);
378 	}
379 	return key_ref_to_ptr(keyref);
380 }
381 
382 /*
383  * Give the current user a "key" in ->mk_users.  This charges the user's quota
384  * and marks the master key as added by the current user, so that it cannot be
385  * removed by another user with the key.  Either ->mk_sem must be held for
386  * write, or the master key must be still undergoing initialization.
387  */
388 static int add_master_key_user(struct fscrypt_master_key *mk)
389 {
390 	char description[FSCRYPT_MK_USER_DESCRIPTION_SIZE];
391 	struct key *mk_user;
392 	int err;
393 
394 	format_mk_user_description(description, mk->mk_spec.u.identifier);
395 	mk_user = key_alloc(&key_type_fscrypt_user, description,
396 			    current_fsuid(), current_gid(), current_cred(),
397 			    KEY_POS_SEARCH | KEY_USR_VIEW, 0, NULL);
398 	if (IS_ERR(mk_user))
399 		return PTR_ERR(mk_user);
400 
401 	err = key_instantiate_and_link(mk_user, NULL, 0, mk->mk_users, NULL);
402 	key_put(mk_user);
403 	return err;
404 }
405 
406 /*
407  * Remove the current user's "key" from ->mk_users.
408  * ->mk_sem must be held for write.
409  *
410  * Returns 0 if removed, -ENOKEY if not found, or another -errno code.
411  */
412 static int remove_master_key_user(struct fscrypt_master_key *mk)
413 {
414 	struct key *mk_user;
415 	int err;
416 
417 	mk_user = find_master_key_user(mk);
418 	if (IS_ERR(mk_user))
419 		return PTR_ERR(mk_user);
420 	err = key_unlink(mk->mk_users, mk_user);
421 	key_put(mk_user);
422 	return err;
423 }
424 
425 /*
426  * Allocate a new fscrypt_master_key, transfer the given secret over to it, and
427  * insert it into sb->s_master_keys.
428  */
429 static int add_new_master_key(struct super_block *sb,
430 			      struct fscrypt_master_key_secret *secret,
431 			      const struct fscrypt_key_specifier *mk_spec)
432 {
433 	struct fscrypt_keyring *keyring = sb->s_master_keys;
434 	struct fscrypt_master_key *mk;
435 	int err;
436 
437 	mk = kzalloc(sizeof(*mk), GFP_KERNEL);
438 	if (!mk)
439 		return -ENOMEM;
440 
441 	init_rwsem(&mk->mk_sem);
442 	refcount_set(&mk->mk_struct_refs, 1);
443 	mk->mk_spec = *mk_spec;
444 
445 	INIT_LIST_HEAD(&mk->mk_decrypted_inodes);
446 	spin_lock_init(&mk->mk_decrypted_inodes_lock);
447 
448 	if (mk_spec->type == FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER) {
449 		err = allocate_master_key_users_keyring(mk);
450 		if (err)
451 			goto out_put;
452 		err = add_master_key_user(mk);
453 		if (err)
454 			goto out_put;
455 	}
456 
457 	move_master_key_secret(&mk->mk_secret, secret);
458 	mk->mk_present = true;
459 	refcount_set(&mk->mk_active_refs, 1); /* ->mk_present is true */
460 
461 	spin_lock(&keyring->lock);
462 	hlist_add_head_rcu(&mk->mk_node,
463 			   fscrypt_mk_hash_bucket(keyring, mk_spec));
464 	spin_unlock(&keyring->lock);
465 	return 0;
466 
467 out_put:
468 	fscrypt_put_master_key(mk);
469 	return err;
470 }
471 
472 #define KEY_DEAD	1
473 
474 static int add_existing_master_key(struct fscrypt_master_key *mk,
475 				   struct fscrypt_master_key_secret *secret)
476 {
477 	int err;
478 
479 	/*
480 	 * If the current user is already in ->mk_users, then there's nothing to
481 	 * do.  Otherwise, we need to add the user to ->mk_users.  (Neither is
482 	 * applicable for v1 policy keys, which have NULL ->mk_users.)
483 	 */
484 	if (mk->mk_users) {
485 		struct key *mk_user = find_master_key_user(mk);
486 
487 		if (mk_user != ERR_PTR(-ENOKEY)) {
488 			if (IS_ERR(mk_user))
489 				return PTR_ERR(mk_user);
490 			key_put(mk_user);
491 			return 0;
492 		}
493 		err = add_master_key_user(mk);
494 		if (err)
495 			return err;
496 	}
497 
498 	/* If the key is incompletely removed, make it present again. */
499 	if (!mk->mk_present) {
500 		if (!refcount_inc_not_zero(&mk->mk_active_refs)) {
501 			/*
502 			 * Raced with the last active ref being dropped, so the
503 			 * key has become, or is about to become, "absent".
504 			 * Therefore, we need to allocate a new key struct.
505 			 */
506 			return KEY_DEAD;
507 		}
508 		move_master_key_secret(&mk->mk_secret, secret);
509 		WRITE_ONCE(mk->mk_present, true);
510 	}
511 
512 	return 0;
513 }
514 
515 static int do_add_master_key(struct super_block *sb,
516 			     struct fscrypt_master_key_secret *secret,
517 			     const struct fscrypt_key_specifier *mk_spec)
518 {
519 	static DEFINE_MUTEX(fscrypt_add_key_mutex);
520 	struct fscrypt_master_key *mk;
521 	int err;
522 
523 	mutex_lock(&fscrypt_add_key_mutex); /* serialize find + link */
524 
525 	mk = fscrypt_find_master_key(sb, mk_spec);
526 	if (!mk) {
527 		/* Didn't find the key in ->s_master_keys.  Add it. */
528 		err = allocate_filesystem_keyring(sb);
529 		if (!err)
530 			err = add_new_master_key(sb, secret, mk_spec);
531 	} else {
532 		/*
533 		 * Found the key in ->s_master_keys.  Add the user to ->mk_users
534 		 * if needed, and make the key "present" again if possible.
535 		 */
536 		down_write(&mk->mk_sem);
537 		err = add_existing_master_key(mk, secret);
538 		up_write(&mk->mk_sem);
539 		if (err == KEY_DEAD) {
540 			/*
541 			 * We found a key struct, but it's already been fully
542 			 * removed.  Ignore the old struct and add a new one.
543 			 * fscrypt_add_key_mutex means we don't need to worry
544 			 * about concurrent adds.
545 			 */
546 			err = add_new_master_key(sb, secret, mk_spec);
547 		}
548 		fscrypt_put_master_key(mk);
549 	}
550 	mutex_unlock(&fscrypt_add_key_mutex);
551 	return err;
552 }
553 
554 static int add_master_key(struct super_block *sb,
555 			  struct fscrypt_master_key_secret *secret,
556 			  struct fscrypt_key_specifier *key_spec)
557 {
558 	int err;
559 
560 	if (key_spec->type == FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER) {
561 		u8 sw_secret[BLK_CRYPTO_SW_SECRET_SIZE];
562 		u8 *kdf_key = secret->bytes;
563 		unsigned int kdf_key_size = secret->size;
564 		u8 keyid_kdf_ctx = HKDF_CONTEXT_KEY_IDENTIFIER_FOR_RAW_KEY;
565 
566 		/*
567 		 * For raw keys, the fscrypt master key is used directly as the
568 		 * fscrypt KDF key.  For hardware-wrapped keys, we have to pass
569 		 * the master key to the hardware to derive the KDF key, which
570 		 * is then only used to derive non-file-contents subkeys.
571 		 */
572 		if (secret->is_hw_wrapped) {
573 			err = fscrypt_derive_sw_secret(sb, secret->bytes,
574 						       secret->size, sw_secret);
575 			if (err)
576 				return err;
577 			kdf_key = sw_secret;
578 			kdf_key_size = sizeof(sw_secret);
579 			/*
580 			 * To avoid weird behavior if someone manages to
581 			 * determine sw_secret and add it as a raw key, ensure
582 			 * that hardware-wrapped keys and raw keys will have
583 			 * different key identifiers by deriving their key
584 			 * identifiers using different KDF contexts.
585 			 */
586 			keyid_kdf_ctx =
587 				HKDF_CONTEXT_KEY_IDENTIFIER_FOR_HW_WRAPPED_KEY;
588 		}
589 		err = fscrypt_init_hkdf(&secret->hkdf, kdf_key, kdf_key_size);
590 		/*
591 		 * Now that the KDF context is initialized, the raw KDF key is
592 		 * no longer needed.
593 		 */
594 		memzero_explicit(kdf_key, kdf_key_size);
595 		if (err)
596 			return err;
597 
598 		/* Calculate the key identifier */
599 		err = fscrypt_hkdf_expand(&secret->hkdf, keyid_kdf_ctx, NULL, 0,
600 					  key_spec->u.identifier,
601 					  FSCRYPT_KEY_IDENTIFIER_SIZE);
602 		if (err)
603 			return err;
604 	}
605 	return do_add_master_key(sb, secret, key_spec);
606 }
607 
608 /*
609  * Validate the size of an fscrypt master key being added.  Note that this is
610  * just an initial check, as we don't know which ciphers will be used yet.
611  * There is a stricter size check later when the key is actually used by a file.
612  */
613 static inline bool fscrypt_valid_key_size(size_t size, u32 add_key_flags)
614 {
615 	u32 max_size = (add_key_flags & FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED) ?
616 		       FSCRYPT_MAX_HW_WRAPPED_KEY_SIZE :
617 		       FSCRYPT_MAX_RAW_KEY_SIZE;
618 
619 	return size >= FSCRYPT_MIN_KEY_SIZE && size <= max_size;
620 }
621 
622 static int fscrypt_provisioning_key_preparse(struct key_preparsed_payload *prep)
623 {
624 	const struct fscrypt_provisioning_key_payload *payload = prep->data;
625 
626 	if (prep->datalen < sizeof(*payload))
627 		return -EINVAL;
628 
629 	if (!fscrypt_valid_key_size(prep->datalen - sizeof(*payload),
630 				    payload->flags))
631 		return -EINVAL;
632 
633 	if (payload->type != FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR &&
634 	    payload->type != FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER)
635 		return -EINVAL;
636 
637 	if (payload->flags & ~FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED)
638 		return -EINVAL;
639 
640 	prep->payload.data[0] = kmemdup(payload, prep->datalen, GFP_KERNEL);
641 	if (!prep->payload.data[0])
642 		return -ENOMEM;
643 
644 	prep->quotalen = prep->datalen;
645 	return 0;
646 }
647 
648 static void fscrypt_provisioning_key_free_preparse(
649 					struct key_preparsed_payload *prep)
650 {
651 	kfree_sensitive(prep->payload.data[0]);
652 }
653 
654 static void fscrypt_provisioning_key_describe(const struct key *key,
655 					      struct seq_file *m)
656 {
657 	seq_puts(m, key->description);
658 	if (key_is_positive(key)) {
659 		const struct fscrypt_provisioning_key_payload *payload =
660 			key->payload.data[0];
661 
662 		seq_printf(m, ": %u [%u]", key->datalen, payload->type);
663 	}
664 }
665 
666 static void fscrypt_provisioning_key_destroy(struct key *key)
667 {
668 	kfree_sensitive(key->payload.data[0]);
669 }
670 
671 static struct key_type key_type_fscrypt_provisioning = {
672 	.name			= "fscrypt-provisioning",
673 	.preparse		= fscrypt_provisioning_key_preparse,
674 	.free_preparse		= fscrypt_provisioning_key_free_preparse,
675 	.instantiate		= generic_key_instantiate,
676 	.describe		= fscrypt_provisioning_key_describe,
677 	.destroy		= fscrypt_provisioning_key_destroy,
678 };
679 
680 /*
681  * Retrieve the key from the Linux keyring key specified by 'key_id', and store
682  * it into 'secret'.
683  *
684  * The key must be of type "fscrypt-provisioning" and must have the 'type' and
685  * 'flags' field of the payload set to the given values, indicating that the key
686  * is intended for use for the specified purpose.  We don't use the "logon" key
687  * type because there's no way to completely restrict the use of such keys; they
688  * can be used by any kernel API that accepts "logon" keys and doesn't require a
689  * specific service prefix.
690  *
691  * The ability to specify the key via Linux keyring key is intended for cases
692  * where userspace needs to re-add keys after the filesystem is unmounted and
693  * re-mounted.  Most users should just provide the key directly instead.
694  */
695 static int get_keyring_key(u32 key_id, u32 type, u32 flags,
696 			   struct fscrypt_master_key_secret *secret)
697 {
698 	key_ref_t ref;
699 	struct key *key;
700 	const struct fscrypt_provisioning_key_payload *payload;
701 	int err;
702 
703 	ref = lookup_user_key(key_id, 0, KEY_NEED_SEARCH);
704 	if (IS_ERR(ref))
705 		return PTR_ERR(ref);
706 	key = key_ref_to_ptr(ref);
707 
708 	if (key->type != &key_type_fscrypt_provisioning)
709 		goto bad_key;
710 	payload = key->payload.data[0];
711 
712 	/*
713 	 * Don't allow fscrypt v1 keys to be used as v2 keys and vice versa.
714 	 * Similarly, don't allow hardware-wrapped keys to be used as
715 	 * non-hardware-wrapped keys and vice versa.
716 	 */
717 	if (payload->type != type || payload->flags != flags)
718 		goto bad_key;
719 
720 	secret->size = key->datalen - sizeof(*payload);
721 	memcpy(secret->bytes, payload->raw, secret->size);
722 	err = 0;
723 	goto out_put;
724 
725 bad_key:
726 	err = -EKEYREJECTED;
727 out_put:
728 	key_ref_put(ref);
729 	return err;
730 }
731 
732 /*
733  * Add a master encryption key to the filesystem, causing all files which were
734  * encrypted with it to appear "unlocked" (decrypted) when accessed.
735  *
736  * When adding a key for use by v1 encryption policies, this ioctl is
737  * privileged, and userspace must provide the 'key_descriptor'.
738  *
739  * When adding a key for use by v2+ encryption policies, this ioctl is
740  * unprivileged.  This is needed, in general, to allow non-root users to use
741  * encryption without encountering the visibility problems of process-subscribed
742  * keyrings and the inability to properly remove keys.  This works by having
743  * each key identified by its cryptographically secure hash --- the
744  * 'key_identifier'.  The cryptographic hash ensures that a malicious user
745  * cannot add the wrong key for a given identifier.  Furthermore, each added key
746  * is charged to the appropriate user's quota for the keyrings service, which
747  * prevents a malicious user from adding too many keys.  Finally, we forbid a
748  * user from removing a key while other users have added it too, which prevents
749  * a user who knows another user's key from causing a denial-of-service by
750  * removing it at an inopportune time.  (We tolerate that a user who knows a key
751  * can prevent other users from removing it.)
752  *
753  * For more details, see the "FS_IOC_ADD_ENCRYPTION_KEY" section of
754  * Documentation/filesystems/fscrypt.rst.
755  */
756 int fscrypt_ioctl_add_key(struct file *filp, void __user *_uarg)
757 {
758 	struct super_block *sb = file_inode(filp)->i_sb;
759 	struct fscrypt_add_key_arg __user *uarg = _uarg;
760 	struct fscrypt_add_key_arg arg;
761 	struct fscrypt_master_key_secret secret;
762 	int err;
763 
764 	if (copy_from_user(&arg, uarg, sizeof(arg)))
765 		return -EFAULT;
766 
767 	if (!valid_key_spec(&arg.key_spec))
768 		return -EINVAL;
769 
770 	if (memchr_inv(arg.__reserved, 0, sizeof(arg.__reserved)))
771 		return -EINVAL;
772 
773 	/*
774 	 * Only root can add keys that are identified by an arbitrary descriptor
775 	 * rather than by a cryptographic hash --- since otherwise a malicious
776 	 * user could add the wrong key.
777 	 */
778 	if (arg.key_spec.type == FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR &&
779 	    !capable(CAP_SYS_ADMIN))
780 		return -EACCES;
781 
782 	memset(&secret, 0, sizeof(secret));
783 
784 	if (arg.flags) {
785 		if (arg.flags & ~FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED)
786 			return -EINVAL;
787 		if (arg.key_spec.type != FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER)
788 			return -EINVAL;
789 		secret.is_hw_wrapped = true;
790 	}
791 
792 	if (arg.key_id) {
793 		if (arg.raw_size != 0)
794 			return -EINVAL;
795 		err = get_keyring_key(arg.key_id, arg.key_spec.type, arg.flags,
796 				      &secret);
797 		if (err)
798 			goto out_wipe_secret;
799 	} else {
800 		if (!fscrypt_valid_key_size(arg.raw_size, arg.flags))
801 			return -EINVAL;
802 		secret.size = arg.raw_size;
803 		err = -EFAULT;
804 		if (copy_from_user(secret.bytes, uarg->raw, secret.size))
805 			goto out_wipe_secret;
806 	}
807 
808 	err = add_master_key(sb, &secret, &arg.key_spec);
809 	if (err)
810 		goto out_wipe_secret;
811 
812 	/* Return the key identifier to userspace, if applicable */
813 	err = -EFAULT;
814 	if (arg.key_spec.type == FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER &&
815 	    copy_to_user(uarg->key_spec.u.identifier, arg.key_spec.u.identifier,
816 			 FSCRYPT_KEY_IDENTIFIER_SIZE))
817 		goto out_wipe_secret;
818 	err = 0;
819 out_wipe_secret:
820 	wipe_master_key_secret(&secret);
821 	return err;
822 }
823 EXPORT_SYMBOL_GPL(fscrypt_ioctl_add_key);
824 
825 static void
826 fscrypt_get_test_dummy_secret(struct fscrypt_master_key_secret *secret)
827 {
828 	static u8 test_key[FSCRYPT_MAX_RAW_KEY_SIZE];
829 
830 	get_random_once(test_key, sizeof(test_key));
831 
832 	memset(secret, 0, sizeof(*secret));
833 	secret->size = sizeof(test_key);
834 	memcpy(secret->bytes, test_key, sizeof(test_key));
835 }
836 
837 int fscrypt_get_test_dummy_key_identifier(
838 				u8 key_identifier[FSCRYPT_KEY_IDENTIFIER_SIZE])
839 {
840 	struct fscrypt_master_key_secret secret;
841 	int err;
842 
843 	fscrypt_get_test_dummy_secret(&secret);
844 
845 	err = fscrypt_init_hkdf(&secret.hkdf, secret.bytes, secret.size);
846 	if (err)
847 		goto out;
848 	err = fscrypt_hkdf_expand(&secret.hkdf,
849 				  HKDF_CONTEXT_KEY_IDENTIFIER_FOR_RAW_KEY,
850 				  NULL, 0, key_identifier,
851 				  FSCRYPT_KEY_IDENTIFIER_SIZE);
852 out:
853 	wipe_master_key_secret(&secret);
854 	return err;
855 }
856 
857 /**
858  * fscrypt_add_test_dummy_key() - add the test dummy encryption key
859  * @sb: the filesystem instance to add the key to
860  * @key_spec: the key specifier of the test dummy encryption key
861  *
862  * Add the key for the test_dummy_encryption mount option to the filesystem.  To
863  * prevent misuse of this mount option, a per-boot random key is used instead of
864  * a hardcoded one.  This makes it so that any encrypted files created using
865  * this option won't be accessible after a reboot.
866  *
867  * Return: 0 on success, -errno on failure
868  */
869 int fscrypt_add_test_dummy_key(struct super_block *sb,
870 			       struct fscrypt_key_specifier *key_spec)
871 {
872 	struct fscrypt_master_key_secret secret;
873 	int err;
874 
875 	fscrypt_get_test_dummy_secret(&secret);
876 	err = add_master_key(sb, &secret, key_spec);
877 	wipe_master_key_secret(&secret);
878 	return err;
879 }
880 
881 /*
882  * Verify that the current user has added a master key with the given identifier
883  * (returns -ENOKEY if not).  This is needed to prevent a user from encrypting
884  * their files using some other user's key which they don't actually know.
885  * Cryptographically this isn't much of a problem, but the semantics of this
886  * would be a bit weird, so it's best to just forbid it.
887  *
888  * The system administrator (CAP_FOWNER) can override this, which should be
889  * enough for any use cases where encryption policies are being set using keys
890  * that were chosen ahead of time but aren't available at the moment.
891  *
892  * Note that the key may have already removed by the time this returns, but
893  * that's okay; we just care whether the key was there at some point.
894  *
895  * Return: 0 if the key is added, -ENOKEY if it isn't, or another -errno code
896  */
897 int fscrypt_verify_key_added(struct super_block *sb,
898 			     const u8 identifier[FSCRYPT_KEY_IDENTIFIER_SIZE])
899 {
900 	struct fscrypt_key_specifier mk_spec;
901 	struct fscrypt_master_key *mk;
902 	struct key *mk_user;
903 	int err;
904 
905 	mk_spec.type = FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
906 	memcpy(mk_spec.u.identifier, identifier, FSCRYPT_KEY_IDENTIFIER_SIZE);
907 
908 	mk = fscrypt_find_master_key(sb, &mk_spec);
909 	if (!mk) {
910 		err = -ENOKEY;
911 		goto out;
912 	}
913 	down_read(&mk->mk_sem);
914 	mk_user = find_master_key_user(mk);
915 	if (IS_ERR(mk_user)) {
916 		err = PTR_ERR(mk_user);
917 	} else {
918 		key_put(mk_user);
919 		err = 0;
920 	}
921 	up_read(&mk->mk_sem);
922 	fscrypt_put_master_key(mk);
923 out:
924 	if (err == -ENOKEY && capable(CAP_FOWNER))
925 		err = 0;
926 	return err;
927 }
928 
929 /*
930  * Try to evict the inode's dentries from the dentry cache.  If the inode is a
931  * directory, then it can have at most one dentry; however, that dentry may be
932  * pinned by child dentries, so first try to evict the children too.
933  */
934 static void shrink_dcache_inode(struct inode *inode)
935 {
936 	struct dentry *dentry;
937 
938 	if (S_ISDIR(inode->i_mode)) {
939 		dentry = d_find_any_alias(inode);
940 		if (dentry) {
941 			shrink_dcache_parent(dentry);
942 			dput(dentry);
943 		}
944 	}
945 	d_prune_aliases(inode);
946 }
947 
948 static void evict_dentries_for_decrypted_inodes(struct fscrypt_master_key *mk)
949 {
950 	struct fscrypt_inode_info *ci;
951 	struct inode *inode;
952 	struct inode *toput_inode = NULL;
953 
954 	spin_lock(&mk->mk_decrypted_inodes_lock);
955 
956 	list_for_each_entry(ci, &mk->mk_decrypted_inodes, ci_master_key_link) {
957 		inode = ci->ci_inode;
958 		spin_lock(&inode->i_lock);
959 		if (inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW)) {
960 			spin_unlock(&inode->i_lock);
961 			continue;
962 		}
963 		__iget(inode);
964 		spin_unlock(&inode->i_lock);
965 		spin_unlock(&mk->mk_decrypted_inodes_lock);
966 
967 		shrink_dcache_inode(inode);
968 		iput(toput_inode);
969 		toput_inode = inode;
970 
971 		spin_lock(&mk->mk_decrypted_inodes_lock);
972 	}
973 
974 	spin_unlock(&mk->mk_decrypted_inodes_lock);
975 	iput(toput_inode);
976 }
977 
978 static int check_for_busy_inodes(struct super_block *sb,
979 				 struct fscrypt_master_key *mk)
980 {
981 	struct list_head *pos;
982 	size_t busy_count = 0;
983 	unsigned long ino;
984 	char ino_str[50] = "";
985 
986 	spin_lock(&mk->mk_decrypted_inodes_lock);
987 
988 	list_for_each(pos, &mk->mk_decrypted_inodes)
989 		busy_count++;
990 
991 	if (busy_count == 0) {
992 		spin_unlock(&mk->mk_decrypted_inodes_lock);
993 		return 0;
994 	}
995 
996 	{
997 		/* select an example file to show for debugging purposes */
998 		struct inode *inode =
999 			list_first_entry(&mk->mk_decrypted_inodes,
1000 					 struct fscrypt_inode_info,
1001 					 ci_master_key_link)->ci_inode;
1002 		ino = inode->i_ino;
1003 	}
1004 	spin_unlock(&mk->mk_decrypted_inodes_lock);
1005 
1006 	/* If the inode is currently being created, ino may still be 0. */
1007 	if (ino)
1008 		snprintf(ino_str, sizeof(ino_str), ", including ino %lu", ino);
1009 
1010 	fscrypt_warn(NULL,
1011 		     "%s: %zu inode(s) still busy after removing key with %s %*phN%s",
1012 		     sb->s_id, busy_count, master_key_spec_type(&mk->mk_spec),
1013 		     master_key_spec_len(&mk->mk_spec), (u8 *)&mk->mk_spec.u,
1014 		     ino_str);
1015 	return -EBUSY;
1016 }
1017 
1018 static int try_to_lock_encrypted_files(struct super_block *sb,
1019 				       struct fscrypt_master_key *mk)
1020 {
1021 	int err1;
1022 	int err2;
1023 
1024 	/*
1025 	 * An inode can't be evicted while it is dirty or has dirty pages.
1026 	 * Thus, we first have to clean the inodes in ->mk_decrypted_inodes.
1027 	 *
1028 	 * Just do it the easy way: call sync_filesystem().  It's overkill, but
1029 	 * it works, and it's more important to minimize the amount of caches we
1030 	 * drop than the amount of data we sync.  Also, unprivileged users can
1031 	 * already call sync_filesystem() via sys_syncfs() or sys_sync().
1032 	 */
1033 	down_read(&sb->s_umount);
1034 	err1 = sync_filesystem(sb);
1035 	up_read(&sb->s_umount);
1036 	/* If a sync error occurs, still try to evict as much as possible. */
1037 
1038 	/*
1039 	 * Inodes are pinned by their dentries, so we have to evict their
1040 	 * dentries.  shrink_dcache_sb() would suffice, but would be overkill
1041 	 * and inappropriate for use by unprivileged users.  So instead go
1042 	 * through the inodes' alias lists and try to evict each dentry.
1043 	 */
1044 	evict_dentries_for_decrypted_inodes(mk);
1045 
1046 	/*
1047 	 * evict_dentries_for_decrypted_inodes() already iput() each inode in
1048 	 * the list; any inodes for which that dropped the last reference will
1049 	 * have been evicted due to fscrypt_drop_inode() detecting the key
1050 	 * removal and telling the VFS to evict the inode.  So to finish, we
1051 	 * just need to check whether any inodes couldn't be evicted.
1052 	 */
1053 	err2 = check_for_busy_inodes(sb, mk);
1054 
1055 	return err1 ?: err2;
1056 }
1057 
1058 /*
1059  * Try to remove an fscrypt master encryption key.
1060  *
1061  * FS_IOC_REMOVE_ENCRYPTION_KEY (all_users=false) removes the current user's
1062  * claim to the key, then removes the key itself if no other users have claims.
1063  * FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS (all_users=true) always removes the
1064  * key itself.
1065  *
1066  * To "remove the key itself", first we transition the key to the "incompletely
1067  * removed" state, so that no more inodes can be unlocked with it.  Then we try
1068  * to evict all cached inodes that had been unlocked with the key.
1069  *
1070  * If all inodes were evicted, then we unlink the fscrypt_master_key from the
1071  * keyring.  Otherwise it remains in the keyring in the "incompletely removed"
1072  * state where it tracks the list of remaining inodes.  Userspace can execute
1073  * the ioctl again later to retry eviction, or alternatively can re-add the key.
1074  *
1075  * For more details, see the "Removing keys" section of
1076  * Documentation/filesystems/fscrypt.rst.
1077  */
1078 static int do_remove_key(struct file *filp, void __user *_uarg, bool all_users)
1079 {
1080 	struct super_block *sb = file_inode(filp)->i_sb;
1081 	struct fscrypt_remove_key_arg __user *uarg = _uarg;
1082 	struct fscrypt_remove_key_arg arg;
1083 	struct fscrypt_master_key *mk;
1084 	u32 status_flags = 0;
1085 	int err;
1086 	bool inodes_remain;
1087 
1088 	if (copy_from_user(&arg, uarg, sizeof(arg)))
1089 		return -EFAULT;
1090 
1091 	if (!valid_key_spec(&arg.key_spec))
1092 		return -EINVAL;
1093 
1094 	if (memchr_inv(arg.__reserved, 0, sizeof(arg.__reserved)))
1095 		return -EINVAL;
1096 
1097 	/*
1098 	 * Only root can add and remove keys that are identified by an arbitrary
1099 	 * descriptor rather than by a cryptographic hash.
1100 	 */
1101 	if (arg.key_spec.type == FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR &&
1102 	    !capable(CAP_SYS_ADMIN))
1103 		return -EACCES;
1104 
1105 	/* Find the key being removed. */
1106 	mk = fscrypt_find_master_key(sb, &arg.key_spec);
1107 	if (!mk)
1108 		return -ENOKEY;
1109 	down_write(&mk->mk_sem);
1110 
1111 	/* If relevant, remove current user's (or all users) claim to the key */
1112 	if (mk->mk_users && mk->mk_users->keys.nr_leaves_on_tree != 0) {
1113 		if (all_users)
1114 			err = keyring_clear(mk->mk_users);
1115 		else
1116 			err = remove_master_key_user(mk);
1117 		if (err) {
1118 			up_write(&mk->mk_sem);
1119 			goto out_put_key;
1120 		}
1121 		if (mk->mk_users->keys.nr_leaves_on_tree != 0) {
1122 			/*
1123 			 * Other users have still added the key too.  We removed
1124 			 * the current user's claim to the key, but we still
1125 			 * can't remove the key itself.
1126 			 */
1127 			status_flags |=
1128 				FSCRYPT_KEY_REMOVAL_STATUS_FLAG_OTHER_USERS;
1129 			err = 0;
1130 			up_write(&mk->mk_sem);
1131 			goto out_put_key;
1132 		}
1133 	}
1134 
1135 	/* No user claims remaining.  Initiate removal of the key. */
1136 	err = -ENOKEY;
1137 	if (mk->mk_present) {
1138 		fscrypt_initiate_key_removal(sb, mk);
1139 		err = 0;
1140 	}
1141 	inodes_remain = refcount_read(&mk->mk_active_refs) > 0;
1142 	up_write(&mk->mk_sem);
1143 
1144 	if (inodes_remain) {
1145 		/* Some inodes still reference this key; try to evict them. */
1146 		err = try_to_lock_encrypted_files(sb, mk);
1147 		if (err == -EBUSY) {
1148 			status_flags |=
1149 				FSCRYPT_KEY_REMOVAL_STATUS_FLAG_FILES_BUSY;
1150 			err = 0;
1151 		}
1152 	}
1153 	/*
1154 	 * We return 0 if we successfully did something: removed a claim to the
1155 	 * key, initiated removal of the key, or tried locking the files again.
1156 	 * Users need to check the informational status flags if they care
1157 	 * whether the key has been fully removed including all files locked.
1158 	 */
1159 out_put_key:
1160 	fscrypt_put_master_key(mk);
1161 	if (err == 0)
1162 		err = put_user(status_flags, &uarg->removal_status_flags);
1163 	return err;
1164 }
1165 
1166 int fscrypt_ioctl_remove_key(struct file *filp, void __user *uarg)
1167 {
1168 	return do_remove_key(filp, uarg, false);
1169 }
1170 EXPORT_SYMBOL_GPL(fscrypt_ioctl_remove_key);
1171 
1172 int fscrypt_ioctl_remove_key_all_users(struct file *filp, void __user *uarg)
1173 {
1174 	if (!capable(CAP_SYS_ADMIN))
1175 		return -EACCES;
1176 	return do_remove_key(filp, uarg, true);
1177 }
1178 EXPORT_SYMBOL_GPL(fscrypt_ioctl_remove_key_all_users);
1179 
1180 /*
1181  * Retrieve the status of an fscrypt master encryption key.
1182  *
1183  * We set ->status to indicate whether the key is absent, present, or
1184  * incompletely removed.  (For an explanation of what these statuses mean and
1185  * how they are represented internally, see struct fscrypt_master_key.)  This
1186  * field allows applications to easily determine the status of an encrypted
1187  * directory without using a hack such as trying to open a regular file in it
1188  * (which can confuse the "incompletely removed" status with absent or present).
1189  *
1190  * In addition, for v2 policy keys we allow applications to determine, via
1191  * ->status_flags and ->user_count, whether the key has been added by the
1192  * current user, by other users, or by both.  Most applications should not need
1193  * this, since ordinarily only one user should know a given key.  However, if a
1194  * secret key is shared by multiple users, applications may wish to add an
1195  * already-present key to prevent other users from removing it.  This ioctl can
1196  * be used to check whether that really is the case before the work is done to
1197  * add the key --- which might e.g. require prompting the user for a passphrase.
1198  *
1199  * For more details, see the "FS_IOC_GET_ENCRYPTION_KEY_STATUS" section of
1200  * Documentation/filesystems/fscrypt.rst.
1201  */
1202 int fscrypt_ioctl_get_key_status(struct file *filp, void __user *uarg)
1203 {
1204 	struct super_block *sb = file_inode(filp)->i_sb;
1205 	struct fscrypt_get_key_status_arg arg;
1206 	struct fscrypt_master_key *mk;
1207 	int err;
1208 
1209 	if (copy_from_user(&arg, uarg, sizeof(arg)))
1210 		return -EFAULT;
1211 
1212 	if (!valid_key_spec(&arg.key_spec))
1213 		return -EINVAL;
1214 
1215 	if (memchr_inv(arg.__reserved, 0, sizeof(arg.__reserved)))
1216 		return -EINVAL;
1217 
1218 	arg.status_flags = 0;
1219 	arg.user_count = 0;
1220 	memset(arg.__out_reserved, 0, sizeof(arg.__out_reserved));
1221 
1222 	mk = fscrypt_find_master_key(sb, &arg.key_spec);
1223 	if (!mk) {
1224 		arg.status = FSCRYPT_KEY_STATUS_ABSENT;
1225 		err = 0;
1226 		goto out;
1227 	}
1228 	down_read(&mk->mk_sem);
1229 
1230 	if (!mk->mk_present) {
1231 		arg.status = refcount_read(&mk->mk_active_refs) > 0 ?
1232 			FSCRYPT_KEY_STATUS_INCOMPLETELY_REMOVED :
1233 			FSCRYPT_KEY_STATUS_ABSENT /* raced with full removal */;
1234 		err = 0;
1235 		goto out_release_key;
1236 	}
1237 
1238 	arg.status = FSCRYPT_KEY_STATUS_PRESENT;
1239 	if (mk->mk_users) {
1240 		struct key *mk_user;
1241 
1242 		arg.user_count = mk->mk_users->keys.nr_leaves_on_tree;
1243 		mk_user = find_master_key_user(mk);
1244 		if (!IS_ERR(mk_user)) {
1245 			arg.status_flags |=
1246 				FSCRYPT_KEY_STATUS_FLAG_ADDED_BY_SELF;
1247 			key_put(mk_user);
1248 		} else if (mk_user != ERR_PTR(-ENOKEY)) {
1249 			err = PTR_ERR(mk_user);
1250 			goto out_release_key;
1251 		}
1252 	}
1253 	err = 0;
1254 out_release_key:
1255 	up_read(&mk->mk_sem);
1256 	fscrypt_put_master_key(mk);
1257 out:
1258 	if (!err && copy_to_user(uarg, &arg, sizeof(arg)))
1259 		err = -EFAULT;
1260 	return err;
1261 }
1262 EXPORT_SYMBOL_GPL(fscrypt_ioctl_get_key_status);
1263 
1264 int __init fscrypt_init_keyring(void)
1265 {
1266 	int err;
1267 
1268 	err = register_key_type(&key_type_fscrypt_user);
1269 	if (err)
1270 		return err;
1271 
1272 	err = register_key_type(&key_type_fscrypt_provisioning);
1273 	if (err)
1274 		goto err_unregister_fscrypt_user;
1275 
1276 	return 0;
1277 
1278 err_unregister_fscrypt_user:
1279 	unregister_key_type(&key_type_fscrypt_user);
1280 	return err;
1281 }
1282