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