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