]> git.ipfire.org Git - thirdparty/kernel/linux.git/blame - fs/crypto/keysetup.c
fscrypt: write CBC-CTS instead of CTS-CBC
[thirdparty/kernel/linux.git] / fs / crypto / keysetup.c
CommitLineData
b2441318 1// SPDX-License-Identifier: GPL-2.0
0adda907 2/*
3ec4f2a6 3 * Key setup facility for FS encryption support.
0adda907
JK
4 *
5 * Copyright (C) 2015, Google, Inc.
6 *
3ec4f2a6
EB
7 * Originally written by Michael Halcrow, Ildar Muslukhov, and Uday Savagaonkar.
8 * Heavily modified since then.
0adda907 9 */
0b81d077 10
a575784c 11#include <crypto/skcipher.h>
a992b20c 12#include <linux/random.h>
0109ce76 13
3325bea5 14#include "fscrypt_private.h"
0adda907 15
85af90e5 16struct fscrypt_mode fscrypt_modes[] = {
3b6df59b 17 [FSCRYPT_MODE_AES_256_XTS] = {
e1cc40e5
EB
18 .friendly_name = "AES-256-XTS",
19 .cipher_str = "xts(aes)",
20 .keysize = 64,
7f595d6a 21 .security_strength = 32,
8094c3ce 22 .ivsize = 16,
5fee3609 23 .blk_crypto_mode = BLK_ENCRYPTION_MODE_AES_256_XTS,
e1cc40e5 24 },
3b6df59b 25 [FSCRYPT_MODE_AES_256_CTS] = {
2f944c66 26 .friendly_name = "AES-256-CBC-CTS",
e1cc40e5
EB
27 .cipher_str = "cts(cbc(aes))",
28 .keysize = 32,
7f595d6a 29 .security_strength = 32,
8094c3ce 30 .ivsize = 16,
e1cc40e5 31 },
3b6df59b 32 [FSCRYPT_MODE_AES_128_CBC] = {
4006d799
EB
33 .friendly_name = "AES-128-CBC-ESSIV",
34 .cipher_str = "essiv(cbc(aes),sha256)",
e1cc40e5 35 .keysize = 16,
7f595d6a 36 .security_strength = 16,
8094c3ce 37 .ivsize = 16,
5fee3609 38 .blk_crypto_mode = BLK_ENCRYPTION_MODE_AES_128_CBC_ESSIV,
e1cc40e5 39 },
3b6df59b 40 [FSCRYPT_MODE_AES_128_CTS] = {
2f944c66 41 .friendly_name = "AES-128-CBC-CTS",
e1cc40e5
EB
42 .cipher_str = "cts(cbc(aes))",
43 .keysize = 16,
7f595d6a 44 .security_strength = 16,
8094c3ce 45 .ivsize = 16,
e0cefada
TZ
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] = {
2f944c66 56 .friendly_name = "SM4-CBC-CTS",
e0cefada
TZ
57 .cipher_str = "cts(cbc(sm4))",
58 .keysize = 16,
59 .security_strength = 16,
60 .ivsize = 16,
8094c3ce 61 },
3b6df59b 62 [FSCRYPT_MODE_ADIANTUM] = {
8094c3ce
EB
63 .friendly_name = "Adiantum",
64 .cipher_str = "adiantum(xchacha12,aes)",
65 .keysize = 32,
7f595d6a 66 .security_strength = 32,
8094c3ce 67 .ivsize = 32,
5fee3609 68 .blk_crypto_mode = BLK_ENCRYPTION_MODE_ADIANTUM,
e1cc40e5 69 },
6b2a51ff
NH
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 },
b7e7cf7a
DW
77};
78
e3b1078b
EB
79static DEFINE_MUTEX(fscrypt_mode_key_setup_mutex);
80
e1cc40e5 81static struct fscrypt_mode *
5dae460c
EB
82select_encryption_mode(const union fscrypt_policy *policy,
83 const struct inode *inode)
8f39850d 84{
3ceb6543
EB
85 BUILD_BUG_ON(ARRAY_SIZE(fscrypt_modes) != FSCRYPT_MODE_MAX + 1);
86
e1cc40e5 87 if (S_ISREG(inode->i_mode))
85af90e5 88 return &fscrypt_modes[fscrypt_policy_contents_mode(policy)];
e1cc40e5
EB
89
90 if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
85af90e5 91 return &fscrypt_modes[fscrypt_policy_fnames_mode(policy)];
8f39850d 92
e1cc40e5
EB
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);
8f39850d
EB
96}
97
3ec4f2a6 98/* Create a symmetric cipher object for the given encryption mode and key */
5fee3609
ST
99static struct crypto_skcipher *
100fscrypt_allocate_skcipher(struct fscrypt_mode *mode, const u8 *raw_key,
101 const struct inode *inode)
8094c3ce
EB
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)) {
29a98c1c 108 if (PTR_ERR(tfm) == -ENOENT) {
a4d14e91
EB
109 fscrypt_warn(inode,
110 "Missing crypto API support for %s (API name: \"%s\")",
111 mode->friendly_name, mode->cipher_str);
29a98c1c
EB
112 return ERR_PTR(-ENOPKG);
113 }
114 fscrypt_err(inode, "Error allocating '%s' transform: %ld",
115 mode->cipher_str, PTR_ERR(tfm));
8094c3ce
EB
116 return tfm;
117 }
a7a5bc5f 118 if (!xchg(&mode->logged_cryptoapi_impl, 1)) {
8094c3ce
EB
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
ff73c2c0 123 * first time a mode is used.
8094c3ce 124 */
8094c3ce 125 pr_info("fscrypt: %s using implementation \"%s\"\n",
6e1adb88 126 mode->friendly_name, crypto_skcipher_driver_name(tfm));
8094c3ce 127 }
41b2ad80 128 if (WARN_ON_ONCE(crypto_skcipher_ivsize(tfm) != mode->ivsize)) {
c64cfb98
EB
129 err = -EINVAL;
130 goto err_free_tfm;
131 }
231baecd 132 crypto_skcipher_set_flags(tfm, CRYPTO_TFM_REQ_FORBID_WEAK_KEYS);
8094c3ce
EB
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
5fee3609
ST
144/*
145 * Prepare the crypto transform object or blk-crypto key in @prep_key, given the
b7e072f9
EB
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).
5fee3609
ST
149 */
150int fscrypt_prepare_key(struct fscrypt_prepared_key *prep_key,
3e7807d5 151 const u8 *raw_key, const struct fscrypt_inode_info *ci)
8094c3ce 152{
4006d799 153 struct crypto_skcipher *tfm;
3ec4f2a6 154
5fee3609
ST
155 if (fscrypt_using_inline_encryption(ci))
156 return fscrypt_prepare_inline_crypt_key(prep_key, raw_key, ci);
157
f592efe7 158 tfm = fscrypt_allocate_skcipher(ci->ci_mode, raw_key, ci->ci_inode);
4006d799
EB
159 if (IS_ERR(tfm))
160 return PTR_ERR(tfm);
5fee3609 161 /*
97c6327f
EB
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.
5fee3609
ST
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. */
22e9947a
EB
172void fscrypt_destroy_prepared_key(struct super_block *sb,
173 struct fscrypt_prepared_key *prep_key)
5fee3609
ST
174{
175 crypto_free_skcipher(prep_key->tfm);
22e9947a 176 fscrypt_destroy_inline_crypt_key(sb, prep_key);
d7e7b9af 177 memzero_explicit(prep_key, sizeof(*prep_key));
5fee3609 178}
8094c3ce 179
5fee3609 180/* Given a per-file encryption key, set up the file's crypto transform object */
3e7807d5
JB
181int fscrypt_set_per_file_enc_key(struct fscrypt_inode_info *ci,
182 const u8 *raw_key)
5fee3609 183{
b103fb76 184 ci->ci_owns_key = true;
5fee3609 185 return fscrypt_prepare_key(&ci->ci_enc_key, raw_key, ci);
8094c3ce
EB
186}
187
3e7807d5 188static int setup_per_mode_enc_key(struct fscrypt_inode_info *ci,
f592efe7 189 struct fscrypt_master_key *mk,
5fee3609 190 struct fscrypt_prepared_key *keys,
f592efe7 191 u8 hkdf_context, bool include_fs_uuid)
5dae460c 192{
b103fb76
EB
193 const struct inode *inode = ci->ci_inode;
194 const struct super_block *sb = inode->i_sb;
5dae460c 195 struct fscrypt_mode *mode = ci->ci_mode;
85af90e5 196 const u8 mode_num = mode - fscrypt_modes;
5fee3609 197 struct fscrypt_prepared_key *prep_key;
5dae460c 198 u8 mode_key[FSCRYPT_MAX_KEY_SIZE];
b103fb76
EB
199 u8 hkdf_info[sizeof(mode_num) + sizeof(sb->s_uuid)];
200 unsigned int hkdf_infolen = 0;
5dae460c
EB
201 int err;
202
41b2ad80 203 if (WARN_ON_ONCE(mode_num > FSCRYPT_MODE_MAX))
5dae460c
EB
204 return -EINVAL;
205
5fee3609
ST
206 prep_key = &keys[mode_num];
207 if (fscrypt_is_key_prepared(prep_key, ci)) {
208 ci->ci_enc_key = *prep_key;
e3b1078b
EB
209 return 0;
210 }
211
212 mutex_lock(&fscrypt_mode_key_setup_mutex);
213
5fee3609 214 if (fscrypt_is_key_prepared(prep_key, ci))
e3b1078b 215 goto done_unlock;
5dae460c
EB
216
217 BUILD_BUG_ON(sizeof(mode_num) != 1);
b103fb76
EB
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 }
5dae460c 226 err = fscrypt_hkdf_expand(&mk->mk_secret.hkdf,
b103fb76 227 hkdf_context, hkdf_info, hkdf_infolen,
5dae460c
EB
228 mode_key, mode->keysize);
229 if (err)
e3b1078b 230 goto out_unlock;
5fee3609 231 err = fscrypt_prepare_key(prep_key, mode_key, ci);
5dae460c 232 memzero_explicit(mode_key, mode->keysize);
5fee3609 233 if (err)
e3b1078b 234 goto out_unlock;
e3b1078b 235done_unlock:
5fee3609 236 ci->ci_enc_key = *prep_key;
e3b1078b
EB
237 err = 0;
238out_unlock:
239 mutex_unlock(&fscrypt_mode_key_setup_mutex);
240 return err;
5dae460c
EB
241}
242
2fc2b430
EB
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
3e7807d5 269int fscrypt_derive_dirhash_key(struct fscrypt_inode_info *ci,
aa408f83
DR
270 const struct fscrypt_master_key *mk)
271{
272 int err;
273
2fc2b430
EB
274 err = fscrypt_derive_siphash_key(mk, HKDF_CONTEXT_DIRHASH_KEY,
275 ci->ci_nonce, FSCRYPT_FILE_NONCE_SIZE,
276 &ci->ci_dirhash_key);
aa408f83
DR
277 if (err)
278 return err;
279 ci->ci_dirhash_key_initialized = true;
280 return 0;
281}
282
3e7807d5 283void fscrypt_hash_inode_number(struct fscrypt_inode_info *ci,
a992b20c
EB
284 const struct fscrypt_master_key *mk)
285{
41b2ad80
EB
286 WARN_ON_ONCE(ci->ci_inode->i_ino == 0);
287 WARN_ON_ONCE(!mk->mk_ino_hash_key_initialized);
a992b20c
EB
288
289 ci->ci_hashed_ino = (u32)siphash_1u64(ci->ci_inode->i_ino,
290 &mk->mk_ino_hash_key);
291}
292
3e7807d5 293static int fscrypt_setup_iv_ino_lblk_32_key(struct fscrypt_inode_info *ci,
e3b1078b
EB
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
2fc2b430
EB
311 err = fscrypt_derive_siphash_key(mk,
312 HKDF_CONTEXT_INODE_HASH_KEY,
313 NULL, 0, &mk->mk_ino_hash_key);
e3b1078b
EB
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
a992b20c
EB
324 /*
325 * New inodes may not have an inode number assigned yet.
326 * Hashing their inode number is delayed until later.
327 */
92cfcd03 328 if (ci->ci_inode->i_ino)
a992b20c 329 fscrypt_hash_inode_number(ci, mk);
e3b1078b
EB
330 return 0;
331}
332
3e7807d5 333static int fscrypt_setup_v2_file_key(struct fscrypt_inode_info *ci,
a992b20c
EB
334 struct fscrypt_master_key *mk,
335 bool need_dirhash_key)
5dae460c 336{
5dae460c
EB
337 int err;
338
339 if (ci->ci_policy.v2.flags & FSCRYPT_POLICY_FLAG_DIRECT_KEY) {
340 /*
f592efe7
EB
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.
5dae460c 347 */
e3b1078b 348 err = setup_per_mode_enc_key(ci, mk, mk->mk_direct_keys,
f592efe7 349 HKDF_CONTEXT_DIRECT_KEY, false);
b103fb76
EB
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
e3b1078b 356 * encryption hardware compliant with the UFS standard.
b103fb76 357 */
e3b1078b 358 err = setup_per_mode_enc_key(ci, mk, mk->mk_iv_ino_lblk_64_keys,
f592efe7
EB
359 HKDF_CONTEXT_IV_INO_LBLK_64_KEY,
360 true);
e3b1078b
EB
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);
aa408f83
DR
364 } else {
365 u8 derived_key[FSCRYPT_MAX_KEY_SIZE];
5dae460c 366
aa408f83 367 err = fscrypt_hkdf_expand(&mk->mk_secret.hkdf,
f592efe7 368 HKDF_CONTEXT_PER_FILE_ENC_KEY,
1d6217a4 369 ci->ci_nonce, FSCRYPT_FILE_NONCE_SIZE,
aa408f83
DR
370 derived_key, ci->ci_mode->keysize);
371 if (err)
372 return err;
373
f592efe7 374 err = fscrypt_set_per_file_enc_key(ci, derived_key);
aa408f83
DR
375 memzero_explicit(derived_key, ci->ci_mode->keysize);
376 }
5dae460c
EB
377 if (err)
378 return err;
379
aa408f83 380 /* Derive a secret dirhash key for directories that need it. */
a992b20c 381 if (need_dirhash_key) {
aa408f83
DR
382 err = fscrypt_derive_dirhash_key(ci, mk);
383 if (err)
384 return err;
385 }
386
387 return 0;
5dae460c
EB
388}
389
7f595d6a
EB
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,
3e7807d5 408 const struct fscrypt_inode_info *ci)
7f595d6a
EB
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
3ec4f2a6
EB
429/*
430 * Find the master key, then set up the inode's actual encryption key.
b1c0ec35 431 *
d7e7b9af
EB
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
3e7807d5
JB
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.
3ec4f2a6 438 */
3e7807d5 439static int setup_file_encryption_key(struct fscrypt_inode_info *ci,
a992b20c 440 bool need_dirhash_key,
d7e7b9af 441 struct fscrypt_master_key **mk_ret)
3ec4f2a6 442{
60e463f0 443 struct super_block *sb = ci->ci_inode->i_sb;
22d94f49 444 struct fscrypt_key_specifier mk_spec;
d7e7b9af 445 struct fscrypt_master_key *mk;
22d94f49
EB
446 int err;
447
5fee3609
ST
448 err = fscrypt_select_encryption_impl(ci);
449 if (err)
450 return err;
451
bfb9700b
EB
452 err = fscrypt_policy_to_key_spec(&ci->ci_policy, &mk_spec);
453 if (err)
454 return err;
22d94f49 455
60e463f0
EB
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)) {
097d7c1f 469 err = fscrypt_add_test_dummy_key(sb, &mk_spec);
60e463f0
EB
470 if (err)
471 return err;
472 mk = fscrypt_find_master_key(sb, &mk_spec);
473 }
474 }
475 if (unlikely(!mk)) {
d7e7b9af
EB
476 if (ci->ci_policy.version != FSCRYPT_POLICY_V1)
477 return -ENOKEY;
22d94f49 478
5dae460c
EB
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 */
22d94f49
EB
485 return fscrypt_setup_v1_file_key_via_subscribed_keyrings(ci);
486 }
d7e7b9af 487 down_read(&mk->mk_sem);
b1c0ec35 488
15baf554
EB
489 if (!mk->mk_present) {
490 /* FS_IOC_REMOVE_ENCRYPTION_KEY has been executed on this key */
b1c0ec35
EB
491 err = -ENOKEY;
492 goto out_release_key;
493 }
22d94f49 494
7f595d6a 495 if (!fscrypt_valid_master_key_size(mk, ci)) {
22d94f49
EB
496 err = -ENOKEY;
497 goto out_release_key;
498 }
499
5dae460c
EB
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:
a992b20c 505 err = fscrypt_setup_v2_file_key(ci, mk, need_dirhash_key);
5dae460c
EB
506 break;
507 default:
41b2ad80 508 WARN_ON_ONCE(1);
5dae460c
EB
509 err = -EINVAL;
510 break;
511 }
b1c0ec35
EB
512 if (err)
513 goto out_release_key;
514
d7e7b9af 515 *mk_ret = mk;
b1c0ec35 516 return 0;
22d94f49
EB
517
518out_release_key:
d7e7b9af
EB
519 up_read(&mk->mk_sem);
520 fscrypt_put_master_key(mk);
22d94f49 521 return err;
3ec4f2a6
EB
522}
523
3e7807d5 524static void put_crypt_info(struct fscrypt_inode_info *ci)
8094c3ce 525{
d7e7b9af 526 struct fscrypt_master_key *mk;
b1c0ec35 527
8094c3ce
EB
528 if (!ci)
529 return;
530
4006d799 531 if (ci->ci_direct_key)
0109ce76 532 fscrypt_put_direct_key(ci->ci_direct_key);
b103fb76 533 else if (ci->ci_owns_key)
22e9947a
EB
534 fscrypt_destroy_prepared_key(ci->ci_inode->i_sb,
535 &ci->ci_enc_key);
b1c0ec35 536
d7e7b9af
EB
537 mk = ci->ci_master_key;
538 if (mk) {
b1c0ec35
EB
539 /*
540 * Remove this inode from the list of inodes that were unlocked
d7e7b9af 541 * with the master key. In addition, if we're removing the last
15baf554
EB
542 * inode from an incompletely removed key, then complete the
543 * full removal of the key.
b1c0ec35
EB
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);
02aef422 548 fscrypt_put_master_key_activeref(ci->ci_inode->i_sb, mk);
b1c0ec35 549 }
6f99756d 550 memzero_explicit(ci, sizeof(*ci));
3e7807d5 551 kmem_cache_free(fscrypt_inode_info_cachep, ci);
8094c3ce
EB
552}
553
a992b20c
EB
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)
0adda907 559{
3e7807d5 560 struct fscrypt_inode_info *crypt_info;
e1cc40e5 561 struct fscrypt_mode *mode;
d7e7b9af 562 struct fscrypt_master_key *mk = NULL;
0adda907
JK
563 int res;
564
83e57e47 565 res = fscrypt_initialize(inode->i_sb);
cfc4d971
JK
566 if (res)
567 return res;
0b81d077 568
3e7807d5 569 crypt_info = kmem_cache_zalloc(fscrypt_inode_info_cachep, GFP_KERNEL);
0adda907
JK
570 if (!crypt_info)
571 return -ENOMEM;
572
59dc6a8e 573 crypt_info->ci_inode = inode;
a992b20c
EB
574 crypt_info->ci_policy = *policy;
575 memcpy(crypt_info->ci_nonce, nonce, FSCRYPT_FILE_NONCE_SIZE);
640778fb 576
5dae460c 577 mode = select_encryption_mode(&crypt_info->ci_policy, inode);
e1cc40e5
EB
578 if (IS_ERR(mode)) {
579 res = PTR_ERR(mode);
26bf3dc7 580 goto out;
e1cc40e5 581 }
41b2ad80 582 WARN_ON_ONCE(mode->ivsize > FSCRYPT_MAX_IV_SIZE);
8094c3ce 583 crypt_info->ci_mode = mode;
8f39850d 584
5b118884
EB
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
d7e7b9af 590 res = setup_file_encryption_key(crypt_info, need_dirhash_key, &mk);
26bf3dc7
JK
591 if (res)
592 goto out;
593
ab673b98 594 /*
a992b20c
EB
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
3e7807d5
JB
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.
ab673b98 599 */
b1c0ec35 600 if (cmpxchg_release(&inode->i_crypt_info, NULL, crypt_info) == NULL) {
ab673b98
EB
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 */
d7e7b9af
EB
605 if (mk) {
606 crypt_info->ci_master_key = mk;
607 refcount_inc(&mk->mk_active_refs);
b1c0ec35
EB
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 }
1b53cf98 613 crypt_info = NULL;
b1c0ec35
EB
614 }
615 res = 0;
26bf3dc7 616out:
d7e7b9af
EB
617 if (mk) {
618 up_read(&mk->mk_sem);
619 fscrypt_put_master_key(mk);
b1c0ec35 620 }
a992b20c
EB
621 put_crypt_info(crypt_info);
622 return res;
623}
624
625/**
626 * fscrypt_get_encryption_info() - set up an inode's encryption key
ac4acb1f 627 * @inode: the inode to set up the key for. Must be encrypted.
a14d0b67
EB
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.
a992b20c
EB
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 */
a14d0b67 643int fscrypt_get_encryption_info(struct inode *inode, bool allow_unsupported)
a992b20c
EB
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) {
a14d0b67
EB
654 if (res == -ERANGE && allow_unsupported)
655 return 0;
ac4acb1f
EB
656 fscrypt_warn(inode, "Error %d getting encryption context", res);
657 return res;
a992b20c
EB
658 }
659
660 res = fscrypt_policy_from_context(&policy, &ctx, res);
661 if (res) {
a14d0b67
EB
662 if (allow_unsupported)
663 return 0;
a992b20c
EB
664 fscrypt_warn(inode,
665 "Unrecognized or corrupt encryption context");
666 return res;
667 }
668
a14d0b67
EB
669 if (!fscrypt_supported_policy(&policy, inode)) {
670 if (allow_unsupported)
671 return 0;
a992b20c 672 return -EINVAL;
a14d0b67 673 }
a992b20c
EB
674
675 res = fscrypt_setup_encryption_info(inode, &policy,
676 fscrypt_context_nonce(&ctx),
677 IS_CASEFOLDED(inode) &&
678 S_ISDIR(inode->i_mode));
a14d0b67
EB
679
680 if (res == -ENOPKG && allow_unsupported) /* Algorithm unavailable? */
681 res = 0;
0b81d077 682 if (res == -ENOKEY)
26bf3dc7 683 res = 0;
0adda907
JK
684 return res;
685}
686
a992b20c
EB
687/**
688 * fscrypt_prepare_new_inode() - prepare to create a new inode in a directory
689 * @dir: a possibly-encrypted directory
5befc19c 690 * @inode: the new inode. ->i_mode and ->i_blkbits must be set already.
a992b20c
EB
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{
ac4acb1f 711 const union fscrypt_policy *policy;
a992b20c
EB
712 u8 nonce[FSCRYPT_FILE_NONCE_SIZE];
713
ac4acb1f
EB
714 policy = fscrypt_policy_to_inherit(dir);
715 if (policy == NULL)
a992b20c 716 return 0;
ac4acb1f
EB
717 if (IS_ERR(policy))
718 return PTR_ERR(policy);
a992b20c 719
5befc19c
XL
720 if (WARN_ON_ONCE(inode->i_blkbits == 0))
721 return -EINVAL;
722
a992b20c
EB
723 if (WARN_ON_ONCE(inode->i_mode == 0))
724 return -EINVAL;
725
726 /*
727 * Only regular files, directories, and symlinks are encrypted.
728 * Special files like device nodes and named pipes aren't.
729 */
730 if (!S_ISREG(inode->i_mode) &&
731 !S_ISDIR(inode->i_mode) &&
732 !S_ISLNK(inode->i_mode))
733 return 0;
734
735 *encrypt_ret = true;
736
737 get_random_bytes(nonce, FSCRYPT_FILE_NONCE_SIZE);
ac4acb1f 738 return fscrypt_setup_encryption_info(inode, policy, nonce,
a992b20c
EB
739 IS_CASEFOLDED(dir) &&
740 S_ISDIR(inode->i_mode));
741}
742EXPORT_SYMBOL_GPL(fscrypt_prepare_new_inode);
743
2c58d548 744/**
d2fe9754
EB
745 * fscrypt_put_encryption_info() - free most of an inode's fscrypt data
746 * @inode: an inode being evicted
2c58d548 747 *
3e7807d5
JB
748 * Free the inode's fscrypt_inode_info. Filesystems must call this when the
749 * inode is being evicted. An RCU grace period need not have elapsed yet.
2c58d548 750 */
3d204e24 751void fscrypt_put_encryption_info(struct inode *inode)
0adda907 752{
3d204e24
EB
753 put_crypt_info(inode->i_crypt_info);
754 inode->i_crypt_info = NULL;
0b81d077
JK
755}
756EXPORT_SYMBOL(fscrypt_put_encryption_info);
2c58d548
EB
757
758/**
d2fe9754
EB
759 * fscrypt_free_inode() - free an inode's fscrypt data requiring RCU delay
760 * @inode: an inode being freed
2c58d548
EB
761 *
762 * Free the inode's cached decrypted symlink target, if any. Filesystems must
763 * call this after an RCU grace period, just before they free the inode.
764 */
765void fscrypt_free_inode(struct inode *inode)
766{
767 if (IS_ENCRYPTED(inode) && S_ISLNK(inode->i_mode)) {
768 kfree(inode->i_link);
769 inode->i_link = NULL;
770 }
771}
772EXPORT_SYMBOL(fscrypt_free_inode);
b1c0ec35
EB
773
774/**
d2fe9754
EB
775 * fscrypt_drop_inode() - check whether the inode's master key has been removed
776 * @inode: an inode being considered for eviction
b1c0ec35
EB
777 *
778 * Filesystems supporting fscrypt must call this from their ->drop_inode()
779 * method so that encrypted inodes are evicted as soon as they're no longer in
780 * use and their master key has been removed.
781 *
782 * Return: 1 if fscrypt wants the inode to be evicted now, otherwise 0
783 */
784int fscrypt_drop_inode(struct inode *inode)
785{
3e7807d5 786 const struct fscrypt_inode_info *ci = fscrypt_get_inode_info(inode);
b1c0ec35
EB
787
788 /*
789 * If ci is NULL, then the inode doesn't have an encryption key set up
790 * so it's irrelevant. If ci_master_key is NULL, then the master key
791 * was provided via the legacy mechanism of the process-subscribed
792 * keyrings, so we don't know whether it's been removed or not.
793 */
794 if (!ci || !ci->ci_master_key)
795 return 0;
b1c0ec35 796
2b4eae95
EB
797 /*
798 * With proper, non-racy use of FS_IOC_REMOVE_ENCRYPTION_KEY, all inodes
799 * protected by the key were cleaned by sync_filesystem(). But if
800 * userspace is still using the files, inodes can be dirtied between
801 * then and now. We mustn't lose any writes, so skip dirty inodes here.
802 */
803 if (inode->i_state & I_DIRTY_ALL)
804 return 0;
805
b1c0ec35 806 /*
15baf554
EB
807 * We can't take ->mk_sem here, since this runs in atomic context.
808 * Therefore, ->mk_present can change concurrently, and our result may
b1c0ec35
EB
809 * immediately become outdated. But there's no correctness problem with
810 * unnecessarily evicting. Nor is there a correctness problem with not
811 * evicting while iput() is racing with the key being removed, since
812 * then the thread removing the key will either evict the inode itself
813 * or will correctly detect that it wasn't evicted due to the race.
814 */
15baf554 815 return !READ_ONCE(ci->ci_master_key->mk_present);
b1c0ec35
EB
816}
817EXPORT_SYMBOL_GPL(fscrypt_drop_inode);