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/skcipher.h>
12 #include <linux/key.h>
14 #include "fscrypt_private.h"
16 struct fscrypt_mode fscrypt_modes[] = {
17 [FSCRYPT_MODE_AES_256_XTS] = {
18 .friendly_name = "AES-256-XTS",
19 .cipher_str = "xts(aes)",
22 .blk_crypto_mode = BLK_ENCRYPTION_MODE_AES_256_XTS,
24 [FSCRYPT_MODE_AES_256_CTS] = {
25 .friendly_name = "AES-256-CTS-CBC",
26 .cipher_str = "cts(cbc(aes))",
30 [FSCRYPT_MODE_AES_128_CBC] = {
31 .friendly_name = "AES-128-CBC-ESSIV",
32 .cipher_str = "essiv(cbc(aes),sha256)",
35 .blk_crypto_mode = BLK_ENCRYPTION_MODE_AES_128_CBC_ESSIV,
37 [FSCRYPT_MODE_AES_128_CTS] = {
38 .friendly_name = "AES-128-CTS-CBC",
39 .cipher_str = "cts(cbc(aes))",
43 [FSCRYPT_MODE_ADIANTUM] = {
44 .friendly_name = "Adiantum",
45 .cipher_str = "adiantum(xchacha12,aes)",
48 .blk_crypto_mode = BLK_ENCRYPTION_MODE_ADIANTUM,
52 static DEFINE_MUTEX(fscrypt_mode_key_setup_mutex);
54 static struct fscrypt_mode *
55 select_encryption_mode(const union fscrypt_policy *policy,
56 const struct inode *inode)
58 if (S_ISREG(inode->i_mode))
59 return &fscrypt_modes[fscrypt_policy_contents_mode(policy)];
61 if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
62 return &fscrypt_modes[fscrypt_policy_fnames_mode(policy)];
64 WARN_ONCE(1, "fscrypt: filesystem tried to load encryption info for inode %lu, which is not encryptable (file type %d)\n",
65 inode->i_ino, (inode->i_mode & S_IFMT));
66 return ERR_PTR(-EINVAL);
69 /* Create a symmetric cipher object for the given encryption mode and key */
70 static struct crypto_skcipher *
71 fscrypt_allocate_skcipher(struct fscrypt_mode *mode, const u8 *raw_key,
72 const struct inode *inode)
74 struct crypto_skcipher *tfm;
77 tfm = crypto_alloc_skcipher(mode->cipher_str, 0, 0);
79 if (PTR_ERR(tfm) == -ENOENT) {
81 "Missing crypto API support for %s (API name: \"%s\")",
82 mode->friendly_name, mode->cipher_str);
83 return ERR_PTR(-ENOPKG);
85 fscrypt_err(inode, "Error allocating '%s' transform: %ld",
86 mode->cipher_str, PTR_ERR(tfm));
89 if (!xchg(&mode->logged_impl_name, 1)) {
91 * fscrypt performance can vary greatly depending on which
92 * crypto algorithm implementation is used. Help people debug
93 * performance problems by logging the ->cra_driver_name the
94 * first time a mode is used.
96 pr_info("fscrypt: %s using implementation \"%s\"\n",
97 mode->friendly_name, crypto_skcipher_driver_name(tfm));
99 if (WARN_ON(crypto_skcipher_ivsize(tfm) != mode->ivsize)) {
103 crypto_skcipher_set_flags(tfm, CRYPTO_TFM_REQ_FORBID_WEAK_KEYS);
104 err = crypto_skcipher_setkey(tfm, raw_key, mode->keysize);
111 crypto_free_skcipher(tfm);
116 * Prepare the crypto transform object or blk-crypto key in @prep_key, given the
117 * raw key, encryption mode, and flag indicating which encryption implementation
118 * (fs-layer or blk-crypto) will be used.
120 int fscrypt_prepare_key(struct fscrypt_prepared_key *prep_key,
121 const u8 *raw_key, const struct fscrypt_info *ci)
123 struct crypto_skcipher *tfm;
125 if (fscrypt_using_inline_encryption(ci))
126 return fscrypt_prepare_inline_crypt_key(prep_key, raw_key, ci);
128 tfm = fscrypt_allocate_skcipher(ci->ci_mode, raw_key, ci->ci_inode);
132 * Pairs with the smp_load_acquire() in fscrypt_is_key_prepared().
133 * I.e., here we publish ->tfm with a RELEASE barrier so that
134 * concurrent tasks can ACQUIRE it. Note that this concurrency is only
135 * possible for per-mode keys, not for per-file keys.
137 smp_store_release(&prep_key->tfm, tfm);
141 /* Destroy a crypto transform object and/or blk-crypto key. */
142 void fscrypt_destroy_prepared_key(struct fscrypt_prepared_key *prep_key)
144 crypto_free_skcipher(prep_key->tfm);
145 fscrypt_destroy_inline_crypt_key(prep_key);
148 /* Given a per-file encryption key, set up the file's crypto transform object */
149 int fscrypt_set_per_file_enc_key(struct fscrypt_info *ci, const u8 *raw_key)
151 ci->ci_owns_key = true;
152 return fscrypt_prepare_key(&ci->ci_enc_key, raw_key, ci);
155 static int setup_per_mode_enc_key(struct fscrypt_info *ci,
156 struct fscrypt_master_key *mk,
157 struct fscrypt_prepared_key *keys,
158 u8 hkdf_context, bool include_fs_uuid)
160 const struct inode *inode = ci->ci_inode;
161 const struct super_block *sb = inode->i_sb;
162 struct fscrypt_mode *mode = ci->ci_mode;
163 const u8 mode_num = mode - fscrypt_modes;
164 struct fscrypt_prepared_key *prep_key;
165 u8 mode_key[FSCRYPT_MAX_KEY_SIZE];
166 u8 hkdf_info[sizeof(mode_num) + sizeof(sb->s_uuid)];
167 unsigned int hkdf_infolen = 0;
170 if (WARN_ON(mode_num > __FSCRYPT_MODE_MAX))
173 prep_key = &keys[mode_num];
174 if (fscrypt_is_key_prepared(prep_key, ci)) {
175 ci->ci_enc_key = *prep_key;
179 mutex_lock(&fscrypt_mode_key_setup_mutex);
181 if (fscrypt_is_key_prepared(prep_key, ci))
184 BUILD_BUG_ON(sizeof(mode_num) != 1);
185 BUILD_BUG_ON(sizeof(sb->s_uuid) != 16);
186 BUILD_BUG_ON(sizeof(hkdf_info) != 17);
187 hkdf_info[hkdf_infolen++] = mode_num;
188 if (include_fs_uuid) {
189 memcpy(&hkdf_info[hkdf_infolen], &sb->s_uuid,
191 hkdf_infolen += sizeof(sb->s_uuid);
193 err = fscrypt_hkdf_expand(&mk->mk_secret.hkdf,
194 hkdf_context, hkdf_info, hkdf_infolen,
195 mode_key, mode->keysize);
198 err = fscrypt_prepare_key(prep_key, mode_key, ci);
199 memzero_explicit(mode_key, mode->keysize);
203 ci->ci_enc_key = *prep_key;
206 mutex_unlock(&fscrypt_mode_key_setup_mutex);
210 int fscrypt_derive_dirhash_key(struct fscrypt_info *ci,
211 const struct fscrypt_master_key *mk)
215 err = fscrypt_hkdf_expand(&mk->mk_secret.hkdf, HKDF_CONTEXT_DIRHASH_KEY,
216 ci->ci_nonce, FSCRYPT_FILE_NONCE_SIZE,
217 (u8 *)&ci->ci_dirhash_key,
218 sizeof(ci->ci_dirhash_key));
221 ci->ci_dirhash_key_initialized = true;
225 static int fscrypt_setup_iv_ino_lblk_32_key(struct fscrypt_info *ci,
226 struct fscrypt_master_key *mk)
230 err = setup_per_mode_enc_key(ci, mk, mk->mk_iv_ino_lblk_32_keys,
231 HKDF_CONTEXT_IV_INO_LBLK_32_KEY, true);
235 /* pairs with smp_store_release() below */
236 if (!smp_load_acquire(&mk->mk_ino_hash_key_initialized)) {
238 mutex_lock(&fscrypt_mode_key_setup_mutex);
240 if (mk->mk_ino_hash_key_initialized)
243 err = fscrypt_hkdf_expand(&mk->mk_secret.hkdf,
244 HKDF_CONTEXT_INODE_HASH_KEY, NULL, 0,
245 (u8 *)&mk->mk_ino_hash_key,
246 sizeof(mk->mk_ino_hash_key));
249 /* pairs with smp_load_acquire() above */
250 smp_store_release(&mk->mk_ino_hash_key_initialized, true);
252 mutex_unlock(&fscrypt_mode_key_setup_mutex);
257 ci->ci_hashed_ino = (u32)siphash_1u64(ci->ci_inode->i_ino,
258 &mk->mk_ino_hash_key);
262 static int fscrypt_setup_v2_file_key(struct fscrypt_info *ci,
263 struct fscrypt_master_key *mk)
267 if (ci->ci_policy.v2.flags & FSCRYPT_POLICY_FLAG_DIRECT_KEY) {
269 * DIRECT_KEY: instead of deriving per-file encryption keys, the
270 * per-file nonce will be included in all the IVs. But unlike
271 * v1 policies, for v2 policies in this case we don't encrypt
272 * with the master key directly but rather derive a per-mode
273 * encryption key. This ensures that the master key is
274 * consistently used only for HKDF, avoiding key reuse issues.
276 err = setup_per_mode_enc_key(ci, mk, mk->mk_direct_keys,
277 HKDF_CONTEXT_DIRECT_KEY, false);
278 } else if (ci->ci_policy.v2.flags &
279 FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64) {
281 * IV_INO_LBLK_64: encryption keys are derived from (master_key,
282 * mode_num, filesystem_uuid), and inode number is included in
283 * the IVs. This format is optimized for use with inline
284 * encryption hardware compliant with the UFS standard.
286 err = setup_per_mode_enc_key(ci, mk, mk->mk_iv_ino_lblk_64_keys,
287 HKDF_CONTEXT_IV_INO_LBLK_64_KEY,
289 } else if (ci->ci_policy.v2.flags &
290 FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32) {
291 err = fscrypt_setup_iv_ino_lblk_32_key(ci, mk);
293 u8 derived_key[FSCRYPT_MAX_KEY_SIZE];
295 err = fscrypt_hkdf_expand(&mk->mk_secret.hkdf,
296 HKDF_CONTEXT_PER_FILE_ENC_KEY,
297 ci->ci_nonce, FSCRYPT_FILE_NONCE_SIZE,
298 derived_key, ci->ci_mode->keysize);
302 err = fscrypt_set_per_file_enc_key(ci, derived_key);
303 memzero_explicit(derived_key, ci->ci_mode->keysize);
308 /* Derive a secret dirhash key for directories that need it. */
309 if (S_ISDIR(ci->ci_inode->i_mode) && IS_CASEFOLDED(ci->ci_inode)) {
310 err = fscrypt_derive_dirhash_key(ci, mk);
319 * Find the master key, then set up the inode's actual encryption key.
321 * If the master key is found in the filesystem-level keyring, then the
322 * corresponding 'struct key' is returned in *master_key_ret with
323 * ->mk_secret_sem read-locked. This is needed to ensure that only one task
324 * links the fscrypt_info into ->mk_decrypted_inodes (as multiple tasks may race
325 * to create an fscrypt_info for the same inode), and to synchronize the master
326 * key being removed with a new inode starting to use it.
328 static int setup_file_encryption_key(struct fscrypt_info *ci,
329 struct key **master_key_ret)
332 struct fscrypt_master_key *mk = NULL;
333 struct fscrypt_key_specifier mk_spec;
336 err = fscrypt_select_encryption_impl(ci);
340 switch (ci->ci_policy.version) {
341 case FSCRYPT_POLICY_V1:
342 mk_spec.type = FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR;
343 memcpy(mk_spec.u.descriptor,
344 ci->ci_policy.v1.master_key_descriptor,
345 FSCRYPT_KEY_DESCRIPTOR_SIZE);
347 case FSCRYPT_POLICY_V2:
348 mk_spec.type = FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
349 memcpy(mk_spec.u.identifier,
350 ci->ci_policy.v2.master_key_identifier,
351 FSCRYPT_KEY_IDENTIFIER_SIZE);
358 key = fscrypt_find_master_key(ci->ci_inode->i_sb, &mk_spec);
360 if (key != ERR_PTR(-ENOKEY) ||
361 ci->ci_policy.version != FSCRYPT_POLICY_V1)
365 * As a legacy fallback for v1 policies, search for the key in
366 * the current task's subscribed keyrings too. Don't move this
367 * to before the search of ->s_master_keys, since users
368 * shouldn't be able to override filesystem-level keys.
370 return fscrypt_setup_v1_file_key_via_subscribed_keyrings(ci);
373 mk = key->payload.data[0];
374 down_read(&mk->mk_secret_sem);
376 /* Has the secret been removed (via FS_IOC_REMOVE_ENCRYPTION_KEY)? */
377 if (!is_master_key_secret_present(&mk->mk_secret)) {
379 goto out_release_key;
383 * Require that the master key be at least as long as the derived key.
384 * Otherwise, the derived key cannot possibly contain as much entropy as
385 * that required by the encryption mode it will be used for. For v1
386 * policies it's also required for the KDF to work at all.
388 if (mk->mk_secret.size < ci->ci_mode->keysize) {
390 "key with %s %*phN is too short (got %u bytes, need %u+ bytes)",
391 master_key_spec_type(&mk_spec),
392 master_key_spec_len(&mk_spec), (u8 *)&mk_spec.u,
393 mk->mk_secret.size, ci->ci_mode->keysize);
395 goto out_release_key;
398 switch (ci->ci_policy.version) {
399 case FSCRYPT_POLICY_V1:
400 err = fscrypt_setup_v1_file_key(ci, mk->mk_secret.raw);
402 case FSCRYPT_POLICY_V2:
403 err = fscrypt_setup_v2_file_key(ci, mk);
411 goto out_release_key;
413 *master_key_ret = key;
417 up_read(&mk->mk_secret_sem);
422 static void put_crypt_info(struct fscrypt_info *ci)
429 if (ci->ci_direct_key)
430 fscrypt_put_direct_key(ci->ci_direct_key);
431 else if (ci->ci_owns_key)
432 fscrypt_destroy_prepared_key(&ci->ci_enc_key);
434 key = ci->ci_master_key;
436 struct fscrypt_master_key *mk = key->payload.data[0];
439 * Remove this inode from the list of inodes that were unlocked
440 * with the master key.
442 * In addition, if we're removing the last inode from a key that
443 * already had its secret removed, invalidate the key so that it
444 * gets removed from ->s_master_keys.
446 spin_lock(&mk->mk_decrypted_inodes_lock);
447 list_del(&ci->ci_master_key_link);
448 spin_unlock(&mk->mk_decrypted_inodes_lock);
449 if (refcount_dec_and_test(&mk->mk_refcount))
453 memzero_explicit(ci, sizeof(*ci));
454 kmem_cache_free(fscrypt_info_cachep, ci);
457 int fscrypt_get_encryption_info(struct inode *inode)
459 struct fscrypt_info *crypt_info;
460 union fscrypt_context ctx;
461 struct fscrypt_mode *mode;
462 struct key *master_key = NULL;
465 if (fscrypt_has_encryption_key(inode))
468 res = fscrypt_initialize(inode->i_sb->s_cop->flags);
472 res = inode->i_sb->s_cop->get_context(inode, &ctx, sizeof(ctx));
474 const union fscrypt_context *dummy_ctx =
475 fscrypt_get_dummy_context(inode->i_sb);
477 if (IS_ENCRYPTED(inode) || !dummy_ctx) {
479 "Error %d getting encryption context",
483 /* Fake up a context for an unencrypted directory */
484 res = fscrypt_context_size(dummy_ctx);
485 memcpy(&ctx, dummy_ctx, res);
488 crypt_info = kmem_cache_zalloc(fscrypt_info_cachep, GFP_NOFS);
492 crypt_info->ci_inode = inode;
494 res = fscrypt_policy_from_context(&crypt_info->ci_policy, &ctx, res);
497 "Unrecognized or corrupt encryption context");
501 memcpy(crypt_info->ci_nonce, fscrypt_context_nonce(&ctx),
502 FSCRYPT_FILE_NONCE_SIZE);
504 if (!fscrypt_supported_policy(&crypt_info->ci_policy, inode)) {
509 mode = select_encryption_mode(&crypt_info->ci_policy, inode);
514 WARN_ON(mode->ivsize > FSCRYPT_MAX_IV_SIZE);
515 crypt_info->ci_mode = mode;
517 res = setup_file_encryption_key(crypt_info, &master_key);
522 * Multiple tasks may race to set ->i_crypt_info, so use
523 * cmpxchg_release(). This pairs with the smp_load_acquire() in
524 * fscrypt_get_info(). I.e., here we publish ->i_crypt_info with a
525 * RELEASE barrier so that other tasks can ACQUIRE it.
527 if (cmpxchg_release(&inode->i_crypt_info, NULL, crypt_info) == NULL) {
529 * We won the race and set ->i_crypt_info to our crypt_info.
530 * Now link it into the master key's inode list.
533 struct fscrypt_master_key *mk =
534 master_key->payload.data[0];
536 refcount_inc(&mk->mk_refcount);
537 crypt_info->ci_master_key = key_get(master_key);
538 spin_lock(&mk->mk_decrypted_inodes_lock);
539 list_add(&crypt_info->ci_master_key_link,
540 &mk->mk_decrypted_inodes);
541 spin_unlock(&mk->mk_decrypted_inodes_lock);
548 struct fscrypt_master_key *mk = master_key->payload.data[0];
550 up_read(&mk->mk_secret_sem);
555 put_crypt_info(crypt_info);
558 EXPORT_SYMBOL(fscrypt_get_encryption_info);
561 * fscrypt_put_encryption_info() - free most of an inode's fscrypt data
562 * @inode: an inode being evicted
564 * Free the inode's fscrypt_info. Filesystems must call this when the inode is
565 * being evicted. An RCU grace period need not have elapsed yet.
567 void fscrypt_put_encryption_info(struct inode *inode)
569 put_crypt_info(inode->i_crypt_info);
570 inode->i_crypt_info = NULL;
572 EXPORT_SYMBOL(fscrypt_put_encryption_info);
575 * fscrypt_free_inode() - free an inode's fscrypt data requiring RCU delay
576 * @inode: an inode being freed
578 * Free the inode's cached decrypted symlink target, if any. Filesystems must
579 * call this after an RCU grace period, just before they free the inode.
581 void fscrypt_free_inode(struct inode *inode)
583 if (IS_ENCRYPTED(inode) && S_ISLNK(inode->i_mode)) {
584 kfree(inode->i_link);
585 inode->i_link = NULL;
588 EXPORT_SYMBOL(fscrypt_free_inode);
591 * fscrypt_drop_inode() - check whether the inode's master key has been removed
592 * @inode: an inode being considered for eviction
594 * Filesystems supporting fscrypt must call this from their ->drop_inode()
595 * method so that encrypted inodes are evicted as soon as they're no longer in
596 * use and their master key has been removed.
598 * Return: 1 if fscrypt wants the inode to be evicted now, otherwise 0
600 int fscrypt_drop_inode(struct inode *inode)
602 const struct fscrypt_info *ci = fscrypt_get_info(inode);
603 const struct fscrypt_master_key *mk;
606 * If ci is NULL, then the inode doesn't have an encryption key set up
607 * so it's irrelevant. If ci_master_key is NULL, then the master key
608 * was provided via the legacy mechanism of the process-subscribed
609 * keyrings, so we don't know whether it's been removed or not.
611 if (!ci || !ci->ci_master_key)
613 mk = ci->ci_master_key->payload.data[0];
616 * With proper, non-racy use of FS_IOC_REMOVE_ENCRYPTION_KEY, all inodes
617 * protected by the key were cleaned by sync_filesystem(). But if
618 * userspace is still using the files, inodes can be dirtied between
619 * then and now. We mustn't lose any writes, so skip dirty inodes here.
621 if (inode->i_state & I_DIRTY_ALL)
625 * Note: since we aren't holding ->mk_secret_sem, the result here can
626 * immediately become outdated. But there's no correctness problem with
627 * unnecessarily evicting. Nor is there a correctness problem with not
628 * evicting while iput() is racing with the key being removed, since
629 * then the thread removing the key will either evict the inode itself
630 * or will correctly detect that it wasn't evicted due to the race.
632 return !is_master_key_secret_present(&mk->mk_secret);
634 EXPORT_SYMBOL_GPL(fscrypt_drop_inode);