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