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