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