1 // SPDX-License-Identifier: GPL-2.0
3 * Key setup facility for FS encryption support.
5 * Copyright (C) 2015, Google, Inc.
7 * Originally written by Michael Halcrow, Ildar Muslukhov, and Uday Savagaonkar.
8 * Heavily modified since then.
11 #include <crypto/aes.h>
12 #include <crypto/sha.h>
13 #include <crypto/skcipher.h>
14 #include <linux/key.h>
16 #include "fscrypt_private.h"
18 static struct crypto_shash *essiv_hash_tfm;
20 static struct fscrypt_mode available_modes[] = {
21 [FSCRYPT_MODE_AES_256_XTS] = {
22 .friendly_name = "AES-256-XTS",
23 .cipher_str = "xts(aes)",
27 [FSCRYPT_MODE_AES_256_CTS] = {
28 .friendly_name = "AES-256-CTS-CBC",
29 .cipher_str = "cts(cbc(aes))",
33 [FSCRYPT_MODE_AES_128_CBC] = {
34 .friendly_name = "AES-128-CBC",
35 .cipher_str = "cbc(aes)",
40 [FSCRYPT_MODE_AES_128_CTS] = {
41 .friendly_name = "AES-128-CTS-CBC",
42 .cipher_str = "cts(cbc(aes))",
46 [FSCRYPT_MODE_ADIANTUM] = {
47 .friendly_name = "Adiantum",
48 .cipher_str = "adiantum(xchacha12,aes)",
54 static struct fscrypt_mode *
55 select_encryption_mode(const union fscrypt_policy *policy,
56 const struct inode *inode)
58 BUILD_BUG_ON(ARRAY_SIZE(available_modes) != FSCRYPT_MODE_MAX + 1);
60 if (S_ISREG(inode->i_mode))
61 return &available_modes[fscrypt_policy_contents_mode(policy)];
63 if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
64 return &available_modes[fscrypt_policy_fnames_mode(policy)];
66 WARN_ONCE(1, "fscrypt: filesystem tried to load encryption info for inode %lu, which is not encryptable (file type %d)\n",
67 inode->i_ino, (inode->i_mode & S_IFMT));
68 return ERR_PTR(-EINVAL);
71 /* Create a symmetric cipher object for the given encryption mode and key */
72 struct crypto_skcipher *fscrypt_allocate_skcipher(struct fscrypt_mode *mode,
74 const struct inode *inode)
76 struct crypto_skcipher *tfm;
79 tfm = crypto_alloc_skcipher(mode->cipher_str, 0, 0);
81 if (PTR_ERR(tfm) == -ENOENT) {
83 "Missing crypto API support for %s (API name: \"%s\")",
84 mode->friendly_name, mode->cipher_str);
85 return ERR_PTR(-ENOPKG);
87 fscrypt_err(inode, "Error allocating '%s' transform: %ld",
88 mode->cipher_str, PTR_ERR(tfm));
91 if (unlikely(!mode->logged_impl_name)) {
93 * fscrypt performance can vary greatly depending on which
94 * crypto algorithm implementation is used. Help people debug
95 * performance problems by logging the ->cra_driver_name the
96 * first time a mode is used. Note that multiple threads can
97 * race here, but it doesn't really matter.
99 mode->logged_impl_name = true;
100 pr_info("fscrypt: %s using implementation \"%s\"\n",
102 crypto_skcipher_alg(tfm)->base.cra_driver_name);
104 crypto_skcipher_set_flags(tfm, CRYPTO_TFM_REQ_FORBID_WEAK_KEYS);
105 err = crypto_skcipher_setkey(tfm, raw_key, mode->keysize);
112 crypto_free_skcipher(tfm);
116 static int derive_essiv_salt(const u8 *key, int keysize, u8 *salt)
118 struct crypto_shash *tfm = READ_ONCE(essiv_hash_tfm);
120 /* init hash transform on demand */
121 if (unlikely(!tfm)) {
122 struct crypto_shash *prev_tfm;
124 tfm = crypto_alloc_shash("sha256", 0, 0);
126 if (PTR_ERR(tfm) == -ENOENT) {
128 "Missing crypto API support for SHA-256");
132 "Error allocating SHA-256 transform: %ld",
136 prev_tfm = cmpxchg(&essiv_hash_tfm, NULL, tfm);
138 crypto_free_shash(tfm);
144 SHASH_DESC_ON_STACK(desc, tfm);
147 return crypto_shash_digest(desc, key, keysize, salt);
151 static int init_essiv_generator(struct fscrypt_info *ci, const u8 *raw_key,
155 struct crypto_cipher *essiv_tfm;
156 u8 salt[SHA256_DIGEST_SIZE];
158 if (WARN_ON(ci->ci_mode->ivsize != AES_BLOCK_SIZE))
161 essiv_tfm = crypto_alloc_cipher("aes", 0, 0);
162 if (IS_ERR(essiv_tfm))
163 return PTR_ERR(essiv_tfm);
165 ci->ci_essiv_tfm = essiv_tfm;
167 err = derive_essiv_salt(raw_key, keysize, salt);
172 * Using SHA256 to derive the salt/key will result in AES-256 being
173 * used for IV generation. File contents encryption will still use the
174 * configured keysize (AES-128) nevertheless.
176 err = crypto_cipher_setkey(essiv_tfm, salt, sizeof(salt));
181 memzero_explicit(salt, sizeof(salt));
185 /* Given the per-file key, set up the file's crypto transform object(s) */
186 int fscrypt_set_derived_key(struct fscrypt_info *ci, const u8 *derived_key)
188 struct fscrypt_mode *mode = ci->ci_mode;
189 struct crypto_skcipher *ctfm;
192 ctfm = fscrypt_allocate_skcipher(mode, derived_key, ci->ci_inode);
194 return PTR_ERR(ctfm);
198 if (mode->needs_essiv) {
199 err = init_essiv_generator(ci, derived_key, mode->keysize);
201 fscrypt_warn(ci->ci_inode,
202 "Error initializing ESSIV generator: %d",
210 static int setup_per_mode_key(struct fscrypt_info *ci,
211 struct fscrypt_master_key *mk)
213 struct fscrypt_mode *mode = ci->ci_mode;
214 u8 mode_num = mode - available_modes;
215 struct crypto_skcipher *tfm, *prev_tfm;
216 u8 mode_key[FSCRYPT_MAX_KEY_SIZE];
219 if (WARN_ON(mode_num >= ARRAY_SIZE(mk->mk_mode_keys)))
222 /* pairs with cmpxchg() below */
223 tfm = READ_ONCE(mk->mk_mode_keys[mode_num]);
224 if (likely(tfm != NULL))
227 BUILD_BUG_ON(sizeof(mode_num) != 1);
228 err = fscrypt_hkdf_expand(&mk->mk_secret.hkdf,
229 HKDF_CONTEXT_PER_MODE_KEY,
230 &mode_num, sizeof(mode_num),
231 mode_key, mode->keysize);
234 tfm = fscrypt_allocate_skcipher(mode, mode_key, ci->ci_inode);
235 memzero_explicit(mode_key, mode->keysize);
239 /* pairs with READ_ONCE() above */
240 prev_tfm = cmpxchg(&mk->mk_mode_keys[mode_num], NULL, tfm);
241 if (prev_tfm != NULL) {
242 crypto_free_skcipher(tfm);
250 static int fscrypt_setup_v2_file_key(struct fscrypt_info *ci,
251 struct fscrypt_master_key *mk)
253 u8 derived_key[FSCRYPT_MAX_KEY_SIZE];
256 if (ci->ci_policy.v2.flags & FSCRYPT_POLICY_FLAG_DIRECT_KEY) {
258 * DIRECT_KEY: instead of deriving per-file keys, the per-file
259 * nonce will be included in all the IVs. But unlike v1
260 * policies, for v2 policies in this case we don't encrypt with
261 * the master key directly but rather derive a per-mode key.
262 * This ensures that the master key is consistently used only
263 * for HKDF, avoiding key reuse issues.
265 if (!fscrypt_mode_supports_direct_key(ci->ci_mode)) {
266 fscrypt_warn(ci->ci_inode,
267 "Direct key flag not allowed with %s",
268 ci->ci_mode->friendly_name);
271 return setup_per_mode_key(ci, mk);
274 err = fscrypt_hkdf_expand(&mk->mk_secret.hkdf,
275 HKDF_CONTEXT_PER_FILE_KEY,
276 ci->ci_nonce, FS_KEY_DERIVATION_NONCE_SIZE,
277 derived_key, ci->ci_mode->keysize);
281 err = fscrypt_set_derived_key(ci, derived_key);
282 memzero_explicit(derived_key, ci->ci_mode->keysize);
287 * Find the master key, then set up the inode's actual encryption key.
289 * If the master key is found in the filesystem-level keyring, then the
290 * corresponding 'struct key' is returned in *master_key_ret with
291 * ->mk_secret_sem read-locked. This is needed to ensure that only one task
292 * links the fscrypt_info into ->mk_decrypted_inodes (as multiple tasks may race
293 * to create an fscrypt_info for the same inode), and to synchronize the master
294 * key being removed with a new inode starting to use it.
296 static int setup_file_encryption_key(struct fscrypt_info *ci,
297 struct key **master_key_ret)
300 struct fscrypt_master_key *mk = NULL;
301 struct fscrypt_key_specifier mk_spec;
304 switch (ci->ci_policy.version) {
305 case FSCRYPT_POLICY_V1:
306 mk_spec.type = FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR;
307 memcpy(mk_spec.u.descriptor,
308 ci->ci_policy.v1.master_key_descriptor,
309 FSCRYPT_KEY_DESCRIPTOR_SIZE);
311 case FSCRYPT_POLICY_V2:
312 mk_spec.type = FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
313 memcpy(mk_spec.u.identifier,
314 ci->ci_policy.v2.master_key_identifier,
315 FSCRYPT_KEY_IDENTIFIER_SIZE);
322 key = fscrypt_find_master_key(ci->ci_inode->i_sb, &mk_spec);
324 if (key != ERR_PTR(-ENOKEY) ||
325 ci->ci_policy.version != FSCRYPT_POLICY_V1)
329 * As a legacy fallback for v1 policies, search for the key in
330 * the current task's subscribed keyrings too. Don't move this
331 * to before the search of ->s_master_keys, since users
332 * shouldn't be able to override filesystem-level keys.
334 return fscrypt_setup_v1_file_key_via_subscribed_keyrings(ci);
337 mk = key->payload.data[0];
338 down_read(&mk->mk_secret_sem);
340 /* Has the secret been removed (via FS_IOC_REMOVE_ENCRYPTION_KEY)? */
341 if (!is_master_key_secret_present(&mk->mk_secret)) {
343 goto out_release_key;
347 * Require that the master key be at least as long as the derived key.
348 * Otherwise, the derived key cannot possibly contain as much entropy as
349 * that required by the encryption mode it will be used for. For v1
350 * policies it's also required for the KDF to work at all.
352 if (mk->mk_secret.size < ci->ci_mode->keysize) {
354 "key with %s %*phN is too short (got %u bytes, need %u+ bytes)",
355 master_key_spec_type(&mk_spec),
356 master_key_spec_len(&mk_spec), (u8 *)&mk_spec.u,
357 mk->mk_secret.size, ci->ci_mode->keysize);
359 goto out_release_key;
362 switch (ci->ci_policy.version) {
363 case FSCRYPT_POLICY_V1:
364 err = fscrypt_setup_v1_file_key(ci, mk->mk_secret.raw);
366 case FSCRYPT_POLICY_V2:
367 err = fscrypt_setup_v2_file_key(ci, mk);
375 goto out_release_key;
377 *master_key_ret = key;
381 up_read(&mk->mk_secret_sem);
386 static void put_crypt_info(struct fscrypt_info *ci)
393 if (ci->ci_direct_key) {
394 fscrypt_put_direct_key(ci->ci_direct_key);
395 } else if ((ci->ci_ctfm != NULL || ci->ci_essiv_tfm != NULL) &&
396 !fscrypt_is_direct_key_policy(&ci->ci_policy)) {
397 crypto_free_skcipher(ci->ci_ctfm);
398 crypto_free_cipher(ci->ci_essiv_tfm);
401 key = ci->ci_master_key;
403 struct fscrypt_master_key *mk = key->payload.data[0];
406 * Remove this inode from the list of inodes that were unlocked
407 * with the master key.
409 * In addition, if we're removing the last inode from a key that
410 * already had its secret removed, invalidate the key so that it
411 * gets removed from ->s_master_keys.
413 spin_lock(&mk->mk_decrypted_inodes_lock);
414 list_del(&ci->ci_master_key_link);
415 spin_unlock(&mk->mk_decrypted_inodes_lock);
416 if (refcount_dec_and_test(&mk->mk_refcount))
420 kmem_cache_free(fscrypt_info_cachep, ci);
423 int fscrypt_get_encryption_info(struct inode *inode)
425 struct fscrypt_info *crypt_info;
426 union fscrypt_context ctx;
427 struct fscrypt_mode *mode;
428 struct key *master_key = NULL;
431 if (fscrypt_has_encryption_key(inode))
434 res = fscrypt_initialize(inode->i_sb->s_cop->flags);
438 res = inode->i_sb->s_cop->get_context(inode, &ctx, sizeof(ctx));
440 if (!fscrypt_dummy_context_enabled(inode) ||
441 IS_ENCRYPTED(inode)) {
443 "Error %d getting encryption context",
447 /* Fake up a context for an unencrypted directory */
448 memset(&ctx, 0, sizeof(ctx));
449 ctx.version = FSCRYPT_CONTEXT_V1;
450 ctx.v1.contents_encryption_mode = FSCRYPT_MODE_AES_256_XTS;
451 ctx.v1.filenames_encryption_mode = FSCRYPT_MODE_AES_256_CTS;
452 memset(ctx.v1.master_key_descriptor, 0x42,
453 FSCRYPT_KEY_DESCRIPTOR_SIZE);
454 res = sizeof(ctx.v1);
457 crypt_info = kmem_cache_zalloc(fscrypt_info_cachep, GFP_NOFS);
461 crypt_info->ci_inode = inode;
463 res = fscrypt_policy_from_context(&crypt_info->ci_policy, &ctx, res);
466 "Unrecognized or corrupt encryption context");
470 switch (ctx.version) {
471 case FSCRYPT_CONTEXT_V1:
472 memcpy(crypt_info->ci_nonce, ctx.v1.nonce,
473 FS_KEY_DERIVATION_NONCE_SIZE);
475 case FSCRYPT_CONTEXT_V2:
476 memcpy(crypt_info->ci_nonce, ctx.v2.nonce,
477 FS_KEY_DERIVATION_NONCE_SIZE);
485 if (!fscrypt_supported_policy(&crypt_info->ci_policy, inode)) {
490 mode = select_encryption_mode(&crypt_info->ci_policy, inode);
495 WARN_ON(mode->ivsize > FSCRYPT_MAX_IV_SIZE);
496 crypt_info->ci_mode = mode;
498 res = setup_file_encryption_key(crypt_info, &master_key);
502 if (cmpxchg_release(&inode->i_crypt_info, NULL, crypt_info) == NULL) {
504 struct fscrypt_master_key *mk =
505 master_key->payload.data[0];
507 refcount_inc(&mk->mk_refcount);
508 crypt_info->ci_master_key = key_get(master_key);
509 spin_lock(&mk->mk_decrypted_inodes_lock);
510 list_add(&crypt_info->ci_master_key_link,
511 &mk->mk_decrypted_inodes);
512 spin_unlock(&mk->mk_decrypted_inodes_lock);
519 struct fscrypt_master_key *mk = master_key->payload.data[0];
521 up_read(&mk->mk_secret_sem);
526 put_crypt_info(crypt_info);
529 EXPORT_SYMBOL(fscrypt_get_encryption_info);
532 * fscrypt_put_encryption_info - free most of an inode's fscrypt data
534 * Free the inode's fscrypt_info. Filesystems must call this when the inode is
535 * being evicted. An RCU grace period need not have elapsed yet.
537 void fscrypt_put_encryption_info(struct inode *inode)
539 put_crypt_info(inode->i_crypt_info);
540 inode->i_crypt_info = NULL;
542 EXPORT_SYMBOL(fscrypt_put_encryption_info);
545 * fscrypt_free_inode - free an inode's fscrypt data requiring RCU delay
547 * Free the inode's cached decrypted symlink target, if any. Filesystems must
548 * call this after an RCU grace period, just before they free the inode.
550 void fscrypt_free_inode(struct inode *inode)
552 if (IS_ENCRYPTED(inode) && S_ISLNK(inode->i_mode)) {
553 kfree(inode->i_link);
554 inode->i_link = NULL;
557 EXPORT_SYMBOL(fscrypt_free_inode);
560 * fscrypt_drop_inode - check whether the inode's master key has been removed
562 * Filesystems supporting fscrypt must call this from their ->drop_inode()
563 * method so that encrypted inodes are evicted as soon as they're no longer in
564 * use and their master key has been removed.
566 * Return: 1 if fscrypt wants the inode to be evicted now, otherwise 0
568 int fscrypt_drop_inode(struct inode *inode)
570 const struct fscrypt_info *ci = READ_ONCE(inode->i_crypt_info);
571 const struct fscrypt_master_key *mk;
574 * If ci is NULL, then the inode doesn't have an encryption key set up
575 * so it's irrelevant. If ci_master_key is NULL, then the master key
576 * was provided via the legacy mechanism of the process-subscribed
577 * keyrings, so we don't know whether it's been removed or not.
579 if (!ci || !ci->ci_master_key)
581 mk = ci->ci_master_key->payload.data[0];
584 * With proper, non-racy use of FS_IOC_REMOVE_ENCRYPTION_KEY, all inodes
585 * protected by the key were cleaned by sync_filesystem(). But if
586 * userspace is still using the files, inodes can be dirtied between
587 * then and now. We mustn't lose any writes, so skip dirty inodes here.
589 if (inode->i_state & I_DIRTY_ALL)
593 * Note: since we aren't holding ->mk_secret_sem, the result here can
594 * immediately become outdated. But there's no correctness problem with
595 * unnecessarily evicting. Nor is there a correctness problem with not
596 * evicting while iput() is racing with the key being removed, since
597 * then the thread removing the key will either evict the inode itself
598 * or will correctly detect that it wasn't evicted due to the race.
600 return !is_master_key_secret_present(&mk->mk_secret);
602 EXPORT_SYMBOL_GPL(fscrypt_drop_inode);