xref: /linux/fs/crypto/keysetup.c (revision 1771c8c9e65a20128f93df107353a5f4cb91546a)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Key setup facility for FS encryption support.
4  *
5  * Copyright (C) 2015, Google, Inc.
6  *
7  * Originally written by Michael Halcrow, Ildar Muslukhov, and Uday Savagaonkar.
8  * Heavily modified since then.
9  */
10 
11 #include <crypto/skcipher.h>
12 #include <linux/key.h>
13 #include <linux/random.h>
14 
15 #include "fscrypt_private.h"
16 
17 struct fscrypt_mode fscrypt_modes[] = {
18 	[FSCRYPT_MODE_AES_256_XTS] = {
19 		.friendly_name = "AES-256-XTS",
20 		.cipher_str = "xts(aes)",
21 		.keysize = 64,
22 		.security_strength = 32,
23 		.ivsize = 16,
24 		.blk_crypto_mode = BLK_ENCRYPTION_MODE_AES_256_XTS,
25 	},
26 	[FSCRYPT_MODE_AES_256_CTS] = {
27 		.friendly_name = "AES-256-CTS-CBC",
28 		.cipher_str = "cts(cbc(aes))",
29 		.keysize = 32,
30 		.security_strength = 32,
31 		.ivsize = 16,
32 	},
33 	[FSCRYPT_MODE_AES_128_CBC] = {
34 		.friendly_name = "AES-128-CBC-ESSIV",
35 		.cipher_str = "essiv(cbc(aes),sha256)",
36 		.keysize = 16,
37 		.security_strength = 16,
38 		.ivsize = 16,
39 		.blk_crypto_mode = BLK_ENCRYPTION_MODE_AES_128_CBC_ESSIV,
40 	},
41 	[FSCRYPT_MODE_AES_128_CTS] = {
42 		.friendly_name = "AES-128-CTS-CBC",
43 		.cipher_str = "cts(cbc(aes))",
44 		.keysize = 16,
45 		.security_strength = 16,
46 		.ivsize = 16,
47 	},
48 	[FSCRYPT_MODE_ADIANTUM] = {
49 		.friendly_name = "Adiantum",
50 		.cipher_str = "adiantum(xchacha12,aes)",
51 		.keysize = 32,
52 		.security_strength = 32,
53 		.ivsize = 32,
54 		.blk_crypto_mode = BLK_ENCRYPTION_MODE_ADIANTUM,
55 	},
56 };
57 
58 static DEFINE_MUTEX(fscrypt_mode_key_setup_mutex);
59 
60 static struct fscrypt_mode *
61 select_encryption_mode(const union fscrypt_policy *policy,
62 		       const struct inode *inode)
63 {
64 	BUILD_BUG_ON(ARRAY_SIZE(fscrypt_modes) != FSCRYPT_MODE_MAX + 1);
65 
66 	if (S_ISREG(inode->i_mode))
67 		return &fscrypt_modes[fscrypt_policy_contents_mode(policy)];
68 
69 	if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
70 		return &fscrypt_modes[fscrypt_policy_fnames_mode(policy)];
71 
72 	WARN_ONCE(1, "fscrypt: filesystem tried to load encryption info for inode %lu, which is not encryptable (file type %d)\n",
73 		  inode->i_ino, (inode->i_mode & S_IFMT));
74 	return ERR_PTR(-EINVAL);
75 }
76 
77 /* Create a symmetric cipher object for the given encryption mode and key */
78 static struct crypto_skcipher *
79 fscrypt_allocate_skcipher(struct fscrypt_mode *mode, const u8 *raw_key,
80 			  const struct inode *inode)
81 {
82 	struct crypto_skcipher *tfm;
83 	int err;
84 
85 	tfm = crypto_alloc_skcipher(mode->cipher_str, 0, 0);
86 	if (IS_ERR(tfm)) {
87 		if (PTR_ERR(tfm) == -ENOENT) {
88 			fscrypt_warn(inode,
89 				     "Missing crypto API support for %s (API name: \"%s\")",
90 				     mode->friendly_name, mode->cipher_str);
91 			return ERR_PTR(-ENOPKG);
92 		}
93 		fscrypt_err(inode, "Error allocating '%s' transform: %ld",
94 			    mode->cipher_str, PTR_ERR(tfm));
95 		return tfm;
96 	}
97 	if (!xchg(&mode->logged_cryptoapi_impl, 1)) {
98 		/*
99 		 * fscrypt performance can vary greatly depending on which
100 		 * crypto algorithm implementation is used.  Help people debug
101 		 * performance problems by logging the ->cra_driver_name the
102 		 * first time a mode is used.
103 		 */
104 		pr_info("fscrypt: %s using implementation \"%s\"\n",
105 			mode->friendly_name, crypto_skcipher_driver_name(tfm));
106 	}
107 	if (WARN_ON(crypto_skcipher_ivsize(tfm) != mode->ivsize)) {
108 		err = -EINVAL;
109 		goto err_free_tfm;
110 	}
111 	crypto_skcipher_set_flags(tfm, CRYPTO_TFM_REQ_FORBID_WEAK_KEYS);
112 	err = crypto_skcipher_setkey(tfm, raw_key, mode->keysize);
113 	if (err)
114 		goto err_free_tfm;
115 
116 	return tfm;
117 
118 err_free_tfm:
119 	crypto_free_skcipher(tfm);
120 	return ERR_PTR(err);
121 }
122 
123 /*
124  * Prepare the crypto transform object or blk-crypto key in @prep_key, given the
125  * raw key, encryption mode (@ci->ci_mode), flag indicating which encryption
126  * implementation (fs-layer or blk-crypto) will be used (@ci->ci_inlinecrypt),
127  * and IV generation method (@ci->ci_policy.flags).
128  */
129 int fscrypt_prepare_key(struct fscrypt_prepared_key *prep_key,
130 			const u8 *raw_key, const struct fscrypt_info *ci)
131 {
132 	struct crypto_skcipher *tfm;
133 
134 	if (fscrypt_using_inline_encryption(ci))
135 		return fscrypt_prepare_inline_crypt_key(prep_key, raw_key, ci);
136 
137 	tfm = fscrypt_allocate_skcipher(ci->ci_mode, raw_key, ci->ci_inode);
138 	if (IS_ERR(tfm))
139 		return PTR_ERR(tfm);
140 	/*
141 	 * Pairs with the smp_load_acquire() in fscrypt_is_key_prepared().
142 	 * I.e., here we publish ->tfm with a RELEASE barrier so that
143 	 * concurrent tasks can ACQUIRE it.  Note that this concurrency is only
144 	 * possible for per-mode keys, not for per-file keys.
145 	 */
146 	smp_store_release(&prep_key->tfm, tfm);
147 	return 0;
148 }
149 
150 /* Destroy a crypto transform object and/or blk-crypto key. */
151 void fscrypt_destroy_prepared_key(struct fscrypt_prepared_key *prep_key)
152 {
153 	crypto_free_skcipher(prep_key->tfm);
154 	fscrypt_destroy_inline_crypt_key(prep_key);
155 }
156 
157 /* Given a per-file encryption key, set up the file's crypto transform object */
158 int fscrypt_set_per_file_enc_key(struct fscrypt_info *ci, const u8 *raw_key)
159 {
160 	ci->ci_owns_key = true;
161 	return fscrypt_prepare_key(&ci->ci_enc_key, raw_key, ci);
162 }
163 
164 static int setup_per_mode_enc_key(struct fscrypt_info *ci,
165 				  struct fscrypt_master_key *mk,
166 				  struct fscrypt_prepared_key *keys,
167 				  u8 hkdf_context, bool include_fs_uuid)
168 {
169 	const struct inode *inode = ci->ci_inode;
170 	const struct super_block *sb = inode->i_sb;
171 	struct fscrypt_mode *mode = ci->ci_mode;
172 	const u8 mode_num = mode - fscrypt_modes;
173 	struct fscrypt_prepared_key *prep_key;
174 	u8 mode_key[FSCRYPT_MAX_KEY_SIZE];
175 	u8 hkdf_info[sizeof(mode_num) + sizeof(sb->s_uuid)];
176 	unsigned int hkdf_infolen = 0;
177 	int err;
178 
179 	if (WARN_ON(mode_num > FSCRYPT_MODE_MAX))
180 		return -EINVAL;
181 
182 	prep_key = &keys[mode_num];
183 	if (fscrypt_is_key_prepared(prep_key, ci)) {
184 		ci->ci_enc_key = *prep_key;
185 		return 0;
186 	}
187 
188 	mutex_lock(&fscrypt_mode_key_setup_mutex);
189 
190 	if (fscrypt_is_key_prepared(prep_key, ci))
191 		goto done_unlock;
192 
193 	BUILD_BUG_ON(sizeof(mode_num) != 1);
194 	BUILD_BUG_ON(sizeof(sb->s_uuid) != 16);
195 	BUILD_BUG_ON(sizeof(hkdf_info) != 17);
196 	hkdf_info[hkdf_infolen++] = mode_num;
197 	if (include_fs_uuid) {
198 		memcpy(&hkdf_info[hkdf_infolen], &sb->s_uuid,
199 		       sizeof(sb->s_uuid));
200 		hkdf_infolen += sizeof(sb->s_uuid);
201 	}
202 	err = fscrypt_hkdf_expand(&mk->mk_secret.hkdf,
203 				  hkdf_context, hkdf_info, hkdf_infolen,
204 				  mode_key, mode->keysize);
205 	if (err)
206 		goto out_unlock;
207 	err = fscrypt_prepare_key(prep_key, mode_key, ci);
208 	memzero_explicit(mode_key, mode->keysize);
209 	if (err)
210 		goto out_unlock;
211 done_unlock:
212 	ci->ci_enc_key = *prep_key;
213 	err = 0;
214 out_unlock:
215 	mutex_unlock(&fscrypt_mode_key_setup_mutex);
216 	return err;
217 }
218 
219 /*
220  * Derive a SipHash key from the given fscrypt master key and the given
221  * application-specific information string.
222  *
223  * Note that the KDF produces a byte array, but the SipHash APIs expect the key
224  * as a pair of 64-bit words.  Therefore, on big endian CPUs we have to do an
225  * endianness swap in order to get the same results as on little endian CPUs.
226  */
227 static int fscrypt_derive_siphash_key(const struct fscrypt_master_key *mk,
228 				      u8 context, const u8 *info,
229 				      unsigned int infolen, siphash_key_t *key)
230 {
231 	int err;
232 
233 	err = fscrypt_hkdf_expand(&mk->mk_secret.hkdf, context, info, infolen,
234 				  (u8 *)key, sizeof(*key));
235 	if (err)
236 		return err;
237 
238 	BUILD_BUG_ON(sizeof(*key) != 16);
239 	BUILD_BUG_ON(ARRAY_SIZE(key->key) != 2);
240 	le64_to_cpus(&key->key[0]);
241 	le64_to_cpus(&key->key[1]);
242 	return 0;
243 }
244 
245 int fscrypt_derive_dirhash_key(struct fscrypt_info *ci,
246 			       const struct fscrypt_master_key *mk)
247 {
248 	int err;
249 
250 	err = fscrypt_derive_siphash_key(mk, HKDF_CONTEXT_DIRHASH_KEY,
251 					 ci->ci_nonce, FSCRYPT_FILE_NONCE_SIZE,
252 					 &ci->ci_dirhash_key);
253 	if (err)
254 		return err;
255 	ci->ci_dirhash_key_initialized = true;
256 	return 0;
257 }
258 
259 void fscrypt_hash_inode_number(struct fscrypt_info *ci,
260 			       const struct fscrypt_master_key *mk)
261 {
262 	WARN_ON(ci->ci_inode->i_ino == 0);
263 	WARN_ON(!mk->mk_ino_hash_key_initialized);
264 
265 	ci->ci_hashed_ino = (u32)siphash_1u64(ci->ci_inode->i_ino,
266 					      &mk->mk_ino_hash_key);
267 }
268 
269 static int fscrypt_setup_iv_ino_lblk_32_key(struct fscrypt_info *ci,
270 					    struct fscrypt_master_key *mk)
271 {
272 	int err;
273 
274 	err = setup_per_mode_enc_key(ci, mk, mk->mk_iv_ino_lblk_32_keys,
275 				     HKDF_CONTEXT_IV_INO_LBLK_32_KEY, true);
276 	if (err)
277 		return err;
278 
279 	/* pairs with smp_store_release() below */
280 	if (!smp_load_acquire(&mk->mk_ino_hash_key_initialized)) {
281 
282 		mutex_lock(&fscrypt_mode_key_setup_mutex);
283 
284 		if (mk->mk_ino_hash_key_initialized)
285 			goto unlock;
286 
287 		err = fscrypt_derive_siphash_key(mk,
288 						 HKDF_CONTEXT_INODE_HASH_KEY,
289 						 NULL, 0, &mk->mk_ino_hash_key);
290 		if (err)
291 			goto unlock;
292 		/* pairs with smp_load_acquire() above */
293 		smp_store_release(&mk->mk_ino_hash_key_initialized, true);
294 unlock:
295 		mutex_unlock(&fscrypt_mode_key_setup_mutex);
296 		if (err)
297 			return err;
298 	}
299 
300 	/*
301 	 * New inodes may not have an inode number assigned yet.
302 	 * Hashing their inode number is delayed until later.
303 	 */
304 	if (ci->ci_inode->i_ino)
305 		fscrypt_hash_inode_number(ci, mk);
306 	return 0;
307 }
308 
309 static int fscrypt_setup_v2_file_key(struct fscrypt_info *ci,
310 				     struct fscrypt_master_key *mk,
311 				     bool need_dirhash_key)
312 {
313 	int err;
314 
315 	if (ci->ci_policy.v2.flags & FSCRYPT_POLICY_FLAG_DIRECT_KEY) {
316 		/*
317 		 * DIRECT_KEY: instead of deriving per-file encryption keys, the
318 		 * per-file nonce will be included in all the IVs.  But unlike
319 		 * v1 policies, for v2 policies in this case we don't encrypt
320 		 * with the master key directly but rather derive a per-mode
321 		 * encryption key.  This ensures that the master key is
322 		 * consistently used only for HKDF, avoiding key reuse issues.
323 		 */
324 		err = setup_per_mode_enc_key(ci, mk, mk->mk_direct_keys,
325 					     HKDF_CONTEXT_DIRECT_KEY, false);
326 	} else if (ci->ci_policy.v2.flags &
327 		   FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64) {
328 		/*
329 		 * IV_INO_LBLK_64: encryption keys are derived from (master_key,
330 		 * mode_num, filesystem_uuid), and inode number is included in
331 		 * the IVs.  This format is optimized for use with inline
332 		 * encryption hardware compliant with the UFS standard.
333 		 */
334 		err = setup_per_mode_enc_key(ci, mk, mk->mk_iv_ino_lblk_64_keys,
335 					     HKDF_CONTEXT_IV_INO_LBLK_64_KEY,
336 					     true);
337 	} else if (ci->ci_policy.v2.flags &
338 		   FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32) {
339 		err = fscrypt_setup_iv_ino_lblk_32_key(ci, mk);
340 	} else {
341 		u8 derived_key[FSCRYPT_MAX_KEY_SIZE];
342 
343 		err = fscrypt_hkdf_expand(&mk->mk_secret.hkdf,
344 					  HKDF_CONTEXT_PER_FILE_ENC_KEY,
345 					  ci->ci_nonce, FSCRYPT_FILE_NONCE_SIZE,
346 					  derived_key, ci->ci_mode->keysize);
347 		if (err)
348 			return err;
349 
350 		err = fscrypt_set_per_file_enc_key(ci, derived_key);
351 		memzero_explicit(derived_key, ci->ci_mode->keysize);
352 	}
353 	if (err)
354 		return err;
355 
356 	/* Derive a secret dirhash key for directories that need it. */
357 	if (need_dirhash_key) {
358 		err = fscrypt_derive_dirhash_key(ci, mk);
359 		if (err)
360 			return err;
361 	}
362 
363 	return 0;
364 }
365 
366 /*
367  * Check whether the size of the given master key (@mk) is appropriate for the
368  * encryption settings which a particular file will use (@ci).
369  *
370  * If the file uses a v1 encryption policy, then the master key must be at least
371  * as long as the derived key, as this is a requirement of the v1 KDF.
372  *
373  * Otherwise, the KDF can accept any size key, so we enforce a slightly looser
374  * requirement: we require that the size of the master key be at least the
375  * maximum security strength of any algorithm whose key will be derived from it
376  * (but in practice we only need to consider @ci->ci_mode, since any other
377  * possible subkeys such as DIRHASH and INODE_HASH will never increase the
378  * required key size over @ci->ci_mode).  This allows AES-256-XTS keys to be
379  * derived from a 256-bit master key, which is cryptographically sufficient,
380  * rather than requiring a 512-bit master key which is unnecessarily long.  (We
381  * still allow 512-bit master keys if the user chooses to use them, though.)
382  */
383 static bool fscrypt_valid_master_key_size(const struct fscrypt_master_key *mk,
384 					  const struct fscrypt_info *ci)
385 {
386 	unsigned int min_keysize;
387 
388 	if (ci->ci_policy.version == FSCRYPT_POLICY_V1)
389 		min_keysize = ci->ci_mode->keysize;
390 	else
391 		min_keysize = ci->ci_mode->security_strength;
392 
393 	if (mk->mk_secret.size < min_keysize) {
394 		fscrypt_warn(NULL,
395 			     "key with %s %*phN is too short (got %u bytes, need %u+ bytes)",
396 			     master_key_spec_type(&mk->mk_spec),
397 			     master_key_spec_len(&mk->mk_spec),
398 			     (u8 *)&mk->mk_spec.u,
399 			     mk->mk_secret.size, min_keysize);
400 		return false;
401 	}
402 	return true;
403 }
404 
405 /*
406  * Find the master key, then set up the inode's actual encryption key.
407  *
408  * If the master key is found in the filesystem-level keyring, then the
409  * corresponding 'struct key' is returned in *master_key_ret with its semaphore
410  * read-locked.  This is needed to ensure that only one task links the
411  * fscrypt_info into ->mk_decrypted_inodes (as multiple tasks may race to create
412  * an fscrypt_info for the same inode), and to synchronize the master key being
413  * removed with a new inode starting to use it.
414  */
415 static int setup_file_encryption_key(struct fscrypt_info *ci,
416 				     bool need_dirhash_key,
417 				     struct key **master_key_ret)
418 {
419 	struct key *key;
420 	struct fscrypt_master_key *mk = NULL;
421 	struct fscrypt_key_specifier mk_spec;
422 	int err;
423 
424 	err = fscrypt_select_encryption_impl(ci);
425 	if (err)
426 		return err;
427 
428 	err = fscrypt_policy_to_key_spec(&ci->ci_policy, &mk_spec);
429 	if (err)
430 		return err;
431 
432 	key = fscrypt_find_master_key(ci->ci_inode->i_sb, &mk_spec);
433 	if (IS_ERR(key)) {
434 		if (key != ERR_PTR(-ENOKEY) ||
435 		    ci->ci_policy.version != FSCRYPT_POLICY_V1)
436 			return PTR_ERR(key);
437 
438 		/*
439 		 * As a legacy fallback for v1 policies, search for the key in
440 		 * the current task's subscribed keyrings too.  Don't move this
441 		 * to before the search of ->s_master_keys, since users
442 		 * shouldn't be able to override filesystem-level keys.
443 		 */
444 		return fscrypt_setup_v1_file_key_via_subscribed_keyrings(ci);
445 	}
446 
447 	mk = key->payload.data[0];
448 	down_read(&key->sem);
449 
450 	/* Has the secret been removed (via FS_IOC_REMOVE_ENCRYPTION_KEY)? */
451 	if (!is_master_key_secret_present(&mk->mk_secret)) {
452 		err = -ENOKEY;
453 		goto out_release_key;
454 	}
455 
456 	if (!fscrypt_valid_master_key_size(mk, ci)) {
457 		err = -ENOKEY;
458 		goto out_release_key;
459 	}
460 
461 	switch (ci->ci_policy.version) {
462 	case FSCRYPT_POLICY_V1:
463 		err = fscrypt_setup_v1_file_key(ci, mk->mk_secret.raw);
464 		break;
465 	case FSCRYPT_POLICY_V2:
466 		err = fscrypt_setup_v2_file_key(ci, mk, need_dirhash_key);
467 		break;
468 	default:
469 		WARN_ON(1);
470 		err = -EINVAL;
471 		break;
472 	}
473 	if (err)
474 		goto out_release_key;
475 
476 	*master_key_ret = key;
477 	return 0;
478 
479 out_release_key:
480 	up_read(&key->sem);
481 	key_put(key);
482 	return err;
483 }
484 
485 static void put_crypt_info(struct fscrypt_info *ci)
486 {
487 	struct key *key;
488 
489 	if (!ci)
490 		return;
491 
492 	if (ci->ci_direct_key)
493 		fscrypt_put_direct_key(ci->ci_direct_key);
494 	else if (ci->ci_owns_key)
495 		fscrypt_destroy_prepared_key(&ci->ci_enc_key);
496 
497 	key = ci->ci_master_key;
498 	if (key) {
499 		struct fscrypt_master_key *mk = key->payload.data[0];
500 
501 		/*
502 		 * Remove this inode from the list of inodes that were unlocked
503 		 * with the master key.
504 		 *
505 		 * In addition, if we're removing the last inode from a key that
506 		 * already had its secret removed, invalidate the key so that it
507 		 * gets removed from ->s_master_keys.
508 		 */
509 		spin_lock(&mk->mk_decrypted_inodes_lock);
510 		list_del(&ci->ci_master_key_link);
511 		spin_unlock(&mk->mk_decrypted_inodes_lock);
512 		if (refcount_dec_and_test(&mk->mk_refcount))
513 			key_invalidate(key);
514 		key_put(key);
515 	}
516 	memzero_explicit(ci, sizeof(*ci));
517 	kmem_cache_free(fscrypt_info_cachep, ci);
518 }
519 
520 static int
521 fscrypt_setup_encryption_info(struct inode *inode,
522 			      const union fscrypt_policy *policy,
523 			      const u8 nonce[FSCRYPT_FILE_NONCE_SIZE],
524 			      bool need_dirhash_key)
525 {
526 	struct fscrypt_info *crypt_info;
527 	struct fscrypt_mode *mode;
528 	struct key *master_key = NULL;
529 	int res;
530 
531 	res = fscrypt_initialize(inode->i_sb->s_cop->flags);
532 	if (res)
533 		return res;
534 
535 	crypt_info = kmem_cache_zalloc(fscrypt_info_cachep, GFP_KERNEL);
536 	if (!crypt_info)
537 		return -ENOMEM;
538 
539 	crypt_info->ci_inode = inode;
540 	crypt_info->ci_policy = *policy;
541 	memcpy(crypt_info->ci_nonce, nonce, FSCRYPT_FILE_NONCE_SIZE);
542 
543 	mode = select_encryption_mode(&crypt_info->ci_policy, inode);
544 	if (IS_ERR(mode)) {
545 		res = PTR_ERR(mode);
546 		goto out;
547 	}
548 	WARN_ON(mode->ivsize > FSCRYPT_MAX_IV_SIZE);
549 	crypt_info->ci_mode = mode;
550 
551 	res = setup_file_encryption_key(crypt_info, need_dirhash_key,
552 					&master_key);
553 	if (res)
554 		goto out;
555 
556 	/*
557 	 * For existing inodes, multiple tasks may race to set ->i_crypt_info.
558 	 * So use cmpxchg_release().  This pairs with the smp_load_acquire() in
559 	 * fscrypt_get_info().  I.e., here we publish ->i_crypt_info with a
560 	 * RELEASE barrier so that other tasks can ACQUIRE it.
561 	 */
562 	if (cmpxchg_release(&inode->i_crypt_info, NULL, crypt_info) == NULL) {
563 		/*
564 		 * We won the race and set ->i_crypt_info to our crypt_info.
565 		 * Now link it into the master key's inode list.
566 		 */
567 		if (master_key) {
568 			struct fscrypt_master_key *mk =
569 				master_key->payload.data[0];
570 
571 			refcount_inc(&mk->mk_refcount);
572 			crypt_info->ci_master_key = key_get(master_key);
573 			spin_lock(&mk->mk_decrypted_inodes_lock);
574 			list_add(&crypt_info->ci_master_key_link,
575 				 &mk->mk_decrypted_inodes);
576 			spin_unlock(&mk->mk_decrypted_inodes_lock);
577 		}
578 		crypt_info = NULL;
579 	}
580 	res = 0;
581 out:
582 	if (master_key) {
583 		up_read(&master_key->sem);
584 		key_put(master_key);
585 	}
586 	put_crypt_info(crypt_info);
587 	return res;
588 }
589 
590 /**
591  * fscrypt_get_encryption_info() - set up an inode's encryption key
592  * @inode: the inode to set up the key for.  Must be encrypted.
593  * @allow_unsupported: if %true, treat an unsupported encryption policy (or
594  *		       unrecognized encryption context) the same way as the key
595  *		       being unavailable, instead of returning an error.  Use
596  *		       %false unless the operation being performed is needed in
597  *		       order for files (or directories) to be deleted.
598  *
599  * Set up ->i_crypt_info, if it hasn't already been done.
600  *
601  * Note: unless ->i_crypt_info is already set, this isn't %GFP_NOFS-safe.  So
602  * generally this shouldn't be called from within a filesystem transaction.
603  *
604  * Return: 0 if ->i_crypt_info was set or was already set, *or* if the
605  *	   encryption key is unavailable.  (Use fscrypt_has_encryption_key() to
606  *	   distinguish these cases.)  Also can return another -errno code.
607  */
608 int fscrypt_get_encryption_info(struct inode *inode, bool allow_unsupported)
609 {
610 	int res;
611 	union fscrypt_context ctx;
612 	union fscrypt_policy policy;
613 
614 	if (fscrypt_has_encryption_key(inode))
615 		return 0;
616 
617 	res = inode->i_sb->s_cop->get_context(inode, &ctx, sizeof(ctx));
618 	if (res < 0) {
619 		if (res == -ERANGE && allow_unsupported)
620 			return 0;
621 		fscrypt_warn(inode, "Error %d getting encryption context", res);
622 		return res;
623 	}
624 
625 	res = fscrypt_policy_from_context(&policy, &ctx, res);
626 	if (res) {
627 		if (allow_unsupported)
628 			return 0;
629 		fscrypt_warn(inode,
630 			     "Unrecognized or corrupt encryption context");
631 		return res;
632 	}
633 
634 	if (!fscrypt_supported_policy(&policy, inode)) {
635 		if (allow_unsupported)
636 			return 0;
637 		return -EINVAL;
638 	}
639 
640 	res = fscrypt_setup_encryption_info(inode, &policy,
641 					    fscrypt_context_nonce(&ctx),
642 					    IS_CASEFOLDED(inode) &&
643 					    S_ISDIR(inode->i_mode));
644 
645 	if (res == -ENOPKG && allow_unsupported) /* Algorithm unavailable? */
646 		res = 0;
647 	if (res == -ENOKEY)
648 		res = 0;
649 	return res;
650 }
651 
652 /**
653  * fscrypt_prepare_new_inode() - prepare to create a new inode in a directory
654  * @dir: a possibly-encrypted directory
655  * @inode: the new inode.  ->i_mode must be set already.
656  *	   ->i_ino doesn't need to be set yet.
657  * @encrypt_ret: (output) set to %true if the new inode will be encrypted
658  *
659  * If the directory is encrypted, set up its ->i_crypt_info in preparation for
660  * encrypting the name of the new file.  Also, if the new inode will be
661  * encrypted, set up its ->i_crypt_info and set *encrypt_ret=true.
662  *
663  * This isn't %GFP_NOFS-safe, and therefore it should be called before starting
664  * any filesystem transaction to create the inode.  For this reason, ->i_ino
665  * isn't required to be set yet, as the filesystem may not have set it yet.
666  *
667  * This doesn't persist the new inode's encryption context.  That still needs to
668  * be done later by calling fscrypt_set_context().
669  *
670  * Return: 0 on success, -ENOKEY if the encryption key is missing, or another
671  *	   -errno code
672  */
673 int fscrypt_prepare_new_inode(struct inode *dir, struct inode *inode,
674 			      bool *encrypt_ret)
675 {
676 	const union fscrypt_policy *policy;
677 	u8 nonce[FSCRYPT_FILE_NONCE_SIZE];
678 
679 	policy = fscrypt_policy_to_inherit(dir);
680 	if (policy == NULL)
681 		return 0;
682 	if (IS_ERR(policy))
683 		return PTR_ERR(policy);
684 
685 	if (WARN_ON_ONCE(inode->i_mode == 0))
686 		return -EINVAL;
687 
688 	/*
689 	 * Only regular files, directories, and symlinks are encrypted.
690 	 * Special files like device nodes and named pipes aren't.
691 	 */
692 	if (!S_ISREG(inode->i_mode) &&
693 	    !S_ISDIR(inode->i_mode) &&
694 	    !S_ISLNK(inode->i_mode))
695 		return 0;
696 
697 	*encrypt_ret = true;
698 
699 	get_random_bytes(nonce, FSCRYPT_FILE_NONCE_SIZE);
700 	return fscrypt_setup_encryption_info(inode, policy, nonce,
701 					     IS_CASEFOLDED(dir) &&
702 					     S_ISDIR(inode->i_mode));
703 }
704 EXPORT_SYMBOL_GPL(fscrypt_prepare_new_inode);
705 
706 /**
707  * fscrypt_put_encryption_info() - free most of an inode's fscrypt data
708  * @inode: an inode being evicted
709  *
710  * Free the inode's fscrypt_info.  Filesystems must call this when the inode is
711  * being evicted.  An RCU grace period need not have elapsed yet.
712  */
713 void fscrypt_put_encryption_info(struct inode *inode)
714 {
715 	put_crypt_info(inode->i_crypt_info);
716 	inode->i_crypt_info = NULL;
717 }
718 EXPORT_SYMBOL(fscrypt_put_encryption_info);
719 
720 /**
721  * fscrypt_free_inode() - free an inode's fscrypt data requiring RCU delay
722  * @inode: an inode being freed
723  *
724  * Free the inode's cached decrypted symlink target, if any.  Filesystems must
725  * call this after an RCU grace period, just before they free the inode.
726  */
727 void fscrypt_free_inode(struct inode *inode)
728 {
729 	if (IS_ENCRYPTED(inode) && S_ISLNK(inode->i_mode)) {
730 		kfree(inode->i_link);
731 		inode->i_link = NULL;
732 	}
733 }
734 EXPORT_SYMBOL(fscrypt_free_inode);
735 
736 /**
737  * fscrypt_drop_inode() - check whether the inode's master key has been removed
738  * @inode: an inode being considered for eviction
739  *
740  * Filesystems supporting fscrypt must call this from their ->drop_inode()
741  * method so that encrypted inodes are evicted as soon as they're no longer in
742  * use and their master key has been removed.
743  *
744  * Return: 1 if fscrypt wants the inode to be evicted now, otherwise 0
745  */
746 int fscrypt_drop_inode(struct inode *inode)
747 {
748 	const struct fscrypt_info *ci = fscrypt_get_info(inode);
749 	const struct fscrypt_master_key *mk;
750 
751 	/*
752 	 * If ci is NULL, then the inode doesn't have an encryption key set up
753 	 * so it's irrelevant.  If ci_master_key is NULL, then the master key
754 	 * was provided via the legacy mechanism of the process-subscribed
755 	 * keyrings, so we don't know whether it's been removed or not.
756 	 */
757 	if (!ci || !ci->ci_master_key)
758 		return 0;
759 	mk = ci->ci_master_key->payload.data[0];
760 
761 	/*
762 	 * With proper, non-racy use of FS_IOC_REMOVE_ENCRYPTION_KEY, all inodes
763 	 * protected by the key were cleaned by sync_filesystem().  But if
764 	 * userspace is still using the files, inodes can be dirtied between
765 	 * then and now.  We mustn't lose any writes, so skip dirty inodes here.
766 	 */
767 	if (inode->i_state & I_DIRTY_ALL)
768 		return 0;
769 
770 	/*
771 	 * Note: since we aren't holding the key semaphore, the result here can
772 	 * immediately become outdated.  But there's no correctness problem with
773 	 * unnecessarily evicting.  Nor is there a correctness problem with not
774 	 * evicting while iput() is racing with the key being removed, since
775 	 * then the thread removing the key will either evict the inode itself
776 	 * or will correctly detect that it wasn't evicted due to the race.
777 	 */
778 	return !is_master_key_secret_present(&mk->mk_secret);
779 }
780 EXPORT_SYMBOL_GPL(fscrypt_drop_inode);
781