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