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