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