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