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