]> git.karo-electronics.de Git - karo-tx-linux.git/blob - fs/ext4/crypto.c
ext4 crypto: handle unexpected lack of encryption keys
[karo-tx-linux.git] / fs / ext4 / crypto.c
1 /*
2  * linux/fs/ext4/crypto.c
3  *
4  * Copyright (C) 2015, Google, Inc.
5  *
6  * This contains encryption functions for ext4
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  *
15  * This has not yet undergone a rigorous security audit.
16  *
17  * The usage of AES-XTS should conform to recommendations in NIST
18  * Special Publication 800-38E and IEEE P1619/D16.
19  */
20
21 #include <crypto/hash.h>
22 #include <crypto/sha.h>
23 #include <keys/user-type.h>
24 #include <keys/encrypted-type.h>
25 #include <linux/crypto.h>
26 #include <linux/ecryptfs.h>
27 #include <linux/gfp.h>
28 #include <linux/kernel.h>
29 #include <linux/key.h>
30 #include <linux/list.h>
31 #include <linux/mempool.h>
32 #include <linux/module.h>
33 #include <linux/mutex.h>
34 #include <linux/random.h>
35 #include <linux/scatterlist.h>
36 #include <linux/spinlock_types.h>
37
38 #include "ext4_extents.h"
39 #include "xattr.h"
40
41 /* Encryption added and removed here! (L: */
42
43 static unsigned int num_prealloc_crypto_pages = 32;
44 static unsigned int num_prealloc_crypto_ctxs = 128;
45
46 module_param(num_prealloc_crypto_pages, uint, 0444);
47 MODULE_PARM_DESC(num_prealloc_crypto_pages,
48                  "Number of crypto pages to preallocate");
49 module_param(num_prealloc_crypto_ctxs, uint, 0444);
50 MODULE_PARM_DESC(num_prealloc_crypto_ctxs,
51                  "Number of crypto contexts to preallocate");
52
53 static mempool_t *ext4_bounce_page_pool;
54
55 static LIST_HEAD(ext4_free_crypto_ctxs);
56 static DEFINE_SPINLOCK(ext4_crypto_ctx_lock);
57
58 static struct kmem_cache *ext4_crypto_ctx_cachep;
59 struct kmem_cache *ext4_crypt_info_cachep;
60
61 /**
62  * ext4_release_crypto_ctx() - Releases an encryption context
63  * @ctx: The encryption context to release.
64  *
65  * If the encryption context was allocated from the pre-allocated pool, returns
66  * it to that pool. Else, frees it.
67  *
68  * If there's a bounce page in the context, this frees that.
69  */
70 void ext4_release_crypto_ctx(struct ext4_crypto_ctx *ctx)
71 {
72         unsigned long flags;
73
74         if (ctx->flags & EXT4_WRITE_PATH_FL && ctx->w.bounce_page) {
75                 if (ctx->flags & EXT4_BOUNCE_PAGE_REQUIRES_FREE_ENCRYPT_FL)
76                         __free_page(ctx->w.bounce_page);
77                 else
78                         mempool_free(ctx->w.bounce_page, ext4_bounce_page_pool);
79         }
80         ctx->w.bounce_page = NULL;
81         ctx->w.control_page = NULL;
82         if (ctx->flags & EXT4_CTX_REQUIRES_FREE_ENCRYPT_FL) {
83                 kmem_cache_free(ext4_crypto_ctx_cachep, ctx);
84         } else {
85                 spin_lock_irqsave(&ext4_crypto_ctx_lock, flags);
86                 list_add(&ctx->free_list, &ext4_free_crypto_ctxs);
87                 spin_unlock_irqrestore(&ext4_crypto_ctx_lock, flags);
88         }
89 }
90
91 /**
92  * ext4_get_crypto_ctx() - Gets an encryption context
93  * @inode:       The inode for which we are doing the crypto
94  *
95  * Allocates and initializes an encryption context.
96  *
97  * Return: An allocated and initialized encryption context on success; error
98  * value or NULL otherwise.
99  */
100 struct ext4_crypto_ctx *ext4_get_crypto_ctx(struct inode *inode)
101 {
102         struct ext4_crypto_ctx *ctx = NULL;
103         int res = 0;
104         unsigned long flags;
105         struct ext4_crypt_info *ci = EXT4_I(inode)->i_crypt_info;
106
107         if (ci == NULL)
108                 return ERR_PTR(-ENOKEY);
109
110         /*
111          * We first try getting the ctx from a free list because in
112          * the common case the ctx will have an allocated and
113          * initialized crypto tfm, so it's probably a worthwhile
114          * optimization. For the bounce page, we first try getting it
115          * from the kernel allocator because that's just about as fast
116          * as getting it from a list and because a cache of free pages
117          * should generally be a "last resort" option for a filesystem
118          * to be able to do its job.
119          */
120         spin_lock_irqsave(&ext4_crypto_ctx_lock, flags);
121         ctx = list_first_entry_or_null(&ext4_free_crypto_ctxs,
122                                        struct ext4_crypto_ctx, free_list);
123         if (ctx)
124                 list_del(&ctx->free_list);
125         spin_unlock_irqrestore(&ext4_crypto_ctx_lock, flags);
126         if (!ctx) {
127                 ctx = kmem_cache_zalloc(ext4_crypto_ctx_cachep, GFP_NOFS);
128                 if (!ctx) {
129                         res = -ENOMEM;
130                         goto out;
131                 }
132                 ctx->flags |= EXT4_CTX_REQUIRES_FREE_ENCRYPT_FL;
133         } else {
134                 ctx->flags &= ~EXT4_CTX_REQUIRES_FREE_ENCRYPT_FL;
135         }
136         ctx->flags &= ~EXT4_WRITE_PATH_FL;
137
138 out:
139         if (res) {
140                 if (!IS_ERR_OR_NULL(ctx))
141                         ext4_release_crypto_ctx(ctx);
142                 ctx = ERR_PTR(res);
143         }
144         return ctx;
145 }
146
147 struct workqueue_struct *ext4_read_workqueue;
148 static DEFINE_MUTEX(crypto_init);
149
150 /**
151  * ext4_exit_crypto() - Shutdown the ext4 encryption system
152  */
153 void ext4_exit_crypto(void)
154 {
155         struct ext4_crypto_ctx *pos, *n;
156
157         list_for_each_entry_safe(pos, n, &ext4_free_crypto_ctxs, free_list)
158                 kmem_cache_free(ext4_crypto_ctx_cachep, pos);
159         INIT_LIST_HEAD(&ext4_free_crypto_ctxs);
160         if (ext4_bounce_page_pool)
161                 mempool_destroy(ext4_bounce_page_pool);
162         ext4_bounce_page_pool = NULL;
163         if (ext4_read_workqueue)
164                 destroy_workqueue(ext4_read_workqueue);
165         ext4_read_workqueue = NULL;
166         if (ext4_crypto_ctx_cachep)
167                 kmem_cache_destroy(ext4_crypto_ctx_cachep);
168         ext4_crypto_ctx_cachep = NULL;
169         if (ext4_crypt_info_cachep)
170                 kmem_cache_destroy(ext4_crypt_info_cachep);
171         ext4_crypt_info_cachep = NULL;
172 }
173
174 /**
175  * ext4_init_crypto() - Set up for ext4 encryption.
176  *
177  * We only call this when we start accessing encrypted files, since it
178  * results in memory getting allocated that wouldn't otherwise be used.
179  *
180  * Return: Zero on success, non-zero otherwise.
181  */
182 int ext4_init_crypto(void)
183 {
184         int i, res = -ENOMEM;
185
186         mutex_lock(&crypto_init);
187         if (ext4_read_workqueue)
188                 goto already_initialized;
189         ext4_read_workqueue = alloc_workqueue("ext4_crypto", WQ_HIGHPRI, 0);
190         if (!ext4_read_workqueue)
191                 goto fail;
192
193         ext4_crypto_ctx_cachep = KMEM_CACHE(ext4_crypto_ctx,
194                                             SLAB_RECLAIM_ACCOUNT);
195         if (!ext4_crypto_ctx_cachep)
196                 goto fail;
197
198         ext4_crypt_info_cachep = KMEM_CACHE(ext4_crypt_info,
199                                             SLAB_RECLAIM_ACCOUNT);
200         if (!ext4_crypt_info_cachep)
201                 goto fail;
202
203         for (i = 0; i < num_prealloc_crypto_ctxs; i++) {
204                 struct ext4_crypto_ctx *ctx;
205
206                 ctx = kmem_cache_zalloc(ext4_crypto_ctx_cachep, GFP_NOFS);
207                 if (!ctx) {
208                         res = -ENOMEM;
209                         goto fail;
210                 }
211                 list_add(&ctx->free_list, &ext4_free_crypto_ctxs);
212         }
213
214         ext4_bounce_page_pool =
215                 mempool_create_page_pool(num_prealloc_crypto_pages, 0);
216         if (!ext4_bounce_page_pool) {
217                 res = -ENOMEM;
218                 goto fail;
219         }
220 already_initialized:
221         mutex_unlock(&crypto_init);
222         return 0;
223 fail:
224         ext4_exit_crypto();
225         mutex_unlock(&crypto_init);
226         return res;
227 }
228
229 void ext4_restore_control_page(struct page *data_page)
230 {
231         struct ext4_crypto_ctx *ctx =
232                 (struct ext4_crypto_ctx *)page_private(data_page);
233
234         set_page_private(data_page, (unsigned long)NULL);
235         ClearPagePrivate(data_page);
236         unlock_page(data_page);
237         ext4_release_crypto_ctx(ctx);
238 }
239
240 /**
241  * ext4_crypt_complete() - The completion callback for page encryption
242  * @req: The asynchronous encryption request context
243  * @res: The result of the encryption operation
244  */
245 static void ext4_crypt_complete(struct crypto_async_request *req, int res)
246 {
247         struct ext4_completion_result *ecr = req->data;
248
249         if (res == -EINPROGRESS)
250                 return;
251         ecr->res = res;
252         complete(&ecr->completion);
253 }
254
255 typedef enum {
256         EXT4_DECRYPT = 0,
257         EXT4_ENCRYPT,
258 } ext4_direction_t;
259
260 static int ext4_page_crypto(struct ext4_crypto_ctx *ctx,
261                             struct inode *inode,
262                             ext4_direction_t rw,
263                             pgoff_t index,
264                             struct page *src_page,
265                             struct page *dest_page)
266
267 {
268         u8 xts_tweak[EXT4_XTS_TWEAK_SIZE];
269         struct ablkcipher_request *req = NULL;
270         DECLARE_EXT4_COMPLETION_RESULT(ecr);
271         struct scatterlist dst, src;
272         struct ext4_crypt_info *ci = EXT4_I(inode)->i_crypt_info;
273         struct crypto_ablkcipher *tfm = ci->ci_ctfm;
274         int res = 0;
275
276         req = ablkcipher_request_alloc(tfm, GFP_NOFS);
277         if (!req) {
278                 printk_ratelimited(KERN_ERR
279                                    "%s: crypto_request_alloc() failed\n",
280                                    __func__);
281                 return -ENOMEM;
282         }
283         ablkcipher_request_set_callback(
284                 req, CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
285                 ext4_crypt_complete, &ecr);
286
287         BUILD_BUG_ON(EXT4_XTS_TWEAK_SIZE < sizeof(index));
288         memcpy(xts_tweak, &index, sizeof(index));
289         memset(&xts_tweak[sizeof(index)], 0,
290                EXT4_XTS_TWEAK_SIZE - sizeof(index));
291
292         sg_init_table(&dst, 1);
293         sg_set_page(&dst, dest_page, PAGE_CACHE_SIZE, 0);
294         sg_init_table(&src, 1);
295         sg_set_page(&src, src_page, PAGE_CACHE_SIZE, 0);
296         ablkcipher_request_set_crypt(req, &src, &dst, PAGE_CACHE_SIZE,
297                                      xts_tweak);
298         if (rw == EXT4_DECRYPT)
299                 res = crypto_ablkcipher_decrypt(req);
300         else
301                 res = crypto_ablkcipher_encrypt(req);
302         if (res == -EINPROGRESS || res == -EBUSY) {
303                 BUG_ON(req->base.data != &ecr);
304                 wait_for_completion(&ecr.completion);
305                 res = ecr.res;
306         }
307         ablkcipher_request_free(req);
308         if (res) {
309                 printk_ratelimited(
310                         KERN_ERR
311                         "%s: crypto_ablkcipher_encrypt() returned %d\n",
312                         __func__, res);
313                 return res;
314         }
315         return 0;
316 }
317
318 static struct page *alloc_bounce_page(struct ext4_crypto_ctx *ctx)
319 {
320         struct page *ciphertext_page = alloc_page(GFP_NOFS);
321
322         if (!ciphertext_page) {
323                 /* This is a potential bottleneck, but at least we'll have
324                  * forward progress. */
325                 ciphertext_page = mempool_alloc(ext4_bounce_page_pool,
326                                                  GFP_NOFS);
327                 if (ciphertext_page == NULL)
328                         return ERR_PTR(-ENOMEM);
329                 ctx->flags &= ~EXT4_BOUNCE_PAGE_REQUIRES_FREE_ENCRYPT_FL;
330         } else {
331                 ctx->flags |= EXT4_BOUNCE_PAGE_REQUIRES_FREE_ENCRYPT_FL;
332         }
333         ctx->flags |= EXT4_WRITE_PATH_FL;
334         ctx->w.bounce_page = ciphertext_page;
335         return ciphertext_page;
336 }
337
338 /**
339  * ext4_encrypt() - Encrypts a page
340  * @inode:          The inode for which the encryption should take place
341  * @plaintext_page: The page to encrypt. Must be locked.
342  *
343  * Allocates a ciphertext page and encrypts plaintext_page into it using the ctx
344  * encryption context.
345  *
346  * Called on the page write path.  The caller must call
347  * ext4_restore_control_page() on the returned ciphertext page to
348  * release the bounce buffer and the encryption context.
349  *
350  * Return: An allocated page with the encrypted content on success. Else, an
351  * error value or NULL.
352  */
353 struct page *ext4_encrypt(struct inode *inode,
354                           struct page *plaintext_page)
355 {
356         struct ext4_crypto_ctx *ctx;
357         struct page *ciphertext_page = NULL;
358         int err;
359
360         BUG_ON(!PageLocked(plaintext_page));
361
362         ctx = ext4_get_crypto_ctx(inode);
363         if (IS_ERR(ctx))
364                 return (struct page *) ctx;
365
366         /* The encryption operation will require a bounce page. */
367         ciphertext_page = alloc_bounce_page(ctx);
368         if (IS_ERR(ciphertext_page))
369                 goto errout;
370         ctx->w.control_page = plaintext_page;
371         err = ext4_page_crypto(ctx, inode, EXT4_ENCRYPT, plaintext_page->index,
372                                plaintext_page, ciphertext_page);
373         if (err) {
374                 ciphertext_page = ERR_PTR(err);
375         errout:
376                 ext4_release_crypto_ctx(ctx);
377                 return ciphertext_page;
378         }
379         SetPagePrivate(ciphertext_page);
380         set_page_private(ciphertext_page, (unsigned long)ctx);
381         lock_page(ciphertext_page);
382         return ciphertext_page;
383 }
384
385 /**
386  * ext4_decrypt() - Decrypts a page in-place
387  * @ctx:  The encryption context.
388  * @page: The page to decrypt. Must be locked.
389  *
390  * Decrypts page in-place using the ctx encryption context.
391  *
392  * Called from the read completion callback.
393  *
394  * Return: Zero on success, non-zero otherwise.
395  */
396 int ext4_decrypt(struct ext4_crypto_ctx *ctx, struct page *page)
397 {
398         BUG_ON(!PageLocked(page));
399
400         return ext4_page_crypto(ctx, page->mapping->host,
401                                 EXT4_DECRYPT, page->index, page, page);
402 }
403
404 /*
405  * Convenience function which takes care of allocating and
406  * deallocating the encryption context
407  */
408 int ext4_decrypt_one(struct inode *inode, struct page *page)
409 {
410         int ret;
411
412         struct ext4_crypto_ctx *ctx = ext4_get_crypto_ctx(inode);
413
414         if (!ctx)
415                 return -ENOMEM;
416         ret = ext4_decrypt(ctx, page);
417         ext4_release_crypto_ctx(ctx);
418         return ret;
419 }
420
421 int ext4_encrypted_zeroout(struct inode *inode, struct ext4_extent *ex)
422 {
423         struct ext4_crypto_ctx  *ctx;
424         struct page             *ciphertext_page = NULL;
425         struct bio              *bio;
426         ext4_lblk_t             lblk = ex->ee_block;
427         ext4_fsblk_t            pblk = ext4_ext_pblock(ex);
428         unsigned int            len = ext4_ext_get_actual_len(ex);
429         int                     err = 0;
430
431         BUG_ON(inode->i_sb->s_blocksize != PAGE_CACHE_SIZE);
432
433         ctx = ext4_get_crypto_ctx(inode);
434         if (IS_ERR(ctx))
435                 return PTR_ERR(ctx);
436
437         ciphertext_page = alloc_bounce_page(ctx);
438         if (IS_ERR(ciphertext_page)) {
439                 err = PTR_ERR(ciphertext_page);
440                 goto errout;
441         }
442
443         while (len--) {
444                 err = ext4_page_crypto(ctx, inode, EXT4_ENCRYPT, lblk,
445                                        ZERO_PAGE(0), ciphertext_page);
446                 if (err)
447                         goto errout;
448
449                 bio = bio_alloc(GFP_KERNEL, 1);
450                 if (!bio) {
451                         err = -ENOMEM;
452                         goto errout;
453                 }
454                 bio->bi_bdev = inode->i_sb->s_bdev;
455                 bio->bi_iter.bi_sector = pblk;
456                 err = bio_add_page(bio, ciphertext_page,
457                                    inode->i_sb->s_blocksize, 0);
458                 if (err) {
459                         bio_put(bio);
460                         goto errout;
461                 }
462                 err = submit_bio_wait(WRITE, bio);
463                 bio_put(bio);
464                 if (err)
465                         goto errout;
466         }
467         err = 0;
468 errout:
469         ext4_release_crypto_ctx(ctx);
470         return err;
471 }
472
473 bool ext4_valid_contents_enc_mode(uint32_t mode)
474 {
475         return (mode == EXT4_ENCRYPTION_MODE_AES_256_XTS);
476 }
477
478 /**
479  * ext4_validate_encryption_key_size() - Validate the encryption key size
480  * @mode: The key mode.
481  * @size: The key size to validate.
482  *
483  * Return: The validated key size for @mode. Zero if invalid.
484  */
485 uint32_t ext4_validate_encryption_key_size(uint32_t mode, uint32_t size)
486 {
487         if (size == ext4_encryption_key_size(mode))
488                 return size;
489         return 0;
490 }