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