Whamcloud - gitweb
c28add00ebd4673e0a8515b5a7276f8678f427e4
[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_NULL] = {
26                 .friendly_name = "NULL",
27                 .cipher_str = "null",
28                 .keysize = 0,
29                 .ivsize = 0,
30         },
31         [LLCRYPT_MODE_AES_256_XTS] = {
32                 .friendly_name = "AES-256-XTS",
33                 .cipher_str = "xts(aes)",
34                 .keysize = 64,
35                 .ivsize = 16,
36         },
37         [LLCRYPT_MODE_AES_256_CTS] = {
38                 .friendly_name = "AES-256-CTS-CBC",
39                 .cipher_str = "cts(cbc(aes))",
40                 .keysize = 32,
41                 .ivsize = 16,
42         },
43         [LLCRYPT_MODE_AES_128_CBC] = {
44                 .friendly_name = "AES-128-CBC",
45                 .cipher_str = "cbc(aes)",
46                 .keysize = 16,
47                 .ivsize = 16,
48                 .needs_essiv = true,
49         },
50         [LLCRYPT_MODE_AES_128_CTS] = {
51                 .friendly_name = "AES-128-CTS-CBC",
52                 .cipher_str = "cts(cbc(aes))",
53                 .keysize = 16,
54                 .ivsize = 16,
55         },
56         [LLCRYPT_MODE_ADIANTUM] = {
57                 .friendly_name = "Adiantum",
58                 .cipher_str = "adiantum(xchacha12,aes)",
59                 .keysize = 32,
60                 .ivsize = 32,
61         },
62 };
63
64 static struct llcrypt_mode *
65 select_encryption_mode(const union llcrypt_policy *policy,
66                        const struct inode *inode)
67 {
68         if (S_ISREG(inode->i_mode))
69                 return &available_modes[llcrypt_policy_contents_mode(policy)];
70
71         if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
72                 return &available_modes[llcrypt_policy_fnames_mode(policy)];
73
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);
77 }
78
79 /* Create a symmetric cipher object for the given encryption mode and key */
80 struct crypto_skcipher *llcrypt_allocate_skcipher(struct llcrypt_mode *mode,
81                                                   const u8 *raw_key,
82                                                   const struct inode *inode)
83 {
84         struct crypto_skcipher *tfm;
85         int err;
86
87         if (!strcmp(mode->cipher_str, "null"))
88                 return NULL;
89
90         tfm = crypto_alloc_skcipher(mode->cipher_str, 0, 0);
91         if (IS_ERR(tfm)) {
92                 if (PTR_ERR(tfm) == -ENOENT) {
93                         llcrypt_warn(inode,
94                                      "Missing crypto API support for %s (API name: \"%s\")",
95                                      mode->friendly_name, mode->cipher_str);
96                         return ERR_PTR(-ENOPKG);
97                 }
98                 llcrypt_err(inode, "Error allocating '%s' transform: %ld",
99                             mode->cipher_str, PTR_ERR(tfm));
100                 return tfm;
101         }
102         if (unlikely(!mode->logged_impl_name)) {
103                 /*
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.
109                  */
110                 mode->logged_impl_name = true;
111                 pr_info("llcrypt: %s using implementation \"%s\"\n",
112                         mode->friendly_name,
113                         crypto_skcipher_alg(tfm)->base.cra_driver_name);
114         }
115         crypto_skcipher_set_flags(tfm, CRYPTO_TFM_REQ_FORBID_WEAK_KEYS);
116         err = crypto_skcipher_setkey(tfm, raw_key, mode->keysize);
117         if (err)
118                 goto err_free_tfm;
119
120         return tfm;
121
122 err_free_tfm:
123         crypto_free_skcipher(tfm);
124         return ERR_PTR(err);
125 }
126
127 static int derive_essiv_salt(const u8 *key, int keysize, u8 *salt)
128 {
129         struct crypto_shash *tfm = READ_ONCE(essiv_hash_tfm);
130
131         /* init hash transform on demand */
132         if (unlikely(!tfm)) {
133                 struct crypto_shash *prev_tfm;
134
135                 tfm = crypto_alloc_shash("sha256", 0, 0);
136                 if (IS_ERR(tfm)) {
137                         if (PTR_ERR(tfm) == -ENOENT) {
138                                 llcrypt_warn(NULL,
139                                              "Missing crypto API support for SHA-256");
140                                 return -ENOPKG;
141                         }
142                         llcrypt_err(NULL,
143                                     "Error allocating SHA-256 transform: %ld",
144                                     PTR_ERR(tfm));
145                         return PTR_ERR(tfm);
146                 }
147                 prev_tfm = cmpxchg(&essiv_hash_tfm, NULL, tfm);
148                 if (prev_tfm) {
149                         crypto_free_shash(tfm);
150                         tfm = prev_tfm;
151                 }
152         }
153
154         {
155                 SHASH_DESC_ON_STACK(desc, tfm);
156                 desc->tfm = tfm;
157
158                 return crypto_shash_digest(desc, key, keysize, salt);
159         }
160 }
161
162 static int init_essiv_generator(struct llcrypt_info *ci, const u8 *raw_key,
163                                 int keysize)
164 {
165         int err;
166         struct crypto_cipher *essiv_tfm;
167         u8 salt[SHA256_DIGEST_SIZE];
168
169         if (WARN_ON(ci->ci_mode->ivsize != AES_BLOCK_SIZE))
170                 return -EINVAL;
171
172         essiv_tfm = crypto_alloc_cipher("aes", 0, 0);
173         if (IS_ERR(essiv_tfm))
174                 return PTR_ERR(essiv_tfm);
175
176         ci->ci_essiv_tfm = essiv_tfm;
177
178         err = derive_essiv_salt(raw_key, keysize, salt);
179         if (err)
180                 goto out;
181
182         /*
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.
186          */
187         err = crypto_cipher_setkey(essiv_tfm, salt, sizeof(salt));
188         if (err)
189                 goto out;
190
191 out:
192         memzero_explicit(salt, sizeof(salt));
193         return err;
194 }
195
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)
198 {
199         struct llcrypt_mode *mode = ci->ci_mode;
200         struct crypto_skcipher *ctfm;
201         int err;
202
203         ctfm = llcrypt_allocate_skcipher(mode, derived_key, ci->ci_inode);
204         if (IS_ERR(ctfm))
205                 return PTR_ERR(ctfm);
206
207         ci->ci_ctfm = ctfm;
208
209         if (mode->needs_essiv) {
210                 err = init_essiv_generator(ci, derived_key, mode->keysize);
211                 if (err) {
212                         llcrypt_warn(ci->ci_inode,
213                                      "Error initializing ESSIV generator: %d",
214                                      err);
215                         return err;
216                 }
217         }
218         return 0;
219 }
220
221 static int setup_per_mode_key(struct llcrypt_info *ci,
222                               struct llcrypt_master_key *mk)
223 {
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];
228         int err;
229
230         if (WARN_ON(mode_num >= ARRAY_SIZE(mk->mk_mode_keys)))
231                 return -EINVAL;
232
233         /* pairs with cmpxchg() below */
234         tfm = READ_ONCE(mk->mk_mode_keys[mode_num]);
235         if (likely(tfm != NULL))
236                 goto done;
237
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);
243         if (err)
244                 return err;
245         tfm = llcrypt_allocate_skcipher(mode, mode_key, ci->ci_inode);
246         memzero_explicit(mode_key, mode->keysize);
247         if (IS_ERR(tfm))
248                 return PTR_ERR(tfm);
249
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);
254                 tfm = prev_tfm;
255         }
256 done:
257         ci->ci_ctfm = tfm;
258         return 0;
259 }
260
261 static int llcrypt_setup_v2_file_key(struct llcrypt_info *ci,
262                                      struct llcrypt_master_key *mk)
263 {
264         u8 derived_key[LLCRYPT_MAX_KEY_SIZE];
265         int err;
266
267         if (ci->ci_policy.v2.flags & LLCRYPT_POLICY_FLAG_DIRECT_KEY) {
268                 /*
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.
275                  */
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);
280                         return -EINVAL;
281                 }
282                 return setup_per_mode_key(ci, mk);
283         }
284
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);
289         if (err)
290                 return err;
291
292         err = llcrypt_set_derived_key(ci, derived_key);
293         memzero_explicit(derived_key, ci->ci_mode->keysize);
294         return err;
295 }
296
297 /*
298  * Find the master key, then set up the inode's actual encryption key.
299  *
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.
306  */
307 static int setup_file_encryption_key(struct llcrypt_info *ci,
308                                      struct key **master_key_ret)
309 {
310         struct key *key;
311         struct llcrypt_master_key *mk = NULL;
312         struct llcrypt_key_specifier mk_spec;
313         int err;
314
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);
321                 break;
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);
327                 break;
328         default:
329                 WARN_ON(1);
330                 return -EINVAL;
331         }
332
333         key = llcrypt_find_master_key(ci->ci_inode->i_sb, &mk_spec);
334         if (IS_ERR(key)) {
335                 if (key != ERR_PTR(-ENOKEY) ||
336                     ci->ci_policy.version != LLCRYPT_POLICY_V1)
337                         return PTR_ERR(key);
338
339                 /*
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.
344                  */
345                 return llcrypt_setup_v1_file_key_via_subscribed_keyrings(ci);
346         }
347
348         mk = key->payload.data[0];
349         down_read(&mk->mk_secret_sem);
350
351         /* Has the secret been removed (via LL_IOC_REMOVE_ENCRYPTION_KEY)? */
352         if (!is_master_key_secret_present(&mk->mk_secret)) {
353                 err = -ENOKEY;
354                 goto out_release_key;
355         }
356
357         /*
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.
362          */
363         if (mk->mk_secret.size < ci->ci_mode->keysize) {
364                 llcrypt_warn(NULL,
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);
369                 err = -ENOKEY;
370                 goto out_release_key;
371         }
372
373         switch (ci->ci_policy.version) {
374         case LLCRYPT_POLICY_V1:
375                 err = llcrypt_setup_v1_file_key(ci, mk->mk_secret.raw);
376                 break;
377         case LLCRYPT_POLICY_V2:
378                 err = llcrypt_setup_v2_file_key(ci, mk);
379                 break;
380         default:
381                 WARN_ON(1);
382                 err = -EINVAL;
383                 break;
384         }
385         if (err)
386                 goto out_release_key;
387
388         *master_key_ret = key;
389         return 0;
390
391 out_release_key:
392         up_read(&mk->mk_secret_sem);
393         key_put(key);
394         return err;
395 }
396
397 static void put_crypt_info(struct llcrypt_info *ci)
398 {
399         struct key *key;
400
401         if (!ci)
402                 return;
403
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)) {
408                 if (ci->ci_ctfm)
409                         crypto_free_skcipher(ci->ci_ctfm);
410                 crypto_free_cipher(ci->ci_essiv_tfm);
411         }
412
413         key = ci->ci_master_key;
414         if (key) {
415                 struct llcrypt_master_key *mk = key->payload.data[0];
416
417                 /*
418                  * Remove this inode from the list of inodes that were unlocked
419                  * with the master key.
420                  *
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.
424                  */
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))
429                         key_invalidate(key);
430                 key_put(key);
431         }
432         kmem_cache_free(llcrypt_info_cachep, ci);
433 }
434
435 int llcrypt_get_encryption_info(struct inode *inode)
436 {
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);
442         int res;
443
444         if (llcrypt_has_encryption_key(inode))
445                 return 0;
446
447         if (!lsi)
448                 return -ENOKEY;
449
450         res = llcrypt_initialize(lsi->lsi_cop->flags);
451         if (res)
452                 return res;
453
454         res = lsi->lsi_cop->get_context(inode, &ctx, sizeof(ctx));
455         if (res < 0) {
456                 if (!llcrypt_dummy_context_enabled(inode) ||
457                     IS_ENCRYPTED(inode)) {
458                         llcrypt_warn(inode,
459                                      "Error %d getting encryption context",
460                                      res);
461                         return res;
462                 }
463                 /* Fake up a context for an unencrypted directory */
464                 memset(&ctx, 0, sizeof(ctx));
465                 ctx.version = LLCRYPT_CONTEXT_V1;
466                 ctx.v1.contents_encryption_mode = LLCRYPT_MODE_AES_256_XTS;
467                 ctx.v1.filenames_encryption_mode = LLCRYPT_MODE_AES_256_CTS;
468                 memset(ctx.v1.master_key_descriptor, 0x42,
469                        LLCRYPT_KEY_DESCRIPTOR_SIZE);
470                 res = sizeof(ctx.v1);
471         }
472
473         crypt_info = kmem_cache_zalloc(llcrypt_info_cachep, GFP_NOFS);
474         if (!crypt_info)
475                 return -ENOMEM;
476
477         crypt_info->ci_inode = inode;
478
479         res = llcrypt_policy_from_context(&crypt_info->ci_policy, &ctx, res);
480         if (res) {
481                 llcrypt_warn(inode,
482                              "Unrecognized or corrupt encryption context");
483                 goto out;
484         }
485
486         switch (ctx.version) {
487         case LLCRYPT_CONTEXT_V1:
488                 memcpy(crypt_info->ci_nonce, ctx.v1.nonce,
489                        FS_KEY_DERIVATION_NONCE_SIZE);
490                 break;
491         case LLCRYPT_CONTEXT_V2:
492                 memcpy(crypt_info->ci_nonce, ctx.v2.nonce,
493                        FS_KEY_DERIVATION_NONCE_SIZE);
494                 break;
495         default:
496                 WARN_ON(1);
497                 res = -EINVAL;
498                 goto out;
499         }
500
501         if (!llcrypt_supported_policy(&crypt_info->ci_policy, inode)) {
502                 res = -EINVAL;
503                 goto out;
504         }
505
506         mode = select_encryption_mode(&crypt_info->ci_policy, inode);
507         if (IS_ERR(mode)) {
508                 res = PTR_ERR(mode);
509                 goto out;
510         }
511         WARN_ON(mode->ivsize > LLCRYPT_MAX_IV_SIZE);
512         crypt_info->ci_mode = mode;
513
514         res = setup_file_encryption_key(crypt_info, &master_key);
515         if (res)
516                 goto out;
517
518         if (cmpxchg_release(&(llcrypt_info_nocast(inode)), NULL,
519                             crypt_info) == NULL) {
520                 if (master_key) {
521                         struct llcrypt_master_key *mk =
522                                 master_key->payload.data[0];
523
524                         refcount_inc(&mk->mk_refcount);
525                         crypt_info->ci_master_key = key_get(master_key);
526                         spin_lock(&mk->mk_decrypted_inodes_lock);
527                         list_add(&crypt_info->ci_master_key_link,
528                                  &mk->mk_decrypted_inodes);
529                         spin_unlock(&mk->mk_decrypted_inodes_lock);
530                 }
531                 crypt_info = NULL;
532         }
533         res = 0;
534 out:
535         if (master_key) {
536                 struct llcrypt_master_key *mk = master_key->payload.data[0];
537
538                 up_read(&mk->mk_secret_sem);
539                 key_put(master_key);
540         }
541         if (res == -ENOKEY)
542                 res = 0;
543         put_crypt_info(crypt_info);
544         return res;
545 }
546 EXPORT_SYMBOL(llcrypt_get_encryption_info);
547
548 /**
549  * llcrypt_put_encryption_info - free most of an inode's llcrypt data
550  *
551  * Free the inode's llcrypt_info.  Filesystems must call this when the inode is
552  * being evicted.  An RCU grace period need not have elapsed yet.
553  */
554 void llcrypt_put_encryption_info(struct inode *inode)
555 {
556         put_crypt_info(llcrypt_info(inode));
557         llcrypt_info_nocast(inode) = NULL;
558 }
559 EXPORT_SYMBOL(llcrypt_put_encryption_info);
560
561 /**
562  * llcrypt_free_inode - free an inode's llcrypt data requiring RCU delay
563  *
564  * Free the inode's cached decrypted symlink target, if any.  Filesystems must
565  * call this after an RCU grace period, just before they free the inode.
566  */
567 void llcrypt_free_inode(struct inode *inode)
568 {
569         if (IS_ENCRYPTED(inode) && S_ISLNK(inode->i_mode)) {
570                 kfree(inode->i_link);
571                 inode->i_link = NULL;
572         }
573 }
574 EXPORT_SYMBOL(llcrypt_free_inode);
575
576 /**
577  * llcrypt_drop_inode - check whether the inode's master key has been removed
578  *
579  * Filesystems supporting llcrypt must call this from their ->drop_inode()
580  * method so that encrypted inodes are evicted as soon as they're no longer in
581  * use and their master key has been removed.
582  *
583  * Return: 1 if llcrypt wants the inode to be evicted now, otherwise 0
584  */
585 int llcrypt_drop_inode(struct inode *inode)
586 {
587         const struct llcrypt_info *ci;
588         const struct llcrypt_master_key *mk;
589
590         ci = (struct llcrypt_info *)READ_ONCE(llcrypt_info_nocast(inode));
591         /*
592          * If ci is NULL, then the inode doesn't have an encryption key set up
593          * so it's irrelevant.  If ci_master_key is NULL, then the master key
594          * was provided via the legacy mechanism of the process-subscribed
595          * keyrings, so we don't know whether it's been removed or not.
596          */
597         if (!ci || !ci->ci_master_key)
598                 return 0;
599         mk = ci->ci_master_key->payload.data[0];
600
601         /*
602          * Note: since we aren't holding ->mk_secret_sem, the result here can
603          * immediately become outdated.  But there's no correctness problem with
604          * unnecessarily evicting.  Nor is there a correctness problem with not
605          * evicting while iput() is racing with the key being removed, since
606          * then the thread removing the key will either evict the inode itself
607          * or will correctly detect that it wasn't evicted due to the race.
608          */
609         return !is_master_key_secret_present(&mk->mk_secret);
610 }
611 EXPORT_SYMBOL_GPL(llcrypt_drop_inode);
612
613 inline bool llcrypt_has_encryption_key(const struct inode *inode)
614 {
615         /* pairs with cmpxchg_release() in llcrypt_get_encryption_info() */
616         return READ_ONCE(llcrypt_info_nocast(inode)) != NULL;
617 }
618 EXPORT_SYMBOL_GPL(llcrypt_has_encryption_key);