crypto.c 14 KB

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