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