crypto.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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/pagemap.h>
  22. #include <linux/mempool.h>
  23. #include <linux/module.h>
  24. #include <linux/scatterlist.h>
  25. #include <linux/ratelimit.h>
  26. #include <linux/dcache.h>
  27. #include <linux/namei.h>
  28. #include <crypto/aes.h>
  29. #include "fscrypt_private.h"
  30. static unsigned int num_prealloc_crypto_pages = 32;
  31. static unsigned int num_prealloc_crypto_ctxs = 128;
  32. module_param(num_prealloc_crypto_pages, uint, 0444);
  33. MODULE_PARM_DESC(num_prealloc_crypto_pages,
  34. "Number of crypto pages to preallocate");
  35. module_param(num_prealloc_crypto_ctxs, uint, 0444);
  36. MODULE_PARM_DESC(num_prealloc_crypto_ctxs,
  37. "Number of crypto contexts to preallocate");
  38. static mempool_t *fscrypt_bounce_page_pool = NULL;
  39. static LIST_HEAD(fscrypt_free_ctxs);
  40. static DEFINE_SPINLOCK(fscrypt_ctx_lock);
  41. struct workqueue_struct *fscrypt_read_workqueue;
  42. static DEFINE_MUTEX(fscrypt_init_mutex);
  43. static struct kmem_cache *fscrypt_ctx_cachep;
  44. struct kmem_cache *fscrypt_info_cachep;
  45. /**
  46. * fscrypt_release_ctx() - Releases an encryption context
  47. * @ctx: The encryption context to release.
  48. *
  49. * If the encryption context was allocated from the pre-allocated pool, returns
  50. * it to that pool. Else, frees it.
  51. *
  52. * If there's a bounce page in the context, this frees that.
  53. */
  54. void fscrypt_release_ctx(struct fscrypt_ctx *ctx)
  55. {
  56. unsigned long flags;
  57. if (ctx->flags & FS_CTX_HAS_BOUNCE_BUFFER_FL && ctx->w.bounce_page) {
  58. mempool_free(ctx->w.bounce_page, fscrypt_bounce_page_pool);
  59. ctx->w.bounce_page = NULL;
  60. }
  61. ctx->w.control_page = NULL;
  62. if (ctx->flags & FS_CTX_REQUIRES_FREE_ENCRYPT_FL) {
  63. kmem_cache_free(fscrypt_ctx_cachep, ctx);
  64. } else {
  65. spin_lock_irqsave(&fscrypt_ctx_lock, flags);
  66. list_add(&ctx->free_list, &fscrypt_free_ctxs);
  67. spin_unlock_irqrestore(&fscrypt_ctx_lock, flags);
  68. }
  69. }
  70. EXPORT_SYMBOL(fscrypt_release_ctx);
  71. /**
  72. * fscrypt_get_ctx() - Gets an encryption context
  73. * @inode: The inode for which we are doing the crypto
  74. * @gfp_flags: The gfp flag for memory allocation
  75. *
  76. * Allocates and initializes an encryption context.
  77. *
  78. * Return: An allocated and initialized encryption context on success; error
  79. * value or NULL otherwise.
  80. */
  81. struct fscrypt_ctx *fscrypt_get_ctx(const struct inode *inode, gfp_t gfp_flags)
  82. {
  83. struct fscrypt_ctx *ctx = NULL;
  84. struct fscrypt_info *ci = inode->i_crypt_info;
  85. unsigned long flags;
  86. if (ci == NULL)
  87. return ERR_PTR(-ENOKEY);
  88. /*
  89. * We first try getting the ctx from a free list because in
  90. * the common case the ctx will have an allocated and
  91. * initialized crypto tfm, so it's probably a worthwhile
  92. * optimization. For the bounce page, we first try getting it
  93. * from the kernel allocator because that's just about as fast
  94. * as getting it from a list and because a cache of free pages
  95. * should generally be a "last resort" option for a filesystem
  96. * to be able to do its job.
  97. */
  98. spin_lock_irqsave(&fscrypt_ctx_lock, flags);
  99. ctx = list_first_entry_or_null(&fscrypt_free_ctxs,
  100. struct fscrypt_ctx, free_list);
  101. if (ctx)
  102. list_del(&ctx->free_list);
  103. spin_unlock_irqrestore(&fscrypt_ctx_lock, flags);
  104. if (!ctx) {
  105. ctx = kmem_cache_zalloc(fscrypt_ctx_cachep, gfp_flags);
  106. if (!ctx)
  107. return ERR_PTR(-ENOMEM);
  108. ctx->flags |= FS_CTX_REQUIRES_FREE_ENCRYPT_FL;
  109. } else {
  110. ctx->flags &= ~FS_CTX_REQUIRES_FREE_ENCRYPT_FL;
  111. }
  112. ctx->flags &= ~FS_CTX_HAS_BOUNCE_BUFFER_FL;
  113. return ctx;
  114. }
  115. EXPORT_SYMBOL(fscrypt_get_ctx);
  116. /**
  117. * page_crypt_complete() - completion callback for page crypto
  118. * @req: The asynchronous cipher request context
  119. * @res: The result of the cipher operation
  120. */
  121. static void page_crypt_complete(struct crypto_async_request *req, int res)
  122. {
  123. struct fscrypt_completion_result *ecr = req->data;
  124. if (res == -EINPROGRESS)
  125. return;
  126. ecr->res = res;
  127. complete(&ecr->completion);
  128. }
  129. int fscrypt_do_page_crypto(const struct inode *inode, fscrypt_direction_t rw,
  130. u64 lblk_num, struct page *src_page,
  131. struct page *dest_page, unsigned int len,
  132. unsigned int offs, gfp_t gfp_flags)
  133. {
  134. struct {
  135. __le64 index;
  136. u8 padding[FS_IV_SIZE - sizeof(__le64)];
  137. } iv;
  138. struct skcipher_request *req = NULL;
  139. DECLARE_FS_COMPLETION_RESULT(ecr);
  140. struct scatterlist dst, src;
  141. struct fscrypt_info *ci = inode->i_crypt_info;
  142. struct crypto_skcipher *tfm = ci->ci_ctfm;
  143. int res = 0;
  144. BUG_ON(len == 0);
  145. BUILD_BUG_ON(sizeof(iv) != FS_IV_SIZE);
  146. BUILD_BUG_ON(AES_BLOCK_SIZE != FS_IV_SIZE);
  147. iv.index = cpu_to_le64(lblk_num);
  148. memset(iv.padding, 0, sizeof(iv.padding));
  149. if (ci->ci_essiv_tfm != NULL) {
  150. crypto_cipher_encrypt_one(ci->ci_essiv_tfm, (u8 *)&iv,
  151. (u8 *)&iv);
  152. }
  153. req = skcipher_request_alloc(tfm, gfp_flags);
  154. if (!req) {
  155. printk_ratelimited(KERN_ERR
  156. "%s: crypto_request_alloc() failed\n",
  157. __func__);
  158. return -ENOMEM;
  159. }
  160. skcipher_request_set_callback(
  161. req, CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
  162. page_crypt_complete, &ecr);
  163. sg_init_table(&dst, 1);
  164. sg_set_page(&dst, dest_page, len, offs);
  165. sg_init_table(&src, 1);
  166. sg_set_page(&src, src_page, len, offs);
  167. skcipher_request_set_crypt(req, &src, &dst, len, &iv);
  168. if (rw == FS_DECRYPT)
  169. res = crypto_skcipher_decrypt(req);
  170. else
  171. res = crypto_skcipher_encrypt(req);
  172. if (res == -EINPROGRESS || res == -EBUSY) {
  173. BUG_ON(req->base.data != &ecr);
  174. wait_for_completion(&ecr.completion);
  175. res = ecr.res;
  176. }
  177. skcipher_request_free(req);
  178. if (res) {
  179. printk_ratelimited(KERN_ERR
  180. "%s: crypto_skcipher_encrypt() returned %d\n",
  181. __func__, res);
  182. return res;
  183. }
  184. return 0;
  185. }
  186. struct page *fscrypt_alloc_bounce_page(struct fscrypt_ctx *ctx,
  187. gfp_t gfp_flags)
  188. {
  189. ctx->w.bounce_page = mempool_alloc(fscrypt_bounce_page_pool, gfp_flags);
  190. if (ctx->w.bounce_page == NULL)
  191. return ERR_PTR(-ENOMEM);
  192. ctx->flags |= FS_CTX_HAS_BOUNCE_BUFFER_FL;
  193. return ctx->w.bounce_page;
  194. }
  195. /**
  196. * fscypt_encrypt_page() - Encrypts a page
  197. * @inode: The inode for which the encryption should take place
  198. * @page: The page to encrypt. Must be locked for bounce-page
  199. * encryption.
  200. * @len: Length of data to encrypt in @page and encrypted
  201. * data in returned page.
  202. * @offs: Offset of data within @page and returned
  203. * page holding encrypted data.
  204. * @lblk_num: Logical block number. This must be unique for multiple
  205. * calls with same inode, except when overwriting
  206. * previously written data.
  207. * @gfp_flags: The gfp flag for memory allocation
  208. *
  209. * Encrypts @page using the ctx encryption context. Performs encryption
  210. * either in-place or into a newly allocated bounce page.
  211. * Called on the page write path.
  212. *
  213. * Bounce page allocation is the default.
  214. * In this case, the contents of @page are encrypted and stored in an
  215. * allocated bounce page. @page has to be locked and the caller must call
  216. * fscrypt_restore_control_page() on the returned ciphertext page to
  217. * release the bounce buffer and the encryption context.
  218. *
  219. * In-place encryption is used by setting the FS_CFLG_OWN_PAGES flag in
  220. * fscrypt_operations. Here, the input-page is returned with its content
  221. * encrypted.
  222. *
  223. * Return: A page with the encrypted content on success. Else, an
  224. * error value or NULL.
  225. */
  226. struct page *fscrypt_encrypt_page(const struct inode *inode,
  227. struct page *page,
  228. unsigned int len,
  229. unsigned int offs,
  230. u64 lblk_num, gfp_t gfp_flags)
  231. {
  232. struct fscrypt_ctx *ctx;
  233. struct page *ciphertext_page = page;
  234. int err;
  235. BUG_ON(len % FS_CRYPTO_BLOCK_SIZE != 0);
  236. if (inode->i_sb->s_cop->flags & FS_CFLG_OWN_PAGES) {
  237. /* with inplace-encryption we just encrypt the page */
  238. err = fscrypt_do_page_crypto(inode, FS_ENCRYPT, lblk_num, page,
  239. ciphertext_page, len, offs,
  240. gfp_flags);
  241. if (err)
  242. return ERR_PTR(err);
  243. return ciphertext_page;
  244. }
  245. BUG_ON(!PageLocked(page));
  246. ctx = fscrypt_get_ctx(inode, gfp_flags);
  247. if (IS_ERR(ctx))
  248. return (struct page *)ctx;
  249. /* The encryption operation will require a bounce page. */
  250. ciphertext_page = fscrypt_alloc_bounce_page(ctx, gfp_flags);
  251. if (IS_ERR(ciphertext_page))
  252. goto errout;
  253. ctx->w.control_page = page;
  254. err = fscrypt_do_page_crypto(inode, FS_ENCRYPT, lblk_num,
  255. page, ciphertext_page, len, offs,
  256. gfp_flags);
  257. if (err) {
  258. ciphertext_page = ERR_PTR(err);
  259. goto errout;
  260. }
  261. SetPagePrivate(ciphertext_page);
  262. set_page_private(ciphertext_page, (unsigned long)ctx);
  263. lock_page(ciphertext_page);
  264. return ciphertext_page;
  265. errout:
  266. fscrypt_release_ctx(ctx);
  267. return ciphertext_page;
  268. }
  269. EXPORT_SYMBOL(fscrypt_encrypt_page);
  270. /**
  271. * fscrypt_decrypt_page() - Decrypts a page in-place
  272. * @inode: The corresponding inode for the page to decrypt.
  273. * @page: The page to decrypt. Must be locked in case
  274. * it is a writeback page (FS_CFLG_OWN_PAGES unset).
  275. * @len: Number of bytes in @page to be decrypted.
  276. * @offs: Start of data in @page.
  277. * @lblk_num: Logical block number.
  278. *
  279. * Decrypts page in-place using the ctx encryption context.
  280. *
  281. * Called from the read completion callback.
  282. *
  283. * Return: Zero on success, non-zero otherwise.
  284. */
  285. int fscrypt_decrypt_page(const struct inode *inode, struct page *page,
  286. unsigned int len, unsigned int offs, u64 lblk_num)
  287. {
  288. if (!(inode->i_sb->s_cop->flags & FS_CFLG_OWN_PAGES))
  289. BUG_ON(!PageLocked(page));
  290. return fscrypt_do_page_crypto(inode, FS_DECRYPT, lblk_num, page, page,
  291. len, offs, GFP_NOFS);
  292. }
  293. EXPORT_SYMBOL(fscrypt_decrypt_page);
  294. /*
  295. * Validate dentries for encrypted directories to make sure we aren't
  296. * potentially caching stale data after a key has been added or
  297. * removed.
  298. */
  299. static int fscrypt_d_revalidate(struct dentry *dentry, unsigned int flags)
  300. {
  301. struct dentry *dir;
  302. int dir_has_key, cached_with_key;
  303. if (flags & LOOKUP_RCU)
  304. return -ECHILD;
  305. dir = dget_parent(dentry);
  306. if (!d_inode(dir)->i_sb->s_cop->is_encrypted(d_inode(dir))) {
  307. dput(dir);
  308. return 0;
  309. }
  310. /* this should eventually be an flag in d_flags */
  311. spin_lock(&dentry->d_lock);
  312. cached_with_key = dentry->d_flags & DCACHE_ENCRYPTED_WITH_KEY;
  313. spin_unlock(&dentry->d_lock);
  314. dir_has_key = (d_inode(dir)->i_crypt_info != NULL);
  315. dput(dir);
  316. /*
  317. * If the dentry was cached without the key, and it is a
  318. * negative dentry, it might be a valid name. We can't check
  319. * if the key has since been made available due to locking
  320. * reasons, so we fail the validation so ext4_lookup() can do
  321. * this check.
  322. *
  323. * We also fail the validation if the dentry was created with
  324. * the key present, but we no longer have the key, or vice versa.
  325. */
  326. if ((!cached_with_key && d_is_negative(dentry)) ||
  327. (!cached_with_key && dir_has_key) ||
  328. (cached_with_key && !dir_has_key))
  329. return 0;
  330. return 1;
  331. }
  332. const struct dentry_operations fscrypt_d_ops = {
  333. .d_revalidate = fscrypt_d_revalidate,
  334. };
  335. EXPORT_SYMBOL(fscrypt_d_ops);
  336. void fscrypt_restore_control_page(struct page *page)
  337. {
  338. struct fscrypt_ctx *ctx;
  339. ctx = (struct fscrypt_ctx *)page_private(page);
  340. set_page_private(page, (unsigned long)NULL);
  341. ClearPagePrivate(page);
  342. unlock_page(page);
  343. fscrypt_release_ctx(ctx);
  344. }
  345. EXPORT_SYMBOL(fscrypt_restore_control_page);
  346. static void fscrypt_destroy(void)
  347. {
  348. struct fscrypt_ctx *pos, *n;
  349. list_for_each_entry_safe(pos, n, &fscrypt_free_ctxs, free_list)
  350. kmem_cache_free(fscrypt_ctx_cachep, pos);
  351. INIT_LIST_HEAD(&fscrypt_free_ctxs);
  352. mempool_destroy(fscrypt_bounce_page_pool);
  353. fscrypt_bounce_page_pool = NULL;
  354. }
  355. /**
  356. * fscrypt_initialize() - allocate major buffers for fs encryption.
  357. * @cop_flags: fscrypt operations flags
  358. *
  359. * We only call this when we start accessing encrypted files, since it
  360. * results in memory getting allocated that wouldn't otherwise be used.
  361. *
  362. * Return: Zero on success, non-zero otherwise.
  363. */
  364. int fscrypt_initialize(unsigned int cop_flags)
  365. {
  366. int i, res = -ENOMEM;
  367. /*
  368. * No need to allocate a bounce page pool if there already is one or
  369. * this FS won't use it.
  370. */
  371. if (cop_flags & FS_CFLG_OWN_PAGES || fscrypt_bounce_page_pool)
  372. return 0;
  373. mutex_lock(&fscrypt_init_mutex);
  374. if (fscrypt_bounce_page_pool)
  375. goto already_initialized;
  376. for (i = 0; i < num_prealloc_crypto_ctxs; i++) {
  377. struct fscrypt_ctx *ctx;
  378. ctx = kmem_cache_zalloc(fscrypt_ctx_cachep, GFP_NOFS);
  379. if (!ctx)
  380. goto fail;
  381. list_add(&ctx->free_list, &fscrypt_free_ctxs);
  382. }
  383. fscrypt_bounce_page_pool =
  384. mempool_create_page_pool(num_prealloc_crypto_pages, 0);
  385. if (!fscrypt_bounce_page_pool)
  386. goto fail;
  387. already_initialized:
  388. mutex_unlock(&fscrypt_init_mutex);
  389. return 0;
  390. fail:
  391. fscrypt_destroy();
  392. mutex_unlock(&fscrypt_init_mutex);
  393. return res;
  394. }
  395. /**
  396. * fscrypt_init() - Set up for fs encryption.
  397. */
  398. static int __init fscrypt_init(void)
  399. {
  400. fscrypt_read_workqueue = alloc_workqueue("fscrypt_read_queue",
  401. WQ_HIGHPRI, 0);
  402. if (!fscrypt_read_workqueue)
  403. goto fail;
  404. fscrypt_ctx_cachep = KMEM_CACHE(fscrypt_ctx, SLAB_RECLAIM_ACCOUNT);
  405. if (!fscrypt_ctx_cachep)
  406. goto fail_free_queue;
  407. fscrypt_info_cachep = KMEM_CACHE(fscrypt_info, SLAB_RECLAIM_ACCOUNT);
  408. if (!fscrypt_info_cachep)
  409. goto fail_free_ctx;
  410. return 0;
  411. fail_free_ctx:
  412. kmem_cache_destroy(fscrypt_ctx_cachep);
  413. fail_free_queue:
  414. destroy_workqueue(fscrypt_read_workqueue);
  415. fail:
  416. return -ENOMEM;
  417. }
  418. module_init(fscrypt_init)
  419. /**
  420. * fscrypt_exit() - Shutdown the fs encryption system
  421. */
  422. static void __exit fscrypt_exit(void)
  423. {
  424. fscrypt_destroy();
  425. if (fscrypt_read_workqueue)
  426. destroy_workqueue(fscrypt_read_workqueue);
  427. kmem_cache_destroy(fscrypt_ctx_cachep);
  428. kmem_cache_destroy(fscrypt_info_cachep);
  429. fscrypt_essiv_cleanup();
  430. }
  431. module_exit(fscrypt_exit);
  432. MODULE_LICENSE("GPL");