Linux Audio

Check our new training course

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