Whamcloud - gitweb
LU-14880 libcfs: Use crypto/sha2.h if available
[fs/lustre-release.git] / libcfs / libcfs / crypto / keysetup.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Key setup facility for FS encryption support.
4  *
5  * Copyright (C) 2015, Google, Inc.
6  *
7  * Originally written by Michael Halcrow, Ildar Muslukhov, and Uday Savagaonkar.
8  * Heavily modified since then.
9  */
10 /*
11  * Linux commit 219d54332a09
12  * tags/v5.4
13  */
14
15 #include <crypto/aes.h>
16 #ifdef HAVE_CRYPTO_SHA2_HEADER
17 #include <crypto/sha2.h>
18 #else
19 #include <crypto/sha.h>
20 #endif
21 #include <crypto/skcipher.h>
22 #include <linux/key.h>
23
24 #include "llcrypt_private.h"
25
26 static struct crypto_shash *essiv_hash_tfm;
27
28 static struct llcrypt_mode available_modes[] = {
29         [LLCRYPT_MODE_NULL] = {
30                 .friendly_name = "NULL",
31                 .cipher_str = "null",
32                 .keysize = 0,
33                 .ivsize = 0,
34         },
35         [LLCRYPT_MODE_AES_256_XTS] = {
36                 .friendly_name = "AES-256-XTS",
37                 .cipher_str = "xts(aes)",
38                 .keysize = 64,
39                 .ivsize = 16,
40         },
41         [LLCRYPT_MODE_AES_256_CTS] = {
42                 .friendly_name = "AES-256-CTS-CBC",
43                 .cipher_str = "cts(cbc(aes))",
44                 .keysize = 32,
45                 .ivsize = 16,
46         },
47         [LLCRYPT_MODE_AES_128_CBC] = {
48                 .friendly_name = "AES-128-CBC",
49                 .cipher_str = "cbc(aes)",
50                 .keysize = 16,
51                 .ivsize = 16,
52                 .needs_essiv = true,
53         },
54         [LLCRYPT_MODE_AES_128_CTS] = {
55                 .friendly_name = "AES-128-CTS-CBC",
56                 .cipher_str = "cts(cbc(aes))",
57                 .keysize = 16,
58                 .ivsize = 16,
59         },
60         [LLCRYPT_MODE_ADIANTUM] = {
61                 .friendly_name = "Adiantum",
62                 .cipher_str = "adiantum(xchacha12,aes)",
63                 .keysize = 32,
64                 .ivsize = 32,
65         },
66 };
67
68 static struct llcrypt_mode *
69 select_encryption_mode(const union llcrypt_policy *policy,
70                        const struct inode *inode)
71 {
72         if (S_ISREG(inode->i_mode))
73                 return &available_modes[llcrypt_policy_contents_mode(policy)];
74
75         if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
76                 return &available_modes[llcrypt_policy_fnames_mode(policy)];
77
78         WARN_ONCE(1, "llcrypt: filesystem tried to load encryption info for inode %lu, which is not encryptable (file type %d)\n",
79                   inode->i_ino, (inode->i_mode & S_IFMT));
80         return ERR_PTR(-EINVAL);
81 }
82
83 /* Create a symmetric cipher object for the given encryption mode and key */
84 struct crypto_skcipher *llcrypt_allocate_skcipher(struct llcrypt_mode *mode,
85                                                   const u8 *raw_key,
86                                                   const struct inode *inode)
87 {
88         struct crypto_skcipher *tfm;
89         int err;
90
91         if (!strcmp(mode->cipher_str, "null"))
92                 return NULL;
93
94         tfm = crypto_alloc_skcipher(mode->cipher_str, 0, 0);
95         if (IS_ERR(tfm)) {
96                 if (PTR_ERR(tfm) == -ENOENT) {
97                         llcrypt_warn(inode,
98                                      "Missing crypto API support for %s (API name: \"%s\")",
99                                      mode->friendly_name, mode->cipher_str);
100                         return ERR_PTR(-ENOPKG);
101                 }
102                 llcrypt_err(inode, "Error allocating '%s' transform: %ld",
103                             mode->cipher_str, PTR_ERR(tfm));
104                 return tfm;
105         }
106         if (unlikely(!mode->logged_impl_name)) {
107                 /*
108                  * llcrypt performance can vary greatly depending on which
109                  * crypto algorithm implementation is used.  Help people debug
110                  * performance problems by logging the ->cra_driver_name the
111                  * first time a mode is used.  Note that multiple threads can
112                  * race here, but it doesn't really matter.
113                  */
114                 mode->logged_impl_name = true;
115                 pr_info("llcrypt: %s using implementation \"%s\"\n",
116                         mode->friendly_name,
117                         crypto_skcipher_alg(tfm)->base.cra_driver_name);
118         }
119         crypto_skcipher_set_flags(tfm, CRYPTO_TFM_REQ_FORBID_WEAK_KEYS);
120         err = crypto_skcipher_setkey(tfm, raw_key, mode->keysize);
121         if (err)
122                 goto err_free_tfm;
123
124         return tfm;
125
126 err_free_tfm:
127         crypto_free_skcipher(tfm);
128         return ERR_PTR(err);
129 }
130
131 static int derive_essiv_salt(const u8 *key, int keysize, u8 *salt)
132 {
133         struct crypto_shash *tfm = READ_ONCE(essiv_hash_tfm);
134
135         /* init hash transform on demand */
136         if (unlikely(!tfm)) {
137                 struct crypto_shash *prev_tfm;
138
139                 tfm = crypto_alloc_shash("sha256", 0, 0);
140                 if (IS_ERR(tfm)) {
141                         if (PTR_ERR(tfm) == -ENOENT) {
142                                 llcrypt_warn(NULL,
143                                              "Missing crypto API support for SHA-256");
144                                 return -ENOPKG;
145                         }
146                         llcrypt_err(NULL,
147                                     "Error allocating SHA-256 transform: %ld",
148                                     PTR_ERR(tfm));
149                         return PTR_ERR(tfm);
150                 }
151                 prev_tfm = cmpxchg(&essiv_hash_tfm, NULL, tfm);
152                 if (prev_tfm) {
153                         crypto_free_shash(tfm);
154                         tfm = prev_tfm;
155                 }
156         }
157
158         {
159                 SHASH_DESC_ON_STACK(desc, tfm);
160                 desc->tfm = tfm;
161
162                 return crypto_shash_digest(desc, key, keysize, salt);
163         }
164 }
165
166 static int init_essiv_generator(struct llcrypt_info *ci, const u8 *raw_key,
167                                 int keysize)
168 {
169         int err;
170         struct crypto_cipher *essiv_tfm;
171         u8 salt[SHA256_DIGEST_SIZE];
172
173         if (WARN_ON(ci->ci_mode->ivsize != AES_BLOCK_SIZE))
174                 return -EINVAL;
175
176         essiv_tfm = crypto_alloc_cipher("aes", 0, 0);
177         if (IS_ERR(essiv_tfm))
178                 return PTR_ERR(essiv_tfm);
179
180         ci->ci_essiv_tfm = essiv_tfm;
181
182         err = derive_essiv_salt(raw_key, keysize, salt);
183         if (err)
184                 goto out;
185
186         /*
187          * Using SHA256 to derive the salt/key will result in AES-256 being
188          * used for IV generation. File contents encryption will still use the
189          * configured keysize (AES-128) nevertheless.
190          */
191         err = crypto_cipher_setkey(essiv_tfm, salt, sizeof(salt));
192         if (err)
193                 goto out;
194
195 out:
196         memzero_explicit(salt, sizeof(salt));
197         return err;
198 }
199
200 /* Given the per-file key, set up the file's crypto transform object(s) */
201 int llcrypt_set_derived_key(struct llcrypt_info *ci, const u8 *derived_key)
202 {
203         struct llcrypt_mode *mode = ci->ci_mode;
204         struct crypto_skcipher *ctfm;
205         int err;
206
207         ctfm = llcrypt_allocate_skcipher(mode, derived_key, ci->ci_inode);
208         if (IS_ERR(ctfm))
209                 return PTR_ERR(ctfm);
210
211         ci->ci_ctfm = ctfm;
212
213         if (mode->needs_essiv) {
214                 err = init_essiv_generator(ci, derived_key, mode->keysize);
215                 if (err) {
216                         llcrypt_warn(ci->ci_inode,
217                                      "Error initializing ESSIV generator: %d",
218                                      err);
219                         return err;
220                 }
221         }
222         return 0;
223 }
224
225 static int setup_per_mode_key(struct llcrypt_info *ci,
226                               struct llcrypt_master_key *mk)
227 {
228         struct llcrypt_mode *mode = ci->ci_mode;
229         u8 mode_num = mode - available_modes;
230         struct crypto_skcipher *tfm, *prev_tfm;
231         u8 mode_key[LLCRYPT_MAX_KEY_SIZE];
232         int err;
233
234         if (WARN_ON(mode_num >= ARRAY_SIZE(mk->mk_mode_keys)))
235                 return -EINVAL;
236
237         /* pairs with cmpxchg() below */
238         tfm = READ_ONCE(mk->mk_mode_keys[mode_num]);
239         if (likely(tfm != NULL))
240                 goto done;
241
242         BUILD_BUG_ON(sizeof(mode_num) != 1);
243         err = llcrypt_hkdf_expand(&mk->mk_secret.hkdf,
244                                   HKDF_CONTEXT_PER_MODE_KEY,
245                                   &mode_num, sizeof(mode_num),
246                                   mode_key, mode->keysize);
247         if (err)
248                 return err;
249         tfm = llcrypt_allocate_skcipher(mode, mode_key, ci->ci_inode);
250         memzero_explicit(mode_key, mode->keysize);
251         if (IS_ERR(tfm))
252                 return PTR_ERR(tfm);
253
254         /* pairs with READ_ONCE() above */
255         prev_tfm = cmpxchg(&mk->mk_mode_keys[mode_num], NULL, tfm);
256         if (prev_tfm != NULL) {
257                 crypto_free_skcipher(tfm);
258                 tfm = prev_tfm;
259         }
260 done:
261         ci->ci_ctfm = tfm;
262         return 0;
263 }
264
265 static int llcrypt_setup_v2_file_key(struct llcrypt_info *ci,
266                                      struct llcrypt_master_key *mk)
267 {
268         u8 derived_key[LLCRYPT_MAX_KEY_SIZE];
269         int err;
270
271         if (ci->ci_policy.v2.flags & LLCRYPT_POLICY_FLAG_DIRECT_KEY) {
272                 /*
273                  * DIRECT_KEY: instead of deriving per-file keys, the per-file
274                  * nonce will be included in all the IVs.  But unlike v1
275                  * policies, for v2 policies in this case we don't encrypt with
276                  * the master key directly but rather derive a per-mode key.
277                  * This ensures that the master key is consistently used only
278                  * for HKDF, avoiding key reuse issues.
279                  */
280                 if (!llcrypt_mode_supports_direct_key(ci->ci_mode)) {
281                         llcrypt_warn(ci->ci_inode,
282                                      "Direct key flag not allowed with %s",
283                                      ci->ci_mode->friendly_name);
284                         return -EINVAL;
285                 }
286                 return setup_per_mode_key(ci, mk);
287         }
288
289         err = llcrypt_hkdf_expand(&mk->mk_secret.hkdf,
290                                   HKDF_CONTEXT_PER_FILE_KEY,
291                                   ci->ci_nonce, FS_KEY_DERIVATION_NONCE_SIZE,
292                                   derived_key, ci->ci_mode->keysize);
293         if (err)
294                 return err;
295
296         err = llcrypt_set_derived_key(ci, derived_key);
297         memzero_explicit(derived_key, ci->ci_mode->keysize);
298         return err;
299 }
300
301 /*
302  * Find the master key, then set up the inode's actual encryption key.
303  *
304  * If the master key is found in the filesystem-level keyring, then the
305  * corresponding 'struct key' is returned in *master_key_ret with
306  * ->mk_secret_sem read-locked.  This is needed to ensure that only one task
307  * links the llcrypt_info into ->mk_decrypted_inodes (as multiple tasks may race
308  * to create an llcrypt_info for the same inode), and to synchronize the master
309  * key being removed with a new inode starting to use it.
310  */
311 static int setup_file_encryption_key(struct llcrypt_info *ci,
312                                      struct key **master_key_ret)
313 {
314         struct key *key;
315         struct llcrypt_master_key *mk = NULL;
316         struct llcrypt_key_specifier mk_spec;
317         int err;
318
319         switch (ci->ci_policy.version) {
320         case LLCRYPT_POLICY_V1:
321                 mk_spec.type = LLCRYPT_KEY_SPEC_TYPE_DESCRIPTOR;
322                 memcpy(mk_spec.u.descriptor,
323                        ci->ci_policy.v1.master_key_descriptor,
324                        LLCRYPT_KEY_DESCRIPTOR_SIZE);
325                 break;
326         case LLCRYPT_POLICY_V2:
327                 mk_spec.type = LLCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
328                 memcpy(mk_spec.u.identifier,
329                        ci->ci_policy.v2.master_key_identifier,
330                        LLCRYPT_KEY_IDENTIFIER_SIZE);
331                 break;
332         default:
333                 WARN_ON(1);
334                 return -EINVAL;
335         }
336
337         key = llcrypt_find_master_key(ci->ci_inode->i_sb, &mk_spec);
338         if (IS_ERR(key)) {
339                 if (key != ERR_PTR(-ENOKEY) ||
340                     ci->ci_policy.version != LLCRYPT_POLICY_V1)
341                         return PTR_ERR(key);
342
343                 /*
344                  * As a legacy fallback for v1 policies, search for the key in
345                  * the current task's subscribed keyrings too.  Don't move this
346                  * to before the search of ->lsi_master_keys, since users
347                  * shouldn't be able to override filesystem-level keys.
348                  */
349                 return llcrypt_setup_v1_file_key_via_subscribed_keyrings(ci);
350         }
351
352         mk = key->payload.data[0];
353         down_read(&mk->mk_secret_sem);
354
355         /* Has the secret been removed (via LL_IOC_REMOVE_ENCRYPTION_KEY)? */
356         if (!is_master_key_secret_present(&mk->mk_secret)) {
357                 err = -ENOKEY;
358                 goto out_release_key;
359         }
360
361         /*
362          * Require that the master key be at least as long as the derived key.
363          * Otherwise, the derived key cannot possibly contain as much entropy as
364          * that required by the encryption mode it will be used for.  For v1
365          * policies it's also required for the KDF to work at all.
366          */
367         if (mk->mk_secret.size < ci->ci_mode->keysize) {
368                 llcrypt_warn(NULL,
369                              "key with %s %*phN is too short (got %u bytes, need %u+ bytes)",
370                              master_key_spec_type(&mk_spec),
371                              master_key_spec_len(&mk_spec), (u8 *)&mk_spec.u,
372                              mk->mk_secret.size, ci->ci_mode->keysize);
373                 err = -ENOKEY;
374                 goto out_release_key;
375         }
376
377         switch (ci->ci_policy.version) {
378         case LLCRYPT_POLICY_V1:
379                 err = llcrypt_setup_v1_file_key(ci, mk->mk_secret.raw);
380                 break;
381         case LLCRYPT_POLICY_V2:
382                 err = llcrypt_setup_v2_file_key(ci, mk);
383                 break;
384         default:
385                 WARN_ON(1);
386                 err = -EINVAL;
387                 break;
388         }
389         if (err)
390                 goto out_release_key;
391
392         *master_key_ret = key;
393         return 0;
394
395 out_release_key:
396         up_read(&mk->mk_secret_sem);
397         key_put(key);
398         return err;
399 }
400
401 static void put_crypt_info(struct llcrypt_info *ci)
402 {
403         struct key *key;
404
405         if (!ci)
406                 return;
407
408         if (ci->ci_direct_key) {
409                 llcrypt_put_direct_key(ci->ci_direct_key);
410         } else if ((ci->ci_ctfm != NULL || ci->ci_essiv_tfm != NULL) &&
411                    !llcrypt_is_direct_key_policy(&ci->ci_policy)) {
412                 if (ci->ci_ctfm)
413                         crypto_free_skcipher(ci->ci_ctfm);
414                 crypto_free_cipher(ci->ci_essiv_tfm);
415         }
416
417         key = ci->ci_master_key;
418         if (key) {
419                 struct llcrypt_master_key *mk = key->payload.data[0];
420
421                 /*
422                  * Remove this inode from the list of inodes that were unlocked
423                  * with the master key.
424                  *
425                  * In addition, if we're removing the last inode from a key that
426                  * already had its secret removed, invalidate the key so that it
427                  * gets removed from ->lsi_master_keys.
428                  */
429                 spin_lock(&mk->mk_decrypted_inodes_lock);
430                 list_del(&ci->ci_master_key_link);
431                 spin_unlock(&mk->mk_decrypted_inodes_lock);
432                 if (refcount_dec_and_test(&mk->mk_refcount))
433                         key_invalidate(key);
434                 key_put(key);
435         }
436         kmem_cache_free(llcrypt_info_cachep, ci);
437 }
438
439 int llcrypt_get_encryption_info(struct inode *inode)
440 {
441         struct llcrypt_info *crypt_info;
442         union llcrypt_context ctx;
443         struct llcrypt_mode *mode;
444         struct key *master_key = NULL;
445         struct lustre_sb_info *lsi = s2lsi(inode->i_sb);
446         int res;
447
448         if (llcrypt_has_encryption_key(inode))
449                 return 0;
450
451         if (!lsi)
452                 return -ENOKEY;
453
454         res = llcrypt_initialize(lsi->lsi_cop->flags);
455         if (res)
456                 return res;
457
458         res = lsi->lsi_cop->get_context(inode, &ctx, sizeof(ctx));
459         if (res < 0) {
460                 if (!llcrypt_dummy_context_enabled(inode) ||
461                     IS_ENCRYPTED(inode)) {
462                         llcrypt_warn(inode,
463                                      "Error %d getting encryption context",
464                                      res);
465                         return res;
466                 }
467                 /* Fake up a context for an unencrypted directory */
468                 memset(&ctx, 0, sizeof(ctx));
469                 ctx.version = LLCRYPT_CONTEXT_V1;
470                 ctx.v1.contents_encryption_mode = LLCRYPT_MODE_AES_256_XTS;
471                 ctx.v1.filenames_encryption_mode = LLCRYPT_MODE_AES_256_CTS;
472                 memset(ctx.v1.master_key_descriptor, 0x42,
473                        LLCRYPT_KEY_DESCRIPTOR_SIZE);
474                 res = sizeof(ctx.v1);
475         }
476
477         crypt_info = kmem_cache_zalloc(llcrypt_info_cachep, GFP_NOFS);
478         if (!crypt_info)
479                 return -ENOMEM;
480
481         crypt_info->ci_inode = inode;
482
483         res = llcrypt_policy_from_context(&crypt_info->ci_policy, &ctx, res);
484         if (res) {
485                 llcrypt_warn(inode,
486                              "Unrecognized or corrupt encryption context");
487                 goto out;
488         }
489
490         switch (ctx.version) {
491         case LLCRYPT_CONTEXT_V1:
492                 memcpy(crypt_info->ci_nonce, ctx.v1.nonce,
493                        FS_KEY_DERIVATION_NONCE_SIZE);
494                 break;
495         case LLCRYPT_CONTEXT_V2:
496                 memcpy(crypt_info->ci_nonce, ctx.v2.nonce,
497                        FS_KEY_DERIVATION_NONCE_SIZE);
498                 break;
499         default:
500                 WARN_ON(1);
501                 res = -EINVAL;
502                 goto out;
503         }
504
505         if (!llcrypt_supported_policy(&crypt_info->ci_policy, inode)) {
506                 res = -EINVAL;
507                 goto out;
508         }
509
510         mode = select_encryption_mode(&crypt_info->ci_policy, inode);
511         if (IS_ERR(mode)) {
512                 res = PTR_ERR(mode);
513                 goto out;
514         }
515         WARN_ON(mode->ivsize > LLCRYPT_MAX_IV_SIZE);
516         crypt_info->ci_mode = mode;
517
518         res = setup_file_encryption_key(crypt_info, &master_key);
519         if (res)
520                 goto out;
521
522         if (cmpxchg_release(&(llcrypt_info_nocast(inode)), NULL,
523                             crypt_info) == NULL) {
524                 if (master_key) {
525                         struct llcrypt_master_key *mk =
526                                 master_key->payload.data[0];
527
528                         refcount_inc(&mk->mk_refcount);
529                         crypt_info->ci_master_key = key_get(master_key);
530                         spin_lock(&mk->mk_decrypted_inodes_lock);
531                         list_add(&crypt_info->ci_master_key_link,
532                                  &mk->mk_decrypted_inodes);
533                         spin_unlock(&mk->mk_decrypted_inodes_lock);
534                 }
535                 crypt_info = NULL;
536         }
537         res = 0;
538 out:
539         if (master_key) {
540                 struct llcrypt_master_key *mk = master_key->payload.data[0];
541
542                 up_read(&mk->mk_secret_sem);
543                 key_put(master_key);
544         }
545         if (res == -ENOKEY)
546                 res = 0;
547         put_crypt_info(crypt_info);
548         return res;
549 }
550 EXPORT_SYMBOL(llcrypt_get_encryption_info);
551
552 /**
553  * llcrypt_put_encryption_info - free most of an inode's llcrypt data
554  *
555  * Free the inode's llcrypt_info.  Filesystems must call this when the inode is
556  * being evicted.  An RCU grace period need not have elapsed yet.
557  */
558 void llcrypt_put_encryption_info(struct inode *inode)
559 {
560         put_crypt_info(llcrypt_info(inode));
561         llcrypt_info_nocast(inode) = NULL;
562 }
563 EXPORT_SYMBOL(llcrypt_put_encryption_info);
564
565 /**
566  * llcrypt_free_inode - free an inode's llcrypt data requiring RCU delay
567  *
568  * Free the inode's cached decrypted symlink target, if any.  Filesystems must
569  * call this after an RCU grace period, just before they free the inode.
570  */
571 void llcrypt_free_inode(struct inode *inode)
572 {
573         if (IS_ENCRYPTED(inode) && S_ISLNK(inode->i_mode)) {
574                 kfree(inode->i_link);
575                 inode->i_link = NULL;
576         }
577 }
578 EXPORT_SYMBOL(llcrypt_free_inode);
579
580 /**
581  * llcrypt_drop_inode - check whether the inode's master key has been removed
582  *
583  * Filesystems supporting llcrypt must call this from their ->drop_inode()
584  * method so that encrypted inodes are evicted as soon as they're no longer in
585  * use and their master key has been removed.
586  *
587  * Return: 1 if llcrypt wants the inode to be evicted now, otherwise 0
588  */
589 int llcrypt_drop_inode(struct inode *inode)
590 {
591         const struct llcrypt_info *ci;
592         const struct llcrypt_master_key *mk;
593
594         ci = (struct llcrypt_info *)READ_ONCE(llcrypt_info_nocast(inode));
595         /*
596          * If ci is NULL, then the inode doesn't have an encryption key set up
597          * so it's irrelevant.  If ci_master_key is NULL, then the master key
598          * was provided via the legacy mechanism of the process-subscribed
599          * keyrings, so we don't know whether it's been removed or not.
600          */
601         if (!ci || !ci->ci_master_key)
602                 return 0;
603         mk = ci->ci_master_key->payload.data[0];
604
605         /*
606          * Note: since we aren't holding ->mk_secret_sem, the result here can
607          * immediately become outdated.  But there's no correctness problem with
608          * unnecessarily evicting.  Nor is there a correctness problem with not
609          * evicting while iput() is racing with the key being removed, since
610          * then the thread removing the key will either evict the inode itself
611          * or will correctly detect that it wasn't evicted due to the race.
612          */
613         return !is_master_key_secret_present(&mk->mk_secret);
614 }
615 EXPORT_SYMBOL_GPL(llcrypt_drop_inode);
616
617 bool llcrypt_has_encryption_key(const struct inode *inode)
618 {
619         /* pairs with cmpxchg_release() in llcrypt_get_encryption_info() */
620         return READ_ONCE(llcrypt_info_nocast(inode)) != NULL;
621 }
622 EXPORT_SYMBOL_GPL(llcrypt_has_encryption_key);