Whamcloud - gitweb
LU-15003 sec: use enc pool for bounce pages
[fs/lustre-release.git] / libcfs / libcfs / crypto / crypto.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * This contains encryption functions for per-file encryption.
4  *
5  * Copyright (C) 2015, Google, Inc.
6  * Copyright (C) 2015, Motorola Mobility
7  *
8  * Written by Michael Halcrow, 2014.
9  *
10  * Filename encryption additions
11  *      Uday Savagaonkar, 2014
12  * Encryption policy handling additions
13  *      Ildar Muslukhov, 2014
14  * Add llcrypt_pullback_bio_page()
15  *      Jaegeuk Kim, 2015.
16  *
17  * This has not yet undergone a rigorous security audit.
18  *
19  * The usage of AES-XTS should conform to recommendations in NIST
20  * Special Publication 800-38E and IEEE P1619/D16.
21  */
22 /*
23  * Linux commit 219d54332a09
24  * tags/v5.4
25  */
26
27 #include <linux/pagemap.h>
28 #include <linux/mempool.h>
29 #include <linux/module.h>
30 #include <linux/scatterlist.h>
31 #include <linux/ratelimit.h>
32 #include <linux/dcache.h>
33 #include <linux/namei.h>
34 #include <crypto/aes.h>
35 #include <crypto/skcipher.h>
36 #include "llcrypt_private.h"
37
38 #ifdef HAVE_CIPHER_H
39 #include <crypto/internal/cipher.h>
40
41 MODULE_IMPORT_NS(CRYPTO_INTERNAL);
42 #endif
43
44 static unsigned int num_prealloc_crypto_pages = 32;
45 static unsigned int num_prealloc_crypto_ctxs = 128;
46
47 module_param(num_prealloc_crypto_pages, uint, 0444);
48 MODULE_PARM_DESC(num_prealloc_crypto_pages,
49                 "Number of crypto pages to preallocate");
50 module_param(num_prealloc_crypto_ctxs, uint, 0444);
51 MODULE_PARM_DESC(num_prealloc_crypto_ctxs,
52                 "Number of crypto contexts to preallocate");
53
54 static mempool_t *llcrypt_bounce_page_pool = NULL;
55
56 static LIST_HEAD(llcrypt_free_ctxs);
57 static DEFINE_SPINLOCK(llcrypt_ctx_lock);
58
59 static struct workqueue_struct *llcrypt_read_workqueue;
60 static DEFINE_MUTEX(llcrypt_init_mutex);
61
62 static struct kmem_cache *llcrypt_ctx_cachep;
63 struct kmem_cache *llcrypt_info_cachep;
64
65 void llcrypt_enqueue_decrypt_work(struct work_struct *work)
66 {
67         queue_work(llcrypt_read_workqueue, work);
68 }
69 EXPORT_SYMBOL(llcrypt_enqueue_decrypt_work);
70
71 /**
72  * llcrypt_release_ctx() - Release a decryption context
73  * @ctx: The decryption context to release.
74  *
75  * If the decryption context was allocated from the pre-allocated pool, return
76  * it to that pool.  Else, free it.
77  */
78 void llcrypt_release_ctx(struct llcrypt_ctx *ctx)
79 {
80         unsigned long flags;
81
82         if (ctx->flags & FS_CTX_REQUIRES_FREE_ENCRYPT_FL) {
83                 kmem_cache_free(llcrypt_ctx_cachep, ctx);
84         } else {
85                 spin_lock_irqsave(&llcrypt_ctx_lock, flags);
86                 list_add(&ctx->free_list, &llcrypt_free_ctxs);
87                 spin_unlock_irqrestore(&llcrypt_ctx_lock, flags);
88         }
89 }
90 EXPORT_SYMBOL(llcrypt_release_ctx);
91
92 /**
93  * llcrypt_get_ctx() - Get a decryption context
94  * @gfp_flags:   The gfp flag for memory allocation
95  *
96  * Allocate and initialize a decryption context.
97  *
98  * Return: A new decryption context on success; an ERR_PTR() otherwise.
99  */
100 struct llcrypt_ctx *llcrypt_get_ctx(gfp_t gfp_flags)
101 {
102         struct llcrypt_ctx *ctx;
103         unsigned long flags;
104
105         /*
106          * First try getting a ctx from the free list so that we don't have to
107          * call into the slab allocator.
108          */
109         spin_lock_irqsave(&llcrypt_ctx_lock, flags);
110         ctx = list_first_entry_or_null(&llcrypt_free_ctxs,
111                                         struct llcrypt_ctx, free_list);
112         if (ctx)
113                 list_del(&ctx->free_list);
114         spin_unlock_irqrestore(&llcrypt_ctx_lock, flags);
115         if (!ctx) {
116                 ctx = kmem_cache_zalloc(llcrypt_ctx_cachep, gfp_flags);
117                 if (!ctx)
118                         return ERR_PTR(-ENOMEM);
119                 ctx->flags |= FS_CTX_REQUIRES_FREE_ENCRYPT_FL;
120         } else {
121                 ctx->flags &= ~FS_CTX_REQUIRES_FREE_ENCRYPT_FL;
122         }
123         return ctx;
124 }
125 EXPORT_SYMBOL(llcrypt_get_ctx);
126
127 struct page *llcrypt_alloc_bounce_page(gfp_t gfp_flags)
128 {
129         return mempool_alloc(llcrypt_bounce_page_pool, gfp_flags);
130 }
131
132 /**
133  * llcrypt_free_bounce_page() - free a ciphertext bounce page
134  *
135  * Free a bounce page that was allocated by llcrypt_encrypt_pagecache_blocks(),
136  * or by llcrypt_alloc_bounce_page() directly.
137  */
138 void llcrypt_free_bounce_page(struct page *bounce_page)
139 {
140         if (!bounce_page)
141                 return;
142         set_page_private(bounce_page, (unsigned long)NULL);
143         ClearPagePrivate(bounce_page);
144         mempool_free(bounce_page, llcrypt_bounce_page_pool);
145 }
146 EXPORT_SYMBOL(llcrypt_free_bounce_page);
147
148 void llcrypt_generate_iv(union llcrypt_iv *iv, u64 lblk_num,
149                          const struct llcrypt_info *ci)
150 {
151         memset(iv, 0, ci->ci_mode->ivsize);
152         iv->lblk_num = cpu_to_le64(lblk_num);
153
154         if (llcrypt_is_direct_key_policy(&ci->ci_policy))
155                 memcpy(iv->nonce, ci->ci_nonce, FS_KEY_DERIVATION_NONCE_SIZE);
156
157         if (ci->ci_essiv_tfm != NULL)
158                 crypto_cipher_encrypt_one(ci->ci_essiv_tfm, iv->raw, iv->raw);
159 }
160
161 /* Encrypt or decrypt a single filesystem block of file contents */
162 int llcrypt_crypt_block(const struct inode *inode, llcrypt_direction_t rw,
163                         u64 lblk_num, struct page *src_page,
164                         struct page *dest_page, unsigned int len,
165                         unsigned int offs, gfp_t gfp_flags)
166 {
167         union llcrypt_iv iv;
168         struct skcipher_request *req = NULL;
169         DECLARE_CRYPTO_WAIT(wait);
170         struct scatterlist dst, src;
171         struct llcrypt_info *ci = llcrypt_info(inode);
172         struct crypto_skcipher *tfm = ci->ci_ctfm;
173         int res = 0;
174
175         if (tfm == NULL) {
176                 if (dest_page != src_page)
177                         memcpy(page_address(dest_page), page_address(src_page),
178                                PAGE_SIZE);
179                 return 0;
180         }
181
182         if (WARN_ON_ONCE(len <= 0))
183                 return -EINVAL;
184         if (WARN_ON_ONCE(len % LL_CRYPTO_BLOCK_SIZE != 0))
185                 return -EINVAL;
186
187         llcrypt_generate_iv(&iv, lblk_num, ci);
188
189         req = skcipher_request_alloc(tfm, gfp_flags);
190         if (!req)
191                 return -ENOMEM;
192
193         skcipher_request_set_callback(
194                 req, CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
195                 crypto_req_done, &wait);
196
197         sg_init_table(&dst, 1);
198         sg_set_page(&dst, dest_page, len, offs);
199         sg_init_table(&src, 1);
200         sg_set_page(&src, src_page, len, offs);
201         skcipher_request_set_crypt(req, &src, &dst, len, &iv);
202         if (rw == FS_DECRYPT)
203                 res = crypto_wait_req(crypto_skcipher_decrypt(req), &wait);
204         else
205                 res = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
206         skcipher_request_free(req);
207         if (res) {
208                 llcrypt_err(inode, "%scryption failed for block %llu: %d",
209                             (rw == FS_DECRYPT ? "De" : "En"), lblk_num, res);
210                 return res;
211         }
212         return 0;
213 }
214
215 /**
216  * llcrypt_encrypt_pagecache_blocks() - Encrypt filesystem blocks from a pagecache page
217  * @page:      The locked pagecache page containing the block(s) to encrypt
218  * @len:       Total size of the block(s) to encrypt.  Must be a nonzero
219  *              multiple of the filesystem's block size.
220  * @offs:      Byte offset within @page of the first block to encrypt.  Must be
221  *              a multiple of the filesystem's block size.
222  * @gfp_flags: Memory allocation flags
223  *
224  * A new bounce page is allocated, and the specified block(s) are encrypted into
225  * it.  In the bounce page, the ciphertext block(s) will be located at the same
226  * offsets at which the plaintext block(s) were located in the source page; any
227  * other parts of the bounce page will be left uninitialized.  However, normally
228  * blocksize == PAGE_SIZE and the whole page is encrypted at once.
229  *
230  * This is for use by the filesystem's ->writepages() method.
231  *
232  * Return: the new encrypted bounce page on success; an ERR_PTR() on failure
233  */
234 struct page *llcrypt_encrypt_pagecache_blocks(struct page *page,
235                                               unsigned int len,
236                                               unsigned int offs,
237                                               gfp_t gfp_flags)
238
239 {
240         const struct inode *inode = page->mapping->host;
241         const unsigned int blockbits = inode->i_blkbits;
242         const unsigned int blocksize = 1 << blockbits;
243         struct page *ciphertext_page;
244         u64 lblk_num = ((u64)page->index << (PAGE_SHIFT - blockbits)) +
245                        (offs >> blockbits);
246         unsigned int i;
247         int err;
248
249         if (WARN_ON_ONCE(!PageLocked(page)))
250                 return ERR_PTR(-EINVAL);
251
252         if (WARN_ON_ONCE(len <= 0 || !IS_ALIGNED(len | offs, blocksize)))
253                 return ERR_PTR(-EINVAL);
254
255         ciphertext_page = llcrypt_alloc_bounce_page(gfp_flags);
256         if (!ciphertext_page)
257                 return ERR_PTR(-ENOMEM);
258
259         for (i = offs; i < offs + len; i += blocksize, lblk_num++) {
260                 err = llcrypt_crypt_block(inode, FS_ENCRYPT, lblk_num,
261                                           page, ciphertext_page,
262                                           blocksize, i, gfp_flags);
263                 if (err) {
264                         llcrypt_free_bounce_page(ciphertext_page);
265                         return ERR_PTR(err);
266                 }
267         }
268         SetPagePrivate(ciphertext_page);
269         set_page_private(ciphertext_page, (unsigned long)page);
270         return ciphertext_page;
271 }
272 EXPORT_SYMBOL(llcrypt_encrypt_pagecache_blocks);
273
274 /**
275  * llcrypt_encrypt_block() - Encrypt a filesystem block in a page
276  * @inode:     The inode to which this block belongs
277  * @src:       The page containing the block to encrypt
278  * @dst:       The page which will contain the encrypted data
279  * @len:       Size of block to encrypt.  Doesn't need to be a multiple of the
280  *              fs block size, but must be a multiple of LL_CRYPTO_BLOCK_SIZE.
281  * @offs:      Byte offset within @page at which the block to encrypt begins
282  * @lblk_num:  Filesystem logical block number of the block, i.e. the 0-based
283  *              number of the block within the file
284  * @gfp_flags: Memory allocation flags
285  *
286  * Encrypt a possibly-compressed filesystem block that is located in an
287  * arbitrary page, not necessarily in the original pagecache page.  The @inode
288  * and @lblk_num must be specified, as they can't be determined from @page.
289  * The decrypted data will be stored in @dst.
290  *
291  * Return: 0 on success; -errno on failure
292  */
293 int llcrypt_encrypt_block(const struct inode *inode, struct page *src,
294                           struct page *dst, unsigned int len, unsigned int offs,
295                           u64 lblk_num, gfp_t gfp_flags)
296 {
297         return llcrypt_crypt_block(inode, FS_ENCRYPT, lblk_num, src, dst,
298                                    len, offs, gfp_flags);
299 }
300 EXPORT_SYMBOL(llcrypt_encrypt_block);
301
302 /**
303  * llcrypt_decrypt_pagecache_blocks() - Decrypt filesystem blocks in a pagecache page
304  * @page:      The locked pagecache page containing the block(s) to decrypt
305  * @len:       Total size of the block(s) to decrypt.  Must be a nonzero
306  *              multiple of the filesystem's block size.
307  * @offs:      Byte offset within @page of the first block to decrypt.  Must be
308  *              a multiple of the filesystem's block size.
309  *
310  * The specified block(s) are decrypted in-place within the pagecache page,
311  * which must still be locked and not uptodate.  Normally, blocksize ==
312  * PAGE_SIZE and the whole page is decrypted at once.
313  *
314  * This is for use by the filesystem's ->readpages() method.
315  *
316  * Return: 0 on success; -errno on failure
317  */
318 int llcrypt_decrypt_pagecache_blocks(struct page *page, unsigned int len,
319                                      unsigned int offs)
320 {
321         const struct inode *inode = page->mapping->host;
322         const unsigned int blockbits = inode->i_blkbits;
323         const unsigned int blocksize = 1 << blockbits;
324         u64 lblk_num = ((u64)page->index << (PAGE_SHIFT - blockbits)) +
325                        (offs >> blockbits);
326         unsigned int i;
327         int err;
328
329         if (WARN_ON_ONCE(!PageLocked(page)))
330                 return -EINVAL;
331
332         if (WARN_ON_ONCE(len <= 0 || !IS_ALIGNED(len | offs, blocksize)))
333                 return -EINVAL;
334
335         for (i = offs; i < offs + len; i += blocksize, lblk_num++) {
336                 err = llcrypt_crypt_block(inode, FS_DECRYPT, lblk_num, page,
337                                           page, blocksize, i, GFP_NOFS);
338                 if (err)
339                         return err;
340         }
341         return 0;
342 }
343 EXPORT_SYMBOL(llcrypt_decrypt_pagecache_blocks);
344
345 /**
346  * llcrypt_decrypt_block() - Cache a decrypted filesystem block in a page
347  * @inode:     The inode to which this block belongs
348  * @src:       The page containing the block to decrypt
349  * @dst:       The page which will contain the plain data
350  * @len:       Size of block to decrypt.  Doesn't need to be a multiple of the
351  *              fs block size, but must be a multiple of LL_CRYPTO_BLOCK_SIZE.
352  * @offs:      Byte offset within @page at which the block to decrypt begins
353  * @lblk_num:  Filesystem logical block number of the block, i.e. the 0-based
354  *              number of the block within the file
355  *
356  * Decrypt a possibly-compressed filesystem block that is located in an
357  * arbitrary page, not necessarily in the original pagecache page.  The @inode
358  * and @lblk_num must be specified, as they can't be determined from @page.
359  * The encrypted data will be stored in @dst.
360  *
361  * Return: 0 on success; -errno on failure
362  */
363 int llcrypt_decrypt_block(const struct inode *inode, struct page *src,
364                           struct page *dst, unsigned int len, unsigned int offs,
365                           u64 lblk_num, gfp_t gfp_flags)
366 {
367         return llcrypt_crypt_block(inode, FS_DECRYPT, lblk_num, src, dst,
368                                    len, offs, gfp_flags);
369 }
370 EXPORT_SYMBOL(llcrypt_decrypt_block);
371
372 /*
373  * Validate dentries in encrypted directories to make sure we aren't potentially
374  * caching stale dentries after a key has been added.
375  */
376 static int llcrypt_d_revalidate(struct dentry *dentry, unsigned int flags)
377 {
378         struct dentry *dir;
379         int err;
380         int valid;
381
382         /*
383          * Plaintext names are always valid, since llcrypt doesn't support
384          * reverting to ciphertext names without evicting the directory's inode
385          * -- which implies eviction of the dentries in the directory.
386          */
387         if (!(dentry->d_flags & DCACHE_ENCRYPTED_NAME))
388                 return 1;
389
390         /*
391          * Ciphertext name; valid if the directory's key is still unavailable.
392          *
393          * Although llcrypt forbids rename() on ciphertext names, we still must
394          * use dget_parent() here rather than use ->d_parent directly.  That's
395          * because a corrupted fs image may contain directory hard links, which
396          * the VFS handles by moving the directory's dentry tree in the dcache
397          * each time ->lookup() finds the directory and it already has a dentry
398          * elsewhere.  Thus ->d_parent can be changing, and we must safely grab
399          * a reference to some ->d_parent to prevent it from being freed.
400          */
401
402         if (flags & LOOKUP_RCU)
403                 return -ECHILD;
404
405         dir = dget_parent(dentry);
406         err = llcrypt_get_encryption_info(d_inode(dir));
407         valid = !llcrypt_has_encryption_key(d_inode(dir));
408         dput(dir);
409
410         if (err < 0)
411                 return err;
412
413         return valid;
414 }
415
416 const struct dentry_operations llcrypt_d_ops = {
417         .d_revalidate = llcrypt_d_revalidate,
418 };
419
420 static void llcrypt_destroy(void)
421 {
422         struct llcrypt_ctx *pos, *n;
423
424         list_for_each_entry_safe(pos, n, &llcrypt_free_ctxs, free_list)
425                 kmem_cache_free(llcrypt_ctx_cachep, pos);
426         INIT_LIST_HEAD(&llcrypt_free_ctxs);
427         mempool_destroy(llcrypt_bounce_page_pool);
428         llcrypt_bounce_page_pool = NULL;
429 }
430
431 /**
432  * llcrypt_initialize() - allocate major buffers for fs encryption.
433  * @cop_flags:  llcrypt operations flags
434  *
435  * We only call this when we start accessing encrypted files, since it
436  * results in memory getting allocated that wouldn't otherwise be used.
437  *
438  * Return: Zero on success, non-zero otherwise.
439  */
440 int llcrypt_initialize(unsigned int cop_flags)
441 {
442         int i, res = -ENOMEM;
443
444         /* No need to allocate a bounce page pool if this FS won't use it. */
445         if (cop_flags & LL_CFLG_OWN_PAGES)
446                 return 0;
447
448         mutex_lock(&llcrypt_init_mutex);
449         if (llcrypt_bounce_page_pool)
450                 goto already_initialized;
451
452         for (i = 0; i < num_prealloc_crypto_ctxs; i++) {
453                 struct llcrypt_ctx *ctx;
454
455                 ctx = kmem_cache_zalloc(llcrypt_ctx_cachep, GFP_NOFS);
456                 if (!ctx)
457                         goto fail;
458                 list_add(&ctx->free_list, &llcrypt_free_ctxs);
459         }
460
461         llcrypt_bounce_page_pool =
462                 mempool_create_page_pool(num_prealloc_crypto_pages, 0);
463         if (!llcrypt_bounce_page_pool)
464                 goto fail;
465
466 already_initialized:
467         mutex_unlock(&llcrypt_init_mutex);
468         return 0;
469 fail:
470         llcrypt_destroy();
471         mutex_unlock(&llcrypt_init_mutex);
472         return res;
473 }
474
475 void llcrypt_msg(const struct inode *inode, int mask,
476                  const char *fmt, ...)
477 {
478         static DEFINE_RATELIMIT_STATE(rs, DEFAULT_RATELIMIT_INTERVAL,
479                                       DEFAULT_RATELIMIT_BURST);
480         struct va_format vaf;
481         va_list args;
482
483         if (!__ratelimit(&rs))
484                 return;
485
486         va_start(args, fmt);
487         vaf.fmt = fmt;
488         vaf.va = &args;
489         if (inode)
490                 CDEBUG(mask, "llcrypt (%s, inode %lu): %pV\n",
491                        inode->i_sb->s_id, inode->i_ino, &vaf);
492         else
493                 CDEBUG(mask, "llcrypt: %pV\n", &vaf);
494         va_end(args);
495 }
496
497 /**
498  * llcrypt_init() - Set up for fs encryption.
499  */
500 int __init llcrypt_init(void)
501 {
502         int err = -ENOMEM;
503
504         /*
505          * Use an unbound workqueue to allow bios to be decrypted in parallel
506          * even when they happen to complete on the same CPU.  This sacrifices
507          * locality, but it's worthwhile since decryption is CPU-intensive.
508          *
509          * Also use a high-priority workqueue to prioritize decryption work,
510          * which blocks reads from completing, over regular application tasks.
511          */
512         llcrypt_read_workqueue = alloc_workqueue("llcrypt_read_queue",
513                                                  WQ_UNBOUND | WQ_HIGHPRI,
514                                                  num_online_cpus());
515         if (!llcrypt_read_workqueue)
516                 goto fail;
517
518         llcrypt_ctx_cachep = KMEM_CACHE(llcrypt_ctx, SLAB_RECLAIM_ACCOUNT);
519         if (!llcrypt_ctx_cachep)
520                 goto fail_free_queue;
521
522         llcrypt_info_cachep = KMEM_CACHE(llcrypt_info, SLAB_RECLAIM_ACCOUNT);
523         if (!llcrypt_info_cachep)
524                 goto fail_free_ctx;
525
526         err = llcrypt_init_keyring();
527         if (err)
528                 goto fail_free_info;
529
530         return 0;
531
532 fail_free_info:
533         kmem_cache_destroy(llcrypt_info_cachep);
534 fail_free_ctx:
535         kmem_cache_destroy(llcrypt_ctx_cachep);
536 fail_free_queue:
537         destroy_workqueue(llcrypt_read_workqueue);
538 fail:
539         return err;
540 }
541
542 /**
543  * llcrypt_exit() - Clean up for fs encryption.
544  */
545 void __exit llcrypt_exit(void)
546 {
547         llcrypt_exit_keyring();
548
549         llcrypt_destroy();
550         /*
551          * Make sure all delayed rcu free inodes are flushed before we
552          * destroy cache.
553          */
554         rcu_barrier();
555
556         kmem_cache_destroy(llcrypt_info_cachep);
557         kmem_cache_destroy(llcrypt_ctx_cachep);
558         destroy_workqueue(llcrypt_read_workqueue);
559 }