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