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