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