blk-crypto.c 14 KB

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