wlcore: Add RX_BA_WIN_SIZE_CHANGE_EVENT event
[linux/fpc-iii.git] / fs / ext4 / crypto.c
blob9d6c2dcf1bd055fa37db1946f8366d8240703e4b
1 /*
2 * linux/fs/ext4/crypto.c
4 * Copyright (C) 2015, Google, Inc.
6 * This contains encryption functions for ext4
8 * Written by Michael Halcrow, 2014.
10 * Filename encryption additions
11 * Uday Savagaonkar, 2014
12 * Encryption policy handling additions
13 * Ildar Muslukhov, 2014
15 * This has not yet undergone a rigorous security audit.
17 * The usage of AES-XTS should conform to recommendations in NIST
18 * Special Publication 800-38E and IEEE P1619/D16.
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 #include <linux/namei.h>
39 #include "ext4_extents.h"
40 #include "xattr.h"
42 /* Encryption added and removed here! (L: */
44 static unsigned int num_prealloc_crypto_pages = 32;
45 static unsigned int num_prealloc_crypto_ctxs = 128;
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");
54 static mempool_t *ext4_bounce_page_pool;
56 static LIST_HEAD(ext4_free_crypto_ctxs);
57 static DEFINE_SPINLOCK(ext4_crypto_ctx_lock);
59 static struct kmem_cache *ext4_crypto_ctx_cachep;
60 struct kmem_cache *ext4_crypt_info_cachep;
62 /**
63 * ext4_release_crypto_ctx() - Releases an encryption context
64 * @ctx: The encryption context to release.
66 * If the encryption context was allocated from the pre-allocated pool, returns
67 * it to that pool. Else, frees it.
69 * If there's a bounce page in the context, this frees that.
71 void ext4_release_crypto_ctx(struct ext4_crypto_ctx *ctx)
73 unsigned long flags;
75 if (ctx->flags & EXT4_WRITE_PATH_FL && ctx->w.bounce_page)
76 mempool_free(ctx->w.bounce_page, ext4_bounce_page_pool);
77 ctx->w.bounce_page = NULL;
78 ctx->w.control_page = NULL;
79 if (ctx->flags & EXT4_CTX_REQUIRES_FREE_ENCRYPT_FL) {
80 kmem_cache_free(ext4_crypto_ctx_cachep, ctx);
81 } else {
82 spin_lock_irqsave(&ext4_crypto_ctx_lock, flags);
83 list_add(&ctx->free_list, &ext4_free_crypto_ctxs);
84 spin_unlock_irqrestore(&ext4_crypto_ctx_lock, flags);
88 /**
89 * ext4_get_crypto_ctx() - Gets an encryption context
90 * @inode: The inode for which we are doing the crypto
92 * Allocates and initializes an encryption context.
94 * Return: An allocated and initialized encryption context on success; error
95 * value or NULL otherwise.
97 struct ext4_crypto_ctx *ext4_get_crypto_ctx(struct inode *inode)
99 struct ext4_crypto_ctx *ctx = NULL;
100 int res = 0;
101 unsigned long flags;
102 struct ext4_crypt_info *ci = EXT4_I(inode)->i_crypt_info;
104 if (ci == NULL)
105 return ERR_PTR(-ENOKEY);
108 * We first try getting the ctx from a free list because in
109 * the common case the ctx will have an allocated and
110 * initialized crypto tfm, so it's probably a worthwhile
111 * optimization. For the bounce page, we first try getting it
112 * from the kernel allocator because that's just about as fast
113 * as getting it from a list and because a cache of free pages
114 * should generally be a "last resort" option for a filesystem
115 * to be able to do its job.
117 spin_lock_irqsave(&ext4_crypto_ctx_lock, flags);
118 ctx = list_first_entry_or_null(&ext4_free_crypto_ctxs,
119 struct ext4_crypto_ctx, free_list);
120 if (ctx)
121 list_del(&ctx->free_list);
122 spin_unlock_irqrestore(&ext4_crypto_ctx_lock, flags);
123 if (!ctx) {
124 ctx = kmem_cache_zalloc(ext4_crypto_ctx_cachep, GFP_NOFS);
125 if (!ctx) {
126 res = -ENOMEM;
127 goto out;
129 ctx->flags |= EXT4_CTX_REQUIRES_FREE_ENCRYPT_FL;
130 } else {
131 ctx->flags &= ~EXT4_CTX_REQUIRES_FREE_ENCRYPT_FL;
133 ctx->flags &= ~EXT4_WRITE_PATH_FL;
135 out:
136 if (res) {
137 if (!IS_ERR_OR_NULL(ctx))
138 ext4_release_crypto_ctx(ctx);
139 ctx = ERR_PTR(res);
141 return ctx;
144 struct workqueue_struct *ext4_read_workqueue;
145 static DEFINE_MUTEX(crypto_init);
148 * ext4_exit_crypto() - Shutdown the ext4 encryption system
150 void ext4_exit_crypto(void)
152 struct ext4_crypto_ctx *pos, *n;
154 list_for_each_entry_safe(pos, n, &ext4_free_crypto_ctxs, free_list)
155 kmem_cache_free(ext4_crypto_ctx_cachep, pos);
156 INIT_LIST_HEAD(&ext4_free_crypto_ctxs);
157 if (ext4_bounce_page_pool)
158 mempool_destroy(ext4_bounce_page_pool);
159 ext4_bounce_page_pool = NULL;
160 if (ext4_read_workqueue)
161 destroy_workqueue(ext4_read_workqueue);
162 ext4_read_workqueue = NULL;
163 if (ext4_crypto_ctx_cachep)
164 kmem_cache_destroy(ext4_crypto_ctx_cachep);
165 ext4_crypto_ctx_cachep = NULL;
166 if (ext4_crypt_info_cachep)
167 kmem_cache_destroy(ext4_crypt_info_cachep);
168 ext4_crypt_info_cachep = NULL;
172 * ext4_init_crypto() - Set up for ext4 encryption.
174 * We only call this when we start accessing encrypted files, since it
175 * results in memory getting allocated that wouldn't otherwise be used.
177 * Return: Zero on success, non-zero otherwise.
179 int ext4_init_crypto(void)
181 int i, res = -ENOMEM;
183 mutex_lock(&crypto_init);
184 if (ext4_read_workqueue)
185 goto already_initialized;
186 ext4_read_workqueue = alloc_workqueue("ext4_crypto", WQ_HIGHPRI, 0);
187 if (!ext4_read_workqueue)
188 goto fail;
190 ext4_crypto_ctx_cachep = KMEM_CACHE(ext4_crypto_ctx,
191 SLAB_RECLAIM_ACCOUNT);
192 if (!ext4_crypto_ctx_cachep)
193 goto fail;
195 ext4_crypt_info_cachep = KMEM_CACHE(ext4_crypt_info,
196 SLAB_RECLAIM_ACCOUNT);
197 if (!ext4_crypt_info_cachep)
198 goto fail;
200 for (i = 0; i < num_prealloc_crypto_ctxs; i++) {
201 struct ext4_crypto_ctx *ctx;
203 ctx = kmem_cache_zalloc(ext4_crypto_ctx_cachep, GFP_NOFS);
204 if (!ctx) {
205 res = -ENOMEM;
206 goto fail;
208 list_add(&ctx->free_list, &ext4_free_crypto_ctxs);
211 ext4_bounce_page_pool =
212 mempool_create_page_pool(num_prealloc_crypto_pages, 0);
213 if (!ext4_bounce_page_pool) {
214 res = -ENOMEM;
215 goto fail;
217 already_initialized:
218 mutex_unlock(&crypto_init);
219 return 0;
220 fail:
221 ext4_exit_crypto();
222 mutex_unlock(&crypto_init);
223 return res;
226 void ext4_restore_control_page(struct page *data_page)
228 struct ext4_crypto_ctx *ctx =
229 (struct ext4_crypto_ctx *)page_private(data_page);
231 set_page_private(data_page, (unsigned long)NULL);
232 ClearPagePrivate(data_page);
233 unlock_page(data_page);
234 ext4_release_crypto_ctx(ctx);
238 * ext4_crypt_complete() - The completion callback for page encryption
239 * @req: The asynchronous encryption request context
240 * @res: The result of the encryption operation
242 static void ext4_crypt_complete(struct crypto_async_request *req, int res)
244 struct ext4_completion_result *ecr = req->data;
246 if (res == -EINPROGRESS)
247 return;
248 ecr->res = res;
249 complete(&ecr->completion);
252 typedef enum {
253 EXT4_DECRYPT = 0,
254 EXT4_ENCRYPT,
255 } ext4_direction_t;
257 static int ext4_page_crypto(struct inode *inode,
258 ext4_direction_t rw,
259 pgoff_t index,
260 struct page *src_page,
261 struct page *dest_page)
264 u8 xts_tweak[EXT4_XTS_TWEAK_SIZE];
265 struct ablkcipher_request *req = NULL;
266 DECLARE_EXT4_COMPLETION_RESULT(ecr);
267 struct scatterlist dst, src;
268 struct ext4_crypt_info *ci = EXT4_I(inode)->i_crypt_info;
269 struct crypto_ablkcipher *tfm = ci->ci_ctfm;
270 int res = 0;
272 req = ablkcipher_request_alloc(tfm, GFP_NOFS);
273 if (!req) {
274 printk_ratelimited(KERN_ERR
275 "%s: crypto_request_alloc() failed\n",
276 __func__);
277 return -ENOMEM;
279 ablkcipher_request_set_callback(
280 req, CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
281 ext4_crypt_complete, &ecr);
283 BUILD_BUG_ON(EXT4_XTS_TWEAK_SIZE < sizeof(index));
284 memcpy(xts_tweak, &index, sizeof(index));
285 memset(&xts_tweak[sizeof(index)], 0,
286 EXT4_XTS_TWEAK_SIZE - sizeof(index));
288 sg_init_table(&dst, 1);
289 sg_set_page(&dst, dest_page, PAGE_CACHE_SIZE, 0);
290 sg_init_table(&src, 1);
291 sg_set_page(&src, src_page, PAGE_CACHE_SIZE, 0);
292 ablkcipher_request_set_crypt(req, &src, &dst, PAGE_CACHE_SIZE,
293 xts_tweak);
294 if (rw == EXT4_DECRYPT)
295 res = crypto_ablkcipher_decrypt(req);
296 else
297 res = crypto_ablkcipher_encrypt(req);
298 if (res == -EINPROGRESS || res == -EBUSY) {
299 wait_for_completion(&ecr.completion);
300 res = ecr.res;
302 ablkcipher_request_free(req);
303 if (res) {
304 printk_ratelimited(
305 KERN_ERR
306 "%s: crypto_ablkcipher_encrypt() returned %d\n",
307 __func__, res);
308 return res;
310 return 0;
313 static struct page *alloc_bounce_page(struct ext4_crypto_ctx *ctx)
315 ctx->w.bounce_page = mempool_alloc(ext4_bounce_page_pool, GFP_NOWAIT);
316 if (ctx->w.bounce_page == NULL)
317 return ERR_PTR(-ENOMEM);
318 ctx->flags |= EXT4_WRITE_PATH_FL;
319 return ctx->w.bounce_page;
323 * ext4_encrypt() - Encrypts a page
324 * @inode: The inode for which the encryption should take place
325 * @plaintext_page: The page to encrypt. Must be locked.
327 * Allocates a ciphertext page and encrypts plaintext_page into it using the ctx
328 * encryption context.
330 * Called on the page write path. The caller must call
331 * ext4_restore_control_page() on the returned ciphertext page to
332 * release the bounce buffer and the encryption context.
334 * Return: An allocated page with the encrypted content on success. Else, an
335 * error value or NULL.
337 struct page *ext4_encrypt(struct inode *inode,
338 struct page *plaintext_page)
340 struct ext4_crypto_ctx *ctx;
341 struct page *ciphertext_page = NULL;
342 int err;
344 BUG_ON(!PageLocked(plaintext_page));
346 ctx = ext4_get_crypto_ctx(inode);
347 if (IS_ERR(ctx))
348 return (struct page *) ctx;
350 /* The encryption operation will require a bounce page. */
351 ciphertext_page = alloc_bounce_page(ctx);
352 if (IS_ERR(ciphertext_page))
353 goto errout;
354 ctx->w.control_page = plaintext_page;
355 err = ext4_page_crypto(inode, EXT4_ENCRYPT, plaintext_page->index,
356 plaintext_page, ciphertext_page);
357 if (err) {
358 ciphertext_page = ERR_PTR(err);
359 errout:
360 ext4_release_crypto_ctx(ctx);
361 return ciphertext_page;
363 SetPagePrivate(ciphertext_page);
364 set_page_private(ciphertext_page, (unsigned long)ctx);
365 lock_page(ciphertext_page);
366 return ciphertext_page;
370 * ext4_decrypt() - Decrypts a page in-place
371 * @ctx: The encryption context.
372 * @page: The page to decrypt. Must be locked.
374 * Decrypts page in-place using the ctx encryption context.
376 * Called from the read completion callback.
378 * Return: Zero on success, non-zero otherwise.
380 int ext4_decrypt(struct page *page)
382 BUG_ON(!PageLocked(page));
384 return ext4_page_crypto(page->mapping->host,
385 EXT4_DECRYPT, page->index, page, page);
388 int ext4_encrypted_zeroout(struct inode *inode, struct ext4_extent *ex)
390 struct ext4_crypto_ctx *ctx;
391 struct page *ciphertext_page = NULL;
392 struct bio *bio;
393 ext4_lblk_t lblk = le32_to_cpu(ex->ee_block);
394 ext4_fsblk_t pblk = ext4_ext_pblock(ex);
395 unsigned int len = ext4_ext_get_actual_len(ex);
396 int ret, err = 0;
398 #if 0
399 ext4_msg(inode->i_sb, KERN_CRIT,
400 "ext4_encrypted_zeroout ino %lu lblk %u len %u",
401 (unsigned long) inode->i_ino, lblk, len);
402 #endif
404 BUG_ON(inode->i_sb->s_blocksize != PAGE_CACHE_SIZE);
406 ctx = ext4_get_crypto_ctx(inode);
407 if (IS_ERR(ctx))
408 return PTR_ERR(ctx);
410 ciphertext_page = alloc_bounce_page(ctx);
411 if (IS_ERR(ciphertext_page)) {
412 err = PTR_ERR(ciphertext_page);
413 goto errout;
416 while (len--) {
417 err = ext4_page_crypto(inode, EXT4_ENCRYPT, lblk,
418 ZERO_PAGE(0), ciphertext_page);
419 if (err)
420 goto errout;
422 bio = bio_alloc(GFP_KERNEL, 1);
423 if (!bio) {
424 err = -ENOMEM;
425 goto errout;
427 bio->bi_bdev = inode->i_sb->s_bdev;
428 bio->bi_iter.bi_sector =
429 pblk << (inode->i_sb->s_blocksize_bits - 9);
430 ret = bio_add_page(bio, ciphertext_page,
431 inode->i_sb->s_blocksize, 0);
432 if (ret != inode->i_sb->s_blocksize) {
433 /* should never happen! */
434 ext4_msg(inode->i_sb, KERN_ERR,
435 "bio_add_page failed: %d", ret);
436 WARN_ON(1);
437 bio_put(bio);
438 err = -EIO;
439 goto errout;
441 err = submit_bio_wait(WRITE, bio);
442 if ((err == 0) && bio->bi_error)
443 err = -EIO;
444 bio_put(bio);
445 if (err)
446 goto errout;
447 lblk++; pblk++;
449 err = 0;
450 errout:
451 ext4_release_crypto_ctx(ctx);
452 return err;
455 bool ext4_valid_contents_enc_mode(uint32_t mode)
457 return (mode == EXT4_ENCRYPTION_MODE_AES_256_XTS);
461 * ext4_validate_encryption_key_size() - Validate the encryption key size
462 * @mode: The key mode.
463 * @size: The key size to validate.
465 * Return: The validated key size for @mode. Zero if invalid.
467 uint32_t ext4_validate_encryption_key_size(uint32_t mode, uint32_t size)
469 if (size == ext4_encryption_key_size(mode))
470 return size;
471 return 0;
475 * Validate dentries for encrypted directories to make sure we aren't
476 * potentially caching stale data after a key has been added or
477 * removed.
479 static int ext4_d_revalidate(struct dentry *dentry, unsigned int flags)
481 struct dentry *dir;
482 struct ext4_crypt_info *ci;
483 int dir_has_key, cached_with_key;
485 if (flags & LOOKUP_RCU)
486 return -ECHILD;
488 dir = dget_parent(dentry);
489 if (!ext4_encrypted_inode(d_inode(dir))) {
490 dput(dir);
491 return 0;
493 ci = EXT4_I(d_inode(dir))->i_crypt_info;
495 /* this should eventually be an flag in d_flags */
496 cached_with_key = dentry->d_fsdata != NULL;
497 dir_has_key = (ci != NULL);
498 dput(dir);
501 * If the dentry was cached without the key, and it is a
502 * negative dentry, it might be a valid name. We can't check
503 * if the key has since been made available due to locking
504 * reasons, so we fail the validation so ext4_lookup() can do
505 * this check.
507 * We also fail the validation if the dentry was created with
508 * the key present, but we no longer have the key, or vice versa.
510 if ((!cached_with_key && d_is_negative(dentry)) ||
511 (!cached_with_key && dir_has_key) ||
512 (cached_with_key && !dir_has_key)) {
513 #if 0 /* Revalidation debug */
514 char buf[80];
515 char *cp = simple_dname(dentry, buf, sizeof(buf));
517 if (IS_ERR(cp))
518 cp = (char *) "???";
519 pr_err("revalidate: %s %p %d %d %d\n", cp, dentry->d_fsdata,
520 cached_with_key, d_is_negative(dentry),
521 dir_has_key);
522 #endif
523 return 0;
525 return 1;
528 const struct dentry_operations ext4_encrypted_d_ops = {
529 .d_revalidate = ext4_d_revalidate,