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 #include <crypto/sha.h>
17 #include <crypto/skcipher.h>
18 #include <linux/key.h>
20 #include "llcrypt_private.h"
22 static struct crypto_shash *essiv_hash_tfm;
24 static struct llcrypt_mode available_modes[] = {
25 [LLCRYPT_MODE_NULL] = {
26 .friendly_name = "NULL",
31 [LLCRYPT_MODE_AES_256_XTS] = {
32 .friendly_name = "AES-256-XTS",
33 .cipher_str = "xts(aes)",
37 [LLCRYPT_MODE_AES_256_CTS] = {
38 .friendly_name = "AES-256-CTS-CBC",
39 .cipher_str = "cts(cbc(aes))",
43 [LLCRYPT_MODE_AES_128_CBC] = {
44 .friendly_name = "AES-128-CBC",
45 .cipher_str = "cbc(aes)",
50 [LLCRYPT_MODE_AES_128_CTS] = {
51 .friendly_name = "AES-128-CTS-CBC",
52 .cipher_str = "cts(cbc(aes))",
56 [LLCRYPT_MODE_ADIANTUM] = {
57 .friendly_name = "Adiantum",
58 .cipher_str = "adiantum(xchacha12,aes)",
64 static struct llcrypt_mode *
65 select_encryption_mode(const union llcrypt_policy *policy,
66 const struct inode *inode)
68 if (S_ISREG(inode->i_mode))
69 return &available_modes[llcrypt_policy_contents_mode(policy)];
71 if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
72 return &available_modes[llcrypt_policy_fnames_mode(policy)];
74 WARN_ONCE(1, "llcrypt: filesystem tried to load encryption info for inode %lu, which is not encryptable (file type %d)\n",
75 inode->i_ino, (inode->i_mode & S_IFMT));
76 return ERR_PTR(-EINVAL);
79 /* Create a symmetric cipher object for the given encryption mode and key */
80 struct crypto_skcipher *llcrypt_allocate_skcipher(struct llcrypt_mode *mode,
82 const struct inode *inode)
84 struct crypto_skcipher *tfm;
87 if (!strcmp(mode->cipher_str, "null"))
90 tfm = crypto_alloc_skcipher(mode->cipher_str, 0, 0);
92 if (PTR_ERR(tfm) == -ENOENT) {
94 "Missing crypto API support for %s (API name: \"%s\")",
95 mode->friendly_name, mode->cipher_str);
96 return ERR_PTR(-ENOPKG);
98 llcrypt_err(inode, "Error allocating '%s' transform: %ld",
99 mode->cipher_str, PTR_ERR(tfm));
102 if (unlikely(!mode->logged_impl_name)) {
104 * llcrypt performance can vary greatly depending on which
105 * crypto algorithm implementation is used. Help people debug
106 * performance problems by logging the ->cra_driver_name the
107 * first time a mode is used. Note that multiple threads can
108 * race here, but it doesn't really matter.
110 mode->logged_impl_name = true;
111 pr_info("llcrypt: %s using implementation \"%s\"\n",
113 crypto_skcipher_alg(tfm)->base.cra_driver_name);
115 crypto_skcipher_set_flags(tfm, CRYPTO_TFM_REQ_FORBID_WEAK_KEYS);
116 err = crypto_skcipher_setkey(tfm, raw_key, mode->keysize);
123 crypto_free_skcipher(tfm);
127 static int derive_essiv_salt(const u8 *key, int keysize, u8 *salt)
129 struct crypto_shash *tfm = READ_ONCE(essiv_hash_tfm);
131 /* init hash transform on demand */
132 if (unlikely(!tfm)) {
133 struct crypto_shash *prev_tfm;
135 tfm = crypto_alloc_shash("sha256", 0, 0);
137 if (PTR_ERR(tfm) == -ENOENT) {
139 "Missing crypto API support for SHA-256");
143 "Error allocating SHA-256 transform: %ld",
147 prev_tfm = cmpxchg(&essiv_hash_tfm, NULL, tfm);
149 crypto_free_shash(tfm);
155 SHASH_DESC_ON_STACK(desc, tfm);
158 return crypto_shash_digest(desc, key, keysize, salt);
162 static int init_essiv_generator(struct llcrypt_info *ci, const u8 *raw_key,
166 struct crypto_cipher *essiv_tfm;
167 u8 salt[SHA256_DIGEST_SIZE];
169 if (WARN_ON(ci->ci_mode->ivsize != AES_BLOCK_SIZE))
172 essiv_tfm = crypto_alloc_cipher("aes", 0, 0);
173 if (IS_ERR(essiv_tfm))
174 return PTR_ERR(essiv_tfm);
176 ci->ci_essiv_tfm = essiv_tfm;
178 err = derive_essiv_salt(raw_key, keysize, salt);
183 * Using SHA256 to derive the salt/key will result in AES-256 being
184 * used for IV generation. File contents encryption will still use the
185 * configured keysize (AES-128) nevertheless.
187 err = crypto_cipher_setkey(essiv_tfm, salt, sizeof(salt));
192 memzero_explicit(salt, sizeof(salt));
196 /* Given the per-file key, set up the file's crypto transform object(s) */
197 int llcrypt_set_derived_key(struct llcrypt_info *ci, const u8 *derived_key)
199 struct llcrypt_mode *mode = ci->ci_mode;
200 struct crypto_skcipher *ctfm;
203 ctfm = llcrypt_allocate_skcipher(mode, derived_key, ci->ci_inode);
205 return PTR_ERR(ctfm);
209 if (mode->needs_essiv) {
210 err = init_essiv_generator(ci, derived_key, mode->keysize);
212 llcrypt_warn(ci->ci_inode,
213 "Error initializing ESSIV generator: %d",
221 static int setup_per_mode_key(struct llcrypt_info *ci,
222 struct llcrypt_master_key *mk)
224 struct llcrypt_mode *mode = ci->ci_mode;
225 u8 mode_num = mode - available_modes;
226 struct crypto_skcipher *tfm, *prev_tfm;
227 u8 mode_key[LLCRYPT_MAX_KEY_SIZE];
230 if (WARN_ON(mode_num >= ARRAY_SIZE(mk->mk_mode_keys)))
233 /* pairs with cmpxchg() below */
234 tfm = READ_ONCE(mk->mk_mode_keys[mode_num]);
235 if (likely(tfm != NULL))
238 BUILD_BUG_ON(sizeof(mode_num) != 1);
239 err = llcrypt_hkdf_expand(&mk->mk_secret.hkdf,
240 HKDF_CONTEXT_PER_MODE_KEY,
241 &mode_num, sizeof(mode_num),
242 mode_key, mode->keysize);
245 tfm = llcrypt_allocate_skcipher(mode, mode_key, ci->ci_inode);
246 memzero_explicit(mode_key, mode->keysize);
250 /* pairs with READ_ONCE() above */
251 prev_tfm = cmpxchg(&mk->mk_mode_keys[mode_num], NULL, tfm);
252 if (prev_tfm != NULL) {
253 crypto_free_skcipher(tfm);
261 static int llcrypt_setup_v2_file_key(struct llcrypt_info *ci,
262 struct llcrypt_master_key *mk)
264 u8 derived_key[LLCRYPT_MAX_KEY_SIZE];
267 if (ci->ci_policy.v2.flags & LLCRYPT_POLICY_FLAG_DIRECT_KEY) {
269 * DIRECT_KEY: instead of deriving per-file keys, the per-file
270 * nonce will be included in all the IVs. But unlike v1
271 * policies, for v2 policies in this case we don't encrypt with
272 * the master key directly but rather derive a per-mode key.
273 * This ensures that the master key is consistently used only
274 * for HKDF, avoiding key reuse issues.
276 if (!llcrypt_mode_supports_direct_key(ci->ci_mode)) {
277 llcrypt_warn(ci->ci_inode,
278 "Direct key flag not allowed with %s",
279 ci->ci_mode->friendly_name);
282 return setup_per_mode_key(ci, mk);
285 err = llcrypt_hkdf_expand(&mk->mk_secret.hkdf,
286 HKDF_CONTEXT_PER_FILE_KEY,
287 ci->ci_nonce, FS_KEY_DERIVATION_NONCE_SIZE,
288 derived_key, ci->ci_mode->keysize);
292 err = llcrypt_set_derived_key(ci, derived_key);
293 memzero_explicit(derived_key, ci->ci_mode->keysize);
298 * Find the master key, then set up the inode's actual encryption key.
300 * If the master key is found in the filesystem-level keyring, then the
301 * corresponding 'struct key' is returned in *master_key_ret with
302 * ->mk_secret_sem read-locked. This is needed to ensure that only one task
303 * links the llcrypt_info into ->mk_decrypted_inodes (as multiple tasks may race
304 * to create an llcrypt_info for the same inode), and to synchronize the master
305 * key being removed with a new inode starting to use it.
307 static int setup_file_encryption_key(struct llcrypt_info *ci,
308 struct key **master_key_ret)
311 struct llcrypt_master_key *mk = NULL;
312 struct llcrypt_key_specifier mk_spec;
315 switch (ci->ci_policy.version) {
316 case LLCRYPT_POLICY_V1:
317 mk_spec.type = LLCRYPT_KEY_SPEC_TYPE_DESCRIPTOR;
318 memcpy(mk_spec.u.descriptor,
319 ci->ci_policy.v1.master_key_descriptor,
320 LLCRYPT_KEY_DESCRIPTOR_SIZE);
322 case LLCRYPT_POLICY_V2:
323 mk_spec.type = LLCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
324 memcpy(mk_spec.u.identifier,
325 ci->ci_policy.v2.master_key_identifier,
326 LLCRYPT_KEY_IDENTIFIER_SIZE);
333 key = llcrypt_find_master_key(ci->ci_inode->i_sb, &mk_spec);
335 if (key != ERR_PTR(-ENOKEY) ||
336 ci->ci_policy.version != LLCRYPT_POLICY_V1)
340 * As a legacy fallback for v1 policies, search for the key in
341 * the current task's subscribed keyrings too. Don't move this
342 * to before the search of ->lsi_master_keys, since users
343 * shouldn't be able to override filesystem-level keys.
345 return llcrypt_setup_v1_file_key_via_subscribed_keyrings(ci);
348 mk = key->payload.data[0];
349 down_read(&mk->mk_secret_sem);
351 /* Has the secret been removed (via LL_IOC_REMOVE_ENCRYPTION_KEY)? */
352 if (!is_master_key_secret_present(&mk->mk_secret)) {
354 goto out_release_key;
358 * Require that the master key be at least as long as the derived key.
359 * Otherwise, the derived key cannot possibly contain as much entropy as
360 * that required by the encryption mode it will be used for. For v1
361 * policies it's also required for the KDF to work at all.
363 if (mk->mk_secret.size < ci->ci_mode->keysize) {
365 "key with %s %*phN is too short (got %u bytes, need %u+ bytes)",
366 master_key_spec_type(&mk_spec),
367 master_key_spec_len(&mk_spec), (u8 *)&mk_spec.u,
368 mk->mk_secret.size, ci->ci_mode->keysize);
370 goto out_release_key;
373 switch (ci->ci_policy.version) {
374 case LLCRYPT_POLICY_V1:
375 err = llcrypt_setup_v1_file_key(ci, mk->mk_secret.raw);
377 case LLCRYPT_POLICY_V2:
378 err = llcrypt_setup_v2_file_key(ci, mk);
386 goto out_release_key;
388 *master_key_ret = key;
392 up_read(&mk->mk_secret_sem);
397 static void put_crypt_info(struct llcrypt_info *ci)
404 if (ci->ci_direct_key) {
405 llcrypt_put_direct_key(ci->ci_direct_key);
406 } else if ((ci->ci_ctfm != NULL || ci->ci_essiv_tfm != NULL) &&
407 !llcrypt_is_direct_key_policy(&ci->ci_policy)) {
409 crypto_free_skcipher(ci->ci_ctfm);
410 crypto_free_cipher(ci->ci_essiv_tfm);
413 key = ci->ci_master_key;
415 struct llcrypt_master_key *mk = key->payload.data[0];
418 * Remove this inode from the list of inodes that were unlocked
419 * with the master key.
421 * In addition, if we're removing the last inode from a key that
422 * already had its secret removed, invalidate the key so that it
423 * gets removed from ->lsi_master_keys.
425 spin_lock(&mk->mk_decrypted_inodes_lock);
426 list_del(&ci->ci_master_key_link);
427 spin_unlock(&mk->mk_decrypted_inodes_lock);
428 if (refcount_dec_and_test(&mk->mk_refcount))
432 kmem_cache_free(llcrypt_info_cachep, ci);
435 int llcrypt_get_encryption_info(struct inode *inode)
437 struct llcrypt_info *crypt_info;
438 union llcrypt_context ctx;
439 struct llcrypt_mode *mode;
440 struct key *master_key = NULL;
441 struct lustre_sb_info *lsi = s2lsi(inode->i_sb);
444 if (llcrypt_has_encryption_key(inode))
450 res = llcrypt_initialize(lsi->lsi_cop->flags);
454 res = lsi->lsi_cop->get_context(inode, &ctx, sizeof(ctx));
456 if (!llcrypt_dummy_context_enabled(inode) ||
457 IS_ENCRYPTED(inode)) {
459 "Error %d getting encryption context",
463 /* Fake up a context for an unencrypted directory */
464 memset(&ctx, 0, sizeof(ctx));
465 ctx.version = LLCRYPT_CONTEXT_V1;
466 /* Force file/directory name encryption policy to null.
467 * This is needed for interoperability with future versions.
468 * Change to be reverted back when Lustre supports name
471 CWARN("inode %lu: setting policy filenames_encryption_mode to null\n",
473 ctx.v1.contents_encryption_mode = LLCRYPT_MODE_AES_256_XTS;
474 ctx.v1.filenames_encryption_mode = LLCRYPT_MODE_NULL;
475 memset(ctx.v1.master_key_descriptor, 0x42,
476 LLCRYPT_KEY_DESCRIPTOR_SIZE);
477 res = sizeof(ctx.v1);
480 crypt_info = kmem_cache_zalloc(llcrypt_info_cachep, GFP_NOFS);
484 crypt_info->ci_inode = inode;
486 res = llcrypt_policy_from_context(&crypt_info->ci_policy, &ctx, res);
489 "Unrecognized or corrupt encryption context");
493 switch (ctx.version) {
494 case LLCRYPT_CONTEXT_V1:
495 memcpy(crypt_info->ci_nonce, ctx.v1.nonce,
496 FS_KEY_DERIVATION_NONCE_SIZE);
498 case LLCRYPT_CONTEXT_V2:
499 memcpy(crypt_info->ci_nonce, ctx.v2.nonce,
500 FS_KEY_DERIVATION_NONCE_SIZE);
508 if (!llcrypt_supported_policy(&crypt_info->ci_policy, inode)) {
513 mode = select_encryption_mode(&crypt_info->ci_policy, inode);
518 WARN_ON(mode->ivsize > LLCRYPT_MAX_IV_SIZE);
519 crypt_info->ci_mode = mode;
521 res = setup_file_encryption_key(crypt_info, &master_key);
525 if (cmpxchg_release(&(llcrypt_info_nocast(inode)), NULL,
526 crypt_info) == NULL) {
528 struct llcrypt_master_key *mk =
529 master_key->payload.data[0];
531 refcount_inc(&mk->mk_refcount);
532 crypt_info->ci_master_key = key_get(master_key);
533 spin_lock(&mk->mk_decrypted_inodes_lock);
534 list_add(&crypt_info->ci_master_key_link,
535 &mk->mk_decrypted_inodes);
536 spin_unlock(&mk->mk_decrypted_inodes_lock);
543 struct llcrypt_master_key *mk = master_key->payload.data[0];
545 up_read(&mk->mk_secret_sem);
550 put_crypt_info(crypt_info);
553 EXPORT_SYMBOL(llcrypt_get_encryption_info);
556 * llcrypt_put_encryption_info - free most of an inode's llcrypt data
558 * Free the inode's llcrypt_info. Filesystems must call this when the inode is
559 * being evicted. An RCU grace period need not have elapsed yet.
561 void llcrypt_put_encryption_info(struct inode *inode)
563 put_crypt_info(llcrypt_info(inode));
564 llcrypt_info_nocast(inode) = NULL;
566 EXPORT_SYMBOL(llcrypt_put_encryption_info);
569 * llcrypt_free_inode - free an inode's llcrypt data requiring RCU delay
571 * Free the inode's cached decrypted symlink target, if any. Filesystems must
572 * call this after an RCU grace period, just before they free the inode.
574 void llcrypt_free_inode(struct inode *inode)
576 if (IS_ENCRYPTED(inode) && S_ISLNK(inode->i_mode)) {
577 kfree(inode->i_link);
578 inode->i_link = NULL;
581 EXPORT_SYMBOL(llcrypt_free_inode);
584 * llcrypt_drop_inode - check whether the inode's master key has been removed
586 * Filesystems supporting llcrypt must call this from their ->drop_inode()
587 * method so that encrypted inodes are evicted as soon as they're no longer in
588 * use and their master key has been removed.
590 * Return: 1 if llcrypt wants the inode to be evicted now, otherwise 0
592 int llcrypt_drop_inode(struct inode *inode)
594 const struct llcrypt_info *ci;
595 const struct llcrypt_master_key *mk;
597 ci = (struct llcrypt_info *)READ_ONCE(llcrypt_info_nocast(inode));
599 * If ci is NULL, then the inode doesn't have an encryption key set up
600 * so it's irrelevant. If ci_master_key is NULL, then the master key
601 * was provided via the legacy mechanism of the process-subscribed
602 * keyrings, so we don't know whether it's been removed or not.
604 if (!ci || !ci->ci_master_key)
606 mk = ci->ci_master_key->payload.data[0];
609 * Note: since we aren't holding ->mk_secret_sem, the result here can
610 * immediately become outdated. But there's no correctness problem with
611 * unnecessarily evicting. Nor is there a correctness problem with not
612 * evicting while iput() is racing with the key being removed, since
613 * then the thread removing the key will either evict the inode itself
614 * or will correctly detect that it wasn't evicted due to the race.
616 return !is_master_key_secret_present(&mk->mk_secret);
618 EXPORT_SYMBOL_GPL(llcrypt_drop_inode);
620 inline bool llcrypt_has_encryption_key(const struct inode *inode)
622 /* pairs with cmpxchg_release() in llcrypt_get_encryption_info() */
623 return READ_ONCE(llcrypt_info_nocast(inode)) != NULL;
625 EXPORT_SYMBOL_GPL(llcrypt_has_encryption_key);