blk-crypto.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Copyright 2019 Google LLC
  4. */
  5. /*
  6. * Refer to Documentation/block/inline-encryption.rst for detailed explanation.
  7. */
  8. #define pr_fmt(fmt) "blk-crypto: " fmt
  9. #include <linux/bio.h>
  10. #include <linux/blkdev.h>
  11. #include <linux/blk-crypto-profile.h>
  12. #include <linux/module.h>
  13. #include <linux/ratelimit.h>
  14. #include <linux/slab.h>
  15. #include "blk-crypto-internal.h"
  16. const struct blk_crypto_mode blk_crypto_modes[] = {
  17. [BLK_ENCRYPTION_MODE_AES_256_XTS] = {
  18. .name = "AES-256-XTS",
  19. .cipher_str = "xts(aes)",
  20. .keysize = 64,
  21. .ivsize = 16,
  22. },
  23. [BLK_ENCRYPTION_MODE_AES_128_CBC_ESSIV] = {
  24. .name = "AES-128-CBC-ESSIV",
  25. .cipher_str = "essiv(cbc(aes),sha256)",
  26. .keysize = 16,
  27. .ivsize = 16,
  28. },
  29. [BLK_ENCRYPTION_MODE_ADIANTUM] = {
  30. .name = "Adiantum",
  31. .cipher_str = "adiantum(xchacha12,aes)",
  32. .keysize = 32,
  33. .ivsize = 32,
  34. },
  35. [BLK_ENCRYPTION_MODE_SM4_XTS] = {
  36. .name = "SM4-XTS",
  37. .cipher_str = "xts(sm4)",
  38. .keysize = 32,
  39. .ivsize = 16,
  40. },
  41. };
  42. /*
  43. * This number needs to be at least (the number of threads doing IO
  44. * concurrently) * (maximum recursive depth of a bio), so that we don't
  45. * deadlock on crypt_ctx allocations. The default is chosen to be the same
  46. * as the default number of post read contexts in both EXT4 and F2FS.
  47. */
  48. static int num_prealloc_crypt_ctxs = 128;
  49. module_param(num_prealloc_crypt_ctxs, int, 0444);
  50. MODULE_PARM_DESC(num_prealloc_crypt_ctxs,
  51. "Number of bio crypto contexts to preallocate");
  52. static struct kmem_cache *bio_crypt_ctx_cache;
  53. static mempool_t *bio_crypt_ctx_pool;
  54. static int __init bio_crypt_ctx_init(void)
  55. {
  56. size_t i;
  57. bio_crypt_ctx_cache = KMEM_CACHE(bio_crypt_ctx, 0);
  58. if (!bio_crypt_ctx_cache)
  59. goto out_no_mem;
  60. bio_crypt_ctx_pool = mempool_create_slab_pool(num_prealloc_crypt_ctxs,
  61. bio_crypt_ctx_cache);
  62. if (!bio_crypt_ctx_pool)
  63. goto out_no_mem;
  64. /* This is assumed in various places. */
  65. BUILD_BUG_ON(BLK_ENCRYPTION_MODE_INVALID != 0);
  66. /* Sanity check that no algorithm exceeds the defined limits. */
  67. for (i = 0; i < BLK_ENCRYPTION_MODE_MAX; i++) {
  68. BUG_ON(blk_crypto_modes[i].keysize > BLK_CRYPTO_MAX_KEY_SIZE);
  69. BUG_ON(blk_crypto_modes[i].ivsize > BLK_CRYPTO_MAX_IV_SIZE);
  70. }
  71. return 0;
  72. out_no_mem:
  73. panic("Failed to allocate mem for bio crypt ctxs\n");
  74. }
  75. subsys_initcall(bio_crypt_ctx_init);
  76. void bio_crypt_set_ctx(struct bio *bio, const struct blk_crypto_key *key,
  77. const u64 dun[BLK_CRYPTO_DUN_ARRAY_SIZE], gfp_t gfp_mask)
  78. {
  79. struct bio_crypt_ctx *bc;
  80. /*
  81. * The caller must use a gfp_mask that contains __GFP_DIRECT_RECLAIM so
  82. * that the mempool_alloc() can't fail.
  83. */
  84. WARN_ON_ONCE(!(gfp_mask & __GFP_DIRECT_RECLAIM));
  85. bc = mempool_alloc(bio_crypt_ctx_pool, gfp_mask);
  86. bc->bc_key = key;
  87. memcpy(bc->bc_dun, dun, sizeof(bc->bc_dun));
  88. bio->bi_crypt_context = bc;
  89. }
  90. void __bio_crypt_free_ctx(struct bio *bio)
  91. {
  92. mempool_free(bio->bi_crypt_context, bio_crypt_ctx_pool);
  93. bio->bi_crypt_context = NULL;
  94. }
  95. int __bio_crypt_clone(struct bio *dst, struct bio *src, gfp_t gfp_mask)
  96. {
  97. dst->bi_crypt_context = mempool_alloc(bio_crypt_ctx_pool, gfp_mask);
  98. if (!dst->bi_crypt_context)
  99. return -ENOMEM;
  100. *dst->bi_crypt_context = *src->bi_crypt_context;
  101. return 0;
  102. }
  103. /* Increments @dun by @inc, treating @dun as a multi-limb integer. */
  104. void bio_crypt_dun_increment(u64 dun[BLK_CRYPTO_DUN_ARRAY_SIZE],
  105. unsigned int inc)
  106. {
  107. int i;
  108. for (i = 0; inc && i < BLK_CRYPTO_DUN_ARRAY_SIZE; i++) {
  109. dun[i] += inc;
  110. /*
  111. * If the addition in this limb overflowed, then we need to
  112. * carry 1 into the next limb. Else the carry is 0.
  113. */
  114. if (dun[i] < inc)
  115. inc = 1;
  116. else
  117. inc = 0;
  118. }
  119. }
  120. void __bio_crypt_advance(struct bio *bio, unsigned int bytes)
  121. {
  122. struct bio_crypt_ctx *bc = bio->bi_crypt_context;
  123. bio_crypt_dun_increment(bc->bc_dun,
  124. bytes >> bc->bc_key->data_unit_size_bits);
  125. }
  126. /*
  127. * Returns true if @bc->bc_dun plus @bytes converted to data units is equal to
  128. * @next_dun, treating the DUNs as multi-limb integers.
  129. */
  130. bool bio_crypt_dun_is_contiguous(const struct bio_crypt_ctx *bc,
  131. unsigned int bytes,
  132. const u64 next_dun[BLK_CRYPTO_DUN_ARRAY_SIZE])
  133. {
  134. int i;
  135. unsigned int carry = bytes >> bc->bc_key->data_unit_size_bits;
  136. for (i = 0; i < BLK_CRYPTO_DUN_ARRAY_SIZE; i++) {
  137. if (bc->bc_dun[i] + carry != next_dun[i])
  138. return false;
  139. /*
  140. * If the addition in this limb overflowed, then we need to
  141. * carry 1 into the next limb. Else the carry is 0.
  142. */
  143. if ((bc->bc_dun[i] + carry) < carry)
  144. carry = 1;
  145. else
  146. carry = 0;
  147. }
  148. /* If the DUN wrapped through 0, don't treat it as contiguous. */
  149. return carry == 0;
  150. }
  151. /*
  152. * Checks that two bio crypt contexts are compatible - i.e. that
  153. * they are mergeable except for data_unit_num continuity.
  154. */
  155. static bool bio_crypt_ctx_compatible(struct bio_crypt_ctx *bc1,
  156. struct bio_crypt_ctx *bc2)
  157. {
  158. if (!bc1)
  159. return !bc2;
  160. return bc2 && bc1->bc_key == bc2->bc_key;
  161. }
  162. bool bio_crypt_rq_ctx_compatible(struct request *rq, struct bio *bio)
  163. {
  164. return bio_crypt_ctx_compatible(rq->crypt_ctx, bio->bi_crypt_context);
  165. }
  166. /*
  167. * Checks that two bio crypt contexts are compatible, and also
  168. * that their data_unit_nums are continuous (and can hence be merged)
  169. * in the order @bc1 followed by @bc2.
  170. */
  171. bool bio_crypt_ctx_mergeable(struct bio_crypt_ctx *bc1, unsigned int bc1_bytes,
  172. struct bio_crypt_ctx *bc2)
  173. {
  174. if (!bio_crypt_ctx_compatible(bc1, bc2))
  175. return false;
  176. return !bc1 || bio_crypt_dun_is_contiguous(bc1, bc1_bytes, bc2->bc_dun);
  177. }
  178. /* Check that all I/O segments are data unit aligned. */
  179. static bool bio_crypt_check_alignment(struct bio *bio)
  180. {
  181. const unsigned int data_unit_size =
  182. bio->bi_crypt_context->bc_key->crypto_cfg.data_unit_size;
  183. struct bvec_iter iter;
  184. struct bio_vec bv;
  185. bio_for_each_segment(bv, bio, iter) {
  186. if (!IS_ALIGNED(bv.bv_len | bv.bv_offset, data_unit_size))
  187. return false;
  188. }
  189. return true;
  190. }
  191. blk_status_t __blk_crypto_rq_get_keyslot(struct request *rq)
  192. {
  193. return blk_crypto_get_keyslot(rq->q->crypto_profile,
  194. rq->crypt_ctx->bc_key,
  195. &rq->crypt_keyslot);
  196. }
  197. void __blk_crypto_rq_put_keyslot(struct request *rq)
  198. {
  199. blk_crypto_put_keyslot(rq->crypt_keyslot);
  200. rq->crypt_keyslot = NULL;
  201. }
  202. void __blk_crypto_free_request(struct request *rq)
  203. {
  204. /* The keyslot, if one was needed, should have been released earlier. */
  205. if (WARN_ON_ONCE(rq->crypt_keyslot))
  206. __blk_crypto_rq_put_keyslot(rq);
  207. mempool_free(rq->crypt_ctx, bio_crypt_ctx_pool);
  208. rq->crypt_ctx = NULL;
  209. }
  210. /**
  211. * __blk_crypto_bio_prep - Prepare bio for inline encryption
  212. *
  213. * @bio_ptr: pointer to original bio pointer
  214. *
  215. * If the bio crypt context provided for the bio is supported by the underlying
  216. * device's inline encryption hardware, do nothing.
  217. *
  218. * Otherwise, try to perform en/decryption for this bio by falling back to the
  219. * kernel crypto API. When the crypto API fallback is used for encryption,
  220. * blk-crypto may choose to split the bio into 2 - the first one that will
  221. * continue to be processed and the second one that will be resubmitted via
  222. * submit_bio_noacct. A bounce bio will be allocated to encrypt the contents
  223. * of the aforementioned "first one", and *bio_ptr will be updated to this
  224. * bounce bio.
  225. *
  226. * Caller must ensure bio has bio_crypt_ctx.
  227. *
  228. * Return: true on success; false on error (and bio->bi_status will be set
  229. * appropriately, and bio_endio() will have been called so bio
  230. * submission should abort).
  231. */
  232. bool __blk_crypto_bio_prep(struct bio **bio_ptr)
  233. {
  234. struct bio *bio = *bio_ptr;
  235. const struct blk_crypto_key *bc_key = bio->bi_crypt_context->bc_key;
  236. /* Error if bio has no data. */
  237. if (WARN_ON_ONCE(!bio_has_data(bio))) {
  238. bio->bi_status = BLK_STS_IOERR;
  239. goto fail;
  240. }
  241. if (!bio_crypt_check_alignment(bio)) {
  242. bio->bi_status = BLK_STS_IOERR;
  243. goto fail;
  244. }
  245. /*
  246. * Success if device supports the encryption context, or if we succeeded
  247. * in falling back to the crypto API.
  248. */
  249. if (blk_crypto_config_supported_natively(bio->bi_bdev,
  250. &bc_key->crypto_cfg))
  251. return true;
  252. if (blk_crypto_fallback_bio_prep(bio_ptr))
  253. return true;
  254. fail:
  255. bio_endio(*bio_ptr);
  256. return false;
  257. }
  258. int __blk_crypto_rq_bio_prep(struct request *rq, struct bio *bio,
  259. gfp_t gfp_mask)
  260. {
  261. if (!rq->crypt_ctx) {
  262. rq->crypt_ctx = mempool_alloc(bio_crypt_ctx_pool, gfp_mask);
  263. if (!rq->crypt_ctx)
  264. return -ENOMEM;
  265. }
  266. *rq->crypt_ctx = *bio->bi_crypt_context;
  267. return 0;
  268. }
  269. /**
  270. * blk_crypto_init_key() - Prepare a key for use with blk-crypto
  271. * @blk_key: Pointer to the blk_crypto_key to initialize.
  272. * @raw_key: Pointer to the raw key. Must be the correct length for the chosen
  273. * @crypto_mode; see blk_crypto_modes[].
  274. * @crypto_mode: identifier for the encryption algorithm to use
  275. * @dun_bytes: number of bytes that will be used to specify the DUN when this
  276. * key is used
  277. * @data_unit_size: the data unit size to use for en/decryption
  278. *
  279. * Return: 0 on success, -errno on failure. The caller is responsible for
  280. * zeroizing both blk_key and raw_key when done with them.
  281. */
  282. int blk_crypto_init_key(struct blk_crypto_key *blk_key, const u8 *raw_key,
  283. enum blk_crypto_mode_num crypto_mode,
  284. unsigned int dun_bytes,
  285. unsigned int data_unit_size)
  286. {
  287. const struct blk_crypto_mode *mode;
  288. memset(blk_key, 0, sizeof(*blk_key));
  289. if (crypto_mode >= ARRAY_SIZE(blk_crypto_modes))
  290. return -EINVAL;
  291. mode = &blk_crypto_modes[crypto_mode];
  292. if (mode->keysize == 0)
  293. return -EINVAL;
  294. if (dun_bytes == 0 || dun_bytes > mode->ivsize)
  295. return -EINVAL;
  296. if (!is_power_of_2(data_unit_size))
  297. return -EINVAL;
  298. blk_key->crypto_cfg.crypto_mode = crypto_mode;
  299. blk_key->crypto_cfg.dun_bytes = dun_bytes;
  300. blk_key->crypto_cfg.data_unit_size = data_unit_size;
  301. blk_key->data_unit_size_bits = ilog2(data_unit_size);
  302. blk_key->size = mode->keysize;
  303. memcpy(blk_key->raw, raw_key, mode->keysize);
  304. return 0;
  305. }
  306. bool blk_crypto_config_supported_natively(struct block_device *bdev,
  307. const struct blk_crypto_config *cfg)
  308. {
  309. return __blk_crypto_cfg_supported(bdev_get_queue(bdev)->crypto_profile,
  310. cfg);
  311. }
  312. /*
  313. * Check if bios with @cfg can be en/decrypted by blk-crypto (i.e. either the
  314. * block_device it's submitted to supports inline crypto, or the
  315. * blk-crypto-fallback is enabled and supports the cfg).
  316. */
  317. bool blk_crypto_config_supported(struct block_device *bdev,
  318. const struct blk_crypto_config *cfg)
  319. {
  320. return IS_ENABLED(CONFIG_BLK_INLINE_ENCRYPTION_FALLBACK) ||
  321. blk_crypto_config_supported_natively(bdev, cfg);
  322. }
  323. /**
  324. * blk_crypto_start_using_key() - Start using a blk_crypto_key on a device
  325. * @bdev: block device to operate on
  326. * @key: A key to use on the device
  327. *
  328. * Upper layers must call this function to ensure that either the hardware
  329. * supports the key's crypto settings, or the crypto API fallback has transforms
  330. * for the needed mode allocated and ready to go. This function may allocate
  331. * an skcipher, and *should not* be called from the data path, since that might
  332. * cause a deadlock
  333. *
  334. * Return: 0 on success; -ENOPKG if the hardware doesn't support the key and
  335. * blk-crypto-fallback is either disabled or the needed algorithm
  336. * is disabled in the crypto API; or another -errno code.
  337. */
  338. int blk_crypto_start_using_key(struct block_device *bdev,
  339. const struct blk_crypto_key *key)
  340. {
  341. if (blk_crypto_config_supported_natively(bdev, &key->crypto_cfg))
  342. return 0;
  343. return blk_crypto_fallback_start_using_mode(key->crypto_cfg.crypto_mode);
  344. }
  345. /**
  346. * blk_crypto_evict_key() - Evict a blk_crypto_key from a block_device
  347. * @bdev: a block_device on which I/O using the key may have been done
  348. * @key: the key to evict
  349. *
  350. * For a given block_device, this function removes the given blk_crypto_key from
  351. * the keyslot management structures and evicts it from any underlying hardware
  352. * keyslot(s) or blk-crypto-fallback keyslot it may have been programmed into.
  353. *
  354. * Upper layers must call this before freeing the blk_crypto_key. It must be
  355. * called for every block_device the key may have been used on. The key must no
  356. * longer be in use by any I/O when this function is called.
  357. *
  358. * Context: May sleep.
  359. */
  360. void blk_crypto_evict_key(struct block_device *bdev,
  361. const struct blk_crypto_key *key)
  362. {
  363. struct request_queue *q = bdev_get_queue(bdev);
  364. int err;
  365. if (blk_crypto_config_supported_natively(bdev, &key->crypto_cfg))
  366. err = __blk_crypto_evict_key(q->crypto_profile, key);
  367. else
  368. err = blk_crypto_fallback_evict_key(key);
  369. /*
  370. * An error can only occur here if the key failed to be evicted from a
  371. * keyslot (due to a hardware or driver issue) or is allegedly still in
  372. * use by I/O (due to a kernel bug). Even in these cases, the key is
  373. * still unlinked from the keyslot management structures, and the caller
  374. * is allowed and expected to free it right away. There's nothing
  375. * callers can do to handle errors, so just log them and return void.
  376. */
  377. if (err)
  378. pr_warn_ratelimited("%pg: error %d evicting key\n", bdev, err);
  379. }
  380. EXPORT_SYMBOL_GPL(blk_crypto_evict_key);