blob: 70a75135688d059f5deb9f7cef0aa3528b171920 [file] [log] [blame]
rjw1f884582022-01-06 17:20:42 +08001/*
2 * This contains encryption functions for per-file encryption.
3 *
4 * Copyright (C) 2015, Google, Inc.
5 * Copyright (C) 2015, Motorola Mobility
6 *
7 * Written by Michael Halcrow, 2014.
8 *
9 * Filename encryption additions
10 * Uday Savagaonkar, 2014
11 * Encryption policy handling additions
12 * Ildar Muslukhov, 2014
13 * Add fscrypt_pullback_bio_page()
14 * Jaegeuk Kim, 2015.
15 *
16 * This has not yet undergone a rigorous security audit.
17 *
18 * The usage of AES-XTS should conform to recommendations in NIST
19 * Special Publication 800-38E and IEEE P1619/D16.
20 */
21
22#include <linux/pagemap.h>
23#include <linux/mempool.h>
24#include <linux/module.h>
25#include <linux/scatterlist.h>
26#include <linux/ratelimit.h>
27#include <linux/dcache.h>
28#include <linux/namei.h>
29#include <crypto/aes.h>
30#include <crypto/skcipher.h>
31#include "fscrypt_private.h"
32
33static unsigned int num_prealloc_crypto_pages = 32;
34static unsigned int num_prealloc_crypto_ctxs = 128;
35
36module_param(num_prealloc_crypto_pages, uint, 0444);
37MODULE_PARM_DESC(num_prealloc_crypto_pages,
38 "Number of crypto pages to preallocate");
39module_param(num_prealloc_crypto_ctxs, uint, 0444);
40MODULE_PARM_DESC(num_prealloc_crypto_ctxs,
41 "Number of crypto contexts to preallocate");
42
43static mempool_t *fscrypt_bounce_page_pool = NULL;
44
45static LIST_HEAD(fscrypt_free_ctxs);
46static DEFINE_SPINLOCK(fscrypt_ctx_lock);
47
48static struct workqueue_struct *fscrypt_read_workqueue;
49static DEFINE_MUTEX(fscrypt_init_mutex);
50
51static struct kmem_cache *fscrypt_ctx_cachep;
52struct kmem_cache *fscrypt_info_cachep;
53
54void fscrypt_enqueue_decrypt_work(struct work_struct *work)
55{
56 queue_work(fscrypt_read_workqueue, work);
57}
58EXPORT_SYMBOL(fscrypt_enqueue_decrypt_work);
59
60/**
61 * fscrypt_release_ctx() - Releases an encryption context
62 * @ctx: The encryption context to release.
63 *
64 * If the encryption context was allocated from the pre-allocated pool, returns
65 * it to that pool. Else, frees it.
66 *
67 * If there's a bounce page in the context, this frees that.
68 */
69void fscrypt_release_ctx(struct fscrypt_ctx *ctx)
70{
71 unsigned long flags;
72
73 if (ctx->flags & FS_CTX_HAS_BOUNCE_BUFFER_FL && ctx->w.bounce_page) {
74 mempool_free(ctx->w.bounce_page, fscrypt_bounce_page_pool);
75 ctx->w.bounce_page = NULL;
76 }
77 ctx->w.control_page = NULL;
78 if (ctx->flags & FS_CTX_REQUIRES_FREE_ENCRYPT_FL) {
79 kmem_cache_free(fscrypt_ctx_cachep, ctx);
80 } else {
81 spin_lock_irqsave(&fscrypt_ctx_lock, flags);
82 list_add(&ctx->free_list, &fscrypt_free_ctxs);
83 spin_unlock_irqrestore(&fscrypt_ctx_lock, flags);
84 }
85}
86EXPORT_SYMBOL(fscrypt_release_ctx);
87
88/**
89 * fscrypt_get_ctx() - Gets an encryption context
90 * @inode: The inode for which we are doing the crypto
91 * @gfp_flags: The gfp flag for memory allocation
92 *
93 * Allocates and initializes an encryption context.
94 *
95 * Return: An allocated and initialized encryption context on success; error
96 * value or NULL otherwise.
97 */
98struct fscrypt_ctx *fscrypt_get_ctx(const struct inode *inode, gfp_t gfp_flags)
99{
100 struct fscrypt_ctx *ctx = NULL;
101 struct fscrypt_info *ci = inode->i_crypt_info;
102 unsigned long flags;
103
104 if (ci == NULL)
105 return ERR_PTR(-ENOKEY);
106
107 /*
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.
116 */
117 spin_lock_irqsave(&fscrypt_ctx_lock, flags);
118 ctx = list_first_entry_or_null(&fscrypt_free_ctxs,
119 struct fscrypt_ctx, free_list);
120 if (ctx)
121 list_del(&ctx->free_list);
122 spin_unlock_irqrestore(&fscrypt_ctx_lock, flags);
123 if (!ctx) {
124 ctx = kmem_cache_zalloc(fscrypt_ctx_cachep, gfp_flags);
125 if (!ctx)
126 return ERR_PTR(-ENOMEM);
127 ctx->flags |= FS_CTX_REQUIRES_FREE_ENCRYPT_FL;
128 } else {
129 ctx->flags &= ~FS_CTX_REQUIRES_FREE_ENCRYPT_FL;
130 }
131 ctx->flags &= ~FS_CTX_HAS_BOUNCE_BUFFER_FL;
132 return ctx;
133}
134EXPORT_SYMBOL(fscrypt_get_ctx);
135
136int fscrypt_do_page_crypto(const struct inode *inode, fscrypt_direction_t rw,
137 u64 lblk_num, struct page *src_page,
138 struct page *dest_page, unsigned int len,
139 unsigned int offs, gfp_t gfp_flags)
140{
141 struct {
142 __le64 index;
143 u8 padding[FS_IV_SIZE - sizeof(__le64)];
144 } iv;
145 struct skcipher_request *req = NULL;
146 DECLARE_CRYPTO_WAIT(wait);
147 struct scatterlist dst, src;
148 struct fscrypt_info *ci = inode->i_crypt_info;
149 struct crypto_skcipher *tfm = ci->ci_ctfm;
150 int res = 0;
151
152 if (WARN_ON_ONCE(len <= 0))
153 return -EINVAL;
154 if (WARN_ON_ONCE(len % FS_CRYPTO_BLOCK_SIZE != 0))
155 return -EINVAL;
156
157 BUILD_BUG_ON(sizeof(iv) != FS_IV_SIZE);
158 BUILD_BUG_ON(AES_BLOCK_SIZE != FS_IV_SIZE);
159 iv.index = cpu_to_le64(lblk_num);
160 memset(iv.padding, 0, sizeof(iv.padding));
161
162 if (ci->ci_essiv_tfm != NULL) {
163 crypto_cipher_encrypt_one(ci->ci_essiv_tfm, (u8 *)&iv,
164 (u8 *)&iv);
165 }
166
167 req = skcipher_request_alloc(tfm, gfp_flags);
168 if (!req) {
169 printk_ratelimited(KERN_ERR
170 "%s: crypto_request_alloc() failed\n",
171 __func__);
172 return -ENOMEM;
173 }
174
175 skcipher_request_set_callback(
176 req, CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
177 crypto_req_done, &wait);
178
179 sg_init_table(&dst, 1);
180 sg_set_page(&dst, dest_page, len, offs);
181 sg_init_table(&src, 1);
182 sg_set_page(&src, src_page, len, offs);
183 skcipher_request_set_crypt(req, &src, &dst, len, &iv);
184 if (rw == FS_DECRYPT)
185 res = crypto_wait_req(crypto_skcipher_decrypt(req), &wait);
186 else
187 res = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
188 skcipher_request_free(req);
189 if (res) {
190 printk_ratelimited(KERN_ERR
191 "%s: crypto_skcipher_encrypt() returned %d\n",
192 __func__, res);
193 return res;
194 }
195 return 0;
196}
197
198struct page *fscrypt_alloc_bounce_page(struct fscrypt_ctx *ctx,
199 gfp_t gfp_flags)
200{
201 ctx->w.bounce_page = mempool_alloc(fscrypt_bounce_page_pool, gfp_flags);
202 if (ctx->w.bounce_page == NULL)
203 return ERR_PTR(-ENOMEM);
204 ctx->flags |= FS_CTX_HAS_BOUNCE_BUFFER_FL;
205 return ctx->w.bounce_page;
206}
207
208/**
209 * fscypt_encrypt_page() - Encrypts a page
210 * @inode: The inode for which the encryption should take place
211 * @page: The page to encrypt. Must be locked for bounce-page
212 * encryption.
213 * @len: Length of data to encrypt in @page and encrypted
214 * data in returned page.
215 * @offs: Offset of data within @page and returned
216 * page holding encrypted data.
217 * @lblk_num: Logical block number. This must be unique for multiple
218 * calls with same inode, except when overwriting
219 * previously written data.
220 * @gfp_flags: The gfp flag for memory allocation
221 *
222 * Encrypts @page using the ctx encryption context. Performs encryption
223 * either in-place or into a newly allocated bounce page.
224 * Called on the page write path.
225 *
226 * Bounce page allocation is the default.
227 * In this case, the contents of @page are encrypted and stored in an
228 * allocated bounce page. @page has to be locked and the caller must call
229 * fscrypt_restore_control_page() on the returned ciphertext page to
230 * release the bounce buffer and the encryption context.
231 *
232 * In-place encryption is used by setting the FS_CFLG_OWN_PAGES flag in
233 * fscrypt_operations. Here, the input-page is returned with its content
234 * encrypted.
235 *
236 * Return: A page with the encrypted content on success. Else, an
237 * error value or NULL.
238 */
239struct page *fscrypt_encrypt_page(const struct inode *inode,
240 struct page *page,
241 unsigned int len,
242 unsigned int offs,
243 u64 lblk_num, gfp_t gfp_flags)
244
245{
246 struct fscrypt_ctx *ctx;
247 struct page *ciphertext_page = page;
248 int err;
249
250 if (inode->i_sb->s_cop->flags & FS_CFLG_OWN_PAGES) {
251 /* with inplace-encryption we just encrypt the page */
252 err = fscrypt_do_page_crypto(inode, FS_ENCRYPT, lblk_num, page,
253 ciphertext_page, len, offs,
254 gfp_flags);
255 if (err)
256 return ERR_PTR(err);
257
258 return ciphertext_page;
259 }
260
261 if (WARN_ON_ONCE(!PageLocked(page)))
262 return ERR_PTR(-EINVAL);
263
264 ctx = fscrypt_get_ctx(inode, gfp_flags);
265 if (IS_ERR(ctx))
266 return (struct page *)ctx;
267
268 /* The encryption operation will require a bounce page. */
269 ciphertext_page = fscrypt_alloc_bounce_page(ctx, gfp_flags);
270 if (IS_ERR(ciphertext_page))
271 goto errout;
272
273 ctx->w.control_page = page;
274 err = fscrypt_do_page_crypto(inode, FS_ENCRYPT, lblk_num,
275 page, ciphertext_page, len, offs,
276 gfp_flags);
277 if (err) {
278 ciphertext_page = ERR_PTR(err);
279 goto errout;
280 }
281 SetPagePrivate(ciphertext_page);
282 set_page_private(ciphertext_page, (unsigned long)ctx);
283 lock_page(ciphertext_page);
284 return ciphertext_page;
285
286errout:
287 fscrypt_release_ctx(ctx);
288 return ciphertext_page;
289}
290EXPORT_SYMBOL(fscrypt_encrypt_page);
291
292/**
293 * fscrypt_decrypt_page() - Decrypts a page in-place
294 * @inode: The corresponding inode for the page to decrypt.
295 * @page: The page to decrypt. Must be locked in case
296 * it is a writeback page (FS_CFLG_OWN_PAGES unset).
297 * @len: Number of bytes in @page to be decrypted.
298 * @offs: Start of data in @page.
299 * @lblk_num: Logical block number.
300 *
301 * Decrypts page in-place using the ctx encryption context.
302 *
303 * Called from the read completion callback.
304 *
305 * Return: Zero on success, non-zero otherwise.
306 */
307int fscrypt_decrypt_page(const struct inode *inode, struct page *page,
308 unsigned int len, unsigned int offs, u64 lblk_num)
309{
310 if (WARN_ON_ONCE(!PageLocked(page) &&
311 !(inode->i_sb->s_cop->flags & FS_CFLG_OWN_PAGES)))
312 return -EINVAL;
313
314 return fscrypt_do_page_crypto(inode, FS_DECRYPT, lblk_num, page, page,
315 len, offs, GFP_NOFS);
316}
317EXPORT_SYMBOL(fscrypt_decrypt_page);
318
319/*
320 * Validate dentries for encrypted directories to make sure we aren't
321 * potentially caching stale data after a key has been added or
322 * removed.
323 */
324static int fscrypt_d_revalidate(struct dentry *dentry, unsigned int flags)
325{
326 struct dentry *dir;
327 int dir_has_key, cached_with_key;
328
329 if (flags & LOOKUP_RCU)
330 return -ECHILD;
331
332 dir = dget_parent(dentry);
333 if (!IS_ENCRYPTED(d_inode(dir))) {
334 dput(dir);
335 return 0;
336 }
337
338 /* this should eventually be an flag in d_flags */
339 spin_lock(&dentry->d_lock);
340 cached_with_key = dentry->d_flags & DCACHE_ENCRYPTED_WITH_KEY;
341 spin_unlock(&dentry->d_lock);
342 dir_has_key = (d_inode(dir)->i_crypt_info != NULL);
343 dput(dir);
344
345 /*
346 * If the dentry was cached without the key, and it is a
347 * negative dentry, it might be a valid name. We can't check
348 * if the key has since been made available due to locking
349 * reasons, so we fail the validation so ext4_lookup() can do
350 * this check.
351 *
352 * We also fail the validation if the dentry was created with
353 * the key present, but we no longer have the key, or vice versa.
354 */
355 if ((!cached_with_key && d_is_negative(dentry)) ||
356 (!cached_with_key && dir_has_key) ||
357 (cached_with_key && !dir_has_key))
358 return 0;
359 return 1;
360}
361
362const struct dentry_operations fscrypt_d_ops = {
363 .d_revalidate = fscrypt_d_revalidate,
364};
365EXPORT_SYMBOL(fscrypt_d_ops);
366
367void fscrypt_restore_control_page(struct page *page)
368{
369 struct fscrypt_ctx *ctx;
370
371 ctx = (struct fscrypt_ctx *)page_private(page);
372 set_page_private(page, (unsigned long)NULL);
373 ClearPagePrivate(page);
374 unlock_page(page);
375 fscrypt_release_ctx(ctx);
376}
377EXPORT_SYMBOL(fscrypt_restore_control_page);
378
379static void fscrypt_destroy(void)
380{
381 struct fscrypt_ctx *pos, *n;
382
383 list_for_each_entry_safe(pos, n, &fscrypt_free_ctxs, free_list)
384 kmem_cache_free(fscrypt_ctx_cachep, pos);
385 INIT_LIST_HEAD(&fscrypt_free_ctxs);
386 mempool_destroy(fscrypt_bounce_page_pool);
387 fscrypt_bounce_page_pool = NULL;
388}
389
390/**
391 * fscrypt_initialize() - allocate major buffers for fs encryption.
392 * @cop_flags: fscrypt operations flags
393 *
394 * We only call this when we start accessing encrypted files, since it
395 * results in memory getting allocated that wouldn't otherwise be used.
396 *
397 * Return: Zero on success, non-zero otherwise.
398 */
399int fscrypt_initialize(unsigned int cop_flags)
400{
401 int i, res = -ENOMEM;
402
403 /* No need to allocate a bounce page pool if this FS won't use it. */
404 if (cop_flags & FS_CFLG_OWN_PAGES)
405 return 0;
406
407 mutex_lock(&fscrypt_init_mutex);
408 if (fscrypt_bounce_page_pool)
409 goto already_initialized;
410
411 for (i = 0; i < num_prealloc_crypto_ctxs; i++) {
412 struct fscrypt_ctx *ctx;
413
414 ctx = kmem_cache_zalloc(fscrypt_ctx_cachep, GFP_NOFS);
415 if (!ctx)
416 goto fail;
417 list_add(&ctx->free_list, &fscrypt_free_ctxs);
418 }
419
420 fscrypt_bounce_page_pool =
421 mempool_create_page_pool(num_prealloc_crypto_pages, 0);
422 if (!fscrypt_bounce_page_pool)
423 goto fail;
424
425already_initialized:
426 mutex_unlock(&fscrypt_init_mutex);
427 return 0;
428fail:
429 fscrypt_destroy();
430 mutex_unlock(&fscrypt_init_mutex);
431 return res;
432}
433
434/**
435 * fscrypt_init() - Set up for fs encryption.
436 */
437static int __init fscrypt_init(void)
438{
439 /*
440 * Use an unbound workqueue to allow bios to be decrypted in parallel
441 * even when they happen to complete on the same CPU. This sacrifices
442 * locality, but it's worthwhile since decryption is CPU-intensive.
443 *
444 * Also use a high-priority workqueue to prioritize decryption work,
445 * which blocks reads from completing, over regular application tasks.
446 */
447 fscrypt_read_workqueue = alloc_workqueue("fscrypt_read_queue",
448 WQ_UNBOUND | WQ_HIGHPRI,
449 num_online_cpus());
450 if (!fscrypt_read_workqueue)
451 goto fail;
452
453 fscrypt_ctx_cachep = KMEM_CACHE(fscrypt_ctx, SLAB_RECLAIM_ACCOUNT);
454 if (!fscrypt_ctx_cachep)
455 goto fail_free_queue;
456
457 fscrypt_info_cachep = KMEM_CACHE(fscrypt_info, SLAB_RECLAIM_ACCOUNT);
458 if (!fscrypt_info_cachep)
459 goto fail_free_ctx;
460
461 return 0;
462
463fail_free_ctx:
464 kmem_cache_destroy(fscrypt_ctx_cachep);
465fail_free_queue:
466 destroy_workqueue(fscrypt_read_workqueue);
467fail:
468 return -ENOMEM;
469}
470module_init(fscrypt_init)
471
472/**
473 * fscrypt_exit() - Shutdown the fs encryption system
474 */
475static void __exit fscrypt_exit(void)
476{
477 fscrypt_destroy();
478
479 if (fscrypt_read_workqueue)
480 destroy_workqueue(fscrypt_read_workqueue);
481 kmem_cache_destroy(fscrypt_ctx_cachep);
482 kmem_cache_destroy(fscrypt_info_cachep);
483
484 fscrypt_essiv_cleanup();
485}
486module_exit(fscrypt_exit);
487
488MODULE_LICENSE("GPL");