crypto.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * This contains encryption functions for per-file encryption.
  4. *
  5. * Copyright (C) 2015, Google, Inc.
  6. * Copyright (C) 2015, Motorola Mobility
  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. * Add fscrypt_pullback_bio_page()
  15. * Jaegeuk Kim, 2015.
  16. *
  17. * This has not yet undergone a rigorous security audit.
  18. *
  19. * The usage of AES-XTS should conform to recommendations in NIST
  20. * Special Publication 800-38E and IEEE P1619/D16.
  21. */
  22. #include <crypto/skcipher.h>
  23. #include <linux/export.h>
  24. #include <linux/mempool.h>
  25. #include <linux/module.h>
  26. #include <linux/pagemap.h>
  27. #include <linux/ratelimit.h>
  28. #include <linux/scatterlist.h>
  29. #include "fscrypt_private.h"
  30. static unsigned int num_prealloc_crypto_pages = 32;
  31. module_param(num_prealloc_crypto_pages, uint, 0444);
  32. MODULE_PARM_DESC(num_prealloc_crypto_pages,
  33. "Number of crypto pages to preallocate");
  34. static mempool_t *fscrypt_bounce_page_pool = NULL;
  35. static struct workqueue_struct *fscrypt_read_workqueue;
  36. static DEFINE_MUTEX(fscrypt_init_mutex);
  37. struct kmem_cache *fscrypt_inode_info_cachep;
  38. void fscrypt_enqueue_decrypt_work(struct work_struct *work)
  39. {
  40. queue_work(fscrypt_read_workqueue, work);
  41. }
  42. EXPORT_SYMBOL(fscrypt_enqueue_decrypt_work);
  43. struct page *fscrypt_alloc_bounce_page(gfp_t gfp_flags)
  44. {
  45. if (WARN_ON_ONCE(!fscrypt_bounce_page_pool)) {
  46. /*
  47. * Oops, the filesystem called a function that uses the bounce
  48. * page pool, but it didn't set needs_bounce_pages.
  49. */
  50. return NULL;
  51. }
  52. return mempool_alloc(fscrypt_bounce_page_pool, gfp_flags);
  53. }
  54. /**
  55. * fscrypt_free_bounce_page() - free a ciphertext bounce page
  56. * @bounce_page: the bounce page to free, or NULL
  57. *
  58. * Free a bounce page that was allocated by fscrypt_encrypt_pagecache_blocks(),
  59. * or by fscrypt_alloc_bounce_page() directly.
  60. */
  61. void fscrypt_free_bounce_page(struct page *bounce_page)
  62. {
  63. if (!bounce_page)
  64. return;
  65. set_page_private(bounce_page, (unsigned long)NULL);
  66. ClearPagePrivate(bounce_page);
  67. mempool_free(bounce_page, fscrypt_bounce_page_pool);
  68. }
  69. EXPORT_SYMBOL(fscrypt_free_bounce_page);
  70. /*
  71. * Generate the IV for the given data unit index within the given file.
  72. * For filenames encryption, index == 0.
  73. *
  74. * Keep this in sync with fscrypt_limit_io_blocks(). fscrypt_limit_io_blocks()
  75. * needs to know about any IV generation methods where the low bits of IV don't
  76. * simply contain the data unit index (e.g., IV_INO_LBLK_32).
  77. */
  78. void fscrypt_generate_iv(union fscrypt_iv *iv, u64 index,
  79. const struct fscrypt_inode_info *ci)
  80. {
  81. u8 flags = fscrypt_policy_flags(&ci->ci_policy);
  82. memset(iv, 0, ci->ci_mode->ivsize);
  83. if (flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64) {
  84. WARN_ON_ONCE(index > U32_MAX);
  85. WARN_ON_ONCE(ci->ci_inode->i_ino > U32_MAX);
  86. index |= (u64)ci->ci_inode->i_ino << 32;
  87. } else if (flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32) {
  88. WARN_ON_ONCE(index > U32_MAX);
  89. index = (u32)(ci->ci_hashed_ino + index);
  90. } else if (flags & FSCRYPT_POLICY_FLAG_DIRECT_KEY) {
  91. memcpy(iv->nonce, ci->ci_nonce, FSCRYPT_FILE_NONCE_SIZE);
  92. }
  93. iv->index = cpu_to_le64(index);
  94. }
  95. /* Encrypt or decrypt a single "data unit" of file contents. */
  96. int fscrypt_crypt_data_unit(const struct fscrypt_inode_info *ci,
  97. fscrypt_direction_t rw, u64 index,
  98. struct page *src_page, struct page *dest_page,
  99. unsigned int len, unsigned int offs)
  100. {
  101. struct crypto_sync_skcipher *tfm = ci->ci_enc_key.tfm;
  102. SYNC_SKCIPHER_REQUEST_ON_STACK(req, tfm);
  103. union fscrypt_iv iv;
  104. struct scatterlist dst, src;
  105. int err;
  106. if (WARN_ON_ONCE(len <= 0))
  107. return -EINVAL;
  108. if (WARN_ON_ONCE(len % FSCRYPT_CONTENTS_ALIGNMENT != 0))
  109. return -EINVAL;
  110. fscrypt_generate_iv(&iv, index, ci);
  111. skcipher_request_set_callback(
  112. req, CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
  113. NULL, NULL);
  114. sg_init_table(&dst, 1);
  115. sg_set_page(&dst, dest_page, len, offs);
  116. sg_init_table(&src, 1);
  117. sg_set_page(&src, src_page, len, offs);
  118. skcipher_request_set_crypt(req, &src, &dst, len, &iv);
  119. if (rw == FS_DECRYPT)
  120. err = crypto_skcipher_decrypt(req);
  121. else
  122. err = crypto_skcipher_encrypt(req);
  123. if (err)
  124. fscrypt_err(ci->ci_inode,
  125. "%scryption failed for data unit %llu: %d",
  126. (rw == FS_DECRYPT ? "De" : "En"), index, err);
  127. return err;
  128. }
  129. /**
  130. * fscrypt_encrypt_pagecache_blocks() - Encrypt data from a pagecache folio
  131. * @folio: the locked pagecache folio containing the data to encrypt
  132. * @len: size of the data to encrypt, in bytes
  133. * @offs: offset within @page of the data to encrypt, in bytes
  134. * @gfp_flags: memory allocation flags; see details below
  135. *
  136. * This allocates a new bounce page and encrypts the given data into it. The
  137. * length and offset of the data must be aligned to the file's crypto data unit
  138. * size. Alignment to the filesystem block size fulfills this requirement, as
  139. * the filesystem block size is always a multiple of the data unit size.
  140. *
  141. * In the bounce page, the ciphertext data will be located at the same offset at
  142. * which the plaintext data was located in the source page. Any other parts of
  143. * the bounce page will be left uninitialized.
  144. *
  145. * This is for use by the filesystem's ->writepages() method.
  146. *
  147. * The bounce page allocation is mempool-backed, so it will always succeed when
  148. * @gfp_flags includes __GFP_DIRECT_RECLAIM, e.g. when it's GFP_NOFS. However,
  149. * only the first page of each bio can be allocated this way. To prevent
  150. * deadlocks, for any additional pages a mask like GFP_NOWAIT must be used.
  151. *
  152. * Return: the new encrypted bounce page on success; an ERR_PTR() on failure
  153. */
  154. struct page *fscrypt_encrypt_pagecache_blocks(struct folio *folio,
  155. size_t len, size_t offs, gfp_t gfp_flags)
  156. {
  157. const struct inode *inode = folio->mapping->host;
  158. const struct fscrypt_inode_info *ci = fscrypt_get_inode_info_raw(inode);
  159. const unsigned int du_bits = ci->ci_data_unit_bits;
  160. const unsigned int du_size = 1U << du_bits;
  161. struct page *ciphertext_page;
  162. u64 index = ((u64)folio->index << (PAGE_SHIFT - du_bits)) +
  163. (offs >> du_bits);
  164. unsigned int i;
  165. int err;
  166. VM_BUG_ON_FOLIO(folio_test_large(folio), folio);
  167. if (WARN_ON_ONCE(!folio_test_locked(folio)))
  168. return ERR_PTR(-EINVAL);
  169. if (WARN_ON_ONCE(len <= 0 || !IS_ALIGNED(len | offs, du_size)))
  170. return ERR_PTR(-EINVAL);
  171. ciphertext_page = fscrypt_alloc_bounce_page(gfp_flags);
  172. if (!ciphertext_page)
  173. return ERR_PTR(-ENOMEM);
  174. for (i = offs; i < offs + len; i += du_size, index++) {
  175. err = fscrypt_crypt_data_unit(ci, FS_ENCRYPT, index,
  176. &folio->page, ciphertext_page,
  177. du_size, i);
  178. if (err) {
  179. fscrypt_free_bounce_page(ciphertext_page);
  180. return ERR_PTR(err);
  181. }
  182. }
  183. SetPagePrivate(ciphertext_page);
  184. set_page_private(ciphertext_page, (unsigned long)folio);
  185. return ciphertext_page;
  186. }
  187. EXPORT_SYMBOL(fscrypt_encrypt_pagecache_blocks);
  188. /**
  189. * fscrypt_encrypt_block_inplace() - Encrypt a filesystem block in-place
  190. * @inode: The inode to which this block belongs
  191. * @page: The page containing the block to encrypt
  192. * @len: Size of block to encrypt. This must be a multiple of
  193. * FSCRYPT_CONTENTS_ALIGNMENT.
  194. * @offs: Byte offset within @page at which the block to encrypt begins
  195. * @lblk_num: Filesystem logical block number of the block, i.e. the 0-based
  196. * number of the block within the file
  197. *
  198. * Encrypt a possibly-compressed filesystem block that is located in an
  199. * arbitrary page, not necessarily in the original pagecache page. The @inode
  200. * and @lblk_num must be specified, as they can't be determined from @page.
  201. *
  202. * This is not compatible with fscrypt_operations::supports_subblock_data_units.
  203. *
  204. * Return: 0 on success; -errno on failure
  205. */
  206. int fscrypt_encrypt_block_inplace(const struct inode *inode, struct page *page,
  207. unsigned int len, unsigned int offs,
  208. u64 lblk_num)
  209. {
  210. if (WARN_ON_ONCE(inode->i_sb->s_cop->supports_subblock_data_units))
  211. return -EOPNOTSUPP;
  212. return fscrypt_crypt_data_unit(fscrypt_get_inode_info_raw(inode),
  213. FS_ENCRYPT, lblk_num, page, page, len,
  214. offs);
  215. }
  216. EXPORT_SYMBOL(fscrypt_encrypt_block_inplace);
  217. /**
  218. * fscrypt_decrypt_pagecache_blocks() - Decrypt data from a pagecache folio
  219. * @folio: the pagecache folio containing the data to decrypt
  220. * @len: size of the data to decrypt, in bytes
  221. * @offs: offset within @folio of the data to decrypt, in bytes
  222. *
  223. * Decrypt data that has just been read from an encrypted file. The data must
  224. * be located in a pagecache folio that is still locked and not yet uptodate.
  225. * The length and offset of the data must be aligned to the file's crypto data
  226. * unit size. Alignment to the filesystem block size fulfills this requirement,
  227. * as the filesystem block size is always a multiple of the data unit size.
  228. *
  229. * Return: 0 on success; -errno on failure
  230. */
  231. int fscrypt_decrypt_pagecache_blocks(struct folio *folio, size_t len,
  232. size_t offs)
  233. {
  234. const struct inode *inode = folio->mapping->host;
  235. const struct fscrypt_inode_info *ci = fscrypt_get_inode_info_raw(inode);
  236. const unsigned int du_bits = ci->ci_data_unit_bits;
  237. const unsigned int du_size = 1U << du_bits;
  238. u64 index = ((u64)folio->index << (PAGE_SHIFT - du_bits)) +
  239. (offs >> du_bits);
  240. size_t i;
  241. int err;
  242. if (WARN_ON_ONCE(!folio_test_locked(folio)))
  243. return -EINVAL;
  244. if (WARN_ON_ONCE(len <= 0 || !IS_ALIGNED(len | offs, du_size)))
  245. return -EINVAL;
  246. for (i = offs; i < offs + len; i += du_size, index++) {
  247. struct page *page = folio_page(folio, i >> PAGE_SHIFT);
  248. err = fscrypt_crypt_data_unit(ci, FS_DECRYPT, index, page,
  249. page, du_size, i & ~PAGE_MASK);
  250. if (err)
  251. return err;
  252. }
  253. return 0;
  254. }
  255. EXPORT_SYMBOL(fscrypt_decrypt_pagecache_blocks);
  256. /**
  257. * fscrypt_decrypt_block_inplace() - Decrypt a filesystem block in-place
  258. * @inode: The inode to which this block belongs
  259. * @page: The page containing the block to decrypt
  260. * @len: Size of block to decrypt. This must be a multiple of
  261. * FSCRYPT_CONTENTS_ALIGNMENT.
  262. * @offs: Byte offset within @page at which the block to decrypt begins
  263. * @lblk_num: Filesystem logical block number of the block, i.e. the 0-based
  264. * number of the block within the file
  265. *
  266. * Decrypt a possibly-compressed filesystem block that is located in an
  267. * arbitrary page, not necessarily in the original pagecache page. The @inode
  268. * and @lblk_num must be specified, as they can't be determined from @page.
  269. *
  270. * This is not compatible with fscrypt_operations::supports_subblock_data_units.
  271. *
  272. * Return: 0 on success; -errno on failure
  273. */
  274. int fscrypt_decrypt_block_inplace(const struct inode *inode, struct page *page,
  275. unsigned int len, unsigned int offs,
  276. u64 lblk_num)
  277. {
  278. if (WARN_ON_ONCE(inode->i_sb->s_cop->supports_subblock_data_units))
  279. return -EOPNOTSUPP;
  280. return fscrypt_crypt_data_unit(fscrypt_get_inode_info_raw(inode),
  281. FS_DECRYPT, lblk_num, page, page, len,
  282. offs);
  283. }
  284. EXPORT_SYMBOL(fscrypt_decrypt_block_inplace);
  285. /**
  286. * fscrypt_initialize() - allocate major buffers for fs encryption.
  287. * @sb: the filesystem superblock
  288. *
  289. * We only call this when we start accessing encrypted files, since it
  290. * results in memory getting allocated that wouldn't otherwise be used.
  291. *
  292. * Return: 0 on success; -errno on failure
  293. */
  294. int fscrypt_initialize(struct super_block *sb)
  295. {
  296. int err = 0;
  297. mempool_t *pool;
  298. /* pairs with smp_store_release() below */
  299. if (likely(smp_load_acquire(&fscrypt_bounce_page_pool)))
  300. return 0;
  301. /* No need to allocate a bounce page pool if this FS won't use it. */
  302. if (!sb->s_cop->needs_bounce_pages)
  303. return 0;
  304. mutex_lock(&fscrypt_init_mutex);
  305. if (fscrypt_bounce_page_pool)
  306. goto out_unlock;
  307. err = -ENOMEM;
  308. pool = mempool_create_page_pool(num_prealloc_crypto_pages, 0);
  309. if (!pool)
  310. goto out_unlock;
  311. /* pairs with smp_load_acquire() above */
  312. smp_store_release(&fscrypt_bounce_page_pool, pool);
  313. err = 0;
  314. out_unlock:
  315. mutex_unlock(&fscrypt_init_mutex);
  316. return err;
  317. }
  318. void fscrypt_msg(const struct inode *inode, const char *level,
  319. const char *fmt, ...)
  320. {
  321. static DEFINE_RATELIMIT_STATE(rs, DEFAULT_RATELIMIT_INTERVAL,
  322. DEFAULT_RATELIMIT_BURST);
  323. struct va_format vaf;
  324. va_list args;
  325. if (!__ratelimit(&rs))
  326. return;
  327. va_start(args, fmt);
  328. vaf.fmt = fmt;
  329. vaf.va = &args;
  330. if (inode && inode->i_ino)
  331. printk("%sfscrypt (%s, inode %lu): %pV\n",
  332. level, inode->i_sb->s_id, inode->i_ino, &vaf);
  333. else if (inode)
  334. printk("%sfscrypt (%s): %pV\n", level, inode->i_sb->s_id, &vaf);
  335. else
  336. printk("%sfscrypt: %pV\n", level, &vaf);
  337. va_end(args);
  338. }
  339. /**
  340. * fscrypt_init() - Set up for fs encryption.
  341. *
  342. * Return: 0 on success; -errno on failure
  343. */
  344. static int __init fscrypt_init(void)
  345. {
  346. int err = -ENOMEM;
  347. /*
  348. * Use an unbound workqueue to allow bios to be decrypted in parallel
  349. * even when they happen to complete on the same CPU. This sacrifices
  350. * locality, but it's worthwhile since decryption is CPU-intensive.
  351. *
  352. * Also use a high-priority workqueue to prioritize decryption work,
  353. * which blocks reads from completing, over regular application tasks.
  354. */
  355. fscrypt_read_workqueue = alloc_workqueue("fscrypt_read_queue",
  356. WQ_UNBOUND | WQ_HIGHPRI,
  357. num_online_cpus());
  358. if (!fscrypt_read_workqueue)
  359. goto fail;
  360. fscrypt_inode_info_cachep = KMEM_CACHE(fscrypt_inode_info,
  361. SLAB_RECLAIM_ACCOUNT);
  362. if (!fscrypt_inode_info_cachep)
  363. goto fail_free_queue;
  364. err = fscrypt_init_keyring();
  365. if (err)
  366. goto fail_free_inode_info;
  367. return 0;
  368. fail_free_inode_info:
  369. kmem_cache_destroy(fscrypt_inode_info_cachep);
  370. fail_free_queue:
  371. destroy_workqueue(fscrypt_read_workqueue);
  372. fail:
  373. return err;
  374. }
  375. late_initcall(fscrypt_init)