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