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