crypto.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. /*
  2. * linux/fs/ext4/crypto.c
  3. *
  4. * Copyright (C) 2015, Google, Inc.
  5. *
  6. * This contains encryption functions for ext4
  7. *
  8. * Written by Michael Halcrow, 2014.
  9. *
  10. * Filename encryption additions
  11. * Uday Savagaonkar, 2014
  12. * Encryption policy handling additions
  13. * Ildar Muslukhov, 2014
  14. *
  15. * This has not yet undergone a rigorous security audit.
  16. *
  17. * The usage of AES-XTS should conform to recommendations in NIST
  18. * Special Publication 800-38E and IEEE P1619/D16.
  19. */
  20. #include <crypto/hash.h>
  21. #include <crypto/sha.h>
  22. #include <keys/user-type.h>
  23. #include <keys/encrypted-type.h>
  24. #include <linux/crypto.h>
  25. #include <linux/ecryptfs.h>
  26. #include <linux/gfp.h>
  27. #include <linux/kernel.h>
  28. #include <linux/key.h>
  29. #include <linux/list.h>
  30. #include <linux/mempool.h>
  31. #include <linux/module.h>
  32. #include <linux/mutex.h>
  33. #include <linux/random.h>
  34. #include <linux/scatterlist.h>
  35. #include <linux/spinlock_types.h>
  36. #include <linux/namei.h>
  37. #include "ext4_extents.h"
  38. #include "xattr.h"
  39. /* Encryption added and removed here! (L: */
  40. static unsigned int num_prealloc_crypto_pages = 32;
  41. static unsigned int num_prealloc_crypto_ctxs = 128;
  42. module_param(num_prealloc_crypto_pages, uint, 0444);
  43. MODULE_PARM_DESC(num_prealloc_crypto_pages,
  44. "Number of crypto pages to preallocate");
  45. module_param(num_prealloc_crypto_ctxs, uint, 0444);
  46. MODULE_PARM_DESC(num_prealloc_crypto_ctxs,
  47. "Number of crypto contexts to preallocate");
  48. static mempool_t *ext4_bounce_page_pool;
  49. static LIST_HEAD(ext4_free_crypto_ctxs);
  50. static DEFINE_SPINLOCK(ext4_crypto_ctx_lock);
  51. static struct kmem_cache *ext4_crypto_ctx_cachep;
  52. struct kmem_cache *ext4_crypt_info_cachep;
  53. /**
  54. * ext4_release_crypto_ctx() - Releases an encryption context
  55. * @ctx: The encryption context to release.
  56. *
  57. * If the encryption context was allocated from the pre-allocated pool, returns
  58. * it to that pool. Else, frees it.
  59. *
  60. * If there's a bounce page in the context, this frees that.
  61. */
  62. void ext4_release_crypto_ctx(struct ext4_crypto_ctx *ctx)
  63. {
  64. unsigned long flags;
  65. if (ctx->flags & EXT4_WRITE_PATH_FL && ctx->w.bounce_page)
  66. mempool_free(ctx->w.bounce_page, ext4_bounce_page_pool);
  67. ctx->w.bounce_page = NULL;
  68. ctx->w.control_page = NULL;
  69. if (ctx->flags & EXT4_CTX_REQUIRES_FREE_ENCRYPT_FL) {
  70. kmem_cache_free(ext4_crypto_ctx_cachep, ctx);
  71. } else {
  72. spin_lock_irqsave(&ext4_crypto_ctx_lock, flags);
  73. list_add(&ctx->free_list, &ext4_free_crypto_ctxs);
  74. spin_unlock_irqrestore(&ext4_crypto_ctx_lock, flags);
  75. }
  76. }
  77. /**
  78. * ext4_get_crypto_ctx() - Gets an encryption context
  79. * @inode: The inode for which we are doing the crypto
  80. *
  81. * Allocates and initializes an encryption context.
  82. *
  83. * Return: An allocated and initialized encryption context on success; error
  84. * value or NULL otherwise.
  85. */
  86. struct ext4_crypto_ctx *ext4_get_crypto_ctx(struct inode *inode,
  87. gfp_t gfp_flags)
  88. {
  89. struct ext4_crypto_ctx *ctx = NULL;
  90. int res = 0;
  91. unsigned long flags;
  92. struct ext4_crypt_info *ci = EXT4_I(inode)->i_crypt_info;
  93. if (ci == NULL)
  94. return ERR_PTR(-ENOKEY);
  95. /*
  96. * We first try getting the ctx from a free list because in
  97. * the common case the ctx will have an allocated and
  98. * initialized crypto tfm, so it's probably a worthwhile
  99. * optimization. For the bounce page, we first try getting it
  100. * from the kernel allocator because that's just about as fast
  101. * as getting it from a list and because a cache of free pages
  102. * should generally be a "last resort" option for a filesystem
  103. * to be able to do its job.
  104. */
  105. spin_lock_irqsave(&ext4_crypto_ctx_lock, flags);
  106. ctx = list_first_entry_or_null(&ext4_free_crypto_ctxs,
  107. struct ext4_crypto_ctx, free_list);
  108. if (ctx)
  109. list_del(&ctx->free_list);
  110. spin_unlock_irqrestore(&ext4_crypto_ctx_lock, flags);
  111. if (!ctx) {
  112. ctx = kmem_cache_zalloc(ext4_crypto_ctx_cachep, gfp_flags);
  113. if (!ctx) {
  114. res = -ENOMEM;
  115. goto out;
  116. }
  117. ctx->flags |= EXT4_CTX_REQUIRES_FREE_ENCRYPT_FL;
  118. } else {
  119. ctx->flags &= ~EXT4_CTX_REQUIRES_FREE_ENCRYPT_FL;
  120. }
  121. ctx->flags &= ~EXT4_WRITE_PATH_FL;
  122. out:
  123. if (res) {
  124. if (!IS_ERR_OR_NULL(ctx))
  125. ext4_release_crypto_ctx(ctx);
  126. ctx = ERR_PTR(res);
  127. }
  128. return ctx;
  129. }
  130. struct workqueue_struct *ext4_read_workqueue;
  131. static DEFINE_MUTEX(crypto_init);
  132. /**
  133. * ext4_exit_crypto() - Shutdown the ext4 encryption system
  134. */
  135. void ext4_exit_crypto(void)
  136. {
  137. struct ext4_crypto_ctx *pos, *n;
  138. list_for_each_entry_safe(pos, n, &ext4_free_crypto_ctxs, free_list)
  139. kmem_cache_free(ext4_crypto_ctx_cachep, pos);
  140. INIT_LIST_HEAD(&ext4_free_crypto_ctxs);
  141. if (ext4_bounce_page_pool)
  142. mempool_destroy(ext4_bounce_page_pool);
  143. ext4_bounce_page_pool = NULL;
  144. if (ext4_read_workqueue)
  145. destroy_workqueue(ext4_read_workqueue);
  146. ext4_read_workqueue = NULL;
  147. if (ext4_crypto_ctx_cachep)
  148. kmem_cache_destroy(ext4_crypto_ctx_cachep);
  149. ext4_crypto_ctx_cachep = NULL;
  150. if (ext4_crypt_info_cachep)
  151. kmem_cache_destroy(ext4_crypt_info_cachep);
  152. ext4_crypt_info_cachep = NULL;
  153. }
  154. /**
  155. * ext4_init_crypto() - Set up for ext4 encryption.
  156. *
  157. * We only call this when we start accessing encrypted files, since it
  158. * results in memory getting allocated that wouldn't otherwise be used.
  159. *
  160. * Return: Zero on success, non-zero otherwise.
  161. */
  162. int ext4_init_crypto(void)
  163. {
  164. int i, res = -ENOMEM;
  165. mutex_lock(&crypto_init);
  166. if (ext4_read_workqueue)
  167. goto already_initialized;
  168. ext4_read_workqueue = alloc_workqueue("ext4_crypto", WQ_HIGHPRI, 0);
  169. if (!ext4_read_workqueue)
  170. goto fail;
  171. ext4_crypto_ctx_cachep = KMEM_CACHE(ext4_crypto_ctx,
  172. SLAB_RECLAIM_ACCOUNT);
  173. if (!ext4_crypto_ctx_cachep)
  174. goto fail;
  175. ext4_crypt_info_cachep = KMEM_CACHE(ext4_crypt_info,
  176. SLAB_RECLAIM_ACCOUNT);
  177. if (!ext4_crypt_info_cachep)
  178. goto fail;
  179. for (i = 0; i < num_prealloc_crypto_ctxs; i++) {
  180. struct ext4_crypto_ctx *ctx;
  181. ctx = kmem_cache_zalloc(ext4_crypto_ctx_cachep, GFP_NOFS);
  182. if (!ctx) {
  183. res = -ENOMEM;
  184. goto fail;
  185. }
  186. list_add(&ctx->free_list, &ext4_free_crypto_ctxs);
  187. }
  188. ext4_bounce_page_pool =
  189. mempool_create_page_pool(num_prealloc_crypto_pages, 0);
  190. if (!ext4_bounce_page_pool) {
  191. res = -ENOMEM;
  192. goto fail;
  193. }
  194. already_initialized:
  195. mutex_unlock(&crypto_init);
  196. return 0;
  197. fail:
  198. ext4_exit_crypto();
  199. mutex_unlock(&crypto_init);
  200. return res;
  201. }
  202. void ext4_restore_control_page(struct page *data_page)
  203. {
  204. struct ext4_crypto_ctx *ctx =
  205. (struct ext4_crypto_ctx *)page_private(data_page);
  206. set_page_private(data_page, (unsigned long)NULL);
  207. ClearPagePrivate(data_page);
  208. unlock_page(data_page);
  209. ext4_release_crypto_ctx(ctx);
  210. }
  211. /**
  212. * ext4_crypt_complete() - The completion callback for page encryption
  213. * @req: The asynchronous encryption request context
  214. * @res: The result of the encryption operation
  215. */
  216. static void ext4_crypt_complete(struct crypto_async_request *req, int res)
  217. {
  218. struct ext4_completion_result *ecr = req->data;
  219. if (res == -EINPROGRESS)
  220. return;
  221. ecr->res = res;
  222. complete(&ecr->completion);
  223. }
  224. typedef enum {
  225. EXT4_DECRYPT = 0,
  226. EXT4_ENCRYPT,
  227. } ext4_direction_t;
  228. static int ext4_page_crypto(struct inode *inode,
  229. ext4_direction_t rw,
  230. pgoff_t index,
  231. struct page *src_page,
  232. struct page *dest_page,
  233. gfp_t gfp_flags)
  234. {
  235. u8 xts_tweak[EXT4_XTS_TWEAK_SIZE];
  236. struct ablkcipher_request *req = NULL;
  237. DECLARE_EXT4_COMPLETION_RESULT(ecr);
  238. struct scatterlist dst, src;
  239. struct ext4_crypt_info *ci = EXT4_I(inode)->i_crypt_info;
  240. struct crypto_ablkcipher *tfm = ci->ci_ctfm;
  241. int res = 0;
  242. req = ablkcipher_request_alloc(tfm, gfp_flags);
  243. if (!req) {
  244. printk_ratelimited(KERN_ERR
  245. "%s: crypto_request_alloc() failed\n",
  246. __func__);
  247. return -ENOMEM;
  248. }
  249. ablkcipher_request_set_callback(
  250. req, CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
  251. ext4_crypt_complete, &ecr);
  252. BUILD_BUG_ON(EXT4_XTS_TWEAK_SIZE < sizeof(index));
  253. memcpy(xts_tweak, &index, sizeof(index));
  254. memset(&xts_tweak[sizeof(index)], 0,
  255. EXT4_XTS_TWEAK_SIZE - sizeof(index));
  256. sg_init_table(&dst, 1);
  257. sg_set_page(&dst, dest_page, PAGE_CACHE_SIZE, 0);
  258. sg_init_table(&src, 1);
  259. sg_set_page(&src, src_page, PAGE_CACHE_SIZE, 0);
  260. ablkcipher_request_set_crypt(req, &src, &dst, PAGE_CACHE_SIZE,
  261. xts_tweak);
  262. if (rw == EXT4_DECRYPT)
  263. res = crypto_ablkcipher_decrypt(req);
  264. else
  265. res = crypto_ablkcipher_encrypt(req);
  266. if (res == -EINPROGRESS || res == -EBUSY) {
  267. wait_for_completion(&ecr.completion);
  268. res = ecr.res;
  269. }
  270. ablkcipher_request_free(req);
  271. if (res) {
  272. printk_ratelimited(
  273. KERN_ERR
  274. "%s: crypto_ablkcipher_encrypt() returned %d\n",
  275. __func__, res);
  276. return res;
  277. }
  278. return 0;
  279. }
  280. static struct page *alloc_bounce_page(struct ext4_crypto_ctx *ctx,
  281. gfp_t gfp_flags)
  282. {
  283. ctx->w.bounce_page = mempool_alloc(ext4_bounce_page_pool, gfp_flags);
  284. if (ctx->w.bounce_page == NULL)
  285. return ERR_PTR(-ENOMEM);
  286. ctx->flags |= EXT4_WRITE_PATH_FL;
  287. return ctx->w.bounce_page;
  288. }
  289. /**
  290. * ext4_encrypt() - Encrypts a page
  291. * @inode: The inode for which the encryption should take place
  292. * @plaintext_page: The page to encrypt. Must be locked.
  293. *
  294. * Allocates a ciphertext page and encrypts plaintext_page into it using the ctx
  295. * encryption context.
  296. *
  297. * Called on the page write path. The caller must call
  298. * ext4_restore_control_page() on the returned ciphertext page to
  299. * release the bounce buffer and the encryption context.
  300. *
  301. * Return: An allocated page with the encrypted content on success. Else, an
  302. * error value or NULL.
  303. */
  304. struct page *ext4_encrypt(struct inode *inode,
  305. struct page *plaintext_page,
  306. gfp_t gfp_flags)
  307. {
  308. struct ext4_crypto_ctx *ctx;
  309. struct page *ciphertext_page = NULL;
  310. int err;
  311. BUG_ON(!PageLocked(plaintext_page));
  312. ctx = ext4_get_crypto_ctx(inode, gfp_flags);
  313. if (IS_ERR(ctx))
  314. return (struct page *) ctx;
  315. /* The encryption operation will require a bounce page. */
  316. ciphertext_page = alloc_bounce_page(ctx, gfp_flags);
  317. if (IS_ERR(ciphertext_page))
  318. goto errout;
  319. ctx->w.control_page = plaintext_page;
  320. err = ext4_page_crypto(inode, EXT4_ENCRYPT, plaintext_page->index,
  321. plaintext_page, ciphertext_page, gfp_flags);
  322. if (err) {
  323. ciphertext_page = ERR_PTR(err);
  324. errout:
  325. ext4_release_crypto_ctx(ctx);
  326. return ciphertext_page;
  327. }
  328. SetPagePrivate(ciphertext_page);
  329. set_page_private(ciphertext_page, (unsigned long)ctx);
  330. lock_page(ciphertext_page);
  331. return ciphertext_page;
  332. }
  333. /**
  334. * ext4_decrypt() - Decrypts a page in-place
  335. * @ctx: The encryption context.
  336. * @page: The page to decrypt. Must be locked.
  337. *
  338. * Decrypts page in-place using the ctx encryption context.
  339. *
  340. * Called from the read completion callback.
  341. *
  342. * Return: Zero on success, non-zero otherwise.
  343. */
  344. int ext4_decrypt(struct page *page)
  345. {
  346. BUG_ON(!PageLocked(page));
  347. return ext4_page_crypto(page->mapping->host, EXT4_DECRYPT,
  348. page->index, page, page, GFP_NOFS);
  349. }
  350. int ext4_encrypted_zeroout(struct inode *inode, struct ext4_extent *ex)
  351. {
  352. struct ext4_crypto_ctx *ctx;
  353. struct page *ciphertext_page = NULL;
  354. struct bio *bio;
  355. ext4_lblk_t lblk = le32_to_cpu(ex->ee_block);
  356. ext4_fsblk_t pblk = ext4_ext_pblock(ex);
  357. unsigned int len = ext4_ext_get_actual_len(ex);
  358. int ret, err = 0;
  359. #if 0
  360. ext4_msg(inode->i_sb, KERN_CRIT,
  361. "ext4_encrypted_zeroout ino %lu lblk %u len %u",
  362. (unsigned long) inode->i_ino, lblk, len);
  363. #endif
  364. BUG_ON(inode->i_sb->s_blocksize != PAGE_CACHE_SIZE);
  365. ctx = ext4_get_crypto_ctx(inode, GFP_NOFS);
  366. if (IS_ERR(ctx))
  367. return PTR_ERR(ctx);
  368. ciphertext_page = alloc_bounce_page(ctx, GFP_NOWAIT);
  369. if (IS_ERR(ciphertext_page)) {
  370. err = PTR_ERR(ciphertext_page);
  371. goto errout;
  372. }
  373. while (len--) {
  374. err = ext4_page_crypto(inode, EXT4_ENCRYPT, lblk,
  375. ZERO_PAGE(0), ciphertext_page,
  376. GFP_NOFS);
  377. if (err)
  378. goto errout;
  379. bio = bio_alloc(GFP_NOWAIT, 1);
  380. if (!bio) {
  381. err = -ENOMEM;
  382. goto errout;
  383. }
  384. bio->bi_bdev = inode->i_sb->s_bdev;
  385. bio->bi_iter.bi_sector =
  386. pblk << (inode->i_sb->s_blocksize_bits - 9);
  387. ret = bio_add_page(bio, ciphertext_page,
  388. inode->i_sb->s_blocksize, 0);
  389. if (ret != inode->i_sb->s_blocksize) {
  390. /* should never happen! */
  391. ext4_msg(inode->i_sb, KERN_ERR,
  392. "bio_add_page failed: %d", ret);
  393. WARN_ON(1);
  394. bio_put(bio);
  395. err = -EIO;
  396. goto errout;
  397. }
  398. err = submit_bio_wait(WRITE, bio);
  399. if ((err == 0) && bio->bi_error)
  400. err = -EIO;
  401. bio_put(bio);
  402. if (err)
  403. goto errout;
  404. lblk++; pblk++;
  405. }
  406. err = 0;
  407. errout:
  408. ext4_release_crypto_ctx(ctx);
  409. return err;
  410. }
  411. bool ext4_valid_contents_enc_mode(uint32_t mode)
  412. {
  413. return (mode == EXT4_ENCRYPTION_MODE_AES_256_XTS);
  414. }
  415. /**
  416. * ext4_validate_encryption_key_size() - Validate the encryption key size
  417. * @mode: The key mode.
  418. * @size: The key size to validate.
  419. *
  420. * Return: The validated key size for @mode. Zero if invalid.
  421. */
  422. uint32_t ext4_validate_encryption_key_size(uint32_t mode, uint32_t size)
  423. {
  424. if (size == ext4_encryption_key_size(mode))
  425. return size;
  426. return 0;
  427. }
  428. /*
  429. * Validate dentries for encrypted directories to make sure we aren't
  430. * potentially caching stale data after a key has been added or
  431. * removed.
  432. */
  433. static int ext4_d_revalidate(struct dentry *dentry, unsigned int flags)
  434. {
  435. struct dentry *dir;
  436. struct ext4_crypt_info *ci;
  437. int dir_has_key, cached_with_key;
  438. if (flags & LOOKUP_RCU)
  439. return -ECHILD;
  440. dir = dget_parent(dentry);
  441. if (!ext4_encrypted_inode(d_inode(dir))) {
  442. dput(dir);
  443. return 0;
  444. }
  445. ci = EXT4_I(d_inode(dir))->i_crypt_info;
  446. /* this should eventually be an flag in d_flags */
  447. cached_with_key = dentry->d_fsdata != NULL;
  448. dir_has_key = (ci != NULL);
  449. dput(dir);
  450. /*
  451. * If the dentry was cached without the key, and it is a
  452. * negative dentry, it might be a valid name. We can't check
  453. * if the key has since been made available due to locking
  454. * reasons, so we fail the validation so ext4_lookup() can do
  455. * this check.
  456. *
  457. * We also fail the validation if the dentry was created with
  458. * the key present, but we no longer have the key, or vice versa.
  459. */
  460. if ((!cached_with_key && d_is_negative(dentry)) ||
  461. (!cached_with_key && dir_has_key) ||
  462. (cached_with_key && !dir_has_key)) {
  463. #if 0 /* Revalidation debug */
  464. char buf[80];
  465. char *cp = simple_dname(dentry, buf, sizeof(buf));
  466. if (IS_ERR(cp))
  467. cp = (char *) "???";
  468. pr_err("revalidate: %s %p %d %d %d\n", cp, dentry->d_fsdata,
  469. cached_with_key, d_is_negative(dentry),
  470. dir_has_key);
  471. #endif
  472. return 0;
  473. }
  474. return 1;
  475. }
  476. const struct dentry_operations ext4_encrypted_d_ops = {
  477. .d_revalidate = ext4_d_revalidate,
  478. };