1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * Copyright (C) 2003 Jana Saout <jana@saout.de>
4 * Copyright (C) 2004 Clemens Fruhwirth <clemens@endorphin.org>
5 * Copyright (C) 2006-2020 Red Hat, Inc. All rights reserved.
6 * Copyright (C) 2013-2020 Milan Broz <gmazyland@gmail.com>
7 *
8 * This file is released under the GPL.
9 */
10
11 #include <linux/completion.h>
12 #include <linux/err.h>
13 #include <linux/module.h>
14 #include <linux/hex.h>
15 #include <linux/init.h>
16 #include <linux/kernel.h>
17 #include <linux/key.h>
18 #include <linux/bio.h>
19 #include <linux/blkdev.h>
20 #include <linux/blk-integrity.h>
21 #include <linux/crc32.h>
22 #include <linux/mempool.h>
23 #include <linux/slab.h>
24 #include <linux/crypto.h>
25 #include <linux/fips.h>
26 #include <linux/workqueue.h>
27 #include <linux/kthread.h>
28 #include <linux/backing-dev.h>
29 #include <linux/atomic.h>
30 #include <linux/scatterlist.h>
31 #include <linux/rbtree.h>
32 #include <linux/ctype.h>
33 #include <asm/page.h>
34 #include <linux/unaligned.h>
35 #include <crypto/hash.h>
36 #include <crypto/md5.h>
37 #include <crypto/skcipher.h>
38 #include <crypto/aead.h>
39 #include <crypto/authenc.h>
40 #include <crypto/utils.h>
41 #include <linux/rtnetlink.h> /* for struct rtattr and RTA macros only */
42 #include <linux/key-type.h>
43 #include <keys/user-type.h>
44 #include <keys/encrypted-type.h>
45 #include <keys/trusted-type.h>
46
47 #include <linux/device-mapper.h>
48
49 #include "dm-audit.h"
50
51 #define DM_MSG_PREFIX "crypt"
52
53 static DEFINE_IDA(workqueue_ida);
54
55 /*
56 * context holding the current state of a multi-part conversion
57 */
58 struct convert_context {
59 struct completion restart;
60 struct bio *bio_in;
61 struct bvec_iter iter_in;
62 struct bio *bio_out;
63 struct bvec_iter iter_out;
64 atomic_t cc_pending;
65 unsigned int tag_offset;
66 u64 cc_sector;
67 union {
68 struct skcipher_request *req;
69 struct aead_request *req_aead;
70 } r;
71 bool aead_recheck;
72 bool aead_failed;
73
74 };
75
76 /*
77 * per bio private data
78 */
79 struct dm_crypt_io {
80 struct crypt_config *cc;
81 struct bio *base_bio;
82 u8 *integrity_metadata;
83 bool integrity_metadata_from_pool:1;
84
85 struct work_struct work;
86
87 struct convert_context ctx;
88
89 atomic_t io_pending;
90 blk_status_t error;
91 sector_t sector;
92
93 struct bvec_iter saved_bi_iter;
94
95 struct rb_node rb_node;
96 } CRYPTO_MINALIGN_ATTR;
97
98 struct dm_crypt_request {
99 struct convert_context *ctx;
100 struct scatterlist sg_in[4];
101 struct scatterlist sg_out[4];
102 u64 iv_sector;
103 };
104
105 struct crypt_config;
106
107 struct crypt_iv_operations {
108 int (*ctr)(struct crypt_config *cc, struct dm_target *ti,
109 const char *opts);
110 void (*dtr)(struct crypt_config *cc);
111 int (*init)(struct crypt_config *cc);
112 int (*wipe)(struct crypt_config *cc);
113 int (*generator)(struct crypt_config *cc, u8 *iv,
114 struct dm_crypt_request *dmreq);
115 int (*post)(struct crypt_config *cc, u8 *iv,
116 struct dm_crypt_request *dmreq);
117 };
118
119 struct iv_benbi_private {
120 int shift;
121 };
122
123 #define LMK_SEED_SIZE 64 /* hash + 0 */
124 struct iv_lmk_private {
125 u8 *seed;
126 };
127
128 #define TCW_WHITENING_SIZE 16
129 struct iv_tcw_private {
130 u8 *iv_seed;
131 u8 *whitening;
132 };
133
134 #define ELEPHANT_MAX_KEY_SIZE 32
135 struct iv_elephant_private {
136 struct crypto_skcipher *tfm;
137 };
138
139 /*
140 * Crypt: maps a linear range of a block device
141 * and encrypts / decrypts at the same time.
142 */
143 enum flags { DM_CRYPT_SUSPENDED, DM_CRYPT_KEY_VALID,
144 DM_CRYPT_SAME_CPU, DM_CRYPT_HIGH_PRIORITY,
145 DM_CRYPT_NO_OFFLOAD, DM_CRYPT_NO_READ_WORKQUEUE,
146 DM_CRYPT_NO_WRITE_WORKQUEUE, DM_CRYPT_WRITE_INLINE };
147
148 enum cipher_flags {
149 CRYPT_MODE_INTEGRITY_AEAD, /* Use authenticated mode for cipher */
150 CRYPT_IV_LARGE_SECTORS, /* Calculate IV from sector_size, not 512B sectors */
151 CRYPT_ENCRYPT_PREPROCESS, /* Must preprocess data for encryption (elephant) */
152 CRYPT_KEY_MAC_SIZE_SET, /* The integrity_key_size option was used */
153 };
154
155 /*
156 * The fields in here must be read only after initialization.
157 */
158 struct crypt_config {
159 struct dm_dev *dev;
160 sector_t start;
161
162 struct percpu_counter n_allocated_pages;
163
164 struct workqueue_struct *io_queue;
165 struct workqueue_struct *crypt_queue;
166
167 spinlock_t write_thread_lock;
168 struct task_struct *write_thread;
169 struct rb_root write_tree;
170
171 char *cipher_string;
172 char *cipher_auth;
173 char *key_string;
174
175 const struct crypt_iv_operations *iv_gen_ops;
176 union {
177 struct iv_benbi_private benbi;
178 struct iv_lmk_private lmk;
179 struct iv_tcw_private tcw;
180 struct iv_elephant_private elephant;
181 } iv_gen_private;
182 u64 iv_offset;
183 unsigned int iv_size;
184 unsigned short sector_size;
185 unsigned char sector_shift;
186
187 union {
188 struct crypto_skcipher **tfms;
189 struct crypto_aead **tfms_aead;
190 } cipher_tfm;
191 unsigned int tfms_count;
192 int workqueue_id;
193 unsigned long cipher_flags;
194
195 /*
196 * Layout of each crypto request:
197 *
198 * struct skcipher_request
199 * context
200 * padding
201 * struct dm_crypt_request
202 * padding
203 * IV
204 *
205 * The padding is added so that dm_crypt_request and the IV are
206 * correctly aligned.
207 */
208 unsigned int dmreq_start;
209
210 unsigned int per_bio_data_size;
211
212 unsigned long flags;
213 unsigned int key_size;
214 unsigned int key_parts; /* independent parts in key buffer */
215 unsigned int key_extra_size; /* additional keys length */
216 unsigned int key_mac_size; /* MAC key size for authenc(...) */
217
218 unsigned int integrity_tag_size;
219 unsigned int integrity_iv_size;
220 unsigned int used_tag_size;
221 unsigned int tuple_size;
222
223 /*
224 * pool for per bio private data, crypto requests,
225 * encryption requeusts/buffer pages and integrity tags
226 */
227 unsigned int tag_pool_max_sectors;
228 mempool_t tag_pool;
229 mempool_t req_pool;
230 mempool_t page_pool;
231
232 struct bio_set bs;
233 struct mutex bio_alloc_lock;
234
235 u8 *authenc_key; /* space for keys in authenc() format (if used) */
236 u8 key[] __counted_by(key_size);
237 };
238
239 #define MIN_IOS 64
240 #define MAX_TAG_SIZE 480
241 #define POOL_ENTRY_SIZE 512
242
243 static DEFINE_SPINLOCK(dm_crypt_clients_lock);
244 static unsigned int dm_crypt_clients_n;
245 static volatile unsigned long dm_crypt_pages_per_client;
246 #define DM_CRYPT_MEMORY_PERCENT 2
247 #define DM_CRYPT_MIN_PAGES_PER_CLIENT (BIO_MAX_VECS * 16)
248 #define DM_CRYPT_DEFAULT_MAX_READ_SIZE 131072
249 #define DM_CRYPT_DEFAULT_MAX_WRITE_SIZE 131072
250
251 static unsigned int max_read_size = 0;
252 module_param(max_read_size, uint, 0644);
253 MODULE_PARM_DESC(max_read_size, "Maximum size of a read request");
254 static unsigned int max_write_size = 0;
255 module_param(max_write_size, uint, 0644);
256 MODULE_PARM_DESC(max_write_size, "Maximum size of a write request");
257
get_max_request_sectors(struct dm_target * ti,struct bio * bio,bool no_split)258 static unsigned get_max_request_sectors(struct dm_target *ti, struct bio *bio, bool no_split)
259 {
260 struct crypt_config *cc = ti->private;
261 unsigned val, sector_align;
262 bool wrt = op_is_write(bio_op(bio));
263
264 if (no_split) {
265 val = -1;
266 } else if (wrt) {
267 val = min_not_zero(READ_ONCE(max_write_size),
268 DM_CRYPT_DEFAULT_MAX_WRITE_SIZE);
269 } else {
270 val = min_not_zero(READ_ONCE(max_read_size),
271 DM_CRYPT_DEFAULT_MAX_READ_SIZE);
272 }
273
274 if (wrt || cc->used_tag_size)
275 val = min(val, BIO_MAX_VECS << PAGE_SHIFT);
276
277 sector_align = max(bdev_logical_block_size(cc->dev->bdev),
278 (unsigned)cc->sector_size);
279 val = round_down(val, sector_align);
280 if (unlikely(!val))
281 val = sector_align;
282 return val >> SECTOR_SHIFT;
283 }
284
285 static void crypt_endio(struct bio *clone);
286 static void kcryptd_queue_crypt(struct dm_crypt_io *io);
287 static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
288 struct scatterlist *sg);
289
290 static bool crypt_integrity_aead(struct crypt_config *cc);
291
292 /*
293 * Use this to access cipher attributes that are independent of the key.
294 */
any_tfm(struct crypt_config * cc)295 static struct crypto_skcipher *any_tfm(struct crypt_config *cc)
296 {
297 return cc->cipher_tfm.tfms[0];
298 }
299
any_tfm_aead(struct crypt_config * cc)300 static struct crypto_aead *any_tfm_aead(struct crypt_config *cc)
301 {
302 return cc->cipher_tfm.tfms_aead[0];
303 }
304
305 /*
306 * Different IV generation algorithms:
307 *
308 * plain: the initial vector is the 32-bit little-endian version of the sector
309 * number, padded with zeros if necessary.
310 *
311 * plain64: the initial vector is the 64-bit little-endian version of the sector
312 * number, padded with zeros if necessary.
313 *
314 * plain64be: the initial vector is the 64-bit big-endian version of the sector
315 * number, padded with zeros if necessary.
316 *
317 * essiv: "encrypted sector|salt initial vector", the sector number is
318 * encrypted with the bulk cipher using a salt as key. The salt
319 * should be derived from the bulk cipher's key via hashing.
320 *
321 * benbi: the 64-bit "big-endian 'narrow block'-count", starting at 1
322 * (needed for LRW-32-AES and possible other narrow block modes)
323 *
324 * null: the initial vector is always zero. Provides compatibility with
325 * obsolete loop_fish2 devices. Do not use for new devices.
326 *
327 * lmk: Compatible implementation of the block chaining mode used
328 * by the Loop-AES block device encryption system
329 * designed by Jari Ruusu. See http://loop-aes.sourceforge.net/
330 * It operates on full 512 byte sectors and uses CBC
331 * with an IV derived from the sector number, the data and
332 * optionally extra IV seed.
333 * This means that after decryption the first block
334 * of sector must be tweaked according to decrypted data.
335 * Loop-AES can use three encryption schemes:
336 * version 1: is plain aes-cbc mode
337 * version 2: uses 64 multikey scheme with lmk IV generator
338 * version 3: the same as version 2 with additional IV seed
339 * (it uses 65 keys, last key is used as IV seed)
340 *
341 * tcw: Compatible implementation of the block chaining mode used
342 * by the TrueCrypt device encryption system (prior to version 4.1).
343 * For more info see: https://gitlab.com/cryptsetup/cryptsetup/wikis/TrueCryptOnDiskFormat
344 * It operates on full 512 byte sectors and uses CBC
345 * with an IV derived from initial key and the sector number.
346 * In addition, whitening value is applied on every sector, whitening
347 * is calculated from initial key, sector number and mixed using CRC32.
348 * Note that this encryption scheme is vulnerable to watermarking attacks
349 * and should be used for old compatible containers access only.
350 *
351 * eboiv: Encrypted byte-offset IV (used in Bitlocker in CBC mode)
352 * The IV is encrypted little-endian byte-offset (with the same key
353 * and cipher as the volume).
354 *
355 * elephant: The extended version of eboiv with additional Elephant diffuser
356 * used with Bitlocker CBC mode.
357 * This mode was used in older Windows systems
358 * https://download.microsoft.com/download/0/2/3/0238acaf-d3bf-4a6d-b3d6-0a0be4bbb36e/bitlockercipher200608.pdf
359 */
360
crypt_iv_plain_gen(struct crypt_config * cc,u8 * iv,struct dm_crypt_request * dmreq)361 static int crypt_iv_plain_gen(struct crypt_config *cc, u8 *iv,
362 struct dm_crypt_request *dmreq)
363 {
364 memset(iv, 0, cc->iv_size);
365 *(__le32 *)iv = cpu_to_le32(dmreq->iv_sector & 0xffffffff);
366
367 return 0;
368 }
369
crypt_iv_plain64_gen(struct crypt_config * cc,u8 * iv,struct dm_crypt_request * dmreq)370 static int crypt_iv_plain64_gen(struct crypt_config *cc, u8 *iv,
371 struct dm_crypt_request *dmreq)
372 {
373 memset(iv, 0, cc->iv_size);
374 *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
375
376 return 0;
377 }
378
crypt_iv_plain64be_gen(struct crypt_config * cc,u8 * iv,struct dm_crypt_request * dmreq)379 static int crypt_iv_plain64be_gen(struct crypt_config *cc, u8 *iv,
380 struct dm_crypt_request *dmreq)
381 {
382 memset(iv, 0, cc->iv_size);
383 /* iv_size is at least of size u64; usually it is 16 bytes */
384 *(__be64 *)&iv[cc->iv_size - sizeof(u64)] = cpu_to_be64(dmreq->iv_sector);
385
386 return 0;
387 }
388
crypt_iv_essiv_gen(struct crypt_config * cc,u8 * iv,struct dm_crypt_request * dmreq)389 static int crypt_iv_essiv_gen(struct crypt_config *cc, u8 *iv,
390 struct dm_crypt_request *dmreq)
391 {
392 /*
393 * ESSIV encryption of the IV is now handled by the crypto API,
394 * so just pass the plain sector number here.
395 */
396 memset(iv, 0, cc->iv_size);
397 *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
398
399 return 0;
400 }
401
crypt_iv_benbi_ctr(struct crypt_config * cc,struct dm_target * ti,const char * opts)402 static int crypt_iv_benbi_ctr(struct crypt_config *cc, struct dm_target *ti,
403 const char *opts)
404 {
405 unsigned int bs;
406 int log;
407
408 if (crypt_integrity_aead(cc))
409 bs = crypto_aead_blocksize(any_tfm_aead(cc));
410 else
411 bs = crypto_skcipher_blocksize(any_tfm(cc));
412 log = ilog2(bs);
413
414 /*
415 * We need to calculate how far we must shift the sector count
416 * to get the cipher block count, we use this shift in _gen.
417 */
418 if (1 << log != bs) {
419 ti->error = "cypher blocksize is not a power of 2";
420 return -EINVAL;
421 }
422
423 if (log > 9) {
424 ti->error = "cypher blocksize is > 512";
425 return -EINVAL;
426 }
427
428 cc->iv_gen_private.benbi.shift = 9 - log;
429
430 return 0;
431 }
432
crypt_iv_benbi_dtr(struct crypt_config * cc)433 static void crypt_iv_benbi_dtr(struct crypt_config *cc)
434 {
435 }
436
crypt_iv_benbi_gen(struct crypt_config * cc,u8 * iv,struct dm_crypt_request * dmreq)437 static int crypt_iv_benbi_gen(struct crypt_config *cc, u8 *iv,
438 struct dm_crypt_request *dmreq)
439 {
440 __be64 val;
441
442 memset(iv, 0, cc->iv_size - sizeof(u64)); /* rest is cleared below */
443
444 val = cpu_to_be64(((u64)dmreq->iv_sector << cc->iv_gen_private.benbi.shift) + 1);
445 put_unaligned(val, (__be64 *)(iv + cc->iv_size - sizeof(u64)));
446
447 return 0;
448 }
449
crypt_iv_null_gen(struct crypt_config * cc,u8 * iv,struct dm_crypt_request * dmreq)450 static int crypt_iv_null_gen(struct crypt_config *cc, u8 *iv,
451 struct dm_crypt_request *dmreq)
452 {
453 memset(iv, 0, cc->iv_size);
454
455 return 0;
456 }
457
crypt_iv_lmk_dtr(struct crypt_config * cc)458 static void crypt_iv_lmk_dtr(struct crypt_config *cc)
459 {
460 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
461
462 kfree_sensitive(lmk->seed);
463 lmk->seed = NULL;
464 }
465
crypt_iv_lmk_ctr(struct crypt_config * cc,struct dm_target * ti,const char * opts)466 static int crypt_iv_lmk_ctr(struct crypt_config *cc, struct dm_target *ti,
467 const char *opts)
468 {
469 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
470
471 if (cc->sector_size != (1 << SECTOR_SHIFT)) {
472 ti->error = "Unsupported sector size for LMK";
473 return -EINVAL;
474 }
475
476 if (fips_enabled) {
477 ti->error = "LMK support is disabled due to FIPS";
478 /* ... because it uses MD5. */
479 return -EINVAL;
480 }
481
482 /* No seed in LMK version 2 */
483 if (cc->key_parts == cc->tfms_count) {
484 lmk->seed = NULL;
485 return 0;
486 }
487
488 lmk->seed = kzalloc(LMK_SEED_SIZE, GFP_KERNEL);
489 if (!lmk->seed) {
490 ti->error = "Error kmallocing seed storage in LMK";
491 return -ENOMEM;
492 }
493
494 return 0;
495 }
496
crypt_iv_lmk_init(struct crypt_config * cc)497 static int crypt_iv_lmk_init(struct crypt_config *cc)
498 {
499 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
500 int subkey_size = cc->key_size / cc->key_parts;
501
502 /* LMK seed is on the position of LMK_KEYS + 1 key */
503 if (lmk->seed)
504 memcpy(lmk->seed, cc->key + (cc->tfms_count * subkey_size),
505 MD5_DIGEST_SIZE);
506
507 return 0;
508 }
509
crypt_iv_lmk_wipe(struct crypt_config * cc)510 static int crypt_iv_lmk_wipe(struct crypt_config *cc)
511 {
512 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
513
514 if (lmk->seed)
515 memset(lmk->seed, 0, LMK_SEED_SIZE);
516
517 return 0;
518 }
519
crypt_iv_lmk_one(struct crypt_config * cc,u8 * iv,struct dm_crypt_request * dmreq,u8 * data)520 static void crypt_iv_lmk_one(struct crypt_config *cc, u8 *iv,
521 struct dm_crypt_request *dmreq, u8 *data)
522 {
523 struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
524 struct md5_ctx ctx;
525 __le32 buf[4];
526
527 md5_init(&ctx);
528
529 if (lmk->seed)
530 md5_update(&ctx, lmk->seed, LMK_SEED_SIZE);
531
532 /* Sector is always 512B, block size 16, add data of blocks 1-31 */
533 md5_update(&ctx, data + 16, 16 * 31);
534
535 /* Sector is cropped to 56 bits here */
536 buf[0] = cpu_to_le32(dmreq->iv_sector & 0xFFFFFFFF);
537 buf[1] = cpu_to_le32((((u64)dmreq->iv_sector >> 32) & 0x00FFFFFF) | 0x80000000);
538 buf[2] = cpu_to_le32(4024);
539 buf[3] = 0;
540 md5_update(&ctx, (u8 *)buf, sizeof(buf));
541
542 /* No MD5 padding here */
543 cpu_to_le32_array(ctx.state.h, ARRAY_SIZE(ctx.state.h));
544 memcpy(iv, ctx.state.h, cc->iv_size);
545 }
546
crypt_iv_lmk_gen(struct crypt_config * cc,u8 * iv,struct dm_crypt_request * dmreq)547 static int crypt_iv_lmk_gen(struct crypt_config *cc, u8 *iv,
548 struct dm_crypt_request *dmreq)
549 {
550 struct scatterlist *sg;
551 u8 *src;
552
553 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
554 sg = crypt_get_sg_data(cc, dmreq->sg_in);
555 src = kmap_local_page(sg_page(sg));
556 crypt_iv_lmk_one(cc, iv, dmreq, src + sg->offset);
557 kunmap_local(src);
558 } else
559 memset(iv, 0, cc->iv_size);
560 return 0;
561 }
562
crypt_iv_lmk_post(struct crypt_config * cc,u8 * iv,struct dm_crypt_request * dmreq)563 static int crypt_iv_lmk_post(struct crypt_config *cc, u8 *iv,
564 struct dm_crypt_request *dmreq)
565 {
566 struct scatterlist *sg;
567 u8 *dst;
568
569 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE)
570 return 0;
571
572 sg = crypt_get_sg_data(cc, dmreq->sg_out);
573 dst = kmap_local_page(sg_page(sg));
574 crypt_iv_lmk_one(cc, iv, dmreq, dst + sg->offset);
575
576 /* Tweak the first block of plaintext sector */
577 crypto_xor(dst + sg->offset, iv, cc->iv_size);
578
579 kunmap_local(dst);
580 return 0;
581 }
582
crypt_iv_tcw_dtr(struct crypt_config * cc)583 static void crypt_iv_tcw_dtr(struct crypt_config *cc)
584 {
585 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
586
587 kfree_sensitive(tcw->iv_seed);
588 tcw->iv_seed = NULL;
589 kfree_sensitive(tcw->whitening);
590 tcw->whitening = NULL;
591 }
592
crypt_iv_tcw_ctr(struct crypt_config * cc,struct dm_target * ti,const char * opts)593 static int crypt_iv_tcw_ctr(struct crypt_config *cc, struct dm_target *ti,
594 const char *opts)
595 {
596 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
597
598 if (cc->sector_size != (1 << SECTOR_SHIFT)) {
599 ti->error = "Unsupported sector size for TCW";
600 return -EINVAL;
601 }
602
603 if (cc->key_size <= (cc->iv_size + TCW_WHITENING_SIZE)) {
604 ti->error = "Wrong key size for TCW";
605 return -EINVAL;
606 }
607
608 tcw->iv_seed = kzalloc(cc->iv_size, GFP_KERNEL);
609 tcw->whitening = kzalloc(TCW_WHITENING_SIZE, GFP_KERNEL);
610 if (!tcw->iv_seed || !tcw->whitening) {
611 crypt_iv_tcw_dtr(cc);
612 ti->error = "Error allocating seed storage in TCW";
613 return -ENOMEM;
614 }
615
616 return 0;
617 }
618
crypt_iv_tcw_init(struct crypt_config * cc)619 static int crypt_iv_tcw_init(struct crypt_config *cc)
620 {
621 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
622 int key_offset = cc->key_size - cc->iv_size - TCW_WHITENING_SIZE;
623
624 memcpy(tcw->iv_seed, &cc->key[key_offset], cc->iv_size);
625 memcpy(tcw->whitening, &cc->key[key_offset + cc->iv_size],
626 TCW_WHITENING_SIZE);
627
628 return 0;
629 }
630
crypt_iv_tcw_wipe(struct crypt_config * cc)631 static int crypt_iv_tcw_wipe(struct crypt_config *cc)
632 {
633 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
634
635 memset(tcw->iv_seed, 0, cc->iv_size);
636 memset(tcw->whitening, 0, TCW_WHITENING_SIZE);
637
638 return 0;
639 }
640
crypt_iv_tcw_whitening(struct crypt_config * cc,struct dm_crypt_request * dmreq,u8 * data)641 static void crypt_iv_tcw_whitening(struct crypt_config *cc,
642 struct dm_crypt_request *dmreq, u8 *data)
643 {
644 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
645 __le64 sector = cpu_to_le64(dmreq->iv_sector);
646 u8 buf[TCW_WHITENING_SIZE];
647 int i;
648
649 /* xor whitening with sector number */
650 crypto_xor_cpy(buf, tcw->whitening, (u8 *)§or, 8);
651 crypto_xor_cpy(&buf[8], tcw->whitening + 8, (u8 *)§or, 8);
652
653 /* calculate crc32 for every 32bit part and xor it */
654 for (i = 0; i < 4; i++)
655 put_unaligned_le32(crc32(0, &buf[i * 4], 4), &buf[i * 4]);
656 crypto_xor(&buf[0], &buf[12], 4);
657 crypto_xor(&buf[4], &buf[8], 4);
658
659 /* apply whitening (8 bytes) to whole sector */
660 for (i = 0; i < ((1 << SECTOR_SHIFT) / 8); i++)
661 crypto_xor(data + i * 8, buf, 8);
662 memzero_explicit(buf, sizeof(buf));
663 }
664
crypt_iv_tcw_gen(struct crypt_config * cc,u8 * iv,struct dm_crypt_request * dmreq)665 static int crypt_iv_tcw_gen(struct crypt_config *cc, u8 *iv,
666 struct dm_crypt_request *dmreq)
667 {
668 struct scatterlist *sg;
669 struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
670 __le64 sector = cpu_to_le64(dmreq->iv_sector);
671 u8 *src;
672
673 /* Remove whitening from ciphertext */
674 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
675 sg = crypt_get_sg_data(cc, dmreq->sg_in);
676 src = kmap_local_page(sg_page(sg));
677 crypt_iv_tcw_whitening(cc, dmreq, src + sg->offset);
678 kunmap_local(src);
679 }
680
681 /* Calculate IV */
682 crypto_xor_cpy(iv, tcw->iv_seed, (u8 *)§or, 8);
683 if (cc->iv_size > 8)
684 crypto_xor_cpy(&iv[8], tcw->iv_seed + 8, (u8 *)§or,
685 cc->iv_size - 8);
686
687 return 0;
688 }
689
crypt_iv_tcw_post(struct crypt_config * cc,u8 * iv,struct dm_crypt_request * dmreq)690 static int crypt_iv_tcw_post(struct crypt_config *cc, u8 *iv,
691 struct dm_crypt_request *dmreq)
692 {
693 struct scatterlist *sg;
694 u8 *dst;
695
696 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
697 return 0;
698
699 /* Apply whitening on ciphertext */
700 sg = crypt_get_sg_data(cc, dmreq->sg_out);
701 dst = kmap_local_page(sg_page(sg));
702 crypt_iv_tcw_whitening(cc, dmreq, dst + sg->offset);
703 kunmap_local(dst);
704
705 return 0;
706 }
707
crypt_iv_random_gen(struct crypt_config * cc,u8 * iv,struct dm_crypt_request * dmreq)708 static int crypt_iv_random_gen(struct crypt_config *cc, u8 *iv,
709 struct dm_crypt_request *dmreq)
710 {
711 /* Used only for writes, there must be an additional space to store IV */
712 get_random_bytes(iv, cc->iv_size);
713 return 0;
714 }
715
crypt_iv_eboiv_ctr(struct crypt_config * cc,struct dm_target * ti,const char * opts)716 static int crypt_iv_eboiv_ctr(struct crypt_config *cc, struct dm_target *ti,
717 const char *opts)
718 {
719 if (crypt_integrity_aead(cc)) {
720 ti->error = "AEAD transforms not supported for EBOIV";
721 return -EINVAL;
722 }
723
724 if (crypto_skcipher_blocksize(any_tfm(cc)) != cc->iv_size) {
725 ti->error = "Block size of EBOIV cipher does not match IV size of block cipher";
726 return -EINVAL;
727 }
728
729 return 0;
730 }
731
crypt_iv_eboiv_gen(struct crypt_config * cc,u8 * iv,struct dm_crypt_request * dmreq)732 static int crypt_iv_eboiv_gen(struct crypt_config *cc, u8 *iv,
733 struct dm_crypt_request *dmreq)
734 {
735 struct crypto_skcipher *tfm = any_tfm(cc);
736 struct skcipher_request *req;
737 struct scatterlist src, dst;
738 DECLARE_CRYPTO_WAIT(wait);
739 unsigned int reqsize;
740 int err;
741 u8 *buf;
742
743 reqsize = sizeof(*req) + crypto_skcipher_reqsize(tfm);
744 reqsize = ALIGN(reqsize, __alignof__(__le64));
745
746 req = kmalloc(reqsize + cc->iv_size, GFP_NOIO);
747 if (!req)
748 return -ENOMEM;
749
750 skcipher_request_set_tfm(req, tfm);
751
752 buf = (u8 *)req + reqsize;
753 memset(buf, 0, cc->iv_size);
754 *(__le64 *)buf = cpu_to_le64(dmreq->iv_sector * cc->sector_size);
755
756 sg_init_one(&src, page_address(ZERO_PAGE(0)), cc->iv_size);
757 sg_init_one(&dst, iv, cc->iv_size);
758 skcipher_request_set_crypt(req, &src, &dst, cc->iv_size, buf);
759 skcipher_request_set_callback(req, 0, crypto_req_done, &wait);
760 err = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
761 kfree_sensitive(req);
762
763 return err;
764 }
765
crypt_iv_elephant_dtr(struct crypt_config * cc)766 static void crypt_iv_elephant_dtr(struct crypt_config *cc)
767 {
768 struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
769
770 crypto_free_skcipher(elephant->tfm);
771 elephant->tfm = NULL;
772 }
773
crypt_iv_elephant_ctr(struct crypt_config * cc,struct dm_target * ti,const char * opts)774 static int crypt_iv_elephant_ctr(struct crypt_config *cc, struct dm_target *ti,
775 const char *opts)
776 {
777 struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
778 int r;
779
780 elephant->tfm = crypto_alloc_skcipher("ecb(aes)", 0,
781 CRYPTO_ALG_ALLOCATES_MEMORY);
782 if (IS_ERR(elephant->tfm)) {
783 r = PTR_ERR(elephant->tfm);
784 elephant->tfm = NULL;
785 return r;
786 }
787
788 r = crypt_iv_eboiv_ctr(cc, ti, NULL);
789 if (r)
790 crypt_iv_elephant_dtr(cc);
791 return r;
792 }
793
diffuser_disk_to_cpu(u32 * d,size_t n)794 static void diffuser_disk_to_cpu(u32 *d, size_t n)
795 {
796 #ifndef __LITTLE_ENDIAN
797 int i;
798
799 for (i = 0; i < n; i++)
800 d[i] = le32_to_cpu((__le32)d[i]);
801 #endif
802 }
803
diffuser_cpu_to_disk(__le32 * d,size_t n)804 static void diffuser_cpu_to_disk(__le32 *d, size_t n)
805 {
806 #ifndef __LITTLE_ENDIAN
807 int i;
808
809 for (i = 0; i < n; i++)
810 d[i] = cpu_to_le32((u32)d[i]);
811 #endif
812 }
813
diffuser_a_decrypt(u32 * d,size_t n)814 static void diffuser_a_decrypt(u32 *d, size_t n)
815 {
816 int i, i1, i2, i3;
817
818 for (i = 0; i < 5; i++) {
819 i1 = 0;
820 i2 = n - 2;
821 i3 = n - 5;
822
823 while (i1 < (n - 1)) {
824 d[i1] += d[i2] ^ (d[i3] << 9 | d[i3] >> 23);
825 i1++; i2++; i3++;
826
827 if (i3 >= n)
828 i3 -= n;
829
830 d[i1] += d[i2] ^ d[i3];
831 i1++; i2++; i3++;
832
833 if (i2 >= n)
834 i2 -= n;
835
836 d[i1] += d[i2] ^ (d[i3] << 13 | d[i3] >> 19);
837 i1++; i2++; i3++;
838
839 d[i1] += d[i2] ^ d[i3];
840 i1++; i2++; i3++;
841 }
842 }
843 }
844
diffuser_a_encrypt(u32 * d,size_t n)845 static void diffuser_a_encrypt(u32 *d, size_t n)
846 {
847 int i, i1, i2, i3;
848
849 for (i = 0; i < 5; i++) {
850 i1 = n - 1;
851 i2 = n - 2 - 1;
852 i3 = n - 5 - 1;
853
854 while (i1 > 0) {
855 d[i1] -= d[i2] ^ d[i3];
856 i1--; i2--; i3--;
857
858 d[i1] -= d[i2] ^ (d[i3] << 13 | d[i3] >> 19);
859 i1--; i2--; i3--;
860
861 if (i2 < 0)
862 i2 += n;
863
864 d[i1] -= d[i2] ^ d[i3];
865 i1--; i2--; i3--;
866
867 if (i3 < 0)
868 i3 += n;
869
870 d[i1] -= d[i2] ^ (d[i3] << 9 | d[i3] >> 23);
871 i1--; i2--; i3--;
872 }
873 }
874 }
875
diffuser_b_decrypt(u32 * d,size_t n)876 static void diffuser_b_decrypt(u32 *d, size_t n)
877 {
878 int i, i1, i2, i3;
879
880 for (i = 0; i < 3; i++) {
881 i1 = 0;
882 i2 = 2;
883 i3 = 5;
884
885 while (i1 < (n - 1)) {
886 d[i1] += d[i2] ^ d[i3];
887 i1++; i2++; i3++;
888
889 d[i1] += d[i2] ^ (d[i3] << 10 | d[i3] >> 22);
890 i1++; i2++; i3++;
891
892 if (i2 >= n)
893 i2 -= n;
894
895 d[i1] += d[i2] ^ d[i3];
896 i1++; i2++; i3++;
897
898 if (i3 >= n)
899 i3 -= n;
900
901 d[i1] += d[i2] ^ (d[i3] << 25 | d[i3] >> 7);
902 i1++; i2++; i3++;
903 }
904 }
905 }
906
diffuser_b_encrypt(u32 * d,size_t n)907 static void diffuser_b_encrypt(u32 *d, size_t n)
908 {
909 int i, i1, i2, i3;
910
911 for (i = 0; i < 3; i++) {
912 i1 = n - 1;
913 i2 = 2 - 1;
914 i3 = 5 - 1;
915
916 while (i1 > 0) {
917 d[i1] -= d[i2] ^ (d[i3] << 25 | d[i3] >> 7);
918 i1--; i2--; i3--;
919
920 if (i3 < 0)
921 i3 += n;
922
923 d[i1] -= d[i2] ^ d[i3];
924 i1--; i2--; i3--;
925
926 if (i2 < 0)
927 i2 += n;
928
929 d[i1] -= d[i2] ^ (d[i3] << 10 | d[i3] >> 22);
930 i1--; i2--; i3--;
931
932 d[i1] -= d[i2] ^ d[i3];
933 i1--; i2--; i3--;
934 }
935 }
936 }
937
crypt_iv_elephant(struct crypt_config * cc,struct dm_crypt_request * dmreq)938 static int crypt_iv_elephant(struct crypt_config *cc, struct dm_crypt_request *dmreq)
939 {
940 struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
941 u8 *es, *ks, *data, *data2, *data_offset;
942 struct skcipher_request *req;
943 struct scatterlist *sg, *sg2, src, dst;
944 DECLARE_CRYPTO_WAIT(wait);
945 int i, r;
946
947 req = skcipher_request_alloc(elephant->tfm, GFP_NOIO);
948 es = kzalloc(16, GFP_NOIO); /* Key for AES */
949 ks = kzalloc(32, GFP_NOIO); /* Elephant sector key */
950
951 if (!req || !es || !ks) {
952 r = -ENOMEM;
953 goto out;
954 }
955
956 *(__le64 *)es = cpu_to_le64(dmreq->iv_sector * cc->sector_size);
957
958 /* E(Ks, e(s)) */
959 sg_init_one(&src, es, 16);
960 sg_init_one(&dst, ks, 16);
961 skcipher_request_set_crypt(req, &src, &dst, 16, NULL);
962 skcipher_request_set_callback(req, 0, crypto_req_done, &wait);
963 r = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
964 if (r)
965 goto out;
966
967 /* E(Ks, e'(s)) */
968 es[15] = 0x80;
969 sg_init_one(&dst, &ks[16], 16);
970 r = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
971 if (r)
972 goto out;
973
974 sg = crypt_get_sg_data(cc, dmreq->sg_out);
975 data = kmap_local_page(sg_page(sg));
976 data_offset = data + sg->offset;
977
978 /* Cannot modify original bio, copy to sg_out and apply Elephant to it */
979 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
980 sg2 = crypt_get_sg_data(cc, dmreq->sg_in);
981 data2 = kmap_local_page(sg_page(sg2));
982 memcpy(data_offset, data2 + sg2->offset, cc->sector_size);
983 kunmap_local(data2);
984 }
985
986 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
987 diffuser_disk_to_cpu((u32 *)data_offset, cc->sector_size / sizeof(u32));
988 diffuser_b_decrypt((u32 *)data_offset, cc->sector_size / sizeof(u32));
989 diffuser_a_decrypt((u32 *)data_offset, cc->sector_size / sizeof(u32));
990 diffuser_cpu_to_disk((__le32 *)data_offset, cc->sector_size / sizeof(u32));
991 }
992
993 for (i = 0; i < (cc->sector_size / 32); i++)
994 crypto_xor(data_offset + i * 32, ks, 32);
995
996 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
997 diffuser_disk_to_cpu((u32 *)data_offset, cc->sector_size / sizeof(u32));
998 diffuser_a_encrypt((u32 *)data_offset, cc->sector_size / sizeof(u32));
999 diffuser_b_encrypt((u32 *)data_offset, cc->sector_size / sizeof(u32));
1000 diffuser_cpu_to_disk((__le32 *)data_offset, cc->sector_size / sizeof(u32));
1001 }
1002
1003 kunmap_local(data);
1004 out:
1005 kfree_sensitive(ks);
1006 kfree_sensitive(es);
1007 skcipher_request_free(req);
1008 return r;
1009 }
1010
crypt_iv_elephant_gen(struct crypt_config * cc,u8 * iv,struct dm_crypt_request * dmreq)1011 static int crypt_iv_elephant_gen(struct crypt_config *cc, u8 *iv,
1012 struct dm_crypt_request *dmreq)
1013 {
1014 int r;
1015
1016 if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
1017 r = crypt_iv_elephant(cc, dmreq);
1018 if (r)
1019 return r;
1020 }
1021
1022 return crypt_iv_eboiv_gen(cc, iv, dmreq);
1023 }
1024
crypt_iv_elephant_post(struct crypt_config * cc,u8 * iv,struct dm_crypt_request * dmreq)1025 static int crypt_iv_elephant_post(struct crypt_config *cc, u8 *iv,
1026 struct dm_crypt_request *dmreq)
1027 {
1028 if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
1029 return crypt_iv_elephant(cc, dmreq);
1030
1031 return 0;
1032 }
1033
crypt_iv_elephant_init(struct crypt_config * cc)1034 static int crypt_iv_elephant_init(struct crypt_config *cc)
1035 {
1036 struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
1037 int key_offset = cc->key_size - cc->key_extra_size;
1038
1039 return crypto_skcipher_setkey(elephant->tfm, &cc->key[key_offset], cc->key_extra_size);
1040 }
1041
crypt_iv_elephant_wipe(struct crypt_config * cc)1042 static int crypt_iv_elephant_wipe(struct crypt_config *cc)
1043 {
1044 struct iv_elephant_private *elephant = &cc->iv_gen_private.elephant;
1045 u8 key[ELEPHANT_MAX_KEY_SIZE];
1046
1047 memset(key, 0, cc->key_extra_size);
1048 return crypto_skcipher_setkey(elephant->tfm, key, cc->key_extra_size);
1049 }
1050
1051 static const struct crypt_iv_operations crypt_iv_plain_ops = {
1052 .generator = crypt_iv_plain_gen
1053 };
1054
1055 static const struct crypt_iv_operations crypt_iv_plain64_ops = {
1056 .generator = crypt_iv_plain64_gen
1057 };
1058
1059 static const struct crypt_iv_operations crypt_iv_plain64be_ops = {
1060 .generator = crypt_iv_plain64be_gen
1061 };
1062
1063 static const struct crypt_iv_operations crypt_iv_essiv_ops = {
1064 .generator = crypt_iv_essiv_gen
1065 };
1066
1067 static const struct crypt_iv_operations crypt_iv_benbi_ops = {
1068 .ctr = crypt_iv_benbi_ctr,
1069 .dtr = crypt_iv_benbi_dtr,
1070 .generator = crypt_iv_benbi_gen
1071 };
1072
1073 static const struct crypt_iv_operations crypt_iv_null_ops = {
1074 .generator = crypt_iv_null_gen
1075 };
1076
1077 static const struct crypt_iv_operations crypt_iv_lmk_ops = {
1078 .ctr = crypt_iv_lmk_ctr,
1079 .dtr = crypt_iv_lmk_dtr,
1080 .init = crypt_iv_lmk_init,
1081 .wipe = crypt_iv_lmk_wipe,
1082 .generator = crypt_iv_lmk_gen,
1083 .post = crypt_iv_lmk_post
1084 };
1085
1086 static const struct crypt_iv_operations crypt_iv_tcw_ops = {
1087 .ctr = crypt_iv_tcw_ctr,
1088 .dtr = crypt_iv_tcw_dtr,
1089 .init = crypt_iv_tcw_init,
1090 .wipe = crypt_iv_tcw_wipe,
1091 .generator = crypt_iv_tcw_gen,
1092 .post = crypt_iv_tcw_post
1093 };
1094
1095 static const struct crypt_iv_operations crypt_iv_random_ops = {
1096 .generator = crypt_iv_random_gen
1097 };
1098
1099 static const struct crypt_iv_operations crypt_iv_eboiv_ops = {
1100 .ctr = crypt_iv_eboiv_ctr,
1101 .generator = crypt_iv_eboiv_gen
1102 };
1103
1104 static const struct crypt_iv_operations crypt_iv_elephant_ops = {
1105 .ctr = crypt_iv_elephant_ctr,
1106 .dtr = crypt_iv_elephant_dtr,
1107 .init = crypt_iv_elephant_init,
1108 .wipe = crypt_iv_elephant_wipe,
1109 .generator = crypt_iv_elephant_gen,
1110 .post = crypt_iv_elephant_post
1111 };
1112
1113 /*
1114 * Integrity extensions
1115 */
crypt_integrity_aead(struct crypt_config * cc)1116 static bool crypt_integrity_aead(struct crypt_config *cc)
1117 {
1118 return test_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
1119 }
1120
crypt_integrity_hmac(struct crypt_config * cc)1121 static bool crypt_integrity_hmac(struct crypt_config *cc)
1122 {
1123 return crypt_integrity_aead(cc) && cc->key_mac_size;
1124 }
1125
1126 /* Get sg containing data */
crypt_get_sg_data(struct crypt_config * cc,struct scatterlist * sg)1127 static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
1128 struct scatterlist *sg)
1129 {
1130 if (unlikely(crypt_integrity_aead(cc)))
1131 return &sg[2];
1132
1133 return sg;
1134 }
1135
dm_crypt_integrity_io_alloc(struct dm_crypt_io * io,struct bio * bio)1136 static int dm_crypt_integrity_io_alloc(struct dm_crypt_io *io, struct bio *bio)
1137 {
1138 struct bio_integrity_payload *bip;
1139 unsigned int tag_len;
1140 int ret;
1141
1142 if (!bio_sectors(bio) || !io->cc->tuple_size)
1143 return 0;
1144
1145 bip = bio_integrity_alloc(bio, GFP_NOIO, 1);
1146 if (IS_ERR(bip))
1147 return PTR_ERR(bip);
1148
1149 tag_len = io->cc->tuple_size * (bio_sectors(bio) >> io->cc->sector_shift);
1150
1151 bip->bip_iter.bi_sector = bio->bi_iter.bi_sector;
1152
1153 ret = bio_integrity_add_page(bio, virt_to_page(io->integrity_metadata),
1154 tag_len, offset_in_page(io->integrity_metadata));
1155 if (unlikely(ret != tag_len))
1156 return -ENOMEM;
1157
1158 return 0;
1159 }
1160
crypt_integrity_ctr(struct crypt_config * cc,struct dm_target * ti)1161 static int crypt_integrity_ctr(struct crypt_config *cc, struct dm_target *ti)
1162 {
1163 #ifdef CONFIG_BLK_DEV_INTEGRITY
1164 struct blk_integrity *bi = blk_get_integrity(cc->dev->bdev->bd_disk);
1165 struct mapped_device *md = dm_table_get_md(ti->table);
1166
1167 /* We require an underlying device with non-PI metadata */
1168 if (!bi || bi->csum_type != BLK_INTEGRITY_CSUM_NONE) {
1169 ti->error = "Integrity profile not supported.";
1170 return -EINVAL;
1171 }
1172
1173 if (bi->metadata_size < cc->used_tag_size) {
1174 ti->error = "Integrity profile tag size mismatch.";
1175 return -EINVAL;
1176 }
1177 cc->tuple_size = bi->metadata_size;
1178 if (1 << bi->interval_exp != cc->sector_size) {
1179 ti->error = "Integrity profile sector size mismatch.";
1180 return -EINVAL;
1181 }
1182
1183 if (crypt_integrity_aead(cc)) {
1184 cc->integrity_tag_size = cc->used_tag_size - cc->integrity_iv_size;
1185 DMDEBUG("%s: Integrity AEAD, tag size %u, IV size %u.", dm_device_name(md),
1186 cc->integrity_tag_size, cc->integrity_iv_size);
1187
1188 if (crypto_aead_setauthsize(any_tfm_aead(cc), cc->integrity_tag_size)) {
1189 ti->error = "Integrity AEAD auth tag size is not supported.";
1190 return -EINVAL;
1191 }
1192 } else if (cc->integrity_iv_size)
1193 DMDEBUG("%s: Additional per-sector space %u bytes for IV.", dm_device_name(md),
1194 cc->integrity_iv_size);
1195
1196 if ((cc->integrity_tag_size + cc->integrity_iv_size) > cc->tuple_size) {
1197 ti->error = "Not enough space for integrity tag in the profile.";
1198 return -EINVAL;
1199 }
1200
1201 return 0;
1202 #else
1203 ti->error = "Integrity profile not supported.";
1204 return -EINVAL;
1205 #endif
1206 }
1207
crypt_convert_init(struct crypt_config * cc,struct convert_context * ctx,struct bio * bio_out,struct bio * bio_in,sector_t sector)1208 static void crypt_convert_init(struct crypt_config *cc,
1209 struct convert_context *ctx,
1210 struct bio *bio_out, struct bio *bio_in,
1211 sector_t sector)
1212 {
1213 ctx->bio_in = bio_in;
1214 ctx->bio_out = bio_out;
1215 if (bio_in)
1216 ctx->iter_in = bio_in->bi_iter;
1217 if (bio_out)
1218 ctx->iter_out = bio_out->bi_iter;
1219 ctx->cc_sector = sector + cc->iv_offset;
1220 ctx->tag_offset = 0;
1221 init_completion(&ctx->restart);
1222 }
1223
dmreq_of_req(struct crypt_config * cc,void * req)1224 static struct dm_crypt_request *dmreq_of_req(struct crypt_config *cc,
1225 void *req)
1226 {
1227 return (struct dm_crypt_request *)((char *)req + cc->dmreq_start);
1228 }
1229
req_of_dmreq(struct crypt_config * cc,struct dm_crypt_request * dmreq)1230 static void *req_of_dmreq(struct crypt_config *cc, struct dm_crypt_request *dmreq)
1231 {
1232 return (void *)((char *)dmreq - cc->dmreq_start);
1233 }
1234
iv_of_dmreq(struct crypt_config * cc,struct dm_crypt_request * dmreq)1235 static u8 *iv_of_dmreq(struct crypt_config *cc,
1236 struct dm_crypt_request *dmreq)
1237 {
1238 if (crypt_integrity_aead(cc))
1239 return (u8 *)ALIGN((unsigned long)(dmreq + 1),
1240 crypto_aead_alignmask(any_tfm_aead(cc)) + 1);
1241 else
1242 return (u8 *)ALIGN((unsigned long)(dmreq + 1),
1243 crypto_skcipher_alignmask(any_tfm(cc)) + 1);
1244 }
1245
org_iv_of_dmreq(struct crypt_config * cc,struct dm_crypt_request * dmreq)1246 static u8 *org_iv_of_dmreq(struct crypt_config *cc,
1247 struct dm_crypt_request *dmreq)
1248 {
1249 return iv_of_dmreq(cc, dmreq) + cc->iv_size;
1250 }
1251
org_sector_of_dmreq(struct crypt_config * cc,struct dm_crypt_request * dmreq)1252 static __le64 *org_sector_of_dmreq(struct crypt_config *cc,
1253 struct dm_crypt_request *dmreq)
1254 {
1255 u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size + cc->iv_size;
1256
1257 return (__le64 *) ptr;
1258 }
1259
org_tag_of_dmreq(struct crypt_config * cc,struct dm_crypt_request * dmreq)1260 static unsigned int *org_tag_of_dmreq(struct crypt_config *cc,
1261 struct dm_crypt_request *dmreq)
1262 {
1263 u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size +
1264 cc->iv_size + sizeof(uint64_t);
1265
1266 return (unsigned int *)ptr;
1267 }
1268
tag_from_dmreq(struct crypt_config * cc,struct dm_crypt_request * dmreq)1269 static void *tag_from_dmreq(struct crypt_config *cc,
1270 struct dm_crypt_request *dmreq)
1271 {
1272 struct convert_context *ctx = dmreq->ctx;
1273 struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
1274
1275 return &io->integrity_metadata[*org_tag_of_dmreq(cc, dmreq) *
1276 cc->tuple_size];
1277 }
1278
iv_tag_from_dmreq(struct crypt_config * cc,struct dm_crypt_request * dmreq)1279 static void *iv_tag_from_dmreq(struct crypt_config *cc,
1280 struct dm_crypt_request *dmreq)
1281 {
1282 return tag_from_dmreq(cc, dmreq) + cc->integrity_tag_size;
1283 }
1284
crypt_convert_block_aead(struct crypt_config * cc,struct convert_context * ctx,struct aead_request * req,unsigned int tag_offset)1285 static int crypt_convert_block_aead(struct crypt_config *cc,
1286 struct convert_context *ctx,
1287 struct aead_request *req,
1288 unsigned int tag_offset)
1289 {
1290 struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
1291 struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
1292 struct dm_crypt_request *dmreq;
1293 u8 *iv, *org_iv, *tag_iv, *tag;
1294 __le64 *sector;
1295 int r = 0;
1296
1297 BUG_ON(cc->integrity_iv_size && cc->integrity_iv_size != cc->iv_size);
1298
1299 /* Reject unexpected unaligned bio. */
1300 if (unlikely(bv_in.bv_len & (cc->sector_size - 1)))
1301 return -EIO;
1302
1303 dmreq = dmreq_of_req(cc, req);
1304 dmreq->iv_sector = ctx->cc_sector;
1305 if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
1306 dmreq->iv_sector >>= cc->sector_shift;
1307 dmreq->ctx = ctx;
1308
1309 *org_tag_of_dmreq(cc, dmreq) = tag_offset;
1310
1311 sector = org_sector_of_dmreq(cc, dmreq);
1312 *sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
1313
1314 iv = iv_of_dmreq(cc, dmreq);
1315 org_iv = org_iv_of_dmreq(cc, dmreq);
1316 tag = tag_from_dmreq(cc, dmreq);
1317 tag_iv = iv_tag_from_dmreq(cc, dmreq);
1318
1319 /* AEAD request:
1320 * |----- AAD -------|------ DATA -------|-- AUTH TAG --|
1321 * | (authenticated) | (auth+encryption) | |
1322 * | sector_LE | IV | sector in/out | tag in/out |
1323 */
1324 sg_init_table(dmreq->sg_in, 4);
1325 sg_set_buf(&dmreq->sg_in[0], sector, sizeof(uint64_t));
1326 sg_set_buf(&dmreq->sg_in[1], org_iv, cc->iv_size);
1327 sg_set_page(&dmreq->sg_in[2], bv_in.bv_page, cc->sector_size, bv_in.bv_offset);
1328 sg_set_buf(&dmreq->sg_in[3], tag, cc->integrity_tag_size);
1329
1330 sg_init_table(dmreq->sg_out, 4);
1331 sg_set_buf(&dmreq->sg_out[0], sector, sizeof(uint64_t));
1332 sg_set_buf(&dmreq->sg_out[1], org_iv, cc->iv_size);
1333 sg_set_page(&dmreq->sg_out[2], bv_out.bv_page, cc->sector_size, bv_out.bv_offset);
1334 sg_set_buf(&dmreq->sg_out[3], tag, cc->integrity_tag_size);
1335
1336 if (cc->iv_gen_ops) {
1337 /* For READs use IV stored in integrity metadata */
1338 if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
1339 memcpy(org_iv, tag_iv, cc->iv_size);
1340 } else {
1341 r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
1342 if (r < 0)
1343 return r;
1344 /* Store generated IV in integrity metadata */
1345 if (cc->integrity_iv_size)
1346 memcpy(tag_iv, org_iv, cc->iv_size);
1347 }
1348 /* Working copy of IV, to be modified in crypto API */
1349 memcpy(iv, org_iv, cc->iv_size);
1350 }
1351
1352 aead_request_set_ad(req, sizeof(uint64_t) + cc->iv_size);
1353 if (bio_data_dir(ctx->bio_in) == WRITE) {
1354 aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
1355 cc->sector_size, iv);
1356 r = crypto_aead_encrypt(req);
1357 if (cc->integrity_tag_size + cc->integrity_iv_size != cc->tuple_size)
1358 memset(tag + cc->integrity_tag_size + cc->integrity_iv_size, 0,
1359 cc->tuple_size - (cc->integrity_tag_size + cc->integrity_iv_size));
1360 } else {
1361 aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
1362 cc->sector_size + cc->integrity_tag_size, iv);
1363 r = crypto_aead_decrypt(req);
1364 }
1365
1366 if (r == -EBADMSG) {
1367 sector_t s = le64_to_cpu(*sector);
1368
1369 ctx->aead_failed = true;
1370 if (ctx->aead_recheck) {
1371 DMERR_LIMIT("%pg: INTEGRITY AEAD ERROR, sector %llu",
1372 ctx->bio_in->bi_bdev, s);
1373 dm_audit_log_bio(DM_MSG_PREFIX, "integrity-aead",
1374 ctx->bio_in, s, 0);
1375 }
1376 }
1377
1378 if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
1379 r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
1380
1381 bio_advance_iter(ctx->bio_in, &ctx->iter_in, cc->sector_size);
1382 bio_advance_iter(ctx->bio_out, &ctx->iter_out, cc->sector_size);
1383
1384 return r;
1385 }
1386
crypt_convert_block_skcipher(struct crypt_config * cc,struct convert_context * ctx,struct skcipher_request * req,unsigned int tag_offset)1387 static int crypt_convert_block_skcipher(struct crypt_config *cc,
1388 struct convert_context *ctx,
1389 struct skcipher_request *req,
1390 unsigned int tag_offset)
1391 {
1392 struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
1393 struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
1394 struct scatterlist *sg_in, *sg_out;
1395 struct dm_crypt_request *dmreq;
1396 u8 *iv, *org_iv, *tag_iv;
1397 __le64 *sector;
1398 int r = 0;
1399
1400 /* Reject unexpected unaligned bio. */
1401 if (unlikely(bv_in.bv_len & (cc->sector_size - 1)))
1402 return -EIO;
1403
1404 dmreq = dmreq_of_req(cc, req);
1405 dmreq->iv_sector = ctx->cc_sector;
1406 if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
1407 dmreq->iv_sector >>= cc->sector_shift;
1408 dmreq->ctx = ctx;
1409
1410 *org_tag_of_dmreq(cc, dmreq) = tag_offset;
1411
1412 iv = iv_of_dmreq(cc, dmreq);
1413 org_iv = org_iv_of_dmreq(cc, dmreq);
1414 tag_iv = iv_tag_from_dmreq(cc, dmreq);
1415
1416 sector = org_sector_of_dmreq(cc, dmreq);
1417 *sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
1418
1419 /* For skcipher we use only the first sg item */
1420 sg_in = &dmreq->sg_in[0];
1421 sg_out = &dmreq->sg_out[0];
1422
1423 sg_init_table(sg_in, 1);
1424 sg_set_page(sg_in, bv_in.bv_page, cc->sector_size, bv_in.bv_offset);
1425
1426 sg_init_table(sg_out, 1);
1427 sg_set_page(sg_out, bv_out.bv_page, cc->sector_size, bv_out.bv_offset);
1428
1429 if (cc->iv_gen_ops) {
1430 /* For READs use IV stored in integrity metadata */
1431 if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
1432 memcpy(org_iv, tag_iv, cc->integrity_iv_size);
1433 } else {
1434 r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
1435 if (r < 0)
1436 return r;
1437 /* Data can be already preprocessed in generator */
1438 if (test_bit(CRYPT_ENCRYPT_PREPROCESS, &cc->cipher_flags))
1439 sg_in = sg_out;
1440 /* Store generated IV in integrity metadata */
1441 if (cc->integrity_iv_size)
1442 memcpy(tag_iv, org_iv, cc->integrity_iv_size);
1443 }
1444 /* Working copy of IV, to be modified in crypto API */
1445 memcpy(iv, org_iv, cc->iv_size);
1446 }
1447
1448 skcipher_request_set_crypt(req, sg_in, sg_out, cc->sector_size, iv);
1449
1450 if (bio_data_dir(ctx->bio_in) == WRITE)
1451 r = crypto_skcipher_encrypt(req);
1452 else
1453 r = crypto_skcipher_decrypt(req);
1454
1455 if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
1456 r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
1457
1458 bio_advance_iter(ctx->bio_in, &ctx->iter_in, cc->sector_size);
1459 bio_advance_iter(ctx->bio_out, &ctx->iter_out, cc->sector_size);
1460
1461 return r;
1462 }
1463
1464 static void kcryptd_async_done(void *async_req, int error);
1465
crypt_alloc_req_skcipher(struct crypt_config * cc,struct convert_context * ctx)1466 static int crypt_alloc_req_skcipher(struct crypt_config *cc,
1467 struct convert_context *ctx)
1468 {
1469 unsigned int key_index = ctx->cc_sector & (cc->tfms_count - 1);
1470
1471 if (!ctx->r.req) {
1472 ctx->r.req = mempool_alloc(&cc->req_pool, in_interrupt() ? GFP_ATOMIC : GFP_NOIO);
1473 if (!ctx->r.req)
1474 return -ENOMEM;
1475 }
1476
1477 skcipher_request_set_tfm(ctx->r.req, cc->cipher_tfm.tfms[key_index]);
1478
1479 /*
1480 * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
1481 * requests if driver request queue is full.
1482 */
1483 skcipher_request_set_callback(ctx->r.req,
1484 CRYPTO_TFM_REQ_MAY_BACKLOG,
1485 kcryptd_async_done, dmreq_of_req(cc, ctx->r.req));
1486
1487 return 0;
1488 }
1489
crypt_alloc_req_aead(struct crypt_config * cc,struct convert_context * ctx)1490 static int crypt_alloc_req_aead(struct crypt_config *cc,
1491 struct convert_context *ctx)
1492 {
1493 if (!ctx->r.req_aead) {
1494 ctx->r.req_aead = mempool_alloc(&cc->req_pool, in_interrupt() ? GFP_ATOMIC : GFP_NOIO);
1495 if (!ctx->r.req_aead)
1496 return -ENOMEM;
1497 }
1498
1499 aead_request_set_tfm(ctx->r.req_aead, cc->cipher_tfm.tfms_aead[0]);
1500
1501 /*
1502 * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
1503 * requests if driver request queue is full.
1504 */
1505 aead_request_set_callback(ctx->r.req_aead,
1506 CRYPTO_TFM_REQ_MAY_BACKLOG,
1507 kcryptd_async_done, dmreq_of_req(cc, ctx->r.req_aead));
1508
1509 return 0;
1510 }
1511
crypt_alloc_req(struct crypt_config * cc,struct convert_context * ctx)1512 static int crypt_alloc_req(struct crypt_config *cc,
1513 struct convert_context *ctx)
1514 {
1515 if (crypt_integrity_aead(cc))
1516 return crypt_alloc_req_aead(cc, ctx);
1517 else
1518 return crypt_alloc_req_skcipher(cc, ctx);
1519 }
1520
crypt_free_req_skcipher(struct crypt_config * cc,struct skcipher_request * req,struct bio * base_bio)1521 static void crypt_free_req_skcipher(struct crypt_config *cc,
1522 struct skcipher_request *req, struct bio *base_bio)
1523 {
1524 struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
1525
1526 if ((struct skcipher_request *)(io + 1) != req)
1527 mempool_free(req, &cc->req_pool);
1528 }
1529
crypt_free_req_aead(struct crypt_config * cc,struct aead_request * req,struct bio * base_bio)1530 static void crypt_free_req_aead(struct crypt_config *cc,
1531 struct aead_request *req, struct bio *base_bio)
1532 {
1533 struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
1534
1535 if ((struct aead_request *)(io + 1) != req)
1536 mempool_free(req, &cc->req_pool);
1537 }
1538
crypt_free_req(struct crypt_config * cc,void * req,struct bio * base_bio)1539 static void crypt_free_req(struct crypt_config *cc, void *req, struct bio *base_bio)
1540 {
1541 if (crypt_integrity_aead(cc))
1542 crypt_free_req_aead(cc, req, base_bio);
1543 else
1544 crypt_free_req_skcipher(cc, req, base_bio);
1545 }
1546
1547 /*
1548 * Encrypt / decrypt data from one bio to another one (can be the same one)
1549 */
crypt_convert(struct crypt_config * cc,struct convert_context * ctx,bool atomic,bool reset_pending)1550 static blk_status_t crypt_convert(struct crypt_config *cc,
1551 struct convert_context *ctx, bool atomic, bool reset_pending)
1552 {
1553 unsigned int sector_step = cc->sector_size >> SECTOR_SHIFT;
1554 int r;
1555
1556 /*
1557 * if reset_pending is set we are dealing with the bio for the first time,
1558 * else we're continuing to work on the previous bio, so don't mess with
1559 * the cc_pending counter
1560 */
1561 if (reset_pending)
1562 atomic_set(&ctx->cc_pending, 1);
1563
1564 while (ctx->iter_in.bi_size && ctx->iter_out.bi_size) {
1565
1566 r = crypt_alloc_req(cc, ctx);
1567 if (r) {
1568 complete(&ctx->restart);
1569 return BLK_STS_DEV_RESOURCE;
1570 }
1571
1572 atomic_inc(&ctx->cc_pending);
1573
1574 if (crypt_integrity_aead(cc))
1575 r = crypt_convert_block_aead(cc, ctx, ctx->r.req_aead, ctx->tag_offset);
1576 else
1577 r = crypt_convert_block_skcipher(cc, ctx, ctx->r.req, ctx->tag_offset);
1578
1579 switch (r) {
1580 /*
1581 * The request was queued by a crypto driver
1582 * but the driver request queue is full, let's wait.
1583 */
1584 case -EBUSY:
1585 if (in_interrupt()) {
1586 if (try_wait_for_completion(&ctx->restart)) {
1587 /*
1588 * we don't have to block to wait for completion,
1589 * so proceed
1590 */
1591 } else {
1592 /*
1593 * we can't wait for completion without blocking
1594 * exit and continue processing in a workqueue
1595 */
1596 ctx->r.req = NULL;
1597 ctx->tag_offset++;
1598 ctx->cc_sector += sector_step;
1599 return BLK_STS_DEV_RESOURCE;
1600 }
1601 } else {
1602 wait_for_completion(&ctx->restart);
1603 }
1604 reinit_completion(&ctx->restart);
1605 fallthrough;
1606 /*
1607 * The request is queued and processed asynchronously,
1608 * completion function kcryptd_async_done() will be called.
1609 */
1610 case -EINPROGRESS:
1611 ctx->r.req = NULL;
1612 ctx->tag_offset++;
1613 ctx->cc_sector += sector_step;
1614 continue;
1615 /*
1616 * The request was already processed (synchronously).
1617 */
1618 case 0:
1619 atomic_dec(&ctx->cc_pending);
1620 ctx->cc_sector += sector_step;
1621 ctx->tag_offset++;
1622 if (!atomic)
1623 cond_resched();
1624 continue;
1625 /*
1626 * There was a data integrity error.
1627 */
1628 case -EBADMSG:
1629 atomic_dec(&ctx->cc_pending);
1630 return BLK_STS_PROTECTION;
1631 /*
1632 * There was an error while processing the request.
1633 */
1634 default:
1635 atomic_dec(&ctx->cc_pending);
1636 return BLK_STS_IOERR;
1637 }
1638 }
1639
1640 return 0;
1641 }
1642
1643 static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone);
1644
1645 /*
1646 * Generate a new unfragmented bio with the given size
1647 * This should never violate the device limitations (but if it did then block
1648 * core should split the bio as needed).
1649 *
1650 * This function may be called concurrently. If we allocate from the mempool
1651 * concurrently, there is a possibility of deadlock. For example, if we have
1652 * mempool of 256 pages, two processes, each wanting 256, pages allocate from
1653 * the mempool concurrently, it may deadlock in a situation where both processes
1654 * have allocated 128 pages and the mempool is exhausted.
1655 *
1656 * In order to avoid this scenario we allocate the pages under a mutex.
1657 *
1658 * In order to not degrade performance with excessive locking, we try
1659 * non-blocking allocations without a mutex first but on failure we fallback
1660 * to blocking allocations with a mutex.
1661 *
1662 * In order to reduce allocation overhead, we try to allocate compound pages in
1663 * the first pass. If they are not available, we fall back to the mempool.
1664 */
crypt_alloc_buffer(struct dm_crypt_io * io,unsigned int size)1665 static struct bio *crypt_alloc_buffer(struct dm_crypt_io *io, unsigned int size)
1666 {
1667 struct crypt_config *cc = io->cc;
1668 struct bio *clone;
1669 unsigned int nr_iovecs = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
1670 gfp_t gfp_mask = GFP_NOWAIT | __GFP_HIGHMEM;
1671 unsigned int remaining_size;
1672 unsigned int order = MAX_PAGE_ORDER;
1673
1674 retry:
1675 if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
1676 mutex_lock(&cc->bio_alloc_lock);
1677
1678 clone = bio_alloc_bioset(cc->dev->bdev, nr_iovecs, io->base_bio->bi_opf,
1679 GFP_NOIO, &cc->bs);
1680 clone->bi_private = io;
1681 clone->bi_end_io = crypt_endio;
1682 clone->bi_ioprio = io->base_bio->bi_ioprio;
1683 clone->bi_iter.bi_sector = cc->start + io->sector;
1684
1685 remaining_size = size;
1686
1687 while (remaining_size) {
1688 struct page *pages;
1689 unsigned size_to_add;
1690 unsigned remaining_order = __fls((remaining_size + PAGE_SIZE - 1) >> PAGE_SHIFT);
1691 order = min(order, remaining_order);
1692
1693 while (order > 0) {
1694 if (unlikely(percpu_counter_read_positive(&cc->n_allocated_pages) +
1695 (1 << order) > dm_crypt_pages_per_client))
1696 goto decrease_order;
1697 pages = alloc_pages(gfp_mask
1698 | __GFP_NOMEMALLOC | __GFP_NORETRY | __GFP_NOWARN | __GFP_COMP,
1699 order);
1700 if (likely(pages != NULL)) {
1701 percpu_counter_add(&cc->n_allocated_pages, 1 << order);
1702 goto have_pages;
1703 }
1704 decrease_order:
1705 order--;
1706 }
1707
1708 pages = mempool_alloc(&cc->page_pool, gfp_mask);
1709 if (!pages) {
1710 crypt_free_buffer_pages(cc, clone);
1711 bio_put(clone);
1712 gfp_mask |= __GFP_DIRECT_RECLAIM;
1713 order = 0;
1714 goto retry;
1715 }
1716
1717 have_pages:
1718 size_to_add = min((unsigned)PAGE_SIZE << order, remaining_size);
1719 __bio_add_page(clone, pages, size_to_add, 0);
1720 remaining_size -= size_to_add;
1721 }
1722
1723 /* Allocate space for integrity tags */
1724 if (dm_crypt_integrity_io_alloc(io, clone)) {
1725 crypt_free_buffer_pages(cc, clone);
1726 bio_put(clone);
1727 clone = NULL;
1728 }
1729
1730 if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
1731 mutex_unlock(&cc->bio_alloc_lock);
1732
1733 return clone;
1734 }
1735
crypt_free_buffer_pages(struct crypt_config * cc,struct bio * clone)1736 static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone)
1737 {
1738 struct folio_iter fi;
1739
1740 if (clone->bi_vcnt > 0) { /* bio_for_each_folio_all crashes with an empty bio */
1741 bio_for_each_folio_all(fi, clone) {
1742 if (folio_test_large(fi.folio)) {
1743 percpu_counter_sub(&cc->n_allocated_pages,
1744 folio_nr_pages(fi.folio));
1745 folio_put(fi.folio);
1746 } else {
1747 mempool_free(&fi.folio->page, &cc->page_pool);
1748 }
1749 }
1750 }
1751 }
1752
crypt_io_init(struct dm_crypt_io * io,struct crypt_config * cc,struct bio * bio,sector_t sector)1753 static void crypt_io_init(struct dm_crypt_io *io, struct crypt_config *cc,
1754 struct bio *bio, sector_t sector)
1755 {
1756 io->cc = cc;
1757 io->base_bio = bio;
1758 io->sector = sector;
1759 io->error = 0;
1760 io->ctx.aead_recheck = false;
1761 io->ctx.aead_failed = false;
1762 io->ctx.r.req = NULL;
1763 io->integrity_metadata = NULL;
1764 io->integrity_metadata_from_pool = false;
1765 atomic_set(&io->io_pending, 0);
1766 }
1767
crypt_inc_pending(struct dm_crypt_io * io)1768 static void crypt_inc_pending(struct dm_crypt_io *io)
1769 {
1770 atomic_inc(&io->io_pending);
1771 }
1772
1773 static void kcryptd_queue_read(struct dm_crypt_io *io);
1774
1775 /*
1776 * One of the bios was finished. Check for completion of
1777 * the whole request and correctly clean up the buffer.
1778 */
crypt_dec_pending(struct dm_crypt_io * io)1779 static void crypt_dec_pending(struct dm_crypt_io *io)
1780 {
1781 struct crypt_config *cc = io->cc;
1782 struct bio *base_bio = io->base_bio;
1783 blk_status_t error = io->error;
1784
1785 if (!atomic_dec_and_test(&io->io_pending))
1786 return;
1787
1788 if (likely(!io->ctx.aead_recheck) && unlikely(io->ctx.aead_failed) &&
1789 cc->used_tag_size && bio_data_dir(base_bio) == READ) {
1790 io->ctx.aead_recheck = true;
1791 io->ctx.aead_failed = false;
1792 io->error = 0;
1793 kcryptd_queue_read(io);
1794 return;
1795 }
1796
1797 if (io->ctx.r.req)
1798 crypt_free_req(cc, io->ctx.r.req, base_bio);
1799
1800 if (unlikely(io->integrity_metadata_from_pool))
1801 mempool_free(io->integrity_metadata, &io->cc->tag_pool);
1802 else
1803 kfree(io->integrity_metadata);
1804
1805 base_bio->bi_status = error;
1806
1807 bio_endio(base_bio);
1808 }
1809
1810 /*
1811 * kcryptd/kcryptd_io:
1812 *
1813 * Needed because it would be very unwise to do decryption in an
1814 * interrupt context.
1815 *
1816 * kcryptd performs the actual encryption or decryption.
1817 *
1818 * kcryptd_io performs the IO submission.
1819 *
1820 * They must be separated as otherwise the final stages could be
1821 * starved by new requests which can block in the first stages due
1822 * to memory allocation.
1823 *
1824 * The work is done per CPU global for all dm-crypt instances.
1825 * They should not depend on each other and do not block.
1826 */
crypt_endio(struct bio * clone)1827 static void crypt_endio(struct bio *clone)
1828 {
1829 struct dm_crypt_io *io = clone->bi_private;
1830 struct crypt_config *cc = io->cc;
1831 unsigned int rw = bio_data_dir(clone);
1832 blk_status_t error = clone->bi_status;
1833
1834 if (io->ctx.aead_recheck && !error) {
1835 kcryptd_queue_crypt(io);
1836 return;
1837 }
1838
1839 /*
1840 * free the processed pages
1841 */
1842 if (rw == WRITE || io->ctx.aead_recheck)
1843 crypt_free_buffer_pages(cc, clone);
1844
1845 bio_put(clone);
1846
1847 if (rw == READ && !error) {
1848 kcryptd_queue_crypt(io);
1849 return;
1850 }
1851
1852 if (unlikely(error))
1853 io->error = error;
1854
1855 crypt_dec_pending(io);
1856 }
1857
1858 #define CRYPT_MAP_READ_GFP GFP_NOWAIT
1859
kcryptd_io_read(struct dm_crypt_io * io,gfp_t gfp)1860 static int kcryptd_io_read(struct dm_crypt_io *io, gfp_t gfp)
1861 {
1862 struct crypt_config *cc = io->cc;
1863 struct bio *clone;
1864
1865 if (io->ctx.aead_recheck) {
1866 if (!(gfp & __GFP_DIRECT_RECLAIM))
1867 return 1;
1868 crypt_inc_pending(io);
1869 clone = crypt_alloc_buffer(io, io->base_bio->bi_iter.bi_size);
1870 if (unlikely(!clone)) {
1871 crypt_dec_pending(io);
1872 return 1;
1873 }
1874 crypt_convert_init(cc, &io->ctx, clone, clone, io->sector);
1875 io->saved_bi_iter = clone->bi_iter;
1876 dm_submit_bio_remap(io->base_bio, clone);
1877 return 0;
1878 }
1879
1880 /*
1881 * We need the original biovec array in order to decrypt the whole bio
1882 * data *afterwards* -- thanks to immutable biovecs we don't need to
1883 * worry about the block layer modifying the biovec array; so leverage
1884 * bio_alloc_clone().
1885 */
1886 clone = bio_alloc_clone(cc->dev->bdev, io->base_bio, gfp, &cc->bs);
1887 if (!clone)
1888 return 1;
1889
1890 clone->bi_iter.bi_sector = cc->start + io->sector;
1891 clone->bi_private = io;
1892 clone->bi_end_io = crypt_endio;
1893
1894 crypt_inc_pending(io);
1895
1896 if (dm_crypt_integrity_io_alloc(io, clone)) {
1897 crypt_dec_pending(io);
1898 bio_put(clone);
1899 return 1;
1900 }
1901
1902 dm_submit_bio_remap(io->base_bio, clone);
1903 return 0;
1904 }
1905
kcryptd_io_read_work(struct work_struct * work)1906 static void kcryptd_io_read_work(struct work_struct *work)
1907 {
1908 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
1909
1910 crypt_inc_pending(io);
1911 if (kcryptd_io_read(io, GFP_NOIO))
1912 io->error = BLK_STS_RESOURCE;
1913 crypt_dec_pending(io);
1914 }
1915
kcryptd_queue_read(struct dm_crypt_io * io)1916 static void kcryptd_queue_read(struct dm_crypt_io *io)
1917 {
1918 struct crypt_config *cc = io->cc;
1919
1920 INIT_WORK(&io->work, kcryptd_io_read_work);
1921 queue_work(cc->io_queue, &io->work);
1922 }
1923
kcryptd_io_write(struct dm_crypt_io * io)1924 static void kcryptd_io_write(struct dm_crypt_io *io)
1925 {
1926 struct bio *clone = io->ctx.bio_out;
1927
1928 dm_submit_bio_remap(io->base_bio, clone);
1929 }
1930
1931 #define crypt_io_from_node(node) rb_entry((node), struct dm_crypt_io, rb_node)
1932
dmcrypt_write(void * data)1933 static int dmcrypt_write(void *data)
1934 {
1935 struct crypt_config *cc = data;
1936 struct dm_crypt_io *io;
1937
1938 while (1) {
1939 struct rb_root write_tree;
1940 struct blk_plug plug;
1941
1942 spin_lock_irq(&cc->write_thread_lock);
1943 continue_locked:
1944
1945 if (!RB_EMPTY_ROOT(&cc->write_tree))
1946 goto pop_from_list;
1947
1948 set_current_state(TASK_INTERRUPTIBLE);
1949
1950 spin_unlock_irq(&cc->write_thread_lock);
1951
1952 if (unlikely(kthread_should_stop())) {
1953 set_current_state(TASK_RUNNING);
1954 break;
1955 }
1956
1957 schedule();
1958
1959 spin_lock_irq(&cc->write_thread_lock);
1960 goto continue_locked;
1961
1962 pop_from_list:
1963 write_tree = cc->write_tree;
1964 cc->write_tree = RB_ROOT;
1965 spin_unlock_irq(&cc->write_thread_lock);
1966
1967 BUG_ON(rb_parent(write_tree.rb_node));
1968
1969 /*
1970 * Note: we cannot walk the tree here with rb_next because
1971 * the structures may be freed when kcryptd_io_write is called.
1972 */
1973 blk_start_plug(&plug);
1974 do {
1975 io = crypt_io_from_node(rb_first(&write_tree));
1976 rb_erase(&io->rb_node, &write_tree);
1977 kcryptd_io_write(io);
1978 cond_resched();
1979 } while (!RB_EMPTY_ROOT(&write_tree));
1980 blk_finish_plug(&plug);
1981 }
1982 return 0;
1983 }
1984
kcryptd_crypt_write_io_submit(struct dm_crypt_io * io,int async)1985 static void kcryptd_crypt_write_io_submit(struct dm_crypt_io *io, int async)
1986 {
1987 struct bio *clone = io->ctx.bio_out;
1988 struct crypt_config *cc = io->cc;
1989 unsigned long flags;
1990 sector_t sector;
1991 struct rb_node **rbp, *parent;
1992
1993 if (unlikely(io->error)) {
1994 crypt_free_buffer_pages(cc, clone);
1995 bio_put(clone);
1996 crypt_dec_pending(io);
1997 return;
1998 }
1999
2000 /* crypt_convert should have filled the clone bio */
2001 BUG_ON(io->ctx.iter_out.bi_size);
2002
2003 if ((likely(!async) && test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags)) ||
2004 test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags)) {
2005 dm_submit_bio_remap(io->base_bio, clone);
2006 return;
2007 }
2008
2009 spin_lock_irqsave(&cc->write_thread_lock, flags);
2010 if (RB_EMPTY_ROOT(&cc->write_tree))
2011 wake_up_process(cc->write_thread);
2012 rbp = &cc->write_tree.rb_node;
2013 parent = NULL;
2014 sector = io->sector;
2015 while (*rbp) {
2016 parent = *rbp;
2017 if (sector < crypt_io_from_node(parent)->sector)
2018 rbp = &(*rbp)->rb_left;
2019 else
2020 rbp = &(*rbp)->rb_right;
2021 }
2022 rb_link_node(&io->rb_node, parent, rbp);
2023 rb_insert_color(&io->rb_node, &cc->write_tree);
2024 spin_unlock_irqrestore(&cc->write_thread_lock, flags);
2025 }
2026
kcryptd_crypt_write_inline(struct crypt_config * cc,struct convert_context * ctx)2027 static bool kcryptd_crypt_write_inline(struct crypt_config *cc,
2028 struct convert_context *ctx)
2029
2030 {
2031 if (!test_bit(DM_CRYPT_WRITE_INLINE, &cc->flags))
2032 return false;
2033
2034 /*
2035 * Note: zone append writes (REQ_OP_ZONE_APPEND) do not have ordering
2036 * constraints so they do not need to be issued inline by
2037 * kcryptd_crypt_write_convert().
2038 */
2039 switch (bio_op(ctx->bio_in)) {
2040 case REQ_OP_WRITE:
2041 case REQ_OP_WRITE_ZEROES:
2042 return true;
2043 default:
2044 return false;
2045 }
2046 }
2047
kcryptd_crypt_write_continue(struct work_struct * work)2048 static void kcryptd_crypt_write_continue(struct work_struct *work)
2049 {
2050 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
2051 struct crypt_config *cc = io->cc;
2052 struct convert_context *ctx = &io->ctx;
2053 int crypt_finished;
2054 blk_status_t r;
2055
2056 wait_for_completion(&ctx->restart);
2057 reinit_completion(&ctx->restart);
2058
2059 r = crypt_convert(cc, &io->ctx, false, false);
2060 if (r)
2061 io->error = r;
2062 crypt_finished = atomic_dec_and_test(&ctx->cc_pending);
2063 if (!crypt_finished && kcryptd_crypt_write_inline(cc, ctx)) {
2064 /* Wait for completion signaled by kcryptd_async_done() */
2065 wait_for_completion(&ctx->restart);
2066 crypt_finished = 1;
2067 }
2068
2069 /* Encryption was already finished, submit io now */
2070 if (crypt_finished)
2071 kcryptd_crypt_write_io_submit(io, 0);
2072
2073 crypt_dec_pending(io);
2074 }
2075
kcryptd_crypt_write_convert(struct dm_crypt_io * io)2076 static void kcryptd_crypt_write_convert(struct dm_crypt_io *io)
2077 {
2078 struct crypt_config *cc = io->cc;
2079 struct convert_context *ctx = &io->ctx;
2080 struct bio *clone;
2081 int crypt_finished;
2082 blk_status_t r;
2083
2084 /*
2085 * Prevent io from disappearing until this function completes.
2086 */
2087 crypt_inc_pending(io);
2088 crypt_convert_init(cc, ctx, NULL, io->base_bio, io->sector);
2089
2090 clone = crypt_alloc_buffer(io, io->base_bio->bi_iter.bi_size);
2091 if (unlikely(!clone)) {
2092 io->error = BLK_STS_IOERR;
2093 goto dec;
2094 }
2095
2096 io->ctx.bio_out = clone;
2097 io->ctx.iter_out = clone->bi_iter;
2098
2099 if (crypt_integrity_aead(cc)) {
2100 bio_copy_data(clone, io->base_bio);
2101 io->ctx.bio_in = clone;
2102 io->ctx.iter_in = clone->bi_iter;
2103 }
2104
2105 crypt_inc_pending(io);
2106 r = crypt_convert(cc, ctx,
2107 test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags), true);
2108 /*
2109 * Crypto API backlogged the request, because its queue was full
2110 * and we're in softirq context, so continue from a workqueue
2111 * (TODO: is it actually possible to be in softirq in the write path?)
2112 */
2113 if (r == BLK_STS_DEV_RESOURCE) {
2114 INIT_WORK(&io->work, kcryptd_crypt_write_continue);
2115 queue_work(cc->crypt_queue, &io->work);
2116 return;
2117 }
2118 if (r)
2119 io->error = r;
2120 crypt_finished = atomic_dec_and_test(&ctx->cc_pending);
2121 if (!crypt_finished && kcryptd_crypt_write_inline(cc, ctx)) {
2122 /* Wait for completion signaled by kcryptd_async_done() */
2123 wait_for_completion(&ctx->restart);
2124 crypt_finished = 1;
2125 }
2126
2127 /* Encryption was already finished, submit io now */
2128 if (crypt_finished)
2129 kcryptd_crypt_write_io_submit(io, 0);
2130
2131 dec:
2132 crypt_dec_pending(io);
2133 }
2134
kcryptd_crypt_read_done(struct dm_crypt_io * io)2135 static void kcryptd_crypt_read_done(struct dm_crypt_io *io)
2136 {
2137 if (io->ctx.aead_recheck) {
2138 if (!io->error) {
2139 io->ctx.bio_in->bi_iter = io->saved_bi_iter;
2140 bio_copy_data(io->base_bio, io->ctx.bio_in);
2141 }
2142 crypt_free_buffer_pages(io->cc, io->ctx.bio_in);
2143 bio_put(io->ctx.bio_in);
2144 }
2145 crypt_dec_pending(io);
2146 }
2147
kcryptd_crypt_read_continue(struct work_struct * work)2148 static void kcryptd_crypt_read_continue(struct work_struct *work)
2149 {
2150 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
2151 struct crypt_config *cc = io->cc;
2152 blk_status_t r;
2153
2154 wait_for_completion(&io->ctx.restart);
2155 reinit_completion(&io->ctx.restart);
2156
2157 r = crypt_convert(cc, &io->ctx, false, false);
2158 if (r)
2159 io->error = r;
2160
2161 if (atomic_dec_and_test(&io->ctx.cc_pending))
2162 kcryptd_crypt_read_done(io);
2163
2164 crypt_dec_pending(io);
2165 }
2166
kcryptd_crypt_read_convert(struct dm_crypt_io * io)2167 static void kcryptd_crypt_read_convert(struct dm_crypt_io *io)
2168 {
2169 struct crypt_config *cc = io->cc;
2170 blk_status_t r;
2171
2172 crypt_inc_pending(io);
2173
2174 if (io->ctx.aead_recheck) {
2175 r = crypt_convert(cc, &io->ctx,
2176 test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags), true);
2177 } else {
2178 crypt_convert_init(cc, &io->ctx, io->base_bio, io->base_bio,
2179 io->sector);
2180
2181 r = crypt_convert(cc, &io->ctx,
2182 test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags), true);
2183 }
2184 /*
2185 * Crypto API backlogged the request, because its queue was full
2186 * and we're in softirq context, so continue from a workqueue
2187 */
2188 if (r == BLK_STS_DEV_RESOURCE) {
2189 INIT_WORK(&io->work, kcryptd_crypt_read_continue);
2190 queue_work(cc->crypt_queue, &io->work);
2191 return;
2192 }
2193 if (r)
2194 io->error = r;
2195
2196 if (atomic_dec_and_test(&io->ctx.cc_pending))
2197 kcryptd_crypt_read_done(io);
2198
2199 crypt_dec_pending(io);
2200 }
2201
kcryptd_async_done(void * data,int error)2202 static void kcryptd_async_done(void *data, int error)
2203 {
2204 struct dm_crypt_request *dmreq = data;
2205 struct convert_context *ctx = dmreq->ctx;
2206 struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
2207 struct crypt_config *cc = io->cc;
2208
2209 /*
2210 * A request from crypto driver backlog is going to be processed now,
2211 * finish the completion and continue in crypt_convert().
2212 * (Callback will be called for the second time for this request.)
2213 */
2214 if (error == -EINPROGRESS) {
2215 complete(&ctx->restart);
2216 return;
2217 }
2218
2219 if (!error && cc->iv_gen_ops && cc->iv_gen_ops->post)
2220 error = cc->iv_gen_ops->post(cc, org_iv_of_dmreq(cc, dmreq), dmreq);
2221
2222 if (error == -EBADMSG) {
2223 sector_t s = le64_to_cpu(*org_sector_of_dmreq(cc, dmreq));
2224
2225 ctx->aead_failed = true;
2226 if (ctx->aead_recheck) {
2227 DMERR_LIMIT("%pg: INTEGRITY AEAD ERROR, sector %llu",
2228 ctx->bio_in->bi_bdev, s);
2229 dm_audit_log_bio(DM_MSG_PREFIX, "integrity-aead",
2230 ctx->bio_in, s, 0);
2231 }
2232 io->error = BLK_STS_PROTECTION;
2233 } else if (error < 0)
2234 io->error = BLK_STS_IOERR;
2235
2236 crypt_free_req(cc, req_of_dmreq(cc, dmreq), io->base_bio);
2237
2238 if (!atomic_dec_and_test(&ctx->cc_pending))
2239 return;
2240
2241 /*
2242 * The request is fully completed: for inline writes, let
2243 * kcryptd_crypt_write_convert() do the IO submission.
2244 */
2245 if (bio_data_dir(io->base_bio) == READ) {
2246 kcryptd_crypt_read_done(io);
2247 return;
2248 }
2249
2250 if (kcryptd_crypt_write_inline(cc, ctx)) {
2251 complete(&ctx->restart);
2252 return;
2253 }
2254
2255 kcryptd_crypt_write_io_submit(io, 1);
2256 }
2257
kcryptd_crypt(struct work_struct * work)2258 static void kcryptd_crypt(struct work_struct *work)
2259 {
2260 struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
2261
2262 if (bio_data_dir(io->base_bio) == READ)
2263 kcryptd_crypt_read_convert(io);
2264 else
2265 kcryptd_crypt_write_convert(io);
2266 }
2267
kcryptd_queue_crypt(struct dm_crypt_io * io)2268 static void kcryptd_queue_crypt(struct dm_crypt_io *io)
2269 {
2270 struct crypt_config *cc = io->cc;
2271
2272 if ((bio_data_dir(io->base_bio) == READ && test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags)) ||
2273 (bio_data_dir(io->base_bio) == WRITE && test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags))) {
2274 /*
2275 * in_hardirq(): Crypto API's skcipher_walk_first() refuses to work in hard IRQ context.
2276 * irqs_disabled(): the kernel may run some IO completion from the idle thread, but
2277 * it is being executed with irqs disabled.
2278 */
2279 if (in_hardirq() || irqs_disabled()) {
2280 INIT_WORK(&io->work, kcryptd_crypt);
2281 queue_work(system_bh_wq, &io->work);
2282 return;
2283 } else {
2284 kcryptd_crypt(&io->work);
2285 return;
2286 }
2287 }
2288
2289 INIT_WORK(&io->work, kcryptd_crypt);
2290 queue_work(cc->crypt_queue, &io->work);
2291 }
2292
crypt_free_tfms_aead(struct crypt_config * cc)2293 static void crypt_free_tfms_aead(struct crypt_config *cc)
2294 {
2295 if (!cc->cipher_tfm.tfms_aead)
2296 return;
2297
2298 if (cc->cipher_tfm.tfms_aead[0] && !IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
2299 crypto_free_aead(cc->cipher_tfm.tfms_aead[0]);
2300 cc->cipher_tfm.tfms_aead[0] = NULL;
2301 }
2302
2303 kfree(cc->cipher_tfm.tfms_aead);
2304 cc->cipher_tfm.tfms_aead = NULL;
2305 }
2306
crypt_free_tfms_skcipher(struct crypt_config * cc)2307 static void crypt_free_tfms_skcipher(struct crypt_config *cc)
2308 {
2309 unsigned int i;
2310
2311 if (!cc->cipher_tfm.tfms)
2312 return;
2313
2314 for (i = 0; i < cc->tfms_count; i++)
2315 if (cc->cipher_tfm.tfms[i] && !IS_ERR(cc->cipher_tfm.tfms[i])) {
2316 crypto_free_skcipher(cc->cipher_tfm.tfms[i]);
2317 cc->cipher_tfm.tfms[i] = NULL;
2318 }
2319
2320 kfree(cc->cipher_tfm.tfms);
2321 cc->cipher_tfm.tfms = NULL;
2322 }
2323
crypt_free_tfms(struct crypt_config * cc)2324 static void crypt_free_tfms(struct crypt_config *cc)
2325 {
2326 if (crypt_integrity_aead(cc))
2327 crypt_free_tfms_aead(cc);
2328 else
2329 crypt_free_tfms_skcipher(cc);
2330 }
2331
crypt_alloc_tfms_skcipher(struct crypt_config * cc,char * ciphermode)2332 static int crypt_alloc_tfms_skcipher(struct crypt_config *cc, char *ciphermode)
2333 {
2334 unsigned int i;
2335 int err;
2336
2337 cc->cipher_tfm.tfms = kzalloc_objs(struct crypto_skcipher *,
2338 cc->tfms_count, GFP_KERNEL);
2339 if (!cc->cipher_tfm.tfms)
2340 return -ENOMEM;
2341
2342 for (i = 0; i < cc->tfms_count; i++) {
2343 cc->cipher_tfm.tfms[i] = crypto_alloc_skcipher(ciphermode, 0,
2344 CRYPTO_ALG_ALLOCATES_MEMORY);
2345 if (IS_ERR(cc->cipher_tfm.tfms[i])) {
2346 err = PTR_ERR(cc->cipher_tfm.tfms[i]);
2347 crypt_free_tfms(cc);
2348 return err;
2349 }
2350 }
2351
2352 /*
2353 * dm-crypt performance can vary greatly depending on which crypto
2354 * algorithm implementation is used. Help people debug performance
2355 * problems by logging the ->cra_driver_name.
2356 */
2357 DMDEBUG_LIMIT("%s using implementation \"%s\"", ciphermode,
2358 crypto_skcipher_alg(any_tfm(cc))->base.cra_driver_name);
2359 return 0;
2360 }
2361
crypt_alloc_tfms_aead(struct crypt_config * cc,char * ciphermode)2362 static int crypt_alloc_tfms_aead(struct crypt_config *cc, char *ciphermode)
2363 {
2364 int err;
2365
2366 cc->cipher_tfm.tfms = kmalloc_obj(struct crypto_skcipher *, GFP_KERNEL);
2367 if (!cc->cipher_tfm.tfms)
2368 return -ENOMEM;
2369
2370 cc->cipher_tfm.tfms_aead[0] = crypto_alloc_aead(ciphermode, 0,
2371 CRYPTO_ALG_ALLOCATES_MEMORY);
2372 if (IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
2373 err = PTR_ERR(cc->cipher_tfm.tfms_aead[0]);
2374 crypt_free_tfms(cc);
2375 return err;
2376 }
2377
2378 DMDEBUG_LIMIT("%s using implementation \"%s\"", ciphermode,
2379 crypto_aead_alg(any_tfm_aead(cc))->base.cra_driver_name);
2380 return 0;
2381 }
2382
crypt_alloc_tfms(struct crypt_config * cc,char * ciphermode)2383 static int crypt_alloc_tfms(struct crypt_config *cc, char *ciphermode)
2384 {
2385 if (crypt_integrity_aead(cc))
2386 return crypt_alloc_tfms_aead(cc, ciphermode);
2387 else
2388 return crypt_alloc_tfms_skcipher(cc, ciphermode);
2389 }
2390
crypt_subkey_size(struct crypt_config * cc)2391 static unsigned int crypt_subkey_size(struct crypt_config *cc)
2392 {
2393 return (cc->key_size - cc->key_extra_size) >> ilog2(cc->tfms_count);
2394 }
2395
crypt_authenckey_size(struct crypt_config * cc)2396 static unsigned int crypt_authenckey_size(struct crypt_config *cc)
2397 {
2398 return crypt_subkey_size(cc) + RTA_SPACE(sizeof(struct crypto_authenc_key_param));
2399 }
2400
2401 /*
2402 * If AEAD is composed like authenc(hmac(sha256),xts(aes)),
2403 * the key must be for some reason in special format.
2404 * This funcion converts cc->key to this special format.
2405 */
crypt_copy_authenckey(char * p,const void * key,unsigned int enckeylen,unsigned int authkeylen)2406 static void crypt_copy_authenckey(char *p, const void *key,
2407 unsigned int enckeylen, unsigned int authkeylen)
2408 {
2409 struct crypto_authenc_key_param *param;
2410 struct rtattr *rta;
2411
2412 rta = (struct rtattr *)p;
2413 param = RTA_DATA(rta);
2414 param->enckeylen = cpu_to_be32(enckeylen);
2415 rta->rta_len = RTA_LENGTH(sizeof(*param));
2416 rta->rta_type = CRYPTO_AUTHENC_KEYA_PARAM;
2417 p += RTA_SPACE(sizeof(*param));
2418 memcpy(p, key + enckeylen, authkeylen);
2419 p += authkeylen;
2420 memcpy(p, key, enckeylen);
2421 }
2422
crypt_setkey(struct crypt_config * cc)2423 static int crypt_setkey(struct crypt_config *cc)
2424 {
2425 unsigned int subkey_size;
2426 int err = 0, i, r;
2427
2428 /* Ignore extra keys (which are used for IV etc) */
2429 subkey_size = crypt_subkey_size(cc);
2430
2431 if (crypt_integrity_hmac(cc)) {
2432 if (subkey_size < cc->key_mac_size)
2433 return -EINVAL;
2434
2435 crypt_copy_authenckey(cc->authenc_key, cc->key,
2436 subkey_size - cc->key_mac_size,
2437 cc->key_mac_size);
2438 }
2439
2440 for (i = 0; i < cc->tfms_count; i++) {
2441 if (crypt_integrity_hmac(cc))
2442 r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
2443 cc->authenc_key, crypt_authenckey_size(cc));
2444 else if (crypt_integrity_aead(cc))
2445 r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
2446 cc->key + (i * subkey_size),
2447 subkey_size);
2448 else
2449 r = crypto_skcipher_setkey(cc->cipher_tfm.tfms[i],
2450 cc->key + (i * subkey_size),
2451 subkey_size);
2452 if (r)
2453 err = r;
2454 }
2455
2456 if (crypt_integrity_hmac(cc))
2457 memzero_explicit(cc->authenc_key, crypt_authenckey_size(cc));
2458
2459 return err;
2460 }
2461
2462 #ifdef CONFIG_KEYS
2463
contains_whitespace(const char * str)2464 static bool contains_whitespace(const char *str)
2465 {
2466 while (*str)
2467 if (isspace(*str++))
2468 return true;
2469 return false;
2470 }
2471
set_key_user(struct crypt_config * cc,struct key * key)2472 static int set_key_user(struct crypt_config *cc, struct key *key)
2473 {
2474 const struct user_key_payload *ukp;
2475
2476 ukp = user_key_payload_locked(key);
2477 if (!ukp)
2478 return -EKEYREVOKED;
2479
2480 if (cc->key_size != ukp->datalen)
2481 return -EINVAL;
2482
2483 memcpy(cc->key, ukp->data, cc->key_size);
2484
2485 return 0;
2486 }
2487
set_key_encrypted(struct crypt_config * cc,struct key * key)2488 static int set_key_encrypted(struct crypt_config *cc, struct key *key)
2489 {
2490 const struct encrypted_key_payload *ekp;
2491
2492 ekp = key->payload.data[0];
2493 if (!ekp)
2494 return -EKEYREVOKED;
2495
2496 if (cc->key_size != ekp->decrypted_datalen)
2497 return -EINVAL;
2498
2499 memcpy(cc->key, ekp->decrypted_data, cc->key_size);
2500
2501 return 0;
2502 }
2503
set_key_trusted(struct crypt_config * cc,struct key * key)2504 static int set_key_trusted(struct crypt_config *cc, struct key *key)
2505 {
2506 const struct trusted_key_payload *tkp;
2507
2508 tkp = key->payload.data[0];
2509 if (!tkp)
2510 return -EKEYREVOKED;
2511
2512 if (cc->key_size != tkp->key_len)
2513 return -EINVAL;
2514
2515 memcpy(cc->key, tkp->key, cc->key_size);
2516
2517 return 0;
2518 }
2519
crypt_set_keyring_key(struct crypt_config * cc,const char * key_string)2520 static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
2521 {
2522 char *new_key_string, *key_desc;
2523 int ret;
2524 struct key_type *type;
2525 struct key *key;
2526 int (*set_key)(struct crypt_config *cc, struct key *key);
2527
2528 /*
2529 * Reject key_string with whitespace. dm core currently lacks code for
2530 * proper whitespace escaping in arguments on DM_TABLE_STATUS path.
2531 */
2532 if (contains_whitespace(key_string)) {
2533 DMERR("whitespace chars not allowed in key string");
2534 return -EINVAL;
2535 }
2536
2537 /* look for next ':' separating key_type from key_description */
2538 key_desc = strchr(key_string, ':');
2539 if (!key_desc || key_desc == key_string || !strlen(key_desc + 1))
2540 return -EINVAL;
2541
2542 if (!strncmp(key_string, "logon:", key_desc - key_string + 1)) {
2543 type = &key_type_logon;
2544 set_key = set_key_user;
2545 } else if (!strncmp(key_string, "user:", key_desc - key_string + 1)) {
2546 type = &key_type_user;
2547 set_key = set_key_user;
2548 } else if (IS_ENABLED(CONFIG_ENCRYPTED_KEYS) &&
2549 !strncmp(key_string, "encrypted:", key_desc - key_string + 1)) {
2550 type = &key_type_encrypted;
2551 set_key = set_key_encrypted;
2552 } else if (IS_ENABLED(CONFIG_TRUSTED_KEYS) &&
2553 !strncmp(key_string, "trusted:", key_desc - key_string + 1)) {
2554 type = &key_type_trusted;
2555 set_key = set_key_trusted;
2556 } else {
2557 return -EINVAL;
2558 }
2559
2560 new_key_string = kstrdup(key_string, GFP_KERNEL);
2561 if (!new_key_string)
2562 return -ENOMEM;
2563
2564 key = request_key(type, key_desc + 1, NULL);
2565 if (IS_ERR(key)) {
2566 ret = PTR_ERR(key);
2567 goto free_new_key_string;
2568 }
2569
2570 down_read(&key->sem);
2571 ret = set_key(cc, key);
2572 up_read(&key->sem);
2573 key_put(key);
2574 if (ret < 0)
2575 goto free_new_key_string;
2576
2577 /* clear the flag since following operations may invalidate previously valid key */
2578 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2579
2580 ret = crypt_setkey(cc);
2581 if (ret)
2582 goto free_new_key_string;
2583
2584 set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2585 kfree_sensitive(cc->key_string);
2586 cc->key_string = new_key_string;
2587 return 0;
2588
2589 free_new_key_string:
2590 kfree_sensitive(new_key_string);
2591 return ret;
2592 }
2593
get_key_size(char ** key_string)2594 static int get_key_size(char **key_string)
2595 {
2596 char *colon, dummy;
2597 int ret;
2598
2599 if (*key_string[0] != ':')
2600 return strlen(*key_string) >> 1;
2601
2602 /* look for next ':' in key string */
2603 colon = strpbrk(*key_string + 1, ":");
2604 if (!colon)
2605 return -EINVAL;
2606
2607 if (sscanf(*key_string + 1, "%u%c", &ret, &dummy) != 2 || dummy != ':')
2608 return -EINVAL;
2609
2610 *key_string = colon;
2611
2612 /* remaining key string should be :<logon|user>:<key_desc> */
2613
2614 return ret;
2615 }
2616
2617 #else
2618
crypt_set_keyring_key(struct crypt_config * cc,const char * key_string)2619 static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
2620 {
2621 return -EINVAL;
2622 }
2623
get_key_size(char ** key_string)2624 static int get_key_size(char **key_string)
2625 {
2626 return (*key_string[0] == ':') ? -EINVAL : (int)(strlen(*key_string) >> 1);
2627 }
2628
2629 #endif /* CONFIG_KEYS */
2630
crypt_set_key(struct crypt_config * cc,char * key)2631 static int crypt_set_key(struct crypt_config *cc, char *key)
2632 {
2633 int r = -EINVAL;
2634 int key_string_len = strlen(key);
2635
2636 /* Hyphen (which gives a key_size of zero) means there is no key. */
2637 if (!cc->key_size && strcmp(key, "-"))
2638 goto out;
2639
2640 /* ':' means the key is in kernel keyring, short-circuit normal key processing */
2641 if (key[0] == ':') {
2642 r = crypt_set_keyring_key(cc, key + 1);
2643 goto out;
2644 }
2645
2646 /* clear the flag since following operations may invalidate previously valid key */
2647 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2648
2649 /* wipe references to any kernel keyring key */
2650 kfree_sensitive(cc->key_string);
2651 cc->key_string = NULL;
2652
2653 /* Decode key from its hex representation. */
2654 if (cc->key_size && hex2bin(cc->key, key, cc->key_size) < 0)
2655 goto out;
2656
2657 r = crypt_setkey(cc);
2658 if (!r)
2659 set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2660
2661 out:
2662 /* Hex key string not needed after here, so wipe it. */
2663 memset(key, '0', key_string_len);
2664
2665 return r;
2666 }
2667
crypt_wipe_key(struct crypt_config * cc)2668 static int crypt_wipe_key(struct crypt_config *cc)
2669 {
2670 int r;
2671
2672 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2673 get_random_bytes(&cc->key, cc->key_size);
2674
2675 /* Wipe IV private keys */
2676 if (cc->iv_gen_ops && cc->iv_gen_ops->wipe) {
2677 r = cc->iv_gen_ops->wipe(cc);
2678 if (r)
2679 return r;
2680 }
2681
2682 kfree_sensitive(cc->key_string);
2683 cc->key_string = NULL;
2684 r = crypt_setkey(cc);
2685 memset(&cc->key, 0, cc->key_size * sizeof(u8));
2686
2687 return r;
2688 }
2689
crypt_calculate_pages_per_client(void)2690 static void crypt_calculate_pages_per_client(void)
2691 {
2692 unsigned long pages = (totalram_pages() - totalhigh_pages()) * DM_CRYPT_MEMORY_PERCENT / 100;
2693
2694 if (!dm_crypt_clients_n)
2695 return;
2696
2697 pages /= dm_crypt_clients_n;
2698 if (pages < DM_CRYPT_MIN_PAGES_PER_CLIENT)
2699 pages = DM_CRYPT_MIN_PAGES_PER_CLIENT;
2700 dm_crypt_pages_per_client = pages;
2701 }
2702
crypt_page_alloc(gfp_t gfp_mask,void * pool_data)2703 static void *crypt_page_alloc(gfp_t gfp_mask, void *pool_data)
2704 {
2705 struct crypt_config *cc = pool_data;
2706 struct page *page;
2707
2708 /*
2709 * Note, percpu_counter_read_positive() may over (and under) estimate
2710 * the current usage by at most (batch - 1) * num_online_cpus() pages,
2711 * but avoids potential spinlock contention of an exact result.
2712 */
2713 if (unlikely(percpu_counter_read_positive(&cc->n_allocated_pages) >= dm_crypt_pages_per_client) &&
2714 likely(gfp_mask & __GFP_NORETRY))
2715 return NULL;
2716
2717 page = alloc_page(gfp_mask);
2718 if (likely(page != NULL))
2719 percpu_counter_add(&cc->n_allocated_pages, 1);
2720
2721 return page;
2722 }
2723
crypt_page_free(void * page,void * pool_data)2724 static void crypt_page_free(void *page, void *pool_data)
2725 {
2726 struct crypt_config *cc = pool_data;
2727
2728 __free_page(page);
2729 percpu_counter_sub(&cc->n_allocated_pages, 1);
2730 }
2731
crypt_dtr(struct dm_target * ti)2732 static void crypt_dtr(struct dm_target *ti)
2733 {
2734 struct crypt_config *cc = ti->private;
2735
2736 ti->private = NULL;
2737
2738 if (!cc)
2739 return;
2740
2741 if (cc->write_thread)
2742 kthread_stop(cc->write_thread);
2743
2744 if (cc->io_queue)
2745 destroy_workqueue(cc->io_queue);
2746 if (cc->crypt_queue)
2747 destroy_workqueue(cc->crypt_queue);
2748
2749 if (cc->workqueue_id)
2750 ida_free(&workqueue_ida, cc->workqueue_id);
2751
2752 crypt_free_tfms(cc);
2753
2754 bioset_exit(&cc->bs);
2755
2756 mempool_exit(&cc->page_pool);
2757 mempool_exit(&cc->req_pool);
2758 mempool_exit(&cc->tag_pool);
2759
2760 WARN_ON(percpu_counter_sum(&cc->n_allocated_pages) != 0);
2761 percpu_counter_destroy(&cc->n_allocated_pages);
2762
2763 if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
2764 cc->iv_gen_ops->dtr(cc);
2765
2766 if (cc->dev)
2767 dm_put_device(ti, cc->dev);
2768
2769 kfree_sensitive(cc->cipher_string);
2770 kfree_sensitive(cc->key_string);
2771 kfree_sensitive(cc->cipher_auth);
2772 kfree_sensitive(cc->authenc_key);
2773
2774 mutex_destroy(&cc->bio_alloc_lock);
2775
2776 /* Must zero key material before freeing */
2777 kfree_sensitive(cc);
2778
2779 spin_lock(&dm_crypt_clients_lock);
2780 WARN_ON(!dm_crypt_clients_n);
2781 dm_crypt_clients_n--;
2782 crypt_calculate_pages_per_client();
2783 spin_unlock(&dm_crypt_clients_lock);
2784
2785 dm_audit_log_dtr(DM_MSG_PREFIX, ti, 1);
2786 }
2787
crypt_ctr_ivmode(struct dm_target * ti,const char * ivmode)2788 static int crypt_ctr_ivmode(struct dm_target *ti, const char *ivmode)
2789 {
2790 struct crypt_config *cc = ti->private;
2791
2792 if (crypt_integrity_aead(cc))
2793 cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
2794 else
2795 cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
2796
2797 if (cc->iv_size)
2798 /* at least a 64 bit sector number should fit in our buffer */
2799 cc->iv_size = max(cc->iv_size,
2800 (unsigned int)(sizeof(u64) / sizeof(u8)));
2801 else if (ivmode) {
2802 DMWARN("Selected cipher does not support IVs");
2803 ivmode = NULL;
2804 }
2805
2806 /* Choose ivmode, see comments at iv code. */
2807 if (ivmode == NULL)
2808 cc->iv_gen_ops = NULL;
2809 else if (strcmp(ivmode, "plain") == 0)
2810 cc->iv_gen_ops = &crypt_iv_plain_ops;
2811 else if (strcmp(ivmode, "plain64") == 0)
2812 cc->iv_gen_ops = &crypt_iv_plain64_ops;
2813 else if (strcmp(ivmode, "plain64be") == 0)
2814 cc->iv_gen_ops = &crypt_iv_plain64be_ops;
2815 else if (strcmp(ivmode, "essiv") == 0)
2816 cc->iv_gen_ops = &crypt_iv_essiv_ops;
2817 else if (strcmp(ivmode, "benbi") == 0)
2818 cc->iv_gen_ops = &crypt_iv_benbi_ops;
2819 else if (strcmp(ivmode, "null") == 0)
2820 cc->iv_gen_ops = &crypt_iv_null_ops;
2821 else if (strcmp(ivmode, "eboiv") == 0)
2822 cc->iv_gen_ops = &crypt_iv_eboiv_ops;
2823 else if (strcmp(ivmode, "elephant") == 0) {
2824 cc->iv_gen_ops = &crypt_iv_elephant_ops;
2825 cc->key_parts = 2;
2826 cc->key_extra_size = cc->key_size / 2;
2827 if (cc->key_extra_size > ELEPHANT_MAX_KEY_SIZE)
2828 return -EINVAL;
2829 set_bit(CRYPT_ENCRYPT_PREPROCESS, &cc->cipher_flags);
2830 } else if (strcmp(ivmode, "lmk") == 0) {
2831 cc->iv_gen_ops = &crypt_iv_lmk_ops;
2832 /*
2833 * Version 2 and 3 is recognised according
2834 * to length of provided multi-key string.
2835 * If present (version 3), last key is used as IV seed.
2836 * All keys (including IV seed) are always the same size.
2837 */
2838 if (cc->key_size % cc->key_parts) {
2839 cc->key_parts++;
2840 cc->key_extra_size = cc->key_size / cc->key_parts;
2841 }
2842 } else if (strcmp(ivmode, "tcw") == 0) {
2843 cc->iv_gen_ops = &crypt_iv_tcw_ops;
2844 cc->key_parts += 2; /* IV + whitening */
2845 cc->key_extra_size = cc->iv_size + TCW_WHITENING_SIZE;
2846 } else if (strcmp(ivmode, "random") == 0) {
2847 cc->iv_gen_ops = &crypt_iv_random_ops;
2848 /* Need storage space in integrity fields. */
2849 cc->integrity_iv_size = cc->iv_size;
2850 } else {
2851 ti->error = "Invalid IV mode";
2852 return -EINVAL;
2853 }
2854
2855 return 0;
2856 }
2857
2858 /*
2859 * Workaround to parse HMAC algorithm from AEAD crypto API spec.
2860 * The HMAC is needed to calculate tag size (HMAC digest size).
2861 * This should be probably done by crypto-api calls (once available...)
2862 */
crypt_ctr_auth_cipher(struct crypt_config * cc,char * cipher_api)2863 static int crypt_ctr_auth_cipher(struct crypt_config *cc, char *cipher_api)
2864 {
2865 char *start, *end, *mac_alg = NULL;
2866 struct crypto_ahash *mac;
2867
2868 if (!strstarts(cipher_api, "authenc("))
2869 return 0;
2870
2871 start = strchr(cipher_api, '(');
2872 end = strchr(cipher_api, ',');
2873 if (!start || !end || ++start > end)
2874 return -EINVAL;
2875
2876 mac_alg = kmemdup_nul(start, end - start, GFP_KERNEL);
2877 if (!mac_alg)
2878 return -ENOMEM;
2879
2880 mac = crypto_alloc_ahash(mac_alg, 0, CRYPTO_ALG_ALLOCATES_MEMORY);
2881 kfree(mac_alg);
2882
2883 if (IS_ERR(mac))
2884 return PTR_ERR(mac);
2885
2886 if (!test_bit(CRYPT_KEY_MAC_SIZE_SET, &cc->cipher_flags))
2887 cc->key_mac_size = crypto_ahash_digestsize(mac);
2888 crypto_free_ahash(mac);
2889
2890 cc->authenc_key = kmalloc(crypt_authenckey_size(cc), GFP_KERNEL);
2891 if (!cc->authenc_key)
2892 return -ENOMEM;
2893
2894 return 0;
2895 }
2896
crypt_ctr_cipher_new(struct dm_target * ti,char * cipher_in,char * key,char ** ivmode,char ** ivopts)2897 static int crypt_ctr_cipher_new(struct dm_target *ti, char *cipher_in, char *key,
2898 char **ivmode, char **ivopts)
2899 {
2900 struct crypt_config *cc = ti->private;
2901 char *tmp, *cipher_api, buf[CRYPTO_MAX_ALG_NAME];
2902 int ret = -EINVAL;
2903
2904 cc->tfms_count = 1;
2905
2906 /*
2907 * New format (capi: prefix)
2908 * capi:cipher_api_spec-iv:ivopts
2909 */
2910 tmp = &cipher_in[strlen("capi:")];
2911
2912 /* Separate IV options if present, it can contain another '-' in hash name */
2913 *ivopts = strrchr(tmp, ':');
2914 if (*ivopts) {
2915 **ivopts = '\0';
2916 (*ivopts)++;
2917 }
2918 /* Parse IV mode */
2919 *ivmode = strrchr(tmp, '-');
2920 if (*ivmode) {
2921 **ivmode = '\0';
2922 (*ivmode)++;
2923 }
2924 /* The rest is crypto API spec */
2925 cipher_api = tmp;
2926
2927 /* Alloc AEAD, can be used only in new format. */
2928 if (crypt_integrity_aead(cc)) {
2929 ret = crypt_ctr_auth_cipher(cc, cipher_api);
2930 if (ret < 0) {
2931 ti->error = "Invalid AEAD cipher spec";
2932 return ret;
2933 }
2934 }
2935
2936 if (*ivmode && !strcmp(*ivmode, "lmk"))
2937 cc->tfms_count = 64;
2938
2939 if (*ivmode && !strcmp(*ivmode, "essiv")) {
2940 if (!*ivopts) {
2941 ti->error = "Digest algorithm missing for ESSIV mode";
2942 return -EINVAL;
2943 }
2944 ret = snprintf(buf, CRYPTO_MAX_ALG_NAME, "essiv(%s,%s)",
2945 cipher_api, *ivopts);
2946 if (ret < 0 || ret >= CRYPTO_MAX_ALG_NAME) {
2947 ti->error = "Cannot allocate cipher string";
2948 return -ENOMEM;
2949 }
2950 cipher_api = buf;
2951 }
2952
2953 cc->key_parts = cc->tfms_count;
2954
2955 /* Allocate cipher */
2956 ret = crypt_alloc_tfms(cc, cipher_api);
2957 if (ret < 0) {
2958 ti->error = "Error allocating crypto tfm";
2959 return ret;
2960 }
2961
2962 if (crypt_integrity_aead(cc))
2963 cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
2964 else
2965 cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
2966
2967 return 0;
2968 }
2969
crypt_ctr_cipher_old(struct dm_target * ti,char * cipher_in,char * key,char ** ivmode,char ** ivopts)2970 static int crypt_ctr_cipher_old(struct dm_target *ti, char *cipher_in, char *key,
2971 char **ivmode, char **ivopts)
2972 {
2973 struct crypt_config *cc = ti->private;
2974 char *tmp, *cipher, *chainmode, *keycount;
2975 char *cipher_api = NULL;
2976 int ret = -EINVAL;
2977 char dummy;
2978
2979 if (strchr(cipher_in, '(') || crypt_integrity_aead(cc)) {
2980 ti->error = "Bad cipher specification";
2981 return -EINVAL;
2982 }
2983
2984 /*
2985 * Legacy dm-crypt cipher specification
2986 * cipher[:keycount]-mode-iv:ivopts
2987 */
2988 tmp = cipher_in;
2989 keycount = strsep(&tmp, "-");
2990 cipher = strsep(&keycount, ":");
2991
2992 if (!keycount)
2993 cc->tfms_count = 1;
2994 else if (sscanf(keycount, "%u%c", &cc->tfms_count, &dummy) != 1 ||
2995 !is_power_of_2(cc->tfms_count)) {
2996 ti->error = "Bad cipher key count specification";
2997 return -EINVAL;
2998 }
2999 cc->key_parts = cc->tfms_count;
3000
3001 chainmode = strsep(&tmp, "-");
3002 *ivmode = strsep(&tmp, ":");
3003 *ivopts = tmp;
3004
3005 /*
3006 * For compatibility with the original dm-crypt mapping format, if
3007 * only the cipher name is supplied, use cbc-plain.
3008 */
3009 if (!chainmode || (!strcmp(chainmode, "plain") && !*ivmode)) {
3010 chainmode = "cbc";
3011 *ivmode = "plain";
3012 }
3013
3014 if (strcmp(chainmode, "ecb") && !*ivmode) {
3015 ti->error = "IV mechanism required";
3016 return -EINVAL;
3017 }
3018
3019 cipher_api = kmalloc(CRYPTO_MAX_ALG_NAME, GFP_KERNEL);
3020 if (!cipher_api)
3021 goto bad_mem;
3022
3023 if (*ivmode && !strcmp(*ivmode, "essiv")) {
3024 if (!*ivopts) {
3025 ti->error = "Digest algorithm missing for ESSIV mode";
3026 kfree(cipher_api);
3027 return -EINVAL;
3028 }
3029 ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
3030 "essiv(%s(%s),%s)", chainmode, cipher, *ivopts);
3031 } else {
3032 ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
3033 "%s(%s)", chainmode, cipher);
3034 }
3035 if (ret < 0 || ret >= CRYPTO_MAX_ALG_NAME) {
3036 kfree(cipher_api);
3037 goto bad_mem;
3038 }
3039
3040 /* Allocate cipher */
3041 ret = crypt_alloc_tfms(cc, cipher_api);
3042 if (ret < 0) {
3043 ti->error = "Error allocating crypto tfm";
3044 kfree(cipher_api);
3045 return ret;
3046 }
3047 kfree(cipher_api);
3048
3049 return 0;
3050 bad_mem:
3051 ti->error = "Cannot allocate cipher strings";
3052 return -ENOMEM;
3053 }
3054
crypt_ctr_cipher(struct dm_target * ti,char * cipher_in,char * key)3055 static int crypt_ctr_cipher(struct dm_target *ti, char *cipher_in, char *key)
3056 {
3057 struct crypt_config *cc = ti->private;
3058 char *ivmode = NULL, *ivopts = NULL;
3059 int ret;
3060
3061 cc->cipher_string = kstrdup(cipher_in, GFP_KERNEL);
3062 if (!cc->cipher_string) {
3063 ti->error = "Cannot allocate cipher strings";
3064 return -ENOMEM;
3065 }
3066
3067 if (strstarts(cipher_in, "capi:"))
3068 ret = crypt_ctr_cipher_new(ti, cipher_in, key, &ivmode, &ivopts);
3069 else
3070 ret = crypt_ctr_cipher_old(ti, cipher_in, key, &ivmode, &ivopts);
3071 if (ret)
3072 return ret;
3073
3074 /* Initialize IV */
3075 ret = crypt_ctr_ivmode(ti, ivmode);
3076 if (ret < 0)
3077 return ret;
3078
3079 /* Initialize and set key */
3080 ret = crypt_set_key(cc, key);
3081 if (ret < 0) {
3082 ti->error = "Error decoding and setting key";
3083 return ret;
3084 }
3085
3086 /* Allocate IV */
3087 if (cc->iv_gen_ops && cc->iv_gen_ops->ctr) {
3088 ret = cc->iv_gen_ops->ctr(cc, ti, ivopts);
3089 if (ret < 0) {
3090 ti->error = "Error creating IV";
3091 return ret;
3092 }
3093 }
3094
3095 /* Initialize IV (set keys for ESSIV etc) */
3096 if (cc->iv_gen_ops && cc->iv_gen_ops->init) {
3097 ret = cc->iv_gen_ops->init(cc);
3098 if (ret < 0) {
3099 ti->error = "Error initialising IV";
3100 return ret;
3101 }
3102 }
3103
3104 /* wipe the kernel key payload copy */
3105 if (cc->key_string)
3106 memset(cc->key, 0, cc->key_size * sizeof(u8));
3107
3108 return ret;
3109 }
3110
crypt_ctr_optional(struct dm_target * ti,unsigned int argc,char ** argv)3111 static int crypt_ctr_optional(struct dm_target *ti, unsigned int argc, char **argv)
3112 {
3113 struct crypt_config *cc = ti->private;
3114 struct dm_arg_set as;
3115 static const struct dm_arg _args[] = {
3116 {0, 9, "Invalid number of feature args"},
3117 };
3118 unsigned int opt_params, val;
3119 const char *opt_string, *sval;
3120 char dummy;
3121 int ret;
3122
3123 /* Optional parameters */
3124 as.argc = argc;
3125 as.argv = argv;
3126
3127 ret = dm_read_arg_group(_args, &as, &opt_params, &ti->error);
3128 if (ret)
3129 return ret;
3130
3131 while (opt_params--) {
3132 opt_string = dm_shift_arg(&as);
3133 if (!opt_string) {
3134 ti->error = "Not enough feature arguments";
3135 return -EINVAL;
3136 }
3137
3138 if (!strcasecmp(opt_string, "allow_discards"))
3139 ti->num_discard_bios = 1;
3140
3141 else if (!strcasecmp(opt_string, "same_cpu_crypt"))
3142 set_bit(DM_CRYPT_SAME_CPU, &cc->flags);
3143 else if (!strcasecmp(opt_string, "high_priority"))
3144 set_bit(DM_CRYPT_HIGH_PRIORITY, &cc->flags);
3145
3146 else if (!strcasecmp(opt_string, "submit_from_crypt_cpus"))
3147 set_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
3148 else if (!strcasecmp(opt_string, "no_read_workqueue"))
3149 set_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags);
3150 else if (!strcasecmp(opt_string, "no_write_workqueue"))
3151 set_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags);
3152 else if (sscanf(opt_string, "integrity:%u:", &val) == 1) {
3153 if (val == 0 || val > MAX_TAG_SIZE) {
3154 ti->error = "Invalid integrity arguments";
3155 return -EINVAL;
3156 }
3157 cc->used_tag_size = val;
3158 sval = strchr(opt_string + strlen("integrity:"), ':') + 1;
3159 if (!strcasecmp(sval, "aead")) {
3160 set_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
3161 } else if (strcasecmp(sval, "none")) {
3162 ti->error = "Unknown integrity profile";
3163 return -EINVAL;
3164 }
3165
3166 cc->cipher_auth = kstrdup(sval, GFP_KERNEL);
3167 if (!cc->cipher_auth)
3168 return -ENOMEM;
3169 } else if (sscanf(opt_string, "integrity_key_size:%u%c", &val, &dummy) == 1) {
3170 if (!val) {
3171 ti->error = "Invalid integrity_key_size argument";
3172 return -EINVAL;
3173 }
3174 cc->key_mac_size = val;
3175 set_bit(CRYPT_KEY_MAC_SIZE_SET, &cc->cipher_flags);
3176 } else if (sscanf(opt_string, "sector_size:%hu%c", &cc->sector_size, &dummy) == 1) {
3177 if (cc->sector_size < (1 << SECTOR_SHIFT) ||
3178 cc->sector_size > 4096 ||
3179 (cc->sector_size & (cc->sector_size - 1))) {
3180 ti->error = "Invalid feature value for sector_size";
3181 return -EINVAL;
3182 }
3183 if (ti->len & ((cc->sector_size >> SECTOR_SHIFT) - 1)) {
3184 ti->error = "Device size is not multiple of sector_size feature";
3185 return -EINVAL;
3186 }
3187 cc->sector_shift = __ffs(cc->sector_size) - SECTOR_SHIFT;
3188 } else if (!strcasecmp(opt_string, "iv_large_sectors"))
3189 set_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
3190 else {
3191 ti->error = "Invalid feature arguments";
3192 return -EINVAL;
3193 }
3194 }
3195
3196 return 0;
3197 }
3198
3199 #ifdef CONFIG_BLK_DEV_ZONED
crypt_report_zones(struct dm_target * ti,struct dm_report_zones_args * args,unsigned int nr_zones)3200 static int crypt_report_zones(struct dm_target *ti,
3201 struct dm_report_zones_args *args, unsigned int nr_zones)
3202 {
3203 struct crypt_config *cc = ti->private;
3204
3205 return dm_report_zones(cc->dev->bdev, cc->start,
3206 cc->start + dm_target_offset(ti, args->next_sector),
3207 args, nr_zones);
3208 }
3209 #else
3210 #define crypt_report_zones NULL
3211 #endif
3212
3213 /*
3214 * Construct an encryption mapping:
3215 * <cipher> [<key>|:<key_size>:<user|logon>:<key_description>] <iv_offset> <dev_path> <start>
3216 */
crypt_ctr(struct dm_target * ti,unsigned int argc,char ** argv)3217 static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
3218 {
3219 struct crypt_config *cc;
3220 const char *devname = dm_table_device_name(ti->table);
3221 int key_size, wq_id;
3222 unsigned int align_mask;
3223 unsigned int common_wq_flags;
3224 unsigned long long tmpll;
3225 int ret;
3226 size_t iv_size_padding, additional_req_size;
3227 char dummy;
3228
3229 if (argc < 5) {
3230 ti->error = "Not enough arguments";
3231 return -EINVAL;
3232 }
3233
3234 key_size = get_key_size(&argv[1]);
3235 if (key_size < 0) {
3236 ti->error = "Cannot parse key size";
3237 return -EINVAL;
3238 }
3239
3240 cc = kzalloc_flex(*cc, key, key_size, GFP_KERNEL);
3241 if (!cc) {
3242 ti->error = "Cannot allocate encryption context";
3243 return -ENOMEM;
3244 }
3245 cc->key_size = key_size;
3246 cc->sector_size = (1 << SECTOR_SHIFT);
3247 cc->sector_shift = 0;
3248
3249 ti->private = cc;
3250
3251 spin_lock(&dm_crypt_clients_lock);
3252 dm_crypt_clients_n++;
3253 crypt_calculate_pages_per_client();
3254 spin_unlock(&dm_crypt_clients_lock);
3255
3256 ret = percpu_counter_init(&cc->n_allocated_pages, 0, GFP_KERNEL);
3257 if (ret < 0)
3258 goto bad;
3259
3260 /* Optional parameters need to be read before cipher constructor */
3261 if (argc > 5) {
3262 ret = crypt_ctr_optional(ti, argc - 5, &argv[5]);
3263 if (ret)
3264 goto bad;
3265 }
3266
3267 ret = crypt_ctr_cipher(ti, argv[0], argv[1]);
3268 if (ret < 0)
3269 goto bad;
3270
3271 if (crypt_integrity_aead(cc)) {
3272 cc->dmreq_start = sizeof(struct aead_request);
3273 cc->dmreq_start += crypto_aead_reqsize(any_tfm_aead(cc));
3274 align_mask = crypto_aead_alignmask(any_tfm_aead(cc));
3275 } else {
3276 cc->dmreq_start = sizeof(struct skcipher_request);
3277 cc->dmreq_start += crypto_skcipher_reqsize(any_tfm(cc));
3278 align_mask = crypto_skcipher_alignmask(any_tfm(cc));
3279 }
3280 cc->dmreq_start = ALIGN(cc->dmreq_start, __alignof__(struct dm_crypt_request));
3281
3282 if (align_mask < CRYPTO_MINALIGN) {
3283 /* Allocate the padding exactly */
3284 iv_size_padding = -(cc->dmreq_start + sizeof(struct dm_crypt_request))
3285 & align_mask;
3286 } else {
3287 /*
3288 * If the cipher requires greater alignment than kmalloc
3289 * alignment, we don't know the exact position of the
3290 * initialization vector. We must assume worst case.
3291 */
3292 iv_size_padding = align_mask;
3293 }
3294
3295 /* ...| IV + padding | original IV | original sec. number | bio tag offset | */
3296 additional_req_size = sizeof(struct dm_crypt_request) +
3297 iv_size_padding + cc->iv_size +
3298 cc->iv_size +
3299 sizeof(uint64_t) +
3300 sizeof(unsigned int);
3301
3302 ret = mempool_init_kmalloc_pool(&cc->req_pool, MIN_IOS, cc->dmreq_start + additional_req_size);
3303 if (ret) {
3304 ti->error = "Cannot allocate crypt request mempool";
3305 goto bad;
3306 }
3307
3308 cc->per_bio_data_size = ti->per_io_data_size =
3309 ALIGN(sizeof(struct dm_crypt_io) + cc->dmreq_start + additional_req_size,
3310 ARCH_DMA_MINALIGN);
3311
3312 ret = mempool_init(&cc->page_pool, BIO_MAX_VECS, crypt_page_alloc, crypt_page_free, cc);
3313 if (ret) {
3314 ti->error = "Cannot allocate page mempool";
3315 goto bad;
3316 }
3317
3318 ret = bioset_init(&cc->bs, MIN_IOS, 0, BIOSET_NEED_BVECS);
3319 if (ret) {
3320 ti->error = "Cannot allocate crypt bioset";
3321 goto bad;
3322 }
3323
3324 mutex_init(&cc->bio_alloc_lock);
3325
3326 ret = -EINVAL;
3327 if ((sscanf(argv[2], "%llu%c", &tmpll, &dummy) != 1) ||
3328 (tmpll & ((cc->sector_size >> SECTOR_SHIFT) - 1))) {
3329 ti->error = "Invalid iv_offset sector";
3330 goto bad;
3331 }
3332 cc->iv_offset = tmpll;
3333
3334 ret = dm_get_device(ti, argv[3], dm_table_get_mode(ti->table), &cc->dev);
3335 if (ret) {
3336 ti->error = "Device lookup failed";
3337 goto bad;
3338 }
3339
3340 ret = -EINVAL;
3341 if (sscanf(argv[4], "%llu%c", &tmpll, &dummy) != 1 || tmpll != (sector_t)tmpll) {
3342 ti->error = "Invalid device sector";
3343 goto bad;
3344 }
3345 cc->start = tmpll;
3346
3347 if (bdev_is_zoned(cc->dev->bdev)) {
3348 /*
3349 * For zoned block devices, we need to preserve the issuer write
3350 * ordering. To do so, disable write workqueues and force inline
3351 * encryption completion.
3352 */
3353 set_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags);
3354 set_bit(DM_CRYPT_WRITE_INLINE, &cc->flags);
3355
3356 /*
3357 * All zone append writes to a zone of a zoned block device will
3358 * have the same BIO sector, the start of the zone. When the
3359 * cypher IV mode uses sector values, all data targeting a
3360 * zone will be encrypted using the first sector numbers of the
3361 * zone. This will not result in write errors but will
3362 * cause most reads to fail as reads will use the sector values
3363 * for the actual data locations, resulting in IV mismatch.
3364 * To avoid this problem, ask DM core to emulate zone append
3365 * operations with regular writes.
3366 */
3367 DMDEBUG("Zone append operations will be emulated");
3368 ti->emulate_zone_append = true;
3369 }
3370
3371 if (crypt_integrity_aead(cc) || cc->integrity_iv_size) {
3372 ret = crypt_integrity_ctr(cc, ti);
3373 if (ret)
3374 goto bad;
3375
3376 cc->tag_pool_max_sectors = POOL_ENTRY_SIZE / cc->tuple_size;
3377 if (!cc->tag_pool_max_sectors)
3378 cc->tag_pool_max_sectors = 1;
3379
3380 ret = mempool_init_kmalloc_pool(&cc->tag_pool, MIN_IOS,
3381 cc->tag_pool_max_sectors * cc->tuple_size);
3382 if (ret) {
3383 ti->error = "Cannot allocate integrity tags mempool";
3384 goto bad;
3385 }
3386
3387 cc->tag_pool_max_sectors <<= cc->sector_shift;
3388 }
3389
3390 wq_id = ida_alloc_min(&workqueue_ida, 1, GFP_KERNEL);
3391 if (wq_id < 0) {
3392 ti->error = "Couldn't get workqueue id";
3393 ret = wq_id;
3394 goto bad;
3395 }
3396 cc->workqueue_id = wq_id;
3397
3398 ret = -ENOMEM;
3399 common_wq_flags = WQ_MEM_RECLAIM | WQ_SYSFS;
3400 if (test_bit(DM_CRYPT_HIGH_PRIORITY, &cc->flags))
3401 common_wq_flags |= WQ_HIGHPRI;
3402
3403 cc->io_queue = alloc_workqueue("kcryptd_io-%s-%d",
3404 common_wq_flags | WQ_PERCPU, 1,
3405 devname, wq_id);
3406 if (!cc->io_queue) {
3407 ti->error = "Couldn't create kcryptd io queue";
3408 goto bad;
3409 }
3410
3411 if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags)) {
3412 cc->crypt_queue = alloc_workqueue("kcryptd-%s-%d",
3413 common_wq_flags | WQ_CPU_INTENSIVE | WQ_PERCPU,
3414 1, devname, wq_id);
3415 } else {
3416 /*
3417 * While crypt_queue is certainly CPU intensive, the use of
3418 * WQ_CPU_INTENSIVE is meaningless with WQ_UNBOUND.
3419 */
3420 cc->crypt_queue = alloc_workqueue("kcryptd-%s-%d",
3421 common_wq_flags | WQ_UNBOUND,
3422 num_online_cpus(), devname, wq_id);
3423 }
3424 if (!cc->crypt_queue) {
3425 ti->error = "Couldn't create kcryptd queue";
3426 goto bad;
3427 }
3428
3429 spin_lock_init(&cc->write_thread_lock);
3430 cc->write_tree = RB_ROOT;
3431
3432 cc->write_thread = kthread_run(dmcrypt_write, cc, "dmcrypt_write/%s", devname);
3433 if (IS_ERR(cc->write_thread)) {
3434 ret = PTR_ERR(cc->write_thread);
3435 cc->write_thread = NULL;
3436 ti->error = "Couldn't spawn write thread";
3437 goto bad;
3438 }
3439 if (test_bit(DM_CRYPT_HIGH_PRIORITY, &cc->flags))
3440 set_user_nice(cc->write_thread, MIN_NICE);
3441
3442 ti->num_flush_bios = 1;
3443 ti->limit_swap_bios = true;
3444 ti->accounts_remapped_io = true;
3445
3446 dm_audit_log_ctr(DM_MSG_PREFIX, ti, 1);
3447 return 0;
3448
3449 bad:
3450 dm_audit_log_ctr(DM_MSG_PREFIX, ti, 0);
3451 crypt_dtr(ti);
3452 return ret;
3453 }
3454
crypt_map(struct dm_target * ti,struct bio * bio)3455 static int crypt_map(struct dm_target *ti, struct bio *bio)
3456 {
3457 struct dm_crypt_io *io;
3458 struct crypt_config *cc = ti->private;
3459 unsigned max_sectors;
3460 bool no_split;
3461
3462 /*
3463 * If bio is REQ_PREFLUSH or REQ_OP_DISCARD, just bypass crypt queues.
3464 * - for REQ_PREFLUSH device-mapper core ensures that no IO is in-flight
3465 * - for REQ_OP_DISCARD caller must use flush if IO ordering matters
3466 */
3467 if (unlikely(bio->bi_opf & REQ_PREFLUSH ||
3468 bio_op(bio) == REQ_OP_DISCARD)) {
3469 bio_set_dev(bio, cc->dev->bdev);
3470 if (bio_sectors(bio))
3471 bio->bi_iter.bi_sector = cc->start +
3472 dm_target_offset(ti, bio->bi_iter.bi_sector);
3473 return DM_MAPIO_REMAPPED;
3474 }
3475
3476 /*
3477 * Check if bio is too large, split as needed.
3478 *
3479 * For zoned devices, splitting write operations creates the
3480 * risk of deadlocking queue freeze operations with zone write
3481 * plugging BIO work when the reminder of a split BIO is
3482 * issued. So always allow the entire BIO to proceed.
3483 */
3484 no_split = (ti->emulate_zone_append && op_is_write(bio_op(bio))) ||
3485 (bio->bi_opf & REQ_ATOMIC);
3486 max_sectors = get_max_request_sectors(ti, bio, no_split);
3487 if (unlikely(bio_sectors(bio) > max_sectors)) {
3488 if (unlikely(no_split))
3489 return DM_MAPIO_KILL;
3490 dm_accept_partial_bio(bio, max_sectors);
3491 }
3492
3493 /*
3494 * Ensure that bio is a multiple of internal sector encryption size
3495 * and is aligned to this size as defined in IO hints.
3496 */
3497 if (unlikely((bio->bi_iter.bi_sector & ((cc->sector_size >> SECTOR_SHIFT) - 1)) != 0))
3498 return DM_MAPIO_KILL;
3499
3500 if (unlikely(bio->bi_iter.bi_size & (cc->sector_size - 1)))
3501 return DM_MAPIO_KILL;
3502
3503 io = dm_per_bio_data(bio, cc->per_bio_data_size);
3504 crypt_io_init(io, cc, bio, dm_target_offset(ti, bio->bi_iter.bi_sector));
3505
3506 if (cc->tuple_size) {
3507 unsigned int tag_len = cc->tuple_size * (bio_sectors(bio) >> cc->sector_shift);
3508
3509 if (unlikely(tag_len > KMALLOC_MAX_SIZE))
3510 io->integrity_metadata = NULL;
3511 else
3512 io->integrity_metadata = kmalloc(tag_len, GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN);
3513
3514 if (unlikely(!io->integrity_metadata)) {
3515 if (bio_sectors(bio) > cc->tag_pool_max_sectors)
3516 dm_accept_partial_bio(bio, cc->tag_pool_max_sectors);
3517 io->integrity_metadata = mempool_alloc(&cc->tag_pool, GFP_NOIO);
3518 io->integrity_metadata_from_pool = true;
3519 }
3520 }
3521
3522 if (crypt_integrity_aead(cc))
3523 io->ctx.r.req_aead = (struct aead_request *)(io + 1);
3524 else
3525 io->ctx.r.req = (struct skcipher_request *)(io + 1);
3526
3527 if (bio_data_dir(io->base_bio) == READ) {
3528 if (kcryptd_io_read(io, CRYPT_MAP_READ_GFP))
3529 kcryptd_queue_read(io);
3530 } else
3531 kcryptd_queue_crypt(io);
3532
3533 return DM_MAPIO_SUBMITTED;
3534 }
3535
hex2asc(unsigned char c)3536 static char hex2asc(unsigned char c)
3537 {
3538 return c + '0' + ((unsigned int)(9 - c) >> 4 & 0x27);
3539 }
3540
crypt_status(struct dm_target * ti,status_type_t type,unsigned int status_flags,char * result,unsigned int maxlen)3541 static void crypt_status(struct dm_target *ti, status_type_t type,
3542 unsigned int status_flags, char *result, unsigned int maxlen)
3543 {
3544 struct crypt_config *cc = ti->private;
3545 unsigned int i, sz = 0;
3546 int num_feature_args = 0;
3547
3548 switch (type) {
3549 case STATUSTYPE_INFO:
3550 result[0] = '\0';
3551 break;
3552
3553 case STATUSTYPE_TABLE:
3554 DMEMIT("%s ", cc->cipher_string);
3555
3556 if (cc->key_size > 0) {
3557 if (cc->key_string)
3558 DMEMIT(":%u:%s", cc->key_size, cc->key_string);
3559 else {
3560 for (i = 0; i < cc->key_size; i++) {
3561 DMEMIT("%c%c", hex2asc(cc->key[i] >> 4),
3562 hex2asc(cc->key[i] & 0xf));
3563 }
3564 }
3565 } else
3566 DMEMIT("-");
3567
3568 DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
3569 cc->dev->name, (unsigned long long)cc->start);
3570
3571 num_feature_args += !!ti->num_discard_bios;
3572 num_feature_args += test_bit(DM_CRYPT_SAME_CPU, &cc->flags);
3573 num_feature_args += test_bit(DM_CRYPT_HIGH_PRIORITY, &cc->flags);
3574 num_feature_args += test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
3575 num_feature_args += test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags);
3576 num_feature_args += test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags);
3577 num_feature_args += !!cc->used_tag_size;
3578 num_feature_args += cc->sector_size != (1 << SECTOR_SHIFT);
3579 num_feature_args += test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
3580 num_feature_args += test_bit(CRYPT_KEY_MAC_SIZE_SET, &cc->cipher_flags);
3581 if (num_feature_args) {
3582 DMEMIT(" %d", num_feature_args);
3583 if (ti->num_discard_bios)
3584 DMEMIT(" allow_discards");
3585 if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
3586 DMEMIT(" same_cpu_crypt");
3587 if (test_bit(DM_CRYPT_HIGH_PRIORITY, &cc->flags))
3588 DMEMIT(" high_priority");
3589 if (test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags))
3590 DMEMIT(" submit_from_crypt_cpus");
3591 if (test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags))
3592 DMEMIT(" no_read_workqueue");
3593 if (test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags))
3594 DMEMIT(" no_write_workqueue");
3595 if (cc->used_tag_size)
3596 DMEMIT(" integrity:%u:%s", cc->used_tag_size, cc->cipher_auth);
3597 if (cc->sector_size != (1 << SECTOR_SHIFT))
3598 DMEMIT(" sector_size:%d", cc->sector_size);
3599 if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
3600 DMEMIT(" iv_large_sectors");
3601 if (test_bit(CRYPT_KEY_MAC_SIZE_SET, &cc->cipher_flags))
3602 DMEMIT(" integrity_key_size:%u", cc->key_mac_size);
3603 }
3604 break;
3605
3606 case STATUSTYPE_IMA:
3607 DMEMIT_TARGET_NAME_VERSION(ti->type);
3608 DMEMIT(",allow_discards=%c", ti->num_discard_bios ? 'y' : 'n');
3609 DMEMIT(",same_cpu_crypt=%c", test_bit(DM_CRYPT_SAME_CPU, &cc->flags) ? 'y' : 'n');
3610 DMEMIT(",high_priority=%c", test_bit(DM_CRYPT_HIGH_PRIORITY, &cc->flags) ? 'y' : 'n');
3611 DMEMIT(",submit_from_crypt_cpus=%c", test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags) ?
3612 'y' : 'n');
3613 DMEMIT(",no_read_workqueue=%c", test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags) ?
3614 'y' : 'n');
3615 DMEMIT(",no_write_workqueue=%c", test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags) ?
3616 'y' : 'n');
3617 DMEMIT(",iv_large_sectors=%c", test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags) ?
3618 'y' : 'n');
3619
3620 if (cc->used_tag_size)
3621 DMEMIT(",integrity_tag_size=%u,cipher_auth=%s",
3622 cc->used_tag_size, cc->cipher_auth);
3623 if (cc->sector_size != (1 << SECTOR_SHIFT))
3624 DMEMIT(",sector_size=%d", cc->sector_size);
3625 if (cc->cipher_string)
3626 DMEMIT(",cipher_string=%s", cc->cipher_string);
3627
3628 DMEMIT(",key_size=%u", cc->key_size);
3629 DMEMIT(",key_parts=%u", cc->key_parts);
3630 DMEMIT(",key_extra_size=%u", cc->key_extra_size);
3631 DMEMIT(",key_mac_size=%u", cc->key_mac_size);
3632 DMEMIT(";");
3633 break;
3634 }
3635 }
3636
crypt_postsuspend(struct dm_target * ti)3637 static void crypt_postsuspend(struct dm_target *ti)
3638 {
3639 struct crypt_config *cc = ti->private;
3640
3641 set_bit(DM_CRYPT_SUSPENDED, &cc->flags);
3642 }
3643
crypt_preresume(struct dm_target * ti)3644 static int crypt_preresume(struct dm_target *ti)
3645 {
3646 struct crypt_config *cc = ti->private;
3647
3648 if (!test_bit(DM_CRYPT_KEY_VALID, &cc->flags)) {
3649 DMERR("aborting resume - crypt key is not set.");
3650 return -EAGAIN;
3651 }
3652
3653 return 0;
3654 }
3655
crypt_resume(struct dm_target * ti)3656 static void crypt_resume(struct dm_target *ti)
3657 {
3658 struct crypt_config *cc = ti->private;
3659
3660 clear_bit(DM_CRYPT_SUSPENDED, &cc->flags);
3661 }
3662
3663 /* Message interface
3664 * key set <key>
3665 * key wipe
3666 */
crypt_message(struct dm_target * ti,unsigned int argc,char ** argv,char * result,unsigned int maxlen)3667 static int crypt_message(struct dm_target *ti, unsigned int argc, char **argv,
3668 char *result, unsigned int maxlen)
3669 {
3670 struct crypt_config *cc = ti->private;
3671 int key_size, ret = -EINVAL;
3672
3673 if (argc < 2)
3674 goto error;
3675
3676 if (!strcasecmp(argv[0], "key")) {
3677 if (!test_bit(DM_CRYPT_SUSPENDED, &cc->flags)) {
3678 DMWARN("not suspended during key manipulation.");
3679 return -EINVAL;
3680 }
3681 if (argc == 3 && !strcasecmp(argv[1], "set")) {
3682 /* The key size may not be changed. */
3683 key_size = get_key_size(&argv[2]);
3684 if (key_size < 0 || cc->key_size != key_size) {
3685 memset(argv[2], '0', strlen(argv[2]));
3686 return -EINVAL;
3687 }
3688
3689 ret = crypt_set_key(cc, argv[2]);
3690 if (ret)
3691 return ret;
3692 if (cc->iv_gen_ops && cc->iv_gen_ops->init)
3693 ret = cc->iv_gen_ops->init(cc);
3694 /* wipe the kernel key payload copy */
3695 if (cc->key_string)
3696 memset(cc->key, 0, cc->key_size * sizeof(u8));
3697 return ret;
3698 }
3699 if (argc == 2 && !strcasecmp(argv[1], "wipe"))
3700 return crypt_wipe_key(cc);
3701 }
3702
3703 error:
3704 DMWARN("unrecognised message received.");
3705 return -EINVAL;
3706 }
3707
crypt_iterate_devices(struct dm_target * ti,iterate_devices_callout_fn fn,void * data)3708 static int crypt_iterate_devices(struct dm_target *ti,
3709 iterate_devices_callout_fn fn, void *data)
3710 {
3711 struct crypt_config *cc = ti->private;
3712
3713 return fn(ti, cc->dev, cc->start, ti->len, data);
3714 }
3715
crypt_io_hints(struct dm_target * ti,struct queue_limits * limits)3716 static void crypt_io_hints(struct dm_target *ti, struct queue_limits *limits)
3717 {
3718 struct crypt_config *cc = ti->private;
3719
3720 limits->logical_block_size =
3721 max_t(unsigned int, limits->logical_block_size, cc->sector_size);
3722 limits->physical_block_size =
3723 max_t(unsigned int, limits->physical_block_size, cc->sector_size);
3724 limits->io_min = max_t(unsigned int, limits->io_min, cc->sector_size);
3725 limits->dma_alignment = limits->logical_block_size - 1;
3726
3727 /*
3728 * For zoned dm-crypt targets, there will be no internal splitting of
3729 * write BIOs to avoid exceeding BIO_MAX_VECS vectors per BIO. But
3730 * without respecting this limit, crypt_alloc_buffer() will trigger a
3731 * BUG(). Avoid this by forcing DM core to split write BIOs to this
3732 * limit.
3733 */
3734 if (ti->emulate_zone_append)
3735 limits->max_hw_sectors = min(limits->max_hw_sectors,
3736 BIO_MAX_VECS << PAGE_SECTORS_SHIFT);
3737
3738 limits->atomic_write_hw_unit_max = min(limits->atomic_write_hw_unit_max,
3739 BIO_MAX_VECS << PAGE_SHIFT);
3740 limits->atomic_write_hw_max = min(limits->atomic_write_hw_max,
3741 BIO_MAX_VECS << PAGE_SHIFT);
3742 }
3743
3744 static struct target_type crypt_target = {
3745 .name = "crypt",
3746 .version = {1, 29, 0},
3747 .module = THIS_MODULE,
3748 .ctr = crypt_ctr,
3749 .dtr = crypt_dtr,
3750 .features = DM_TARGET_ZONED_HM | DM_TARGET_ATOMIC_WRITES,
3751 .report_zones = crypt_report_zones,
3752 .map = crypt_map,
3753 .status = crypt_status,
3754 .postsuspend = crypt_postsuspend,
3755 .preresume = crypt_preresume,
3756 .resume = crypt_resume,
3757 .message = crypt_message,
3758 .iterate_devices = crypt_iterate_devices,
3759 .io_hints = crypt_io_hints,
3760 };
3761 module_dm(crypt);
3762
3763 MODULE_AUTHOR("Jana Saout <jana@saout.de>");
3764 MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
3765 MODULE_LICENSE("GPL");
3766