inline_crypt.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Inline encryption support for fscrypt
  4. *
  5. * Copyright 2019 Google LLC
  6. */
  7. /*
  8. * With "inline encryption", the block layer handles the decryption/encryption
  9. * as part of the bio, instead of the filesystem doing the crypto itself via
  10. * crypto API. See Documentation/block/inline-encryption.rst. fscrypt still
  11. * provides the key and IV to use.
  12. */
  13. #include <linux/blk-crypto.h>
  14. #include <linux/blkdev.h>
  15. #include <linux/buffer_head.h>
  16. #include <linux/export.h>
  17. #include <linux/sched/mm.h>
  18. #include <linux/slab.h>
  19. #include <linux/uio.h>
  20. #include "fscrypt_private.h"
  21. static struct block_device **fscrypt_get_devices(struct super_block *sb,
  22. unsigned int *num_devs)
  23. {
  24. struct block_device **devs;
  25. if (sb->s_cop->get_devices) {
  26. devs = sb->s_cop->get_devices(sb, num_devs);
  27. if (devs)
  28. return devs;
  29. }
  30. devs = kmalloc_obj(*devs);
  31. if (!devs)
  32. return ERR_PTR(-ENOMEM);
  33. devs[0] = sb->s_bdev;
  34. *num_devs = 1;
  35. return devs;
  36. }
  37. static unsigned int fscrypt_get_dun_bytes(const struct fscrypt_inode_info *ci)
  38. {
  39. const struct super_block *sb = ci->ci_inode->i_sb;
  40. unsigned int flags = fscrypt_policy_flags(&ci->ci_policy);
  41. int dun_bits;
  42. if (flags & FSCRYPT_POLICY_FLAG_DIRECT_KEY)
  43. return offsetofend(union fscrypt_iv, nonce);
  44. if (flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64)
  45. return sizeof(__le64);
  46. if (flags & FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32)
  47. return sizeof(__le32);
  48. /* Default case: IVs are just the file data unit index */
  49. dun_bits = fscrypt_max_file_dun_bits(sb, ci->ci_data_unit_bits);
  50. return DIV_ROUND_UP(dun_bits, 8);
  51. }
  52. /*
  53. * Log a message when starting to use blk-crypto (native) or blk-crypto-fallback
  54. * for an encryption mode for the first time. This is the blk-crypto
  55. * counterpart to the message logged when starting to use the crypto API for the
  56. * first time. A limitation is that these messages don't convey which specific
  57. * filesystems or files are using each implementation. However, *usually*
  58. * systems use just one implementation per mode, which makes these messages
  59. * helpful for debugging problems where the "wrong" implementation is used.
  60. */
  61. static void fscrypt_log_blk_crypto_impl(struct fscrypt_mode *mode,
  62. struct block_device **devs,
  63. unsigned int num_devs,
  64. const struct blk_crypto_config *cfg)
  65. {
  66. unsigned int i;
  67. for (i = 0; i < num_devs; i++) {
  68. if (!IS_ENABLED(CONFIG_BLK_INLINE_ENCRYPTION_FALLBACK) ||
  69. blk_crypto_config_supported_natively(devs[i], cfg)) {
  70. if (!xchg(&mode->logged_blk_crypto_native, 1))
  71. pr_info("fscrypt: %s using blk-crypto (native)\n",
  72. mode->friendly_name);
  73. } else if (!xchg(&mode->logged_blk_crypto_fallback, 1)) {
  74. pr_info("fscrypt: %s using blk-crypto-fallback\n",
  75. mode->friendly_name);
  76. }
  77. }
  78. }
  79. /* Enable inline encryption for this file if supported. */
  80. int fscrypt_select_encryption_impl(struct fscrypt_inode_info *ci,
  81. bool is_hw_wrapped_key)
  82. {
  83. const struct inode *inode = ci->ci_inode;
  84. struct super_block *sb = inode->i_sb;
  85. struct blk_crypto_config crypto_cfg;
  86. struct block_device **devs;
  87. unsigned int num_devs;
  88. unsigned int i;
  89. /* The file must need contents encryption, not filenames encryption */
  90. if (!S_ISREG(inode->i_mode))
  91. return 0;
  92. /* The crypto mode must have a blk-crypto counterpart */
  93. if (ci->ci_mode->blk_crypto_mode == BLK_ENCRYPTION_MODE_INVALID)
  94. return 0;
  95. /* The filesystem must be mounted with -o inlinecrypt */
  96. if (!(sb->s_flags & SB_INLINECRYPT))
  97. return 0;
  98. /*
  99. * When a page contains multiple logically contiguous filesystem blocks,
  100. * some filesystem code only calls fscrypt_mergeable_bio() for the first
  101. * block in the page. This is fine for most of fscrypt's IV generation
  102. * strategies, where contiguous blocks imply contiguous IVs. But it
  103. * doesn't work with IV_INO_LBLK_32. For now, simply exclude
  104. * IV_INO_LBLK_32 with blocksize != PAGE_SIZE from inline encryption.
  105. */
  106. if ((fscrypt_policy_flags(&ci->ci_policy) &
  107. FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32) &&
  108. sb->s_blocksize != PAGE_SIZE)
  109. return 0;
  110. /*
  111. * On all the filesystem's block devices, blk-crypto must support the
  112. * crypto configuration that the file would use.
  113. */
  114. crypto_cfg.crypto_mode = ci->ci_mode->blk_crypto_mode;
  115. crypto_cfg.data_unit_size = 1U << ci->ci_data_unit_bits;
  116. crypto_cfg.dun_bytes = fscrypt_get_dun_bytes(ci);
  117. crypto_cfg.key_type = is_hw_wrapped_key ?
  118. BLK_CRYPTO_KEY_TYPE_HW_WRAPPED : BLK_CRYPTO_KEY_TYPE_RAW;
  119. devs = fscrypt_get_devices(sb, &num_devs);
  120. if (IS_ERR(devs))
  121. return PTR_ERR(devs);
  122. for (i = 0; i < num_devs; i++) {
  123. if (!blk_crypto_config_supported(devs[i], &crypto_cfg))
  124. goto out_free_devs;
  125. }
  126. fscrypt_log_blk_crypto_impl(ci->ci_mode, devs, num_devs, &crypto_cfg);
  127. ci->ci_inlinecrypt = true;
  128. out_free_devs:
  129. kfree(devs);
  130. return 0;
  131. }
  132. int fscrypt_prepare_inline_crypt_key(struct fscrypt_prepared_key *prep_key,
  133. const u8 *key_bytes, size_t key_size,
  134. bool is_hw_wrapped,
  135. const struct fscrypt_inode_info *ci)
  136. {
  137. const struct inode *inode = ci->ci_inode;
  138. struct super_block *sb = inode->i_sb;
  139. enum blk_crypto_mode_num crypto_mode = ci->ci_mode->blk_crypto_mode;
  140. enum blk_crypto_key_type key_type = is_hw_wrapped ?
  141. BLK_CRYPTO_KEY_TYPE_HW_WRAPPED : BLK_CRYPTO_KEY_TYPE_RAW;
  142. struct blk_crypto_key *blk_key;
  143. struct block_device **devs;
  144. unsigned int num_devs;
  145. unsigned int i;
  146. int err;
  147. blk_key = kmalloc_obj(*blk_key);
  148. if (!blk_key)
  149. return -ENOMEM;
  150. err = blk_crypto_init_key(blk_key, key_bytes, key_size, key_type,
  151. crypto_mode, fscrypt_get_dun_bytes(ci),
  152. 1U << ci->ci_data_unit_bits);
  153. if (err) {
  154. fscrypt_err(inode, "error %d initializing blk-crypto key", err);
  155. goto fail;
  156. }
  157. /* Start using blk-crypto on all the filesystem's block devices. */
  158. devs = fscrypt_get_devices(sb, &num_devs);
  159. if (IS_ERR(devs)) {
  160. err = PTR_ERR(devs);
  161. goto fail;
  162. }
  163. for (i = 0; i < num_devs; i++) {
  164. err = blk_crypto_start_using_key(devs[i], blk_key);
  165. if (err)
  166. break;
  167. }
  168. kfree(devs);
  169. if (err) {
  170. fscrypt_err(inode, "error %d starting to use blk-crypto", err);
  171. goto fail;
  172. }
  173. /*
  174. * Pairs with the smp_load_acquire() in fscrypt_is_key_prepared().
  175. * I.e., here we publish ->blk_key with a RELEASE barrier so that
  176. * concurrent tasks can ACQUIRE it. Note that this concurrency is only
  177. * possible for per-mode keys, not for per-file keys.
  178. */
  179. smp_store_release(&prep_key->blk_key, blk_key);
  180. return 0;
  181. fail:
  182. kfree_sensitive(blk_key);
  183. return err;
  184. }
  185. void fscrypt_destroy_inline_crypt_key(struct super_block *sb,
  186. struct fscrypt_prepared_key *prep_key)
  187. {
  188. struct blk_crypto_key *blk_key = prep_key->blk_key;
  189. struct block_device **devs;
  190. unsigned int num_devs;
  191. unsigned int i;
  192. if (!blk_key)
  193. return;
  194. /* Evict the key from all the filesystem's block devices. */
  195. devs = fscrypt_get_devices(sb, &num_devs);
  196. if (!IS_ERR(devs)) {
  197. for (i = 0; i < num_devs; i++)
  198. blk_crypto_evict_key(devs[i], blk_key);
  199. kfree(devs);
  200. }
  201. kfree_sensitive(blk_key);
  202. }
  203. /*
  204. * Ask the inline encryption hardware to derive the software secret from a
  205. * hardware-wrapped key. Returns -EOPNOTSUPP if hardware-wrapped keys aren't
  206. * supported on this filesystem or hardware.
  207. */
  208. int fscrypt_derive_sw_secret(struct super_block *sb,
  209. const u8 *wrapped_key, size_t wrapped_key_size,
  210. u8 sw_secret[BLK_CRYPTO_SW_SECRET_SIZE])
  211. {
  212. int err;
  213. /* The filesystem must be mounted with -o inlinecrypt. */
  214. if (!(sb->s_flags & SB_INLINECRYPT)) {
  215. fscrypt_warn(NULL,
  216. "%s: filesystem not mounted with inlinecrypt\n",
  217. sb->s_id);
  218. return -EOPNOTSUPP;
  219. }
  220. err = blk_crypto_derive_sw_secret(sb->s_bdev, wrapped_key,
  221. wrapped_key_size, sw_secret);
  222. if (err == -EOPNOTSUPP)
  223. fscrypt_warn(NULL,
  224. "%s: block device doesn't support hardware-wrapped keys\n",
  225. sb->s_id);
  226. return err;
  227. }
  228. bool __fscrypt_inode_uses_inline_crypto(const struct inode *inode)
  229. {
  230. return fscrypt_get_inode_info_raw(inode)->ci_inlinecrypt;
  231. }
  232. EXPORT_SYMBOL_GPL(__fscrypt_inode_uses_inline_crypto);
  233. static void fscrypt_generate_dun(const struct fscrypt_inode_info *ci,
  234. u64 lblk_num,
  235. u64 dun[BLK_CRYPTO_DUN_ARRAY_SIZE])
  236. {
  237. u64 index = lblk_num << ci->ci_data_units_per_block_bits;
  238. union fscrypt_iv iv;
  239. int i;
  240. fscrypt_generate_iv(&iv, index, ci);
  241. BUILD_BUG_ON(FSCRYPT_MAX_IV_SIZE > BLK_CRYPTO_MAX_IV_SIZE);
  242. memset(dun, 0, BLK_CRYPTO_MAX_IV_SIZE);
  243. for (i = 0; i < ci->ci_mode->ivsize/sizeof(dun[0]); i++)
  244. dun[i] = le64_to_cpu(iv.dun[i]);
  245. }
  246. /**
  247. * fscrypt_set_bio_crypt_ctx() - prepare a file contents bio for inline crypto
  248. * @bio: a bio which will eventually be submitted to the file
  249. * @inode: the file's inode
  250. * @first_lblk: the first file logical block number in the I/O
  251. * @gfp_mask: memory allocation flags - these must be a waiting mask so that
  252. * bio_crypt_set_ctx can't fail.
  253. *
  254. * If the contents of the file should be encrypted (or decrypted) with inline
  255. * encryption, then assign the appropriate encryption context to the bio.
  256. *
  257. * Normally the bio should be newly allocated (i.e. no pages added yet), as
  258. * otherwise fscrypt_mergeable_bio() won't work as intended.
  259. *
  260. * The encryption context will be freed automatically when the bio is freed.
  261. */
  262. void fscrypt_set_bio_crypt_ctx(struct bio *bio, const struct inode *inode,
  263. u64 first_lblk, gfp_t gfp_mask)
  264. {
  265. const struct fscrypt_inode_info *ci;
  266. u64 dun[BLK_CRYPTO_DUN_ARRAY_SIZE];
  267. if (!fscrypt_inode_uses_inline_crypto(inode))
  268. return;
  269. ci = fscrypt_get_inode_info_raw(inode);
  270. fscrypt_generate_dun(ci, first_lblk, dun);
  271. bio_crypt_set_ctx(bio, ci->ci_enc_key.blk_key, dun, gfp_mask);
  272. }
  273. EXPORT_SYMBOL_GPL(fscrypt_set_bio_crypt_ctx);
  274. /* Extract the inode and logical block number from a buffer_head. */
  275. static bool bh_get_inode_and_lblk_num(const struct buffer_head *bh,
  276. const struct inode **inode_ret,
  277. u64 *lblk_num_ret)
  278. {
  279. struct folio *folio = bh->b_folio;
  280. const struct address_space *mapping;
  281. const struct inode *inode;
  282. /*
  283. * The ext4 journal (jbd2) can submit a buffer_head it directly created
  284. * for a non-pagecache page. fscrypt doesn't care about these.
  285. */
  286. mapping = folio_mapping(folio);
  287. if (!mapping)
  288. return false;
  289. inode = mapping->host;
  290. *inode_ret = inode;
  291. *lblk_num_ret = (folio_pos(folio) + bh_offset(bh)) >> inode->i_blkbits;
  292. return true;
  293. }
  294. /**
  295. * fscrypt_set_bio_crypt_ctx_bh() - prepare a file contents bio for inline
  296. * crypto
  297. * @bio: a bio which will eventually be submitted to the file
  298. * @first_bh: the first buffer_head for which I/O will be submitted
  299. * @gfp_mask: memory allocation flags
  300. *
  301. * Same as fscrypt_set_bio_crypt_ctx(), except this takes a buffer_head instead
  302. * of an inode and block number directly.
  303. */
  304. void fscrypt_set_bio_crypt_ctx_bh(struct bio *bio,
  305. const struct buffer_head *first_bh,
  306. gfp_t gfp_mask)
  307. {
  308. const struct inode *inode;
  309. u64 first_lblk;
  310. if (bh_get_inode_and_lblk_num(first_bh, &inode, &first_lblk))
  311. fscrypt_set_bio_crypt_ctx(bio, inode, first_lblk, gfp_mask);
  312. }
  313. EXPORT_SYMBOL_GPL(fscrypt_set_bio_crypt_ctx_bh);
  314. /**
  315. * fscrypt_mergeable_bio() - test whether data can be added to a bio
  316. * @bio: the bio being built up
  317. * @inode: the inode for the next part of the I/O
  318. * @next_lblk: the next file logical block number in the I/O
  319. *
  320. * When building a bio which may contain data which should undergo inline
  321. * encryption (or decryption) via fscrypt, filesystems should call this function
  322. * to ensure that the resulting bio contains only contiguous data unit numbers.
  323. * This will return false if the next part of the I/O cannot be merged with the
  324. * bio because either the encryption key would be different or the encryption
  325. * data unit numbers would be discontiguous.
  326. *
  327. * fscrypt_set_bio_crypt_ctx() must have already been called on the bio.
  328. *
  329. * This function isn't required in cases where crypto-mergeability is ensured in
  330. * another way, such as I/O targeting only a single file (and thus a single key)
  331. * combined with fscrypt_limit_io_blocks() to ensure DUN contiguity.
  332. *
  333. * Return: true iff the I/O is mergeable
  334. */
  335. bool fscrypt_mergeable_bio(struct bio *bio, const struct inode *inode,
  336. u64 next_lblk)
  337. {
  338. const struct bio_crypt_ctx *bc = bio->bi_crypt_context;
  339. const struct fscrypt_inode_info *ci;
  340. u64 next_dun[BLK_CRYPTO_DUN_ARRAY_SIZE];
  341. if (!!bc != fscrypt_inode_uses_inline_crypto(inode))
  342. return false;
  343. if (!bc)
  344. return true;
  345. ci = fscrypt_get_inode_info_raw(inode);
  346. /*
  347. * Comparing the key pointers is good enough, as all I/O for each key
  348. * uses the same pointer. I.e., there's currently no need to support
  349. * merging requests where the keys are the same but the pointers differ.
  350. */
  351. if (bc->bc_key != ci->ci_enc_key.blk_key)
  352. return false;
  353. fscrypt_generate_dun(ci, next_lblk, next_dun);
  354. return bio_crypt_dun_is_contiguous(bc, bio->bi_iter.bi_size, next_dun);
  355. }
  356. EXPORT_SYMBOL_GPL(fscrypt_mergeable_bio);
  357. /**
  358. * fscrypt_mergeable_bio_bh() - test whether data can be added to a bio
  359. * @bio: the bio being built up
  360. * @next_bh: the next buffer_head for which I/O will be submitted
  361. *
  362. * Same as fscrypt_mergeable_bio(), except this takes a buffer_head instead of
  363. * an inode and block number directly.
  364. *
  365. * Return: true iff the I/O is mergeable
  366. */
  367. bool fscrypt_mergeable_bio_bh(struct bio *bio,
  368. const struct buffer_head *next_bh)
  369. {
  370. const struct inode *inode;
  371. u64 next_lblk;
  372. if (!bh_get_inode_and_lblk_num(next_bh, &inode, &next_lblk))
  373. return !bio->bi_crypt_context;
  374. return fscrypt_mergeable_bio(bio, inode, next_lblk);
  375. }
  376. EXPORT_SYMBOL_GPL(fscrypt_mergeable_bio_bh);
  377. /**
  378. * fscrypt_dio_supported() - check whether DIO (direct I/O) is supported on an
  379. * inode, as far as encryption is concerned
  380. * @inode: the inode in question
  381. *
  382. * Return: %true if there are no encryption constraints that prevent DIO from
  383. * being supported; %false if DIO is unsupported. (Note that in the
  384. * %true case, the filesystem might have other, non-encryption-related
  385. * constraints that prevent DIO from actually being supported. Also, on
  386. * encrypted files the filesystem is still responsible for only allowing
  387. * DIO when requests are filesystem-block-aligned.)
  388. */
  389. bool fscrypt_dio_supported(struct inode *inode)
  390. {
  391. int err;
  392. /* If the file is unencrypted, no veto from us. */
  393. if (!fscrypt_needs_contents_encryption(inode))
  394. return true;
  395. /*
  396. * We only support DIO with inline crypto, not fs-layer crypto.
  397. *
  398. * To determine whether the inode is using inline crypto, we have to set
  399. * up the key if it wasn't already done. This is because in the current
  400. * design of fscrypt, the decision of whether to use inline crypto or
  401. * not isn't made until the inode's encryption key is being set up. In
  402. * the DIO read/write case, the key will always be set up already, since
  403. * the file will be open. But in the case of statx(), the key might not
  404. * be set up yet, as the file might not have been opened yet.
  405. */
  406. err = fscrypt_require_key(inode);
  407. if (err) {
  408. /*
  409. * Key unavailable or couldn't be set up. This edge case isn't
  410. * worth worrying about; just report that DIO is unsupported.
  411. */
  412. return false;
  413. }
  414. return fscrypt_inode_uses_inline_crypto(inode);
  415. }
  416. EXPORT_SYMBOL_GPL(fscrypt_dio_supported);
  417. /**
  418. * fscrypt_limit_io_blocks() - limit I/O blocks to avoid discontiguous DUNs
  419. * @inode: the file on which I/O is being done
  420. * @lblk: the block at which the I/O is being started from
  421. * @nr_blocks: the number of blocks we want to submit starting at @lblk
  422. *
  423. * Determine the limit to the number of blocks that can be submitted in a bio
  424. * targeting @lblk without causing a data unit number (DUN) discontiguity.
  425. *
  426. * This is normally just @nr_blocks, as normally the DUNs just increment along
  427. * with the logical blocks. (Or the file is not encrypted.)
  428. *
  429. * In rare cases, fscrypt can be using an IV generation method that allows the
  430. * DUN to wrap around within logically contiguous blocks, and that wraparound
  431. * will occur. If this happens, a value less than @nr_blocks will be returned
  432. * so that the wraparound doesn't occur in the middle of a bio, which would
  433. * cause encryption/decryption to produce wrong results.
  434. *
  435. * Return: the actual number of blocks that can be submitted
  436. */
  437. u64 fscrypt_limit_io_blocks(const struct inode *inode, u64 lblk, u64 nr_blocks)
  438. {
  439. const struct fscrypt_inode_info *ci;
  440. u32 dun;
  441. if (!fscrypt_inode_uses_inline_crypto(inode))
  442. return nr_blocks;
  443. if (nr_blocks <= 1)
  444. return nr_blocks;
  445. ci = fscrypt_get_inode_info_raw(inode);
  446. if (!(fscrypt_policy_flags(&ci->ci_policy) &
  447. FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32))
  448. return nr_blocks;
  449. /* With IV_INO_LBLK_32, the DUN can wrap around from U32_MAX to 0. */
  450. dun = ci->ci_hashed_ino + lblk;
  451. return min_t(u64, nr_blocks, (u64)U32_MAX + 1 - dun);
  452. }
  453. EXPORT_SYMBOL_GPL(fscrypt_limit_io_blocks);