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