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