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