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 * Linux commit 219d54332a09
15 #include <crypto/aes.h>
16 #ifdef HAVE_CRYPTO_SHA2_HEADER
17 #include <crypto/sha2.h>
19 #include <crypto/sha.h>
21 #include <crypto/skcipher.h>
22 #include <linux/key.h>
24 #include "llcrypt_private.h"
27 #include <crypto/internal/cipher.h>
29 MODULE_IMPORT_NS(CRYPTO_INTERNAL);
32 static struct crypto_shash *essiv_hash_tfm;
34 static struct llcrypt_mode available_modes[] = {
35 [LLCRYPT_MODE_NULL] = {
36 .friendly_name = "NULL",
41 [LLCRYPT_MODE_AES_256_XTS] = {
42 .friendly_name = "AES-256-XTS",
43 .cipher_str = "xts(aes)",
44 .engine_aesni_str = "xts-aes-aesni",
48 [LLCRYPT_MODE_AES_256_CTS] = {
49 .friendly_name = "AES-256-CTS-CBC",
50 .cipher_str = "cts(cbc(aes))",
51 .engine_aesni_str = "cts-cbc-aes-aesni",
55 [LLCRYPT_MODE_AES_128_CBC] = {
56 .friendly_name = "AES-128-CBC",
57 .cipher_str = "cbc(aes)",
58 .engine_aesni_str = "cbc-aes-aesni",
63 [LLCRYPT_MODE_AES_128_CTS] = {
64 .friendly_name = "AES-128-CTS-CBC",
65 .cipher_str = "cts(cbc(aes))",
66 .engine_aesni_str = "cts-cbc-aes-aesni",
70 [LLCRYPT_MODE_ADIANTUM] = {
71 .friendly_name = "Adiantum",
72 .cipher_str = "adiantum(xchacha12,aes)",
78 static struct llcrypt_mode *
79 select_encryption_mode(const union llcrypt_policy *policy,
80 const struct inode *inode)
82 if (S_ISREG(inode->i_mode))
83 return &available_modes[llcrypt_policy_contents_mode(policy)];
85 if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
86 return &available_modes[llcrypt_policy_fnames_mode(policy)];
88 WARN_ONCE(1, "llcrypt: filesystem tried to load encryption info for inode %lu, which is not encryptable (file type %d)\n",
89 inode->i_ino, (inode->i_mode & S_IFMT));
90 return ERR_PTR(-EINVAL);
93 static inline char *crypto_engine_to_use(struct llcrypt_mode *mode)
95 switch (llcrypt_crypto_engine) {
96 case LLCRYPT_ENGINE_SYSTEM_DEFAULT:
97 return (char *)mode->cipher_str;
98 case LLCRYPT_ENGINE_AES_NI:
99 return (char *)mode->engine_aesni_str;
105 /* Create a symmetric cipher object for the given encryption mode and key */
106 struct crypto_skcipher *llcrypt_allocate_skcipher(struct llcrypt_mode *mode,
108 const struct inode *inode)
110 struct crypto_skcipher *tfm;
114 if (!strcmp(mode->cipher_str, "null"))
117 cipher = crypto_engine_to_use(mode);
119 return ERR_PTR(-EINVAL);
122 tfm = crypto_alloc_skcipher(cipher, 0, 0);
124 if (PTR_ERR(tfm) == -ENOENT) {
125 if (cipher != mode->cipher_str) {
126 cipher = (char *)mode->cipher_str;
130 "Missing crypto API support for %s (API name: \"%s\")",
131 mode->friendly_name, mode->cipher_str);
132 return ERR_PTR(-ENOPKG);
134 llcrypt_err(inode, "Error allocating '%s' transform: %ld",
135 mode->cipher_str, PTR_ERR(tfm));
138 if (unlikely(!mode->logged_impl_name)) {
140 * llcrypt performance can vary greatly depending on which
141 * crypto algorithm implementation is used. Help people debug
142 * performance problems by logging the ->cra_driver_name the
143 * first time a mode is used. Note that multiple threads can
144 * race here, but it doesn't really matter.
146 mode->logged_impl_name = true;
147 pr_info("llcrypt: %s using implementation \"%s\"\n",
149 crypto_skcipher_alg(tfm)->base.cra_driver_name);
151 crypto_skcipher_set_flags(tfm, CRYPTO_TFM_REQ_FORBID_WEAK_KEYS);
152 err = crypto_skcipher_setkey(tfm, raw_key, mode->keysize);
159 crypto_free_skcipher(tfm);
163 static int derive_essiv_salt(const u8 *key, int keysize, u8 *salt)
165 struct crypto_shash *tfm = READ_ONCE(essiv_hash_tfm);
167 /* init hash transform on demand */
168 if (unlikely(!tfm)) {
169 struct crypto_shash *prev_tfm;
171 tfm = crypto_alloc_shash("sha256", 0, 0);
173 if (PTR_ERR(tfm) == -ENOENT) {
175 "Missing crypto API support for SHA-256");
179 "Error allocating SHA-256 transform: %ld",
183 prev_tfm = cmpxchg(&essiv_hash_tfm, NULL, tfm);
185 crypto_free_shash(tfm);
191 SHASH_DESC_ON_STACK(desc, tfm);
194 return crypto_shash_digest(desc, key, keysize, salt);
198 static int init_essiv_generator(struct llcrypt_info *ci, const u8 *raw_key,
202 struct crypto_cipher *essiv_tfm;
203 u8 salt[SHA256_DIGEST_SIZE];
205 if (WARN_ON(ci->ci_mode->ivsize != AES_BLOCK_SIZE))
208 essiv_tfm = crypto_alloc_cipher("aes", 0, 0);
209 if (IS_ERR(essiv_tfm))
210 return PTR_ERR(essiv_tfm);
212 ci->ci_essiv_tfm = essiv_tfm;
214 err = derive_essiv_salt(raw_key, keysize, salt);
219 * Using SHA256 to derive the salt/key will result in AES-256 being
220 * used for IV generation. File contents encryption will still use the
221 * configured keysize (AES-128) nevertheless.
223 err = crypto_cipher_setkey(essiv_tfm, salt, sizeof(salt));
228 memzero_explicit(salt, sizeof(salt));
232 /* Given the per-file key, set up the file's crypto transform object(s) */
233 int llcrypt_set_derived_key(struct llcrypt_info *ci, const u8 *derived_key)
235 struct llcrypt_mode *mode = ci->ci_mode;
236 struct crypto_skcipher *ctfm;
239 ctfm = llcrypt_allocate_skcipher(mode, derived_key, ci->ci_inode);
241 return PTR_ERR(ctfm);
245 if (mode->needs_essiv) {
246 err = init_essiv_generator(ci, derived_key, mode->keysize);
248 llcrypt_warn(ci->ci_inode,
249 "Error initializing ESSIV generator: %d",
257 static int setup_per_mode_key(struct llcrypt_info *ci,
258 struct llcrypt_master_key *mk)
260 struct llcrypt_mode *mode = ci->ci_mode;
261 u8 mode_num = mode - available_modes;
262 struct crypto_skcipher *tfm, *prev_tfm;
263 u8 mode_key[LLCRYPT_MAX_KEY_SIZE];
266 if (WARN_ON(mode_num >= ARRAY_SIZE(mk->mk_mode_keys)))
269 /* pairs with cmpxchg() below */
270 tfm = READ_ONCE(mk->mk_mode_keys[mode_num]);
271 if (likely(tfm != NULL))
274 BUILD_BUG_ON(sizeof(mode_num) != 1);
275 err = llcrypt_hkdf_expand(&mk->mk_secret.hkdf,
276 HKDF_CONTEXT_PER_MODE_KEY,
277 &mode_num, sizeof(mode_num),
278 mode_key, mode->keysize);
281 tfm = llcrypt_allocate_skcipher(mode, mode_key, ci->ci_inode);
282 memzero_explicit(mode_key, mode->keysize);
286 /* pairs with READ_ONCE() above */
287 prev_tfm = cmpxchg(&mk->mk_mode_keys[mode_num], NULL, tfm);
288 if (prev_tfm != NULL) {
289 crypto_free_skcipher(tfm);
297 static int llcrypt_setup_v2_file_key(struct llcrypt_info *ci,
298 struct llcrypt_master_key *mk)
300 u8 derived_key[LLCRYPT_MAX_KEY_SIZE];
303 if (ci->ci_policy.v2.flags & LLCRYPT_POLICY_FLAG_DIRECT_KEY) {
305 * DIRECT_KEY: instead of deriving per-file keys, the per-file
306 * nonce will be included in all the IVs. But unlike v1
307 * policies, for v2 policies in this case we don't encrypt with
308 * the master key directly but rather derive a per-mode key.
309 * This ensures that the master key is consistently used only
310 * for HKDF, avoiding key reuse issues.
312 if (!llcrypt_mode_supports_direct_key(ci->ci_mode)) {
313 llcrypt_warn(ci->ci_inode,
314 "Direct key flag not allowed with %s",
315 ci->ci_mode->friendly_name);
318 return setup_per_mode_key(ci, mk);
321 err = llcrypt_hkdf_expand(&mk->mk_secret.hkdf,
322 HKDF_CONTEXT_PER_FILE_KEY,
323 ci->ci_nonce, FS_KEY_DERIVATION_NONCE_SIZE,
324 derived_key, ci->ci_mode->keysize);
328 err = llcrypt_set_derived_key(ci, derived_key);
329 memzero_explicit(derived_key, ci->ci_mode->keysize);
334 * Find the master key, then set up the inode's actual encryption key.
336 * If the master key is found in the filesystem-level keyring, then the
337 * corresponding 'struct key' is returned in *master_key_ret with
338 * ->mk_secret_sem read-locked. This is needed to ensure that only one task
339 * links the llcrypt_info into ->mk_decrypted_inodes (as multiple tasks may race
340 * to create an llcrypt_info for the same inode), and to synchronize the master
341 * key being removed with a new inode starting to use it.
343 static int setup_file_encryption_key(struct llcrypt_info *ci,
344 struct key **master_key_ret)
347 struct llcrypt_master_key *mk = NULL;
348 struct llcrypt_key_specifier mk_spec;
351 switch (ci->ci_policy.version) {
352 case LLCRYPT_POLICY_V1:
353 mk_spec.type = LLCRYPT_KEY_SPEC_TYPE_DESCRIPTOR;
354 memcpy(mk_spec.u.descriptor,
355 ci->ci_policy.v1.master_key_descriptor,
356 LLCRYPT_KEY_DESCRIPTOR_SIZE);
358 case LLCRYPT_POLICY_V2:
359 mk_spec.type = LLCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
360 memcpy(mk_spec.u.identifier,
361 ci->ci_policy.v2.master_key_identifier,
362 LLCRYPT_KEY_IDENTIFIER_SIZE);
369 key = llcrypt_find_master_key(ci->ci_inode->i_sb, &mk_spec);
371 if (key != ERR_PTR(-ENOKEY) ||
372 ci->ci_policy.version != LLCRYPT_POLICY_V1)
376 * As a legacy fallback for v1 policies, search for the key in
377 * the current task's subscribed keyrings too. Don't move this
378 * to before the search of ->lsi_master_keys, since users
379 * shouldn't be able to override filesystem-level keys.
381 return llcrypt_setup_v1_file_key_via_subscribed_keyrings(ci);
384 mk = key->payload.data[0];
385 down_read(&mk->mk_secret_sem);
387 /* Has the secret been removed (via LL_IOC_REMOVE_ENCRYPTION_KEY)? */
388 if (!is_master_key_secret_present(&mk->mk_secret)) {
390 goto out_release_key;
394 * Require that the master key be at least as long as the derived key.
395 * Otherwise, the derived key cannot possibly contain as much entropy as
396 * that required by the encryption mode it will be used for. For v1
397 * policies it's also required for the KDF to work at all.
399 if (mk->mk_secret.size < ci->ci_mode->keysize) {
401 "key with %s %*phN is too short (got %u bytes, need %u+ bytes)",
402 master_key_spec_type(&mk_spec),
403 master_key_spec_len(&mk_spec), (u8 *)&mk_spec.u,
404 mk->mk_secret.size, ci->ci_mode->keysize);
406 goto out_release_key;
409 switch (ci->ci_policy.version) {
410 case LLCRYPT_POLICY_V1:
411 err = llcrypt_setup_v1_file_key(ci, mk->mk_secret.raw);
413 case LLCRYPT_POLICY_V2:
414 err = llcrypt_setup_v2_file_key(ci, mk);
422 goto out_release_key;
424 *master_key_ret = key;
428 up_read(&mk->mk_secret_sem);
433 static void put_crypt_info(struct llcrypt_info *ci)
440 if (ci->ci_direct_key) {
441 llcrypt_put_direct_key(ci->ci_direct_key);
442 } else if ((ci->ci_ctfm != NULL || ci->ci_essiv_tfm != NULL) &&
443 !llcrypt_is_direct_key_policy(&ci->ci_policy)) {
445 crypto_free_skcipher(ci->ci_ctfm);
446 crypto_free_cipher(ci->ci_essiv_tfm);
449 key = ci->ci_master_key;
451 struct llcrypt_master_key *mk = key->payload.data[0];
454 * Remove this inode from the list of inodes that were unlocked
455 * with the master key.
457 * In addition, if we're removing the last inode from a key that
458 * already had its secret removed, invalidate the key so that it
459 * gets removed from ->lsi_master_keys.
461 spin_lock(&mk->mk_decrypted_inodes_lock);
462 list_del(&ci->ci_master_key_link);
463 spin_unlock(&mk->mk_decrypted_inodes_lock);
464 if (refcount_dec_and_test(&mk->mk_refcount))
468 kmem_cache_free(llcrypt_info_cachep, ci);
471 int llcrypt_get_encryption_info(struct inode *inode)
473 struct llcrypt_info *crypt_info;
474 union llcrypt_context ctx;
475 struct llcrypt_mode *mode;
476 struct key *master_key = NULL;
477 struct lustre_sb_info *lsi = s2lsi(inode->i_sb);
480 if (llcrypt_has_encryption_key(inode))
486 res = llcrypt_initialize(lsi->lsi_cop->flags);
490 res = lsi->lsi_cop->get_context(inode, &ctx, sizeof(ctx));
492 if (!llcrypt_dummy_context_enabled(inode) ||
493 IS_ENCRYPTED(inode)) {
495 "Error %d getting encryption context",
499 /* Fake up a context for an unencrypted directory */
500 memset(&ctx, 0, sizeof(ctx));
501 ctx.version = LLCRYPT_CONTEXT_V1;
502 ctx.v1.contents_encryption_mode = LLCRYPT_MODE_AES_256_XTS;
503 if (lsi->lsi_flags & LSI_FILENAME_ENC) {
504 ctx.v1.filenames_encryption_mode =
505 LLCRYPT_MODE_AES_256_CTS;
508 "dummy enc: forcing filenames_encryption_mode to null");
509 ctx.v1.filenames_encryption_mode = LLCRYPT_MODE_NULL;
511 memset(ctx.v1.master_key_descriptor, 0x42,
512 LLCRYPT_KEY_DESCRIPTOR_SIZE);
513 res = sizeof(ctx.v1);
516 crypt_info = kmem_cache_zalloc(llcrypt_info_cachep, GFP_NOFS);
520 crypt_info->ci_inode = inode;
522 res = llcrypt_policy_from_context(&crypt_info->ci_policy, &ctx, res);
525 "Unrecognized or corrupt encryption context");
529 switch (ctx.version) {
530 case LLCRYPT_CONTEXT_V1:
531 memcpy(crypt_info->ci_nonce, ctx.v1.nonce,
532 FS_KEY_DERIVATION_NONCE_SIZE);
534 case LLCRYPT_CONTEXT_V2:
535 memcpy(crypt_info->ci_nonce, ctx.v2.nonce,
536 FS_KEY_DERIVATION_NONCE_SIZE);
544 if (!llcrypt_supported_policy(&crypt_info->ci_policy, inode)) {
549 mode = select_encryption_mode(&crypt_info->ci_policy, inode);
554 WARN_ON(mode->ivsize > LLCRYPT_MAX_IV_SIZE);
555 crypt_info->ci_mode = mode;
557 res = setup_file_encryption_key(crypt_info, &master_key);
561 if (cmpxchg_release(&(llcrypt_info_nocast(inode)), NULL,
562 crypt_info) == NULL) {
564 struct llcrypt_master_key *mk =
565 master_key->payload.data[0];
567 refcount_inc(&mk->mk_refcount);
568 crypt_info->ci_master_key = key_get(master_key);
569 spin_lock(&mk->mk_decrypted_inodes_lock);
570 list_add(&crypt_info->ci_master_key_link,
571 &mk->mk_decrypted_inodes);
572 spin_unlock(&mk->mk_decrypted_inodes_lock);
579 struct llcrypt_master_key *mk = master_key->payload.data[0];
581 up_read(&mk->mk_secret_sem);
586 put_crypt_info(crypt_info);
589 EXPORT_SYMBOL(llcrypt_get_encryption_info);
592 * llcrypt_put_encryption_info - free most of an inode's llcrypt data
594 * Free the inode's llcrypt_info. Filesystems must call this when the inode is
595 * being evicted. An RCU grace period need not have elapsed yet.
597 void llcrypt_put_encryption_info(struct inode *inode)
599 put_crypt_info(llcrypt_info(inode));
600 llcrypt_info_nocast(inode) = NULL;
602 EXPORT_SYMBOL(llcrypt_put_encryption_info);
605 * llcrypt_free_inode - free an inode's llcrypt data requiring RCU delay
607 * Free the inode's cached decrypted symlink target, if any. Filesystems must
608 * call this after an RCU grace period, just before they free the inode.
610 void llcrypt_free_inode(struct inode *inode)
612 if (IS_ENCRYPTED(inode) && S_ISLNK(inode->i_mode)) {
613 kfree(inode->i_link);
614 inode->i_link = NULL;
617 EXPORT_SYMBOL(llcrypt_free_inode);
620 * llcrypt_drop_inode - check whether the inode's master key has been removed
622 * Filesystems supporting llcrypt must call this from their ->drop_inode()
623 * method so that encrypted inodes are evicted as soon as they're no longer in
624 * use and their master key has been removed.
626 * Return: 1 if llcrypt wants the inode to be evicted now, otherwise 0
628 int llcrypt_drop_inode(struct inode *inode)
630 const struct llcrypt_info *ci;
631 const struct llcrypt_master_key *mk;
633 ci = (struct llcrypt_info *)READ_ONCE(llcrypt_info_nocast(inode));
635 * If ci is NULL, then the inode doesn't have an encryption key set up
636 * so it's irrelevant. If ci_master_key is NULL, then the master key
637 * was provided via the legacy mechanism of the process-subscribed
638 * keyrings, so we don't know whether it's been removed or not.
640 if (!ci || !ci->ci_master_key)
642 mk = ci->ci_master_key->payload.data[0];
645 * Note: since we aren't holding ->mk_secret_sem, the result here can
646 * immediately become outdated. But there's no correctness problem with
647 * unnecessarily evicting. Nor is there a correctness problem with not
648 * evicting while iput() is racing with the key being removed, since
649 * then the thread removing the key will either evict the inode itself
650 * or will correctly detect that it wasn't evicted due to the race.
652 return !is_master_key_secret_present(&mk->mk_secret);
654 EXPORT_SYMBOL_GPL(llcrypt_drop_inode);
656 bool llcrypt_has_encryption_key(const struct inode *inode)
658 /* pairs with cmpxchg_release() in llcrypt_get_encryption_info() */
659 return READ_ONCE(llcrypt_info_nocast(inode)) != NULL;
661 EXPORT_SYMBOL_GPL(llcrypt_has_encryption_key);