Clean up whitespace and fixed a bug in the context inheritance error path
[ext4-patch-queue.git] / add-ext4-encryption-facilities
blob58e4a25065f05d13fc27051951e4a6116afcbb9c
1 ext4 crypto: add ext4 encryption facilities
3 From: Michael Halcrow <mhalcrow@google.com>
5 On encrypt, we will re-assign the buffer_heads to point to a bounce
6 page rather than the control_page (which is the original page to write
7 that contains the plaintext). The block I/O occurs against the bounce
8 page.  On write completion, we re-assign the buffer_heads to the
9 original plaintext page.
11 On decrypt, we will attach a read completion callback to the bio
12 struct. This read completion will decrypt the read contents in-place
13 prior to setting the page up-to-date.
15 The current encryption mode, AES-256-XTS, lacks cryptographic
16 integrity. AES-256-GCM is in-plan, but we will need to devise a
17 mechanism for handling the integrity data.
19 Signed-off-by: Michael Halcrow <mhalcrow@google.com>
20 Signed-off-by: Ildar Muslukhov <ildarm@google.com>
21 Signed-off-by: Theodore Ts'o <tytso@mit.edu>
22 diff --git a/fs/ext4/Makefile b/fs/ext4/Makefile
23 index 3886ee4..1b1c561 100644
24 --- a/fs/ext4/Makefile
25 +++ b/fs/ext4/Makefile
26 @@ -12,4 +12,4 @@ ext4-y        := balloc.o bitmap.o dir.o file.o fsync.o ialloc.o inode.o page-io.o \
28  ext4-$(CONFIG_EXT4_FS_POSIX_ACL)       += acl.o
29  ext4-$(CONFIG_EXT4_FS_SECURITY)                += xattr_security.o
30 -ext4-$(CONFIG_EXT4_FS_ENCRYPTION)      += crypto_policy.o
31 +ext4-$(CONFIG_EXT4_FS_ENCRYPTION)      += crypto_policy.o crypto.o
32 diff --git a/fs/ext4/crypto.c b/fs/ext4/crypto.c
33 new file mode 100644
34 index 0000000..49b1656
35 --- /dev/null
36 +++ b/fs/ext4/crypto.c
37 @@ -0,0 +1,558 @@
38 +/*
39 + * linux/fs/ext4/crypto.c
40 + *
41 + * Copyright (C) 2015, Google, Inc.
42 + *
43 + * This contains encryption functions for ext4
44 + *
45 + * Written by Michael Halcrow, 2014.
46 + *
47 + * Filename encryption additions
48 + *     Uday Savagaonkar, 2014
49 + * Encryption policy handling additions
50 + *     Ildar Muslukhov, 2014
51 + *
52 + * This has not yet undergone a rigorous security audit.
53 + *
54 + * The usage of AES-XTS should conform to recommendations in NIST
55 + * Special Publication 800-38E and IEEE P1619/D16.
56 + */
58 +#include <crypto/hash.h>
59 +#include <crypto/sha.h>
60 +#include <keys/user-type.h>
61 +#include <keys/encrypted-type.h>
62 +#include <linux/crypto.h>
63 +#include <linux/ecryptfs.h>
64 +#include <linux/gfp.h>
65 +#include <linux/kernel.h>
66 +#include <linux/key.h>
67 +#include <linux/list.h>
68 +#include <linux/mempool.h>
69 +#include <linux/module.h>
70 +#include <linux/mutex.h>
71 +#include <linux/random.h>
72 +#include <linux/scatterlist.h>
73 +#include <linux/spinlock_types.h>
75 +#include "ext4_extents.h"
76 +#include "xattr.h"
78 +/* Encryption added and removed here! (L: */
80 +static unsigned int num_prealloc_crypto_pages = 32;
81 +static unsigned int num_prealloc_crypto_ctxs = 128;
83 +module_param(num_prealloc_crypto_pages, uint, 0444);
84 +MODULE_PARM_DESC(num_prealloc_crypto_pages,
85 +                "Number of crypto pages to preallocate");
86 +module_param(num_prealloc_crypto_ctxs, uint, 0444);
87 +MODULE_PARM_DESC(num_prealloc_crypto_ctxs,
88 +                "Number of crypto contexts to preallocate");
90 +static mempool_t *ext4_bounce_page_pool;
92 +static LIST_HEAD(ext4_free_crypto_ctxs);
93 +static DEFINE_SPINLOCK(ext4_crypto_ctx_lock);
95 +/**
96 + * ext4_release_crypto_ctx() - Releases an encryption context
97 + * @ctx: The encryption context to release.
98 + *
99 + * If the encryption context was allocated from the pre-allocated pool, returns
100 + * it to that pool. Else, frees it.
101 + *
102 + * If there's a bounce page in the context, this frees that.
103 + */
104 +void ext4_release_crypto_ctx(struct ext4_crypto_ctx *ctx)
106 +       unsigned long flags;
108 +       if (ctx->bounce_page) {
109 +               if (ctx->flags & EXT4_BOUNCE_PAGE_REQUIRES_FREE_ENCRYPT_FL)
110 +                       __free_page(ctx->bounce_page);
111 +               else
112 +                       mempool_free(ctx->bounce_page, ext4_bounce_page_pool);
113 +               ctx->bounce_page = NULL;
114 +       }
115 +       ctx->control_page = NULL;
116 +       if (ctx->flags & EXT4_CTX_REQUIRES_FREE_ENCRYPT_FL) {
117 +               if (ctx->tfm)
118 +                       crypto_free_tfm(ctx->tfm);
119 +               kfree(ctx);
120 +       } else {
121 +               spin_lock_irqsave(&ext4_crypto_ctx_lock, flags);
122 +               list_add(&ctx->free_list, &ext4_free_crypto_ctxs);
123 +               spin_unlock_irqrestore(&ext4_crypto_ctx_lock, flags);
124 +       }
127 +/**
128 + * ext4_alloc_and_init_crypto_ctx() - Allocates and inits an encryption context
129 + * @mask: The allocation mask.
130 + *
131 + * Return: An allocated and initialized encryption context on success. An error
132 + * value or NULL otherwise.
133 + */
134 +static struct ext4_crypto_ctx *ext4_alloc_and_init_crypto_ctx(gfp_t mask)
136 +       struct ext4_crypto_ctx *ctx = kzalloc(sizeof(struct ext4_crypto_ctx),
137 +                                             mask);
139 +       if (!ctx)
140 +               return ERR_PTR(-ENOMEM);
141 +       return ctx;
144 +/**
145 + * ext4_get_crypto_ctx() - Gets an encryption context
146 + * @inode:       The inode for which we are doing the crypto
147 + *
148 + * Allocates and initializes an encryption context.
149 + *
150 + * Return: An allocated and initialized encryption context on success; error
151 + * value or NULL otherwise.
152 + */
153 +struct ext4_crypto_ctx *ext4_get_crypto_ctx(struct inode *inode)
155 +       struct ext4_crypto_ctx *ctx = NULL;
156 +       int res = 0;
157 +       unsigned long flags;
158 +       struct ext4_encryption_key *key = &EXT4_I(inode)->i_encryption_key;
160 +       if (!ext4_read_workqueue)
161 +               ext4_init_crypto();
163 +       /*
164 +        * We first try getting the ctx from a free list because in
165 +        * the common case the ctx will have an allocated and
166 +        * initialized crypto tfm, so it's probably a worthwhile
167 +        * optimization. For the bounce page, we first try getting it
168 +        * from the kernel allocator because that's just about as fast
169 +        * as getting it from a list and because a cache of free pages
170 +        * should generally be a "last resort" option for a filesystem
171 +        * to be able to do its job.
172 +        */
173 +       spin_lock_irqsave(&ext4_crypto_ctx_lock, flags);
174 +       ctx = list_first_entry_or_null(&ext4_free_crypto_ctxs,
175 +                                      struct ext4_crypto_ctx, free_list);
176 +       if (ctx)
177 +               list_del(&ctx->free_list);
178 +       spin_unlock_irqrestore(&ext4_crypto_ctx_lock, flags);
179 +       if (!ctx) {
180 +               ctx = ext4_alloc_and_init_crypto_ctx(GFP_NOFS);
181 +               if (IS_ERR(ctx)) {
182 +                       res = PTR_ERR(ctx);
183 +                       goto out;
184 +               }
185 +               ctx->flags |= EXT4_CTX_REQUIRES_FREE_ENCRYPT_FL;
186 +       } else {
187 +               ctx->flags &= ~EXT4_CTX_REQUIRES_FREE_ENCRYPT_FL;
188 +       }
190 +       /* Allocate a new Crypto API context if we don't already have
191 +        * one or if it isn't the right mode. */
192 +       BUG_ON(key->mode == EXT4_ENCRYPTION_MODE_INVALID);
193 +       if (ctx->tfm && (ctx->mode != key->mode)) {
194 +               crypto_free_tfm(ctx->tfm);
195 +               ctx->tfm = NULL;
196 +               ctx->mode = EXT4_ENCRYPTION_MODE_INVALID;
197 +       }
198 +       if (!ctx->tfm) {
199 +               switch (key->mode) {
200 +               case EXT4_ENCRYPTION_MODE_AES_256_XTS:
201 +                       ctx->tfm = crypto_ablkcipher_tfm(
202 +                               crypto_alloc_ablkcipher("xts(aes)", 0, 0));
203 +                       break;
204 +               case EXT4_ENCRYPTION_MODE_AES_256_GCM:
205 +                       /* TODO(mhalcrow): AEAD w/ gcm(aes);
206 +                        * crypto_aead_setauthsize() */
207 +                       ctx->tfm = ERR_PTR(-ENOTSUPP);
208 +                       break;
209 +               default:
210 +                       BUG();
211 +               }
212 +               if (IS_ERR_OR_NULL(ctx->tfm)) {
213 +                       res = PTR_ERR(ctx->tfm);
214 +                       ctx->tfm = NULL;
215 +                       goto out;
216 +               }
217 +               ctx->mode = key->mode;
218 +       }
219 +       BUG_ON(key->size != ext4_encryption_key_size(key->mode));
221 +       /* There shouldn't be a bounce page attached to the crypto
222 +        * context at this point. */
223 +       BUG_ON(ctx->bounce_page);
225 +out:
226 +       if (res) {
227 +               if (!IS_ERR_OR_NULL(ctx))
228 +                       ext4_release_crypto_ctx(ctx);
229 +               ctx = ERR_PTR(res);
230 +       }
231 +       return ctx;
234 +struct workqueue_struct *ext4_read_workqueue;
235 +static DEFINE_MUTEX(crypto_init);
237 +/**
238 + * ext4_exit_crypto() - Shutdown the ext4 encryption system
239 + */
240 +void ext4_exit_crypto(void)
242 +       struct ext4_crypto_ctx *pos, *n;
244 +       list_for_each_entry_safe(pos, n, &ext4_free_crypto_ctxs, free_list) {
245 +               if (pos->bounce_page) {
246 +                       if (pos->flags &
247 +                           EXT4_BOUNCE_PAGE_REQUIRES_FREE_ENCRYPT_FL) {
248 +                               __free_page(pos->bounce_page);
249 +                       } else {
250 +                               mempool_free(pos->bounce_page,
251 +                                            ext4_bounce_page_pool);
252 +                       }
253 +               }
254 +               if (pos->tfm)
255 +                       crypto_free_tfm(pos->tfm);
256 +               kfree(pos);
257 +       }
258 +       INIT_LIST_HEAD(&ext4_free_crypto_ctxs);
259 +       if (ext4_bounce_page_pool)
260 +               mempool_destroy(ext4_bounce_page_pool);
261 +       ext4_bounce_page_pool = NULL;
262 +       if (ext4_read_workqueue)
263 +               destroy_workqueue(ext4_read_workqueue);
264 +       ext4_read_workqueue = NULL;
267 +/**
268 + * ext4_init_crypto() - Set up for ext4 encryption.
269 + *
270 + * We only call this when we start accessing encrypted files, since it
271 + * results in memory getting allocated that wouldn't otherwise be used.
272 + *
273 + * Return: Zero on success, non-zero otherwise.
274 + */
275 +int ext4_init_crypto(void)
277 +       int i, res;
279 +       mutex_lock(&crypto_init);
280 +       if (ext4_read_workqueue)
281 +               goto already_initialized;
282 +       ext4_read_workqueue = alloc_workqueue("ext4_crypto", WQ_HIGHPRI, 0);
283 +       if (!ext4_read_workqueue) {
284 +               res = -ENOMEM;
285 +               goto fail;
286 +       }
288 +       for (i = 0; i < num_prealloc_crypto_ctxs; i++) {
289 +               struct ext4_crypto_ctx *ctx;
291 +               ctx = ext4_alloc_and_init_crypto_ctx(GFP_KERNEL);
292 +               if (IS_ERR(ctx)) {
293 +                       res = PTR_ERR(ctx);
294 +                       goto fail;
295 +               }
296 +               list_add(&ctx->free_list, &ext4_free_crypto_ctxs);
297 +       }
299 +       ext4_bounce_page_pool =
300 +               mempool_create_page_pool(num_prealloc_crypto_pages, 0);
301 +       if (!ext4_bounce_page_pool) {
302 +               res = -ENOMEM;
303 +               goto fail;
304 +       }
305 +already_initialized:
306 +       mutex_unlock(&crypto_init);
307 +       return 0;
308 +fail:
309 +       ext4_exit_crypto();
310 +       mutex_unlock(&crypto_init);
311 +       return res;
314 +void ext4_restore_control_page(struct page *data_page)
316 +       struct ext4_crypto_ctx *ctx =
317 +               (struct ext4_crypto_ctx *)page_private(data_page);
319 +       set_page_private(data_page, (unsigned long)NULL);
320 +       ClearPagePrivate(data_page);
321 +       unlock_page(data_page);
322 +       ext4_release_crypto_ctx(ctx);
325 +/**
326 + * ext4_crypt_complete() - The completion callback for page encryption
327 + * @req: The asynchronous encryption request context
328 + * @res: The result of the encryption operation
329 + */
330 +static void ext4_crypt_complete(struct crypto_async_request *req, int res)
332 +       struct ext4_completion_result *ecr = req->data;
334 +       if (res == -EINPROGRESS)
335 +               return;
336 +       ecr->res = res;
337 +       complete(&ecr->completion);
340 +typedef enum {
341 +       EXT4_DECRYPT = 0,
342 +       EXT4_ENCRYPT,
343 +} ext4_direction_t;
345 +static int ext4_page_crypto(struct ext4_crypto_ctx *ctx,
346 +                           struct inode *inode,
347 +                           ext4_direction_t rw,
348 +                           pgoff_t index,
349 +                           struct page *src_page,
350 +                           struct page *dest_page)
353 +       u8 xts_tweak[EXT4_XTS_TWEAK_SIZE];
354 +       struct ablkcipher_request *req = NULL;
355 +       DECLARE_EXT4_COMPLETION_RESULT(ecr);
356 +       struct scatterlist dst, src;
357 +       struct ext4_inode_info *ei = EXT4_I(inode);
358 +       struct crypto_ablkcipher *atfm = __crypto_ablkcipher_cast(ctx->tfm);
359 +       int res = 0;
361 +       BUG_ON(!ctx->tfm);
362 +       BUG_ON(ctx->mode != ei->i_encryption_key.mode);
364 +       if (ctx->mode != EXT4_ENCRYPTION_MODE_AES_256_XTS) {
365 +               printk_ratelimited(KERN_ERR
366 +                                  "%s: unsupported crypto algorithm: %d\n",
367 +                                  __func__, ctx->mode);
368 +               return -ENOTSUPP;
369 +       }
371 +       crypto_ablkcipher_clear_flags(atfm, ~0);
372 +       crypto_tfm_set_flags(ctx->tfm, CRYPTO_TFM_REQ_WEAK_KEY);
374 +       res = crypto_ablkcipher_setkey(atfm, ei->i_encryption_key.raw,
375 +                                      ei->i_encryption_key.size);
376 +       if (res) {
377 +               printk_ratelimited(KERN_ERR
378 +                                  "%s: crypto_ablkcipher_setkey() failed\n",
379 +                                  __func__);
380 +               return res;
381 +       }
382 +       req = ablkcipher_request_alloc(atfm, GFP_NOFS);
383 +       if (!req) {
384 +               printk_ratelimited(KERN_ERR
385 +                                  "%s: crypto_request_alloc() failed\n",
386 +                                  __func__);
387 +               return -ENOMEM;
388 +       }
389 +       ablkcipher_request_set_callback(
390 +               req, CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
391 +               ext4_crypt_complete, &ecr);
393 +       BUILD_BUG_ON(EXT4_XTS_TWEAK_SIZE < sizeof(index));
394 +       memcpy(xts_tweak, &index, sizeof(index));
395 +       memset(&xts_tweak[sizeof(index)], 0,
396 +              EXT4_XTS_TWEAK_SIZE - sizeof(index));
398 +       sg_init_table(&dst, 1);
399 +       sg_set_page(&dst, dest_page, PAGE_CACHE_SIZE, 0);
400 +       sg_init_table(&src, 1);
401 +       sg_set_page(&src, src_page, PAGE_CACHE_SIZE, 0);
402 +       ablkcipher_request_set_crypt(req, &src, &dst, PAGE_CACHE_SIZE,
403 +                                    xts_tweak);
404 +       if (rw == EXT4_DECRYPT)
405 +               res = crypto_ablkcipher_decrypt(req);
406 +       else
407 +               res = crypto_ablkcipher_encrypt(req);
408 +       if (res == -EINPROGRESS || res == -EBUSY) {
409 +               BUG_ON(req->base.data != &ecr);
410 +               wait_for_completion(&ecr.completion);
411 +               res = ecr.res;
412 +       }
413 +       ablkcipher_request_free(req);
414 +       if (res) {
415 +               printk_ratelimited(
416 +                       KERN_ERR
417 +                       "%s: crypto_ablkcipher_encrypt() returned %d\n",
418 +                       __func__, res);
419 +               return res;
420 +       }
421 +       return 0;
424 +/**
425 + * ext4_encrypt() - Encrypts a page
426 + * @inode:          The inode for which the encryption should take place
427 + * @plaintext_page: The page to encrypt. Must be locked.
428 + *
429 + * Allocates a ciphertext page and encrypts plaintext_page into it using the ctx
430 + * encryption context.
431 + *
432 + * Called on the page write path.  The caller must call
433 + * ext4_restore_control_page() on the returned ciphertext page to
434 + * release the bounce buffer and the encryption context.
435 + *
436 + * Return: An allocated page with the encrypted content on success. Else, an
437 + * error value or NULL.
438 + */
439 +struct page *ext4_encrypt(struct inode *inode,
440 +                         struct page *plaintext_page)
442 +       struct ext4_crypto_ctx *ctx;
443 +       struct page *ciphertext_page = NULL;
444 +       int err;
446 +       BUG_ON(!PageLocked(plaintext_page));
448 +       ctx = ext4_get_crypto_ctx(inode);
449 +       if (IS_ERR(ctx))
450 +               return (struct page *) ctx;
452 +       /* The encryption operation will require a bounce page. */
453 +       ciphertext_page = alloc_page(GFP_NOFS);
454 +       if (!ciphertext_page) {
455 +               /* This is a potential bottleneck, but at least we'll have
456 +                * forward progress. */
457 +               ciphertext_page = mempool_alloc(ext4_bounce_page_pool,
458 +                                                GFP_NOFS);
459 +               if (WARN_ON_ONCE(!ciphertext_page)) {
460 +                       ciphertext_page = mempool_alloc(ext4_bounce_page_pool,
461 +                                                        GFP_NOFS | __GFP_WAIT);
462 +               }
463 +               ctx->flags &= ~EXT4_BOUNCE_PAGE_REQUIRES_FREE_ENCRYPT_FL;
464 +       } else {
465 +               ctx->flags |= EXT4_BOUNCE_PAGE_REQUIRES_FREE_ENCRYPT_FL;
466 +       }
467 +       ctx->bounce_page = ciphertext_page;
468 +       ctx->control_page = plaintext_page;
469 +       err = ext4_page_crypto(ctx, inode, EXT4_ENCRYPT, plaintext_page->index,
470 +                              plaintext_page, ciphertext_page);
471 +       if (err) {
472 +               ext4_release_crypto_ctx(ctx);
473 +               return ERR_PTR(err);
474 +       }
475 +       SetPagePrivate(ciphertext_page);
476 +       set_page_private(ciphertext_page, (unsigned long)ctx);
477 +       lock_page(ciphertext_page);
478 +       return ciphertext_page;
481 +/**
482 + * ext4_decrypt() - Decrypts a page in-place
483 + * @ctx:  The encryption context.
484 + * @page: The page to decrypt. Must be locked.
485 + *
486 + * Decrypts page in-place using the ctx encryption context.
487 + *
488 + * Called from the read completion callback.
489 + *
490 + * Return: Zero on success, non-zero otherwise.
491 + */
492 +int ext4_decrypt(struct ext4_crypto_ctx *ctx, struct page *page)
494 +       BUG_ON(!PageLocked(page));
496 +       return ext4_page_crypto(ctx, page->mapping->host,
497 +                               EXT4_DECRYPT, page->index, page, page);
501 + * Convenience function which takes care of allocating and
502 + * deallocating the encryption context
503 + */
504 +int ext4_decrypt_one(struct inode *inode, struct page *page)
506 +       int ret;
508 +       struct ext4_crypto_ctx *ctx = ext4_get_crypto_ctx(inode);
510 +       if (!ctx)
511 +               return -ENOMEM;
512 +       ret = ext4_decrypt(ctx, page);
513 +       ext4_release_crypto_ctx(ctx);
514 +       return ret;
517 +int ext4_encrypted_zeroout(struct inode *inode, struct ext4_extent *ex)
519 +       struct ext4_crypto_ctx  *ctx;
520 +       struct page             *ciphertext_page = NULL;
521 +       struct bio              *bio;
522 +       ext4_lblk_t             lblk = ex->ee_block;
523 +       ext4_fsblk_t            pblk = ext4_ext_pblock(ex);
524 +       unsigned int            len = ext4_ext_get_actual_len(ex);
525 +       int                     err = 0;
527 +       BUG_ON(inode->i_sb->s_blocksize != PAGE_CACHE_SIZE);
529 +       ctx = ext4_get_crypto_ctx(inode);
530 +       if (IS_ERR(ctx))
531 +               return PTR_ERR(ctx);
533 +       ciphertext_page = alloc_page(GFP_NOFS);
534 +       if (!ciphertext_page) {
535 +               /* This is a potential bottleneck, but at least we'll have
536 +                * forward progress. */
537 +               ciphertext_page = mempool_alloc(ext4_bounce_page_pool,
538 +                                                GFP_NOFS);
539 +               if (WARN_ON_ONCE(!ciphertext_page)) {
540 +                       ciphertext_page = mempool_alloc(ext4_bounce_page_pool,
541 +                                                        GFP_NOFS | __GFP_WAIT);
542 +               }
543 +               ctx->flags &= ~EXT4_BOUNCE_PAGE_REQUIRES_FREE_ENCRYPT_FL;
544 +       } else {
545 +               ctx->flags |= EXT4_BOUNCE_PAGE_REQUIRES_FREE_ENCRYPT_FL;
546 +       }
547 +       ctx->bounce_page = ciphertext_page;
549 +       while (len--) {
550 +               err = ext4_page_crypto(ctx, inode, EXT4_ENCRYPT, lblk,
551 +                                      ZERO_PAGE(0), ciphertext_page);
552 +               if (err)
553 +                       goto errout;
555 +               bio = bio_alloc(GFP_KERNEL, 1);
556 +               if (!bio) {
557 +                       err = -ENOMEM;
558 +                       goto errout;
559 +               }
560 +               bio->bi_bdev = inode->i_sb->s_bdev;
561 +               bio->bi_iter.bi_sector = pblk;
562 +               err = bio_add_page(bio, ciphertext_page,
563 +                                  inode->i_sb->s_blocksize, 0);
564 +               if (err) {
565 +                       bio_put(bio);
566 +                       goto errout;
567 +               }
568 +               err = submit_bio_wait(WRITE, bio);
569 +               if (err)
570 +                       goto errout;
571 +       }
572 +       err = 0;
573 +errout:
574 +       ext4_release_crypto_ctx(ctx);
575 +       return err;
578 +bool ext4_valid_contents_enc_mode(uint32_t mode)
580 +       return (mode == EXT4_ENCRYPTION_MODE_AES_256_XTS);
583 +/**
584 + * ext4_validate_encryption_key_size() - Validate the encryption key size
585 + * @mode: The key mode.
586 + * @size: The key size to validate.
587 + *
588 + * Return: The validated key size for @mode. Zero if invalid.
589 + */
590 +uint32_t ext4_validate_encryption_key_size(uint32_t mode, uint32_t size)
592 +       if (size == ext4_encryption_key_size(mode))
593 +               return size;
594 +       return 0;
596 diff --git a/fs/ext4/crypto_policy.c b/fs/ext4/crypto_policy.c
597 index 532b69c..a4bf762 100644
598 --- a/fs/ext4/crypto_policy.c
599 +++ b/fs/ext4/crypto_policy.c
600 @@ -52,6 +52,13 @@ static int ext4_create_encryption_context_from_policy(
601         ctx.format = EXT4_ENCRYPTION_CONTEXT_FORMAT_V1;
602         memcpy(ctx.master_key_descriptor, policy->master_key_descriptor,
603                EXT4_KEY_DESCRIPTOR_SIZE);
604 +       if (!ext4_valid_contents_enc_mode(policy->contents_encryption_mode)) {
605 +               printk(KERN_WARNING
606 +                      "%s: Invalid contents encryption mode %d\n", __func__,
607 +                       policy->contents_encryption_mode);
608 +               res = -EINVAL;
609 +               goto out;
610 +       }
611         ctx.contents_encryption_mode = policy->contents_encryption_mode;
612         ctx.filenames_encryption_mode = policy->filenames_encryption_mode;
613         BUILD_BUG_ON(sizeof(ctx.nonce) != EXT4_KEY_DERIVATION_NONCE_SIZE);
614 @@ -60,6 +67,7 @@ static int ext4_create_encryption_context_from_policy(
615         res = ext4_xattr_set(inode, EXT4_XATTR_INDEX_ENCRYPTION,
616                              EXT4_XATTR_NAME_ENCRYPTION_CONTEXT, &ctx,
617                              sizeof(ctx), 0);
618 +out:
619         if (!res)
620                 ext4_set_inode_flag(inode, EXT4_INODE_ENCRYPT);
621         return res;
622 diff --git a/fs/ext4/ext4.h b/fs/ext4/ext4.h
623 index e0956b7..620179e 100644
624 --- a/fs/ext4/ext4.h
625 +++ b/fs/ext4/ext4.h
626 @@ -951,6 +951,11 @@ struct ext4_inode_info {
628         /* Precomputed uuid+inum+igen checksum for seeding inode checksums */
629         __u32 i_csum_seed;
631 +#ifdef CONFIG_EXT4_FS_ENCRYPTION
632 +       /* Encryption params */
633 +       struct ext4_encryption_key i_encryption_key;
634 +#endif
635  };
637  /*
638 @@ -1355,6 +1360,12 @@ struct ext4_sb_info {
639         struct ratelimit_state s_err_ratelimit_state;
640         struct ratelimit_state s_warning_ratelimit_state;
641         struct ratelimit_state s_msg_ratelimit_state;
643 +#ifdef CONFIG_EXT4_FS_ENCRYPTION
644 +       /* Encryption */
645 +       uint32_t s_file_encryption_mode;
646 +       uint32_t s_dir_encryption_mode;
647 +#endif
648  };
650  static inline struct ext4_sb_info *EXT4_SB(struct super_block *sb)
651 @@ -1470,6 +1481,18 @@ static inline void ext4_clear_state_flags(struct ext4_inode_info *ei)
652  #define EXT4_SB(sb)    (sb)
653  #endif
656 + * Returns true if the inode is inode is encrypted
657 + */
658 +static inline int ext4_encrypted_inode(struct inode *inode)
660 +#ifdef CONFIG_EXT4_FS_ENCRYPTION
661 +       return ext4_test_inode_flag(inode, EXT4_INODE_ENCRYPT);
662 +#else
663 +       return 0;
664 +#endif
667  #define NEXT_ORPHAN(inode) EXT4_I(inode)->i_dtime
669  /*
670 @@ -2014,6 +2037,35 @@ int ext4_process_policy(const struct ext4_encryption_policy *policy,
671  int ext4_get_policy(struct inode *inode,
672                     struct ext4_encryption_policy *policy);
674 +/* crypto.c */
675 +bool ext4_valid_contents_enc_mode(uint32_t mode);
676 +uint32_t ext4_validate_encryption_key_size(uint32_t mode, uint32_t size);
677 +extern struct workqueue_struct *ext4_read_workqueue;
678 +struct ext4_crypto_ctx *ext4_get_crypto_ctx(struct inode *inode);
679 +void ext4_release_crypto_ctx(struct ext4_crypto_ctx *ctx);
680 +void ext4_restore_control_page(struct page *data_page);
681 +struct page *ext4_encrypt(struct inode *inode,
682 +                         struct page *plaintext_page);
683 +int ext4_decrypt(struct ext4_crypto_ctx *ctx, struct page *page);
684 +int ext4_decrypt_one(struct inode *inode, struct page *page);
685 +int ext4_encrypted_zeroout(struct inode *inode, struct ext4_extent *ex);
687 +#ifdef CONFIG_EXT4_FS_ENCRYPTION
688 +int ext4_init_crypto(void);
689 +void ext4_exit_crypto(void);
690 +static inline int ext4_sb_has_crypto(struct super_block *sb)
692 +       return EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_ENCRYPT);
694 +#else
695 +static inline int ext4_init_crypto(void) { return 0; }
696 +static inline void ext4_exit_crypto(void) { }
697 +static inline int ext4_sb_has_crypto(struct super_block *sb)
699 +       return 0;
701 +#endif
703  /* dir.c */
704  extern int __ext4_check_dir_entry(const char *, unsigned int, struct inode *,
705                                   struct file *,
706 diff --git a/fs/ext4/ext4_crypto.h b/fs/ext4/ext4_crypto.h
707 index a69d2ba..9d5d2e5 100644
708 --- a/fs/ext4/ext4_crypto.h
709 +++ b/fs/ext4/ext4_crypto.h
710 @@ -46,4 +46,59 @@ struct ext4_encryption_context {
711         char nonce[EXT4_KEY_DERIVATION_NONCE_SIZE];
712  } __attribute__((__packed__));
714 +/* Encryption parameters */
715 +#define EXT4_XTS_TWEAK_SIZE 16
716 +#define EXT4_AES_128_ECB_KEY_SIZE 16
717 +#define EXT4_AES_256_GCM_KEY_SIZE 32
718 +#define EXT4_AES_256_CBC_KEY_SIZE 32
719 +#define EXT4_AES_256_CTS_KEY_SIZE 32
720 +#define EXT4_AES_256_XTS_KEY_SIZE 64
721 +#define EXT4_MAX_KEY_SIZE 64
723 +struct ext4_encryption_key {
724 +       uint32_t mode;
725 +       char raw[EXT4_MAX_KEY_SIZE];
726 +       uint32_t size;
729 +#define EXT4_CTX_REQUIRES_FREE_ENCRYPT_FL             0x00000001
730 +#define EXT4_BOUNCE_PAGE_REQUIRES_FREE_ENCRYPT_FL     0x00000002
732 +struct ext4_crypto_ctx {
733 +       struct crypto_tfm *tfm;         /* Crypto API context */
734 +       struct page *bounce_page;       /* Ciphertext page on write path */
735 +       struct page *control_page;      /* Original page on write path */
736 +       struct bio *bio;                /* The bio for this context */
737 +       struct work_struct work;        /* Work queue for read complete path */
738 +       struct list_head free_list;     /* Free list */
739 +       int flags;                      /* Flags */
740 +       int mode;                       /* Encryption mode for tfm */
743 +struct ext4_completion_result {
744 +       struct completion completion;
745 +       int res;
748 +#define DECLARE_EXT4_COMPLETION_RESULT(ecr) \
749 +       struct ext4_completion_result ecr = { \
750 +               COMPLETION_INITIALIZER((ecr).completion), 0 }
752 +static inline int ext4_encryption_key_size(int mode)
754 +       switch (mode) {
755 +       case EXT4_ENCRYPTION_MODE_AES_256_XTS:
756 +               return EXT4_AES_256_XTS_KEY_SIZE;
757 +       case EXT4_ENCRYPTION_MODE_AES_256_GCM:
758 +               return EXT4_AES_256_GCM_KEY_SIZE;
759 +       case EXT4_ENCRYPTION_MODE_AES_256_CBC:
760 +               return EXT4_AES_256_CBC_KEY_SIZE;
761 +       case EXT4_ENCRYPTION_MODE_AES_256_CTS:
762 +               return EXT4_AES_256_CTS_KEY_SIZE;
763 +       default:
764 +               BUG();
765 +       }
766 +       return 0;
769  #endif /* _EXT4_CRYPTO_H */
770 diff --git a/fs/ext4/super.c b/fs/ext4/super.c
771 index 74c5f53..1a44e74 100644
772 --- a/fs/ext4/super.c
773 +++ b/fs/ext4/super.c
774 @@ -893,6 +893,9 @@ static struct inode *ext4_alloc_inode(struct super_block *sb)
775         atomic_set(&ei->i_ioend_count, 0);
776         atomic_set(&ei->i_unwritten, 0);
777         INIT_WORK(&ei->i_rsv_conversion_work, ext4_end_io_rsv_work);
778 +#ifdef CONFIG_EXT4_FS_ENCRYPTION
779 +       ei->i_encryption_key.mode = EXT4_ENCRYPTION_MODE_INVALID;
780 +#endif
782         return &ei->vfs_inode;
784 @@ -3439,6 +3442,11 @@ static int ext4_fill_super(struct super_block *sb, void *data, int silent)
785         if (sb->s_bdev->bd_part)
786                 sbi->s_sectors_written_start =
787                         part_stat_read(sb->s_bdev->bd_part, sectors[1]);
788 +#ifdef CONFIG_EXT4_FS_ENCRYPTION
789 +       /* Modes of operations for file and directory encryption. */
790 +       sbi->s_file_encryption_mode = EXT4_ENCRYPTION_MODE_AES_256_XTS;
791 +       sbi->s_dir_encryption_mode = EXT4_ENCRYPTION_MODE_INVALID;
792 +#endif
794         /* Cleanup superblock name */
795         for (cp = sb->s_id; (cp = strchr(cp, '/'));)