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