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