crypto.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. /*
  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. #include <linux/crypto.h>
  22. #include <linux/ecryptfs.h>
  23. #include <linux/pagemap.h>
  24. #include <linux/mempool.h>
  25. #include <linux/module.h>
  26. #include <linux/scatterlist.h>
  27. #include <linux/ratelimit.h>
  28. #include <linux/bio.h>
  29. #include <linux/dcache.h>
  30. #include <linux/namei.h>
  31. #include <linux/fscrypto.h>
  32. static unsigned int num_prealloc_crypto_pages = 32;
  33. static unsigned int num_prealloc_crypto_ctxs = 128;
  34. module_param(num_prealloc_crypto_pages, uint, 0444);
  35. MODULE_PARM_DESC(num_prealloc_crypto_pages,
  36. "Number of crypto pages to preallocate");
  37. module_param(num_prealloc_crypto_ctxs, uint, 0444);
  38. MODULE_PARM_DESC(num_prealloc_crypto_ctxs,
  39. "Number of crypto contexts to preallocate");
  40. static mempool_t *fscrypt_bounce_page_pool = NULL;
  41. static LIST_HEAD(fscrypt_free_ctxs);
  42. static DEFINE_SPINLOCK(fscrypt_ctx_lock);
  43. static struct workqueue_struct *fscrypt_read_workqueue;
  44. static DEFINE_MUTEX(fscrypt_init_mutex);
  45. static struct kmem_cache *fscrypt_ctx_cachep;
  46. struct kmem_cache *fscrypt_info_cachep;
  47. /**
  48. * fscrypt_release_ctx() - Releases an encryption context
  49. * @ctx: The encryption context to release.
  50. *
  51. * If the encryption context was allocated from the pre-allocated pool, returns
  52. * it to that pool. Else, frees it.
  53. *
  54. * If there's a bounce page in the context, this frees that.
  55. */
  56. void fscrypt_release_ctx(struct fscrypt_ctx *ctx)
  57. {
  58. unsigned long flags;
  59. if (ctx->flags & FS_WRITE_PATH_FL && ctx->w.bounce_page) {
  60. mempool_free(ctx->w.bounce_page, fscrypt_bounce_page_pool);
  61. ctx->w.bounce_page = NULL;
  62. }
  63. ctx->w.control_page = NULL;
  64. if (ctx->flags & FS_CTX_REQUIRES_FREE_ENCRYPT_FL) {
  65. kmem_cache_free(fscrypt_ctx_cachep, ctx);
  66. } else {
  67. spin_lock_irqsave(&fscrypt_ctx_lock, flags);
  68. list_add(&ctx->free_list, &fscrypt_free_ctxs);
  69. spin_unlock_irqrestore(&fscrypt_ctx_lock, flags);
  70. }
  71. }
  72. EXPORT_SYMBOL(fscrypt_release_ctx);
  73. /**
  74. * fscrypt_get_ctx() - Gets an encryption context
  75. * @inode: The inode for which we are doing the crypto
  76. * @gfp_flags: The gfp flag for memory allocation
  77. *
  78. * Allocates and initializes an encryption context.
  79. *
  80. * Return: An allocated and initialized encryption context on success; error
  81. * value or NULL otherwise.
  82. */
  83. struct fscrypt_ctx *fscrypt_get_ctx(struct inode *inode, gfp_t gfp_flags)
  84. {
  85. struct fscrypt_ctx *ctx = NULL;
  86. struct fscrypt_info *ci = inode->i_crypt_info;
  87. unsigned long flags;
  88. if (ci == NULL)
  89. return ERR_PTR(-ENOKEY);
  90. /*
  91. * We first try getting the ctx from a free list because in
  92. * the common case the ctx will have an allocated and
  93. * initialized crypto tfm, so it's probably a worthwhile
  94. * optimization. For the bounce page, we first try getting it
  95. * from the kernel allocator because that's just about as fast
  96. * as getting it from a list and because a cache of free pages
  97. * should generally be a "last resort" option for a filesystem
  98. * to be able to do its job.
  99. */
  100. spin_lock_irqsave(&fscrypt_ctx_lock, flags);
  101. ctx = list_first_entry_or_null(&fscrypt_free_ctxs,
  102. struct fscrypt_ctx, free_list);
  103. if (ctx)
  104. list_del(&ctx->free_list);
  105. spin_unlock_irqrestore(&fscrypt_ctx_lock, flags);
  106. if (!ctx) {
  107. ctx = kmem_cache_zalloc(fscrypt_ctx_cachep, gfp_flags);
  108. if (!ctx)
  109. return ERR_PTR(-ENOMEM);
  110. ctx->flags |= FS_CTX_REQUIRES_FREE_ENCRYPT_FL;
  111. } else {
  112. ctx->flags &= ~FS_CTX_REQUIRES_FREE_ENCRYPT_FL;
  113. }
  114. ctx->flags &= ~FS_WRITE_PATH_FL;
  115. return ctx;
  116. }
  117. EXPORT_SYMBOL(fscrypt_get_ctx);
  118. /**
  119. * fscrypt_complete() - The completion callback for page encryption
  120. * @req: The asynchronous encryption request context
  121. * @res: The result of the encryption operation
  122. */
  123. static void fscrypt_complete(struct crypto_async_request *req, int res)
  124. {
  125. struct fscrypt_completion_result *ecr = req->data;
  126. if (res == -EINPROGRESS)
  127. return;
  128. ecr->res = res;
  129. complete(&ecr->completion);
  130. }
  131. typedef enum {
  132. FS_DECRYPT = 0,
  133. FS_ENCRYPT,
  134. } fscrypt_direction_t;
  135. static int do_page_crypto(struct inode *inode,
  136. fscrypt_direction_t rw, pgoff_t index,
  137. struct page *src_page, struct page *dest_page,
  138. gfp_t gfp_flags)
  139. {
  140. u8 xts_tweak[FS_XTS_TWEAK_SIZE];
  141. struct ablkcipher_request *req = NULL;
  142. DECLARE_FS_COMPLETION_RESULT(ecr);
  143. struct scatterlist dst, src;
  144. struct fscrypt_info *ci = inode->i_crypt_info;
  145. struct crypto_ablkcipher *tfm = ci->ci_ctfm;
  146. int res = 0;
  147. req = ablkcipher_request_alloc(tfm, gfp_flags);
  148. if (!req) {
  149. printk_ratelimited(KERN_ERR
  150. "%s: crypto_request_alloc() failed\n",
  151. __func__);
  152. return -ENOMEM;
  153. }
  154. ablkcipher_request_set_callback(
  155. req, CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
  156. fscrypt_complete, &ecr);
  157. BUILD_BUG_ON(FS_XTS_TWEAK_SIZE < sizeof(index));
  158. memcpy(xts_tweak, &index, sizeof(index));
  159. memset(&xts_tweak[sizeof(index)], 0,
  160. FS_XTS_TWEAK_SIZE - sizeof(index));
  161. sg_init_table(&dst, 1);
  162. sg_set_page(&dst, dest_page, PAGE_CACHE_SIZE, 0);
  163. sg_init_table(&src, 1);
  164. sg_set_page(&src, src_page, PAGE_CACHE_SIZE, 0);
  165. ablkcipher_request_set_crypt(req, &src, &dst, PAGE_CACHE_SIZE,
  166. xts_tweak);
  167. if (rw == FS_DECRYPT)
  168. res = crypto_ablkcipher_decrypt(req);
  169. else
  170. res = crypto_ablkcipher_encrypt(req);
  171. if (res == -EINPROGRESS || res == -EBUSY) {
  172. BUG_ON(req->base.data != &ecr);
  173. wait_for_completion(&ecr.completion);
  174. res = ecr.res;
  175. }
  176. ablkcipher_request_free(req);
  177. if (res) {
  178. printk_ratelimited(KERN_ERR
  179. "%s: crypto_ablkcipher_encrypt() returned %d\n",
  180. __func__, res);
  181. return res;
  182. }
  183. return 0;
  184. }
  185. static struct page *alloc_bounce_page(struct fscrypt_ctx *ctx, gfp_t gfp_flags)
  186. {
  187. ctx->w.bounce_page = mempool_alloc(fscrypt_bounce_page_pool, gfp_flags);
  188. if (ctx->w.bounce_page == NULL)
  189. return ERR_PTR(-ENOMEM);
  190. ctx->flags |= FS_WRITE_PATH_FL;
  191. return ctx->w.bounce_page;
  192. }
  193. /**
  194. * fscypt_encrypt_page() - Encrypts a page
  195. * @inode: The inode for which the encryption should take place
  196. * @plaintext_page: The page to encrypt. Must be locked.
  197. * @gfp_flags: The gfp flag for memory allocation
  198. *
  199. * Allocates a ciphertext page and encrypts plaintext_page into it using the ctx
  200. * encryption context.
  201. *
  202. * Called on the page write path. The caller must call
  203. * fscrypt_restore_control_page() on the returned ciphertext page to
  204. * release the bounce buffer and the encryption context.
  205. *
  206. * Return: An allocated page with the encrypted content on success. Else, an
  207. * error value or NULL.
  208. */
  209. struct page *fscrypt_encrypt_page(struct inode *inode,
  210. struct page *plaintext_page, gfp_t gfp_flags)
  211. {
  212. struct fscrypt_ctx *ctx;
  213. struct page *ciphertext_page = NULL;
  214. int err;
  215. BUG_ON(!PageLocked(plaintext_page));
  216. ctx = fscrypt_get_ctx(inode, gfp_flags);
  217. if (IS_ERR(ctx))
  218. return (struct page *)ctx;
  219. /* The encryption operation will require a bounce page. */
  220. ciphertext_page = alloc_bounce_page(ctx, gfp_flags);
  221. if (IS_ERR(ciphertext_page))
  222. goto errout;
  223. ctx->w.control_page = plaintext_page;
  224. err = do_page_crypto(inode, FS_ENCRYPT, plaintext_page->index,
  225. plaintext_page, ciphertext_page,
  226. gfp_flags);
  227. if (err) {
  228. ciphertext_page = ERR_PTR(err);
  229. goto errout;
  230. }
  231. SetPagePrivate(ciphertext_page);
  232. set_page_private(ciphertext_page, (unsigned long)ctx);
  233. lock_page(ciphertext_page);
  234. return ciphertext_page;
  235. errout:
  236. fscrypt_release_ctx(ctx);
  237. return ciphertext_page;
  238. }
  239. EXPORT_SYMBOL(fscrypt_encrypt_page);
  240. /**
  241. * f2crypt_decrypt_page() - Decrypts a page in-place
  242. * @page: The page to decrypt. Must be locked.
  243. *
  244. * Decrypts page in-place using the ctx encryption context.
  245. *
  246. * Called from the read completion callback.
  247. *
  248. * Return: Zero on success, non-zero otherwise.
  249. */
  250. int fscrypt_decrypt_page(struct page *page)
  251. {
  252. BUG_ON(!PageLocked(page));
  253. return do_page_crypto(page->mapping->host,
  254. FS_DECRYPT, page->index, page, page, GFP_NOFS);
  255. }
  256. EXPORT_SYMBOL(fscrypt_decrypt_page);
  257. int fscrypt_zeroout_range(struct inode *inode, pgoff_t lblk,
  258. sector_t pblk, unsigned int len)
  259. {
  260. struct fscrypt_ctx *ctx;
  261. struct page *ciphertext_page = NULL;
  262. struct bio *bio;
  263. int ret, err = 0;
  264. BUG_ON(inode->i_sb->s_blocksize != PAGE_CACHE_SIZE);
  265. ctx = fscrypt_get_ctx(inode, GFP_NOFS);
  266. if (IS_ERR(ctx))
  267. return PTR_ERR(ctx);
  268. ciphertext_page = alloc_bounce_page(ctx, GFP_NOWAIT);
  269. if (IS_ERR(ciphertext_page)) {
  270. err = PTR_ERR(ciphertext_page);
  271. goto errout;
  272. }
  273. while (len--) {
  274. err = do_page_crypto(inode, FS_ENCRYPT, lblk,
  275. ZERO_PAGE(0), ciphertext_page,
  276. GFP_NOFS);
  277. if (err)
  278. goto errout;
  279. bio = bio_alloc(GFP_NOWAIT, 1);
  280. if (!bio) {
  281. err = -ENOMEM;
  282. goto errout;
  283. }
  284. bio->bi_bdev = inode->i_sb->s_bdev;
  285. bio->bi_sector =
  286. pblk << (inode->i_sb->s_blocksize_bits - 9);
  287. ret = bio_add_page(bio, ciphertext_page,
  288. inode->i_sb->s_blocksize, 0);
  289. if (ret != inode->i_sb->s_blocksize) {
  290. /* should never happen! */
  291. WARN_ON(1);
  292. bio_put(bio);
  293. err = -EIO;
  294. goto errout;
  295. }
  296. err = submit_bio_wait(WRITE, bio);
  297. bio_put(bio);
  298. if (err)
  299. goto errout;
  300. lblk++;
  301. pblk++;
  302. }
  303. err = 0;
  304. errout:
  305. fscrypt_release_ctx(ctx);
  306. return err;
  307. }
  308. EXPORT_SYMBOL(fscrypt_zeroout_range);
  309. /*
  310. * Validate dentries for encrypted directories to make sure we aren't
  311. * potentially caching stale data after a key has been added or
  312. * removed.
  313. */
  314. static int fscrypt_d_revalidate(struct dentry *dentry, unsigned int flags)
  315. {
  316. struct dentry *dir;
  317. int dir_has_key, cached_with_key;
  318. if (flags & LOOKUP_RCU)
  319. return -ECHILD;
  320. dir = dget_parent(dentry);
  321. if (!d_inode(dir)->i_sb->s_cop->is_encrypted(d_inode(dir))) {
  322. dput(dir);
  323. return 0;
  324. }
  325. /* this should eventually be an flag in d_flags */
  326. spin_lock(&dentry->d_lock);
  327. cached_with_key = dentry->d_flags & DCACHE_ENCRYPTED_WITH_KEY;
  328. spin_unlock(&dentry->d_lock);
  329. dir_has_key = (d_inode(dir)->i_crypt_info != NULL);
  330. dput(dir);
  331. /*
  332. * If the dentry was cached without the key, and it is a
  333. * negative dentry, it might be a valid name. We can't check
  334. * if the key has since been made available due to locking
  335. * reasons, so we fail the validation so ext4_lookup() can do
  336. * this check.
  337. *
  338. * We also fail the validation if the dentry was created with
  339. * the key present, but we no longer have the key, or vice versa.
  340. */
  341. if (!cached_with_key ||
  342. (!cached_with_key && dir_has_key) ||
  343. (cached_with_key && !dir_has_key))
  344. return 0;
  345. return 1;
  346. }
  347. const struct dentry_operations fscrypt_d_ops = {
  348. .d_revalidate = fscrypt_d_revalidate,
  349. };
  350. EXPORT_SYMBOL(fscrypt_d_ops);
  351. /*
  352. * Call fscrypt_decrypt_page on every single page, reusing the encryption
  353. * context.
  354. */
  355. static void completion_pages(struct work_struct *work)
  356. {
  357. struct fscrypt_ctx *ctx =
  358. container_of(work, struct fscrypt_ctx, r.work);
  359. struct bio *bio = ctx->r.bio;
  360. struct bio_vec *bv;
  361. int i;
  362. bio_for_each_segment_all(bv, bio, i) {
  363. struct page *page = bv->bv_page;
  364. int ret = fscrypt_decrypt_page(page);
  365. if (ret) {
  366. WARN_ON_ONCE(1);
  367. SetPageError(page);
  368. } else {
  369. SetPageUptodate(page);
  370. }
  371. unlock_page(page);
  372. }
  373. fscrypt_release_ctx(ctx);
  374. bio_put(bio);
  375. }
  376. void fscrypt_decrypt_bio_pages(struct fscrypt_ctx *ctx, struct bio *bio)
  377. {
  378. INIT_WORK(&ctx->r.work, completion_pages);
  379. ctx->r.bio = bio;
  380. queue_work(fscrypt_read_workqueue, &ctx->r.work);
  381. }
  382. EXPORT_SYMBOL(fscrypt_decrypt_bio_pages);
  383. void fscrypt_pullback_bio_page(struct page **page, bool restore)
  384. {
  385. struct fscrypt_ctx *ctx;
  386. struct page *bounce_page;
  387. /* The bounce data pages are unmapped. */
  388. if ((*page)->mapping)
  389. return;
  390. /* The bounce data page is unmapped. */
  391. bounce_page = *page;
  392. ctx = (struct fscrypt_ctx *)page_private(bounce_page);
  393. /* restore control page */
  394. *page = ctx->w.control_page;
  395. if (restore)
  396. fscrypt_restore_control_page(bounce_page);
  397. }
  398. EXPORT_SYMBOL(fscrypt_pullback_bio_page);
  399. void fscrypt_restore_control_page(struct page *page)
  400. {
  401. struct fscrypt_ctx *ctx;
  402. ctx = (struct fscrypt_ctx *)page_private(page);
  403. set_page_private(page, (unsigned long)NULL);
  404. ClearPagePrivate(page);
  405. unlock_page(page);
  406. fscrypt_release_ctx(ctx);
  407. }
  408. EXPORT_SYMBOL(fscrypt_restore_control_page);
  409. static void fscrypt_destroy(void)
  410. {
  411. struct fscrypt_ctx *pos, *n;
  412. list_for_each_entry_safe(pos, n, &fscrypt_free_ctxs, free_list)
  413. kmem_cache_free(fscrypt_ctx_cachep, pos);
  414. INIT_LIST_HEAD(&fscrypt_free_ctxs);
  415. mempool_destroy(fscrypt_bounce_page_pool);
  416. fscrypt_bounce_page_pool = NULL;
  417. }
  418. /**
  419. * fscrypt_initialize() - allocate major buffers for fs encryption.
  420. *
  421. * We only call this when we start accessing encrypted files, since it
  422. * results in memory getting allocated that wouldn't otherwise be used.
  423. *
  424. * Return: Zero on success, non-zero otherwise.
  425. */
  426. int fscrypt_initialize(void)
  427. {
  428. int i, res = -ENOMEM;
  429. if (fscrypt_bounce_page_pool)
  430. return 0;
  431. mutex_lock(&fscrypt_init_mutex);
  432. if (fscrypt_bounce_page_pool)
  433. goto already_initialized;
  434. for (i = 0; i < num_prealloc_crypto_ctxs; i++) {
  435. struct fscrypt_ctx *ctx;
  436. ctx = kmem_cache_zalloc(fscrypt_ctx_cachep, GFP_NOFS);
  437. if (!ctx)
  438. goto fail;
  439. list_add(&ctx->free_list, &fscrypt_free_ctxs);
  440. }
  441. fscrypt_bounce_page_pool =
  442. mempool_create_page_pool(num_prealloc_crypto_pages, 0);
  443. if (!fscrypt_bounce_page_pool)
  444. goto fail;
  445. already_initialized:
  446. mutex_unlock(&fscrypt_init_mutex);
  447. return 0;
  448. fail:
  449. fscrypt_destroy();
  450. mutex_unlock(&fscrypt_init_mutex);
  451. return res;
  452. }
  453. EXPORT_SYMBOL(fscrypt_initialize);
  454. /**
  455. * fscrypt_init() - Set up for fs encryption.
  456. */
  457. static int __init fscrypt_init(void)
  458. {
  459. fscrypt_read_workqueue = alloc_workqueue("fscrypt_read_queue",
  460. WQ_HIGHPRI, 0);
  461. if (!fscrypt_read_workqueue)
  462. goto fail;
  463. fscrypt_ctx_cachep = KMEM_CACHE(fscrypt_ctx, SLAB_RECLAIM_ACCOUNT);
  464. if (!fscrypt_ctx_cachep)
  465. goto fail_free_queue;
  466. fscrypt_info_cachep = KMEM_CACHE(fscrypt_info, SLAB_RECLAIM_ACCOUNT);
  467. if (!fscrypt_info_cachep)
  468. goto fail_free_ctx;
  469. return 0;
  470. fail_free_ctx:
  471. kmem_cache_destroy(fscrypt_ctx_cachep);
  472. fail_free_queue:
  473. destroy_workqueue(fscrypt_read_workqueue);
  474. fail:
  475. return -ENOMEM;
  476. }
  477. module_init(fscrypt_init)
  478. /**
  479. * fscrypt_exit() - Shutdown the fs encryption system
  480. */
  481. static void __exit fscrypt_exit(void)
  482. {
  483. fscrypt_destroy();
  484. if (fscrypt_read_workqueue)
  485. destroy_workqueue(fscrypt_read_workqueue);
  486. kmem_cache_destroy(fscrypt_ctx_cachep);
  487. kmem_cache_destroy(fscrypt_info_cachep);
  488. }
  489. module_exit(fscrypt_exit);
  490. MODULE_LICENSE("GPL");