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