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 static struct fscrypt_mode available_modes[] = {
17 [FSCRYPT_MODE_AES_256_XTS] = {
18 .friendly_name = "AES-256-XTS",
19 .cipher_str = "xts(aes)",
23 [FSCRYPT_MODE_AES_256_CTS] = {
24 .friendly_name = "AES-256-CTS-CBC",
25 .cipher_str = "cts(cbc(aes))",
29 [FSCRYPT_MODE_AES_128_CBC] = {
30 .friendly_name = "AES-128-CBC-ESSIV",
31 .cipher_str = "essiv(cbc(aes),sha256)",
35 [FSCRYPT_MODE_AES_128_CTS] = {
36 .friendly_name = "AES-128-CTS-CBC",
37 .cipher_str = "cts(cbc(aes))",
41 [FSCRYPT_MODE_ADIANTUM] = {
42 .friendly_name = "Adiantum",
43 .cipher_str = "adiantum(xchacha12,aes)",
49 static struct fscrypt_mode *
50 select_encryption_mode(const union fscrypt_policy *policy,
51 const struct inode *inode)
53 if (S_ISREG(inode->i_mode))
54 return &available_modes[fscrypt_policy_contents_mode(policy)];
56 if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
57 return &available_modes[fscrypt_policy_fnames_mode(policy)];
59 WARN_ONCE(1, "fscrypt: filesystem tried to load encryption info for inode %lu, which is not encryptable (file type %d)\n",
60 inode->i_ino, (inode->i_mode & S_IFMT));
61 return ERR_PTR(-EINVAL);
64 /* Create a symmetric cipher object for the given encryption mode and key */
65 struct crypto_skcipher *fscrypt_allocate_skcipher(struct fscrypt_mode *mode,
67 const struct inode *inode)
69 struct crypto_skcipher *tfm;
72 tfm = crypto_alloc_skcipher(mode->cipher_str, 0, 0);
74 if (PTR_ERR(tfm) == -ENOENT) {
76 "Missing crypto API support for %s (API name: \"%s\")",
77 mode->friendly_name, mode->cipher_str);
78 return ERR_PTR(-ENOPKG);
80 fscrypt_err(inode, "Error allocating '%s' transform: %ld",
81 mode->cipher_str, PTR_ERR(tfm));
84 if (!xchg(&mode->logged_impl_name, 1)) {
86 * fscrypt performance can vary greatly depending on which
87 * crypto algorithm implementation is used. Help people debug
88 * performance problems by logging the ->cra_driver_name the
89 * first time a mode is used.
91 pr_info("fscrypt: %s using implementation \"%s\"\n",
92 mode->friendly_name, crypto_skcipher_driver_name(tfm));
94 crypto_skcipher_set_flags(tfm, CRYPTO_TFM_REQ_FORBID_WEAK_KEYS);
95 err = crypto_skcipher_setkey(tfm, raw_key, mode->keysize);
102 crypto_free_skcipher(tfm);
106 /* Given the per-file key, set up the file's crypto transform object */
107 int fscrypt_set_derived_key(struct fscrypt_info *ci, const u8 *derived_key)
109 struct crypto_skcipher *tfm;
111 tfm = fscrypt_allocate_skcipher(ci->ci_mode, derived_key, ci->ci_inode);
116 ci->ci_owns_key = true;
120 static int setup_per_mode_key(struct fscrypt_info *ci,
121 struct fscrypt_master_key *mk,
122 struct crypto_skcipher **tfms,
123 u8 hkdf_context, bool include_fs_uuid)
125 const struct inode *inode = ci->ci_inode;
126 const struct super_block *sb = inode->i_sb;
127 struct fscrypt_mode *mode = ci->ci_mode;
128 u8 mode_num = mode - available_modes;
129 struct crypto_skcipher *tfm, *prev_tfm;
130 u8 mode_key[FSCRYPT_MAX_KEY_SIZE];
131 u8 hkdf_info[sizeof(mode_num) + sizeof(sb->s_uuid)];
132 unsigned int hkdf_infolen = 0;
135 if (WARN_ON(mode_num > __FSCRYPT_MODE_MAX))
138 /* pairs with cmpxchg() below */
139 tfm = READ_ONCE(tfms[mode_num]);
140 if (likely(tfm != NULL))
143 BUILD_BUG_ON(sizeof(mode_num) != 1);
144 BUILD_BUG_ON(sizeof(sb->s_uuid) != 16);
145 BUILD_BUG_ON(sizeof(hkdf_info) != 17);
146 hkdf_info[hkdf_infolen++] = mode_num;
147 if (include_fs_uuid) {
148 memcpy(&hkdf_info[hkdf_infolen], &sb->s_uuid,
150 hkdf_infolen += sizeof(sb->s_uuid);
152 err = fscrypt_hkdf_expand(&mk->mk_secret.hkdf,
153 hkdf_context, hkdf_info, hkdf_infolen,
154 mode_key, mode->keysize);
157 tfm = fscrypt_allocate_skcipher(mode, mode_key, inode);
158 memzero_explicit(mode_key, mode->keysize);
162 /* pairs with READ_ONCE() above */
163 prev_tfm = cmpxchg(&tfms[mode_num], NULL, tfm);
164 if (prev_tfm != NULL) {
165 crypto_free_skcipher(tfm);
173 static int fscrypt_setup_v2_file_key(struct fscrypt_info *ci,
174 struct fscrypt_master_key *mk)
176 u8 derived_key[FSCRYPT_MAX_KEY_SIZE];
179 if (ci->ci_policy.v2.flags & FSCRYPT_POLICY_FLAG_DIRECT_KEY) {
181 * DIRECT_KEY: instead of deriving per-file keys, the per-file
182 * nonce will be included in all the IVs. But unlike v1
183 * policies, for v2 policies in this case we don't encrypt with
184 * the master key directly but rather derive a per-mode key.
185 * This ensures that the master key is consistently used only
186 * for HKDF, avoiding key reuse issues.
188 if (!fscrypt_mode_supports_direct_key(ci->ci_mode)) {
189 fscrypt_warn(ci->ci_inode,
190 "Direct key flag not allowed with %s",
191 ci->ci_mode->friendly_name);
194 return setup_per_mode_key(ci, mk, mk->mk_direct_tfms,
195 HKDF_CONTEXT_DIRECT_KEY, false);
196 } else if (ci->ci_policy.v2.flags &
197 FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64) {
199 * IV_INO_LBLK_64: encryption keys are derived from (master_key,
200 * mode_num, filesystem_uuid), and inode number is included in
201 * the IVs. This format is optimized for use with inline
202 * encryption hardware compliant with the UFS or eMMC standards.
204 return setup_per_mode_key(ci, mk, mk->mk_iv_ino_lblk_64_tfms,
205 HKDF_CONTEXT_IV_INO_LBLK_64_KEY,
209 err = fscrypt_hkdf_expand(&mk->mk_secret.hkdf,
210 HKDF_CONTEXT_PER_FILE_KEY,
211 ci->ci_nonce, FS_KEY_DERIVATION_NONCE_SIZE,
212 derived_key, ci->ci_mode->keysize);
216 err = fscrypt_set_derived_key(ci, derived_key);
217 memzero_explicit(derived_key, ci->ci_mode->keysize);
222 * Find the master key, then set up the inode's actual encryption key.
224 * If the master key is found in the filesystem-level keyring, then the
225 * corresponding 'struct key' is returned in *master_key_ret with
226 * ->mk_secret_sem read-locked. This is needed to ensure that only one task
227 * links the fscrypt_info into ->mk_decrypted_inodes (as multiple tasks may race
228 * to create an fscrypt_info for the same inode), and to synchronize the master
229 * key being removed with a new inode starting to use it.
231 static int setup_file_encryption_key(struct fscrypt_info *ci,
232 struct key **master_key_ret)
235 struct fscrypt_master_key *mk = NULL;
236 struct fscrypt_key_specifier mk_spec;
239 switch (ci->ci_policy.version) {
240 case FSCRYPT_POLICY_V1:
241 mk_spec.type = FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR;
242 memcpy(mk_spec.u.descriptor,
243 ci->ci_policy.v1.master_key_descriptor,
244 FSCRYPT_KEY_DESCRIPTOR_SIZE);
246 case FSCRYPT_POLICY_V2:
247 mk_spec.type = FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
248 memcpy(mk_spec.u.identifier,
249 ci->ci_policy.v2.master_key_identifier,
250 FSCRYPT_KEY_IDENTIFIER_SIZE);
257 key = fscrypt_find_master_key(ci->ci_inode->i_sb, &mk_spec);
259 if (key != ERR_PTR(-ENOKEY) ||
260 ci->ci_policy.version != FSCRYPT_POLICY_V1)
264 * As a legacy fallback for v1 policies, search for the key in
265 * the current task's subscribed keyrings too. Don't move this
266 * to before the search of ->s_master_keys, since users
267 * shouldn't be able to override filesystem-level keys.
269 return fscrypt_setup_v1_file_key_via_subscribed_keyrings(ci);
272 mk = key->payload.data[0];
273 down_read(&mk->mk_secret_sem);
275 /* Has the secret been removed (via FS_IOC_REMOVE_ENCRYPTION_KEY)? */
276 if (!is_master_key_secret_present(&mk->mk_secret)) {
278 goto out_release_key;
282 * Require that the master key be at least as long as the derived key.
283 * Otherwise, the derived key cannot possibly contain as much entropy as
284 * that required by the encryption mode it will be used for. For v1
285 * policies it's also required for the KDF to work at all.
287 if (mk->mk_secret.size < ci->ci_mode->keysize) {
289 "key with %s %*phN is too short (got %u bytes, need %u+ bytes)",
290 master_key_spec_type(&mk_spec),
291 master_key_spec_len(&mk_spec), (u8 *)&mk_spec.u,
292 mk->mk_secret.size, ci->ci_mode->keysize);
294 goto out_release_key;
297 switch (ci->ci_policy.version) {
298 case FSCRYPT_POLICY_V1:
299 err = fscrypt_setup_v1_file_key(ci, mk->mk_secret.raw);
301 case FSCRYPT_POLICY_V2:
302 err = fscrypt_setup_v2_file_key(ci, mk);
310 goto out_release_key;
312 *master_key_ret = key;
316 up_read(&mk->mk_secret_sem);
321 static void put_crypt_info(struct fscrypt_info *ci)
328 if (ci->ci_direct_key)
329 fscrypt_put_direct_key(ci->ci_direct_key);
330 else if (ci->ci_owns_key)
331 crypto_free_skcipher(ci->ci_ctfm);
333 key = ci->ci_master_key;
335 struct fscrypt_master_key *mk = key->payload.data[0];
338 * Remove this inode from the list of inodes that were unlocked
339 * with the master key.
341 * In addition, if we're removing the last inode from a key that
342 * already had its secret removed, invalidate the key so that it
343 * gets removed from ->s_master_keys.
345 spin_lock(&mk->mk_decrypted_inodes_lock);
346 list_del(&ci->ci_master_key_link);
347 spin_unlock(&mk->mk_decrypted_inodes_lock);
348 if (refcount_dec_and_test(&mk->mk_refcount))
352 memzero_explicit(ci, sizeof(*ci));
353 kmem_cache_free(fscrypt_info_cachep, ci);
356 int fscrypt_get_encryption_info(struct inode *inode)
358 struct fscrypt_info *crypt_info;
359 union fscrypt_context ctx;
360 struct fscrypt_mode *mode;
361 struct key *master_key = NULL;
364 if (fscrypt_has_encryption_key(inode))
367 res = fscrypt_initialize(inode->i_sb->s_cop->flags);
371 res = inode->i_sb->s_cop->get_context(inode, &ctx, sizeof(ctx));
373 if (!fscrypt_dummy_context_enabled(inode) ||
374 IS_ENCRYPTED(inode)) {
376 "Error %d getting encryption context",
380 /* Fake up a context for an unencrypted directory */
381 memset(&ctx, 0, sizeof(ctx));
382 ctx.version = FSCRYPT_CONTEXT_V1;
383 ctx.v1.contents_encryption_mode = FSCRYPT_MODE_AES_256_XTS;
384 ctx.v1.filenames_encryption_mode = FSCRYPT_MODE_AES_256_CTS;
385 memset(ctx.v1.master_key_descriptor, 0x42,
386 FSCRYPT_KEY_DESCRIPTOR_SIZE);
387 res = sizeof(ctx.v1);
390 crypt_info = kmem_cache_zalloc(fscrypt_info_cachep, GFP_NOFS);
394 crypt_info->ci_inode = inode;
396 res = fscrypt_policy_from_context(&crypt_info->ci_policy, &ctx, res);
399 "Unrecognized or corrupt encryption context");
403 switch (ctx.version) {
404 case FSCRYPT_CONTEXT_V1:
405 memcpy(crypt_info->ci_nonce, ctx.v1.nonce,
406 FS_KEY_DERIVATION_NONCE_SIZE);
408 case FSCRYPT_CONTEXT_V2:
409 memcpy(crypt_info->ci_nonce, ctx.v2.nonce,
410 FS_KEY_DERIVATION_NONCE_SIZE);
418 if (!fscrypt_supported_policy(&crypt_info->ci_policy, inode)) {
423 mode = select_encryption_mode(&crypt_info->ci_policy, inode);
428 WARN_ON(mode->ivsize > FSCRYPT_MAX_IV_SIZE);
429 crypt_info->ci_mode = mode;
431 res = setup_file_encryption_key(crypt_info, &master_key);
435 if (cmpxchg_release(&inode->i_crypt_info, NULL, crypt_info) == NULL) {
437 struct fscrypt_master_key *mk =
438 master_key->payload.data[0];
440 refcount_inc(&mk->mk_refcount);
441 crypt_info->ci_master_key = key_get(master_key);
442 spin_lock(&mk->mk_decrypted_inodes_lock);
443 list_add(&crypt_info->ci_master_key_link,
444 &mk->mk_decrypted_inodes);
445 spin_unlock(&mk->mk_decrypted_inodes_lock);
452 struct fscrypt_master_key *mk = master_key->payload.data[0];
454 up_read(&mk->mk_secret_sem);
459 put_crypt_info(crypt_info);
462 EXPORT_SYMBOL(fscrypt_get_encryption_info);
465 * fscrypt_put_encryption_info - free most of an inode's fscrypt data
467 * Free the inode's fscrypt_info. Filesystems must call this when the inode is
468 * being evicted. An RCU grace period need not have elapsed yet.
470 void fscrypt_put_encryption_info(struct inode *inode)
472 put_crypt_info(inode->i_crypt_info);
473 inode->i_crypt_info = NULL;
475 EXPORT_SYMBOL(fscrypt_put_encryption_info);
478 * fscrypt_free_inode - free an inode's fscrypt data requiring RCU delay
480 * Free the inode's cached decrypted symlink target, if any. Filesystems must
481 * call this after an RCU grace period, just before they free the inode.
483 void fscrypt_free_inode(struct inode *inode)
485 if (IS_ENCRYPTED(inode) && S_ISLNK(inode->i_mode)) {
486 kfree(inode->i_link);
487 inode->i_link = NULL;
490 EXPORT_SYMBOL(fscrypt_free_inode);
493 * fscrypt_drop_inode - check whether the inode's master key has been removed
495 * Filesystems supporting fscrypt must call this from their ->drop_inode()
496 * method so that encrypted inodes are evicted as soon as they're no longer in
497 * use and their master key has been removed.
499 * Return: 1 if fscrypt wants the inode to be evicted now, otherwise 0
501 int fscrypt_drop_inode(struct inode *inode)
503 const struct fscrypt_info *ci = READ_ONCE(inode->i_crypt_info);
504 const struct fscrypt_master_key *mk;
507 * If ci is NULL, then the inode doesn't have an encryption key set up
508 * so it's irrelevant. If ci_master_key is NULL, then the master key
509 * was provided via the legacy mechanism of the process-subscribed
510 * keyrings, so we don't know whether it's been removed or not.
512 if (!ci || !ci->ci_master_key)
514 mk = ci->ci_master_key->payload.data[0];
517 * Note: since we aren't holding ->mk_secret_sem, the result here can
518 * immediately become outdated. But there's no correctness problem with
519 * unnecessarily evicting. Nor is there a correctness problem with not
520 * evicting while iput() is racing with the key being removed, since
521 * then the thread removing the key will either evict the inode itself
522 * or will correctly detect that it wasn't evicted due to the race.
524 return !is_master_key_secret_present(&mk->mk_secret);
526 EXPORT_SYMBOL_GPL(fscrypt_drop_inode);