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 = kcalloc(cc->tfms_count,
2338 sizeof(struct crypto_skcipher *),
2339 GFP_KERNEL);
2340 if (!cc->cipher_tfm.tfms)
2341 return -ENOMEM;
2342
2343 for (i = 0; i < cc->tfms_count; i++) {
2344 cc->cipher_tfm.tfms[i] = crypto_alloc_skcipher(ciphermode, 0,
2345 CRYPTO_ALG_ALLOCATES_MEMORY);
2346 if (IS_ERR(cc->cipher_tfm.tfms[i])) {
2347 err = PTR_ERR(cc->cipher_tfm.tfms[i]);
2348 crypt_free_tfms(cc);
2349 return err;
2350 }
2351 }
2352
2353 /*
2354 * dm-crypt performance can vary greatly depending on which crypto
2355 * algorithm implementation is used. Help people debug performance
2356 * problems by logging the ->cra_driver_name.
2357 */
2358 DMDEBUG_LIMIT("%s using implementation \"%s\"", ciphermode,
2359 crypto_skcipher_alg(any_tfm(cc))->base.cra_driver_name);
2360 return 0;
2361 }
2362
crypt_alloc_tfms_aead(struct crypt_config * cc,char * ciphermode)2363 static int crypt_alloc_tfms_aead(struct crypt_config *cc, char *ciphermode)
2364 {
2365 int err;
2366
2367 cc->cipher_tfm.tfms = kmalloc(sizeof(struct crypto_skcipher *), GFP_KERNEL);
2368 if (!cc->cipher_tfm.tfms)
2369 return -ENOMEM;
2370
2371 cc->cipher_tfm.tfms_aead[0] = crypto_alloc_aead(ciphermode, 0,
2372 CRYPTO_ALG_ALLOCATES_MEMORY);
2373 if (IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
2374 err = PTR_ERR(cc->cipher_tfm.tfms_aead[0]);
2375 crypt_free_tfms(cc);
2376 return err;
2377 }
2378
2379 DMDEBUG_LIMIT("%s using implementation \"%s\"", ciphermode,
2380 crypto_aead_alg(any_tfm_aead(cc))->base.cra_driver_name);
2381 return 0;
2382 }
2383
crypt_alloc_tfms(struct crypt_config * cc,char * ciphermode)2384 static int crypt_alloc_tfms(struct crypt_config *cc, char *ciphermode)
2385 {
2386 if (crypt_integrity_aead(cc))
2387 return crypt_alloc_tfms_aead(cc, ciphermode);
2388 else
2389 return crypt_alloc_tfms_skcipher(cc, ciphermode);
2390 }
2391
crypt_subkey_size(struct crypt_config * cc)2392 static unsigned int crypt_subkey_size(struct crypt_config *cc)
2393 {
2394 return (cc->key_size - cc->key_extra_size) >> ilog2(cc->tfms_count);
2395 }
2396
crypt_authenckey_size(struct crypt_config * cc)2397 static unsigned int crypt_authenckey_size(struct crypt_config *cc)
2398 {
2399 return crypt_subkey_size(cc) + RTA_SPACE(sizeof(struct crypto_authenc_key_param));
2400 }
2401
2402 /*
2403 * If AEAD is composed like authenc(hmac(sha256),xts(aes)),
2404 * the key must be for some reason in special format.
2405 * This funcion converts cc->key to this special format.
2406 */
crypt_copy_authenckey(char * p,const void * key,unsigned int enckeylen,unsigned int authkeylen)2407 static void crypt_copy_authenckey(char *p, const void *key,
2408 unsigned int enckeylen, unsigned int authkeylen)
2409 {
2410 struct crypto_authenc_key_param *param;
2411 struct rtattr *rta;
2412
2413 rta = (struct rtattr *)p;
2414 param = RTA_DATA(rta);
2415 param->enckeylen = cpu_to_be32(enckeylen);
2416 rta->rta_len = RTA_LENGTH(sizeof(*param));
2417 rta->rta_type = CRYPTO_AUTHENC_KEYA_PARAM;
2418 p += RTA_SPACE(sizeof(*param));
2419 memcpy(p, key + enckeylen, authkeylen);
2420 p += authkeylen;
2421 memcpy(p, key, enckeylen);
2422 }
2423
crypt_setkey(struct crypt_config * cc)2424 static int crypt_setkey(struct crypt_config *cc)
2425 {
2426 unsigned int subkey_size;
2427 int err = 0, i, r;
2428
2429 /* Ignore extra keys (which are used for IV etc) */
2430 subkey_size = crypt_subkey_size(cc);
2431
2432 if (crypt_integrity_hmac(cc)) {
2433 if (subkey_size < cc->key_mac_size)
2434 return -EINVAL;
2435
2436 crypt_copy_authenckey(cc->authenc_key, cc->key,
2437 subkey_size - cc->key_mac_size,
2438 cc->key_mac_size);
2439 }
2440
2441 for (i = 0; i < cc->tfms_count; i++) {
2442 if (crypt_integrity_hmac(cc))
2443 r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
2444 cc->authenc_key, crypt_authenckey_size(cc));
2445 else if (crypt_integrity_aead(cc))
2446 r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
2447 cc->key + (i * subkey_size),
2448 subkey_size);
2449 else
2450 r = crypto_skcipher_setkey(cc->cipher_tfm.tfms[i],
2451 cc->key + (i * subkey_size),
2452 subkey_size);
2453 if (r)
2454 err = r;
2455 }
2456
2457 if (crypt_integrity_hmac(cc))
2458 memzero_explicit(cc->authenc_key, crypt_authenckey_size(cc));
2459
2460 return err;
2461 }
2462
2463 #ifdef CONFIG_KEYS
2464
contains_whitespace(const char * str)2465 static bool contains_whitespace(const char *str)
2466 {
2467 while (*str)
2468 if (isspace(*str++))
2469 return true;
2470 return false;
2471 }
2472
set_key_user(struct crypt_config * cc,struct key * key)2473 static int set_key_user(struct crypt_config *cc, struct key *key)
2474 {
2475 const struct user_key_payload *ukp;
2476
2477 ukp = user_key_payload_locked(key);
2478 if (!ukp)
2479 return -EKEYREVOKED;
2480
2481 if (cc->key_size != ukp->datalen)
2482 return -EINVAL;
2483
2484 memcpy(cc->key, ukp->data, cc->key_size);
2485
2486 return 0;
2487 }
2488
set_key_encrypted(struct crypt_config * cc,struct key * key)2489 static int set_key_encrypted(struct crypt_config *cc, struct key *key)
2490 {
2491 const struct encrypted_key_payload *ekp;
2492
2493 ekp = key->payload.data[0];
2494 if (!ekp)
2495 return -EKEYREVOKED;
2496
2497 if (cc->key_size != ekp->decrypted_datalen)
2498 return -EINVAL;
2499
2500 memcpy(cc->key, ekp->decrypted_data, cc->key_size);
2501
2502 return 0;
2503 }
2504
set_key_trusted(struct crypt_config * cc,struct key * key)2505 static int set_key_trusted(struct crypt_config *cc, struct key *key)
2506 {
2507 const struct trusted_key_payload *tkp;
2508
2509 tkp = key->payload.data[0];
2510 if (!tkp)
2511 return -EKEYREVOKED;
2512
2513 if (cc->key_size != tkp->key_len)
2514 return -EINVAL;
2515
2516 memcpy(cc->key, tkp->key, cc->key_size);
2517
2518 return 0;
2519 }
2520
crypt_set_keyring_key(struct crypt_config * cc,const char * key_string)2521 static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
2522 {
2523 char *new_key_string, *key_desc;
2524 int ret;
2525 struct key_type *type;
2526 struct key *key;
2527 int (*set_key)(struct crypt_config *cc, struct key *key);
2528
2529 /*
2530 * Reject key_string with whitespace. dm core currently lacks code for
2531 * proper whitespace escaping in arguments on DM_TABLE_STATUS path.
2532 */
2533 if (contains_whitespace(key_string)) {
2534 DMERR("whitespace chars not allowed in key string");
2535 return -EINVAL;
2536 }
2537
2538 /* look for next ':' separating key_type from key_description */
2539 key_desc = strchr(key_string, ':');
2540 if (!key_desc || key_desc == key_string || !strlen(key_desc + 1))
2541 return -EINVAL;
2542
2543 if (!strncmp(key_string, "logon:", key_desc - key_string + 1)) {
2544 type = &key_type_logon;
2545 set_key = set_key_user;
2546 } else if (!strncmp(key_string, "user:", key_desc - key_string + 1)) {
2547 type = &key_type_user;
2548 set_key = set_key_user;
2549 } else if (IS_ENABLED(CONFIG_ENCRYPTED_KEYS) &&
2550 !strncmp(key_string, "encrypted:", key_desc - key_string + 1)) {
2551 type = &key_type_encrypted;
2552 set_key = set_key_encrypted;
2553 } else if (IS_ENABLED(CONFIG_TRUSTED_KEYS) &&
2554 !strncmp(key_string, "trusted:", key_desc - key_string + 1)) {
2555 type = &key_type_trusted;
2556 set_key = set_key_trusted;
2557 } else {
2558 return -EINVAL;
2559 }
2560
2561 new_key_string = kstrdup(key_string, GFP_KERNEL);
2562 if (!new_key_string)
2563 return -ENOMEM;
2564
2565 key = request_key(type, key_desc + 1, NULL);
2566 if (IS_ERR(key)) {
2567 ret = PTR_ERR(key);
2568 goto free_new_key_string;
2569 }
2570
2571 down_read(&key->sem);
2572 ret = set_key(cc, key);
2573 up_read(&key->sem);
2574 key_put(key);
2575 if (ret < 0)
2576 goto free_new_key_string;
2577
2578 /* clear the flag since following operations may invalidate previously valid key */
2579 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2580
2581 ret = crypt_setkey(cc);
2582 if (ret)
2583 goto free_new_key_string;
2584
2585 set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2586 kfree_sensitive(cc->key_string);
2587 cc->key_string = new_key_string;
2588 return 0;
2589
2590 free_new_key_string:
2591 kfree_sensitive(new_key_string);
2592 return ret;
2593 }
2594
get_key_size(char ** key_string)2595 static int get_key_size(char **key_string)
2596 {
2597 char *colon, dummy;
2598 int ret;
2599
2600 if (*key_string[0] != ':')
2601 return strlen(*key_string) >> 1;
2602
2603 /* look for next ':' in key string */
2604 colon = strpbrk(*key_string + 1, ":");
2605 if (!colon)
2606 return -EINVAL;
2607
2608 if (sscanf(*key_string + 1, "%u%c", &ret, &dummy) != 2 || dummy != ':')
2609 return -EINVAL;
2610
2611 *key_string = colon;
2612
2613 /* remaining key string should be :<logon|user>:<key_desc> */
2614
2615 return ret;
2616 }
2617
2618 #else
2619
crypt_set_keyring_key(struct crypt_config * cc,const char * key_string)2620 static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
2621 {
2622 return -EINVAL;
2623 }
2624
get_key_size(char ** key_string)2625 static int get_key_size(char **key_string)
2626 {
2627 return (*key_string[0] == ':') ? -EINVAL : (int)(strlen(*key_string) >> 1);
2628 }
2629
2630 #endif /* CONFIG_KEYS */
2631
crypt_set_key(struct crypt_config * cc,char * key)2632 static int crypt_set_key(struct crypt_config *cc, char *key)
2633 {
2634 int r = -EINVAL;
2635 int key_string_len = strlen(key);
2636
2637 /* Hyphen (which gives a key_size of zero) means there is no key. */
2638 if (!cc->key_size && strcmp(key, "-"))
2639 goto out;
2640
2641 /* ':' means the key is in kernel keyring, short-circuit normal key processing */
2642 if (key[0] == ':') {
2643 r = crypt_set_keyring_key(cc, key + 1);
2644 goto out;
2645 }
2646
2647 /* clear the flag since following operations may invalidate previously valid key */
2648 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2649
2650 /* wipe references to any kernel keyring key */
2651 kfree_sensitive(cc->key_string);
2652 cc->key_string = NULL;
2653
2654 /* Decode key from its hex representation. */
2655 if (cc->key_size && hex2bin(cc->key, key, cc->key_size) < 0)
2656 goto out;
2657
2658 r = crypt_setkey(cc);
2659 if (!r)
2660 set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2661
2662 out:
2663 /* Hex key string not needed after here, so wipe it. */
2664 memset(key, '0', key_string_len);
2665
2666 return r;
2667 }
2668
crypt_wipe_key(struct crypt_config * cc)2669 static int crypt_wipe_key(struct crypt_config *cc)
2670 {
2671 int r;
2672
2673 clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
2674 get_random_bytes(&cc->key, cc->key_size);
2675
2676 /* Wipe IV private keys */
2677 if (cc->iv_gen_ops && cc->iv_gen_ops->wipe) {
2678 r = cc->iv_gen_ops->wipe(cc);
2679 if (r)
2680 return r;
2681 }
2682
2683 kfree_sensitive(cc->key_string);
2684 cc->key_string = NULL;
2685 r = crypt_setkey(cc);
2686 memset(&cc->key, 0, cc->key_size * sizeof(u8));
2687
2688 return r;
2689 }
2690
crypt_calculate_pages_per_client(void)2691 static void crypt_calculate_pages_per_client(void)
2692 {
2693 unsigned long pages = (totalram_pages() - totalhigh_pages()) * DM_CRYPT_MEMORY_PERCENT / 100;
2694
2695 if (!dm_crypt_clients_n)
2696 return;
2697
2698 pages /= dm_crypt_clients_n;
2699 if (pages < DM_CRYPT_MIN_PAGES_PER_CLIENT)
2700 pages = DM_CRYPT_MIN_PAGES_PER_CLIENT;
2701 dm_crypt_pages_per_client = pages;
2702 }
2703
crypt_page_alloc(gfp_t gfp_mask,void * pool_data)2704 static void *crypt_page_alloc(gfp_t gfp_mask, void *pool_data)
2705 {
2706 struct crypt_config *cc = pool_data;
2707 struct page *page;
2708
2709 /*
2710 * Note, percpu_counter_read_positive() may over (and under) estimate
2711 * the current usage by at most (batch - 1) * num_online_cpus() pages,
2712 * but avoids potential spinlock contention of an exact result.
2713 */
2714 if (unlikely(percpu_counter_read_positive(&cc->n_allocated_pages) >= dm_crypt_pages_per_client) &&
2715 likely(gfp_mask & __GFP_NORETRY))
2716 return NULL;
2717
2718 page = alloc_page(gfp_mask);
2719 if (likely(page != NULL))
2720 percpu_counter_add(&cc->n_allocated_pages, 1);
2721
2722 return page;
2723 }
2724
crypt_page_free(void * page,void * pool_data)2725 static void crypt_page_free(void *page, void *pool_data)
2726 {
2727 struct crypt_config *cc = pool_data;
2728
2729 __free_page(page);
2730 percpu_counter_sub(&cc->n_allocated_pages, 1);
2731 }
2732
crypt_dtr(struct dm_target * ti)2733 static void crypt_dtr(struct dm_target *ti)
2734 {
2735 struct crypt_config *cc = ti->private;
2736
2737 ti->private = NULL;
2738
2739 if (!cc)
2740 return;
2741
2742 if (cc->write_thread)
2743 kthread_stop(cc->write_thread);
2744
2745 if (cc->io_queue)
2746 destroy_workqueue(cc->io_queue);
2747 if (cc->crypt_queue)
2748 destroy_workqueue(cc->crypt_queue);
2749
2750 if (cc->workqueue_id)
2751 ida_free(&workqueue_ida, cc->workqueue_id);
2752
2753 crypt_free_tfms(cc);
2754
2755 bioset_exit(&cc->bs);
2756
2757 mempool_exit(&cc->page_pool);
2758 mempool_exit(&cc->req_pool);
2759 mempool_exit(&cc->tag_pool);
2760
2761 WARN_ON(percpu_counter_sum(&cc->n_allocated_pages) != 0);
2762 percpu_counter_destroy(&cc->n_allocated_pages);
2763
2764 if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
2765 cc->iv_gen_ops->dtr(cc);
2766
2767 if (cc->dev)
2768 dm_put_device(ti, cc->dev);
2769
2770 kfree_sensitive(cc->cipher_string);
2771 kfree_sensitive(cc->key_string);
2772 kfree_sensitive(cc->cipher_auth);
2773 kfree_sensitive(cc->authenc_key);
2774
2775 mutex_destroy(&cc->bio_alloc_lock);
2776
2777 /* Must zero key material before freeing */
2778 kfree_sensitive(cc);
2779
2780 spin_lock(&dm_crypt_clients_lock);
2781 WARN_ON(!dm_crypt_clients_n);
2782 dm_crypt_clients_n--;
2783 crypt_calculate_pages_per_client();
2784 spin_unlock(&dm_crypt_clients_lock);
2785
2786 dm_audit_log_dtr(DM_MSG_PREFIX, ti, 1);
2787 }
2788
crypt_ctr_ivmode(struct dm_target * ti,const char * ivmode)2789 static int crypt_ctr_ivmode(struct dm_target *ti, const char *ivmode)
2790 {
2791 struct crypt_config *cc = ti->private;
2792
2793 if (crypt_integrity_aead(cc))
2794 cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
2795 else
2796 cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
2797
2798 if (cc->iv_size)
2799 /* at least a 64 bit sector number should fit in our buffer */
2800 cc->iv_size = max(cc->iv_size,
2801 (unsigned int)(sizeof(u64) / sizeof(u8)));
2802 else if (ivmode) {
2803 DMWARN("Selected cipher does not support IVs");
2804 ivmode = NULL;
2805 }
2806
2807 /* Choose ivmode, see comments at iv code. */
2808 if (ivmode == NULL)
2809 cc->iv_gen_ops = NULL;
2810 else if (strcmp(ivmode, "plain") == 0)
2811 cc->iv_gen_ops = &crypt_iv_plain_ops;
2812 else if (strcmp(ivmode, "plain64") == 0)
2813 cc->iv_gen_ops = &crypt_iv_plain64_ops;
2814 else if (strcmp(ivmode, "plain64be") == 0)
2815 cc->iv_gen_ops = &crypt_iv_plain64be_ops;
2816 else if (strcmp(ivmode, "essiv") == 0)
2817 cc->iv_gen_ops = &crypt_iv_essiv_ops;
2818 else if (strcmp(ivmode, "benbi") == 0)
2819 cc->iv_gen_ops = &crypt_iv_benbi_ops;
2820 else if (strcmp(ivmode, "null") == 0)
2821 cc->iv_gen_ops = &crypt_iv_null_ops;
2822 else if (strcmp(ivmode, "eboiv") == 0)
2823 cc->iv_gen_ops = &crypt_iv_eboiv_ops;
2824 else if (strcmp(ivmode, "elephant") == 0) {
2825 cc->iv_gen_ops = &crypt_iv_elephant_ops;
2826 cc->key_parts = 2;
2827 cc->key_extra_size = cc->key_size / 2;
2828 if (cc->key_extra_size > ELEPHANT_MAX_KEY_SIZE)
2829 return -EINVAL;
2830 set_bit(CRYPT_ENCRYPT_PREPROCESS, &cc->cipher_flags);
2831 } else if (strcmp(ivmode, "lmk") == 0) {
2832 cc->iv_gen_ops = &crypt_iv_lmk_ops;
2833 /*
2834 * Version 2 and 3 is recognised according
2835 * to length of provided multi-key string.
2836 * If present (version 3), last key is used as IV seed.
2837 * All keys (including IV seed) are always the same size.
2838 */
2839 if (cc->key_size % cc->key_parts) {
2840 cc->key_parts++;
2841 cc->key_extra_size = cc->key_size / cc->key_parts;
2842 }
2843 } else if (strcmp(ivmode, "tcw") == 0) {
2844 cc->iv_gen_ops = &crypt_iv_tcw_ops;
2845 cc->key_parts += 2; /* IV + whitening */
2846 cc->key_extra_size = cc->iv_size + TCW_WHITENING_SIZE;
2847 } else if (strcmp(ivmode, "random") == 0) {
2848 cc->iv_gen_ops = &crypt_iv_random_ops;
2849 /* Need storage space in integrity fields. */
2850 cc->integrity_iv_size = cc->iv_size;
2851 } else {
2852 ti->error = "Invalid IV mode";
2853 return -EINVAL;
2854 }
2855
2856 return 0;
2857 }
2858
2859 /*
2860 * Workaround to parse HMAC algorithm from AEAD crypto API spec.
2861 * The HMAC is needed to calculate tag size (HMAC digest size).
2862 * This should be probably done by crypto-api calls (once available...)
2863 */
crypt_ctr_auth_cipher(struct crypt_config * cc,char * cipher_api)2864 static int crypt_ctr_auth_cipher(struct crypt_config *cc, char *cipher_api)
2865 {
2866 char *start, *end, *mac_alg = NULL;
2867 struct crypto_ahash *mac;
2868
2869 if (!strstarts(cipher_api, "authenc("))
2870 return 0;
2871
2872 start = strchr(cipher_api, '(');
2873 end = strchr(cipher_api, ',');
2874 if (!start || !end || ++start > end)
2875 return -EINVAL;
2876
2877 mac_alg = kmemdup_nul(start, end - start, GFP_KERNEL);
2878 if (!mac_alg)
2879 return -ENOMEM;
2880
2881 mac = crypto_alloc_ahash(mac_alg, 0, CRYPTO_ALG_ALLOCATES_MEMORY);
2882 kfree(mac_alg);
2883
2884 if (IS_ERR(mac))
2885 return PTR_ERR(mac);
2886
2887 if (!test_bit(CRYPT_KEY_MAC_SIZE_SET, &cc->cipher_flags))
2888 cc->key_mac_size = crypto_ahash_digestsize(mac);
2889 crypto_free_ahash(mac);
2890
2891 cc->authenc_key = kmalloc(crypt_authenckey_size(cc), GFP_KERNEL);
2892 if (!cc->authenc_key)
2893 return -ENOMEM;
2894
2895 return 0;
2896 }
2897
crypt_ctr_cipher_new(struct dm_target * ti,char * cipher_in,char * key,char ** ivmode,char ** ivopts)2898 static int crypt_ctr_cipher_new(struct dm_target *ti, char *cipher_in, char *key,
2899 char **ivmode, char **ivopts)
2900 {
2901 struct crypt_config *cc = ti->private;
2902 char *tmp, *cipher_api, buf[CRYPTO_MAX_ALG_NAME];
2903 int ret = -EINVAL;
2904
2905 cc->tfms_count = 1;
2906
2907 /*
2908 * New format (capi: prefix)
2909 * capi:cipher_api_spec-iv:ivopts
2910 */
2911 tmp = &cipher_in[strlen("capi:")];
2912
2913 /* Separate IV options if present, it can contain another '-' in hash name */
2914 *ivopts = strrchr(tmp, ':');
2915 if (*ivopts) {
2916 **ivopts = '\0';
2917 (*ivopts)++;
2918 }
2919 /* Parse IV mode */
2920 *ivmode = strrchr(tmp, '-');
2921 if (*ivmode) {
2922 **ivmode = '\0';
2923 (*ivmode)++;
2924 }
2925 /* The rest is crypto API spec */
2926 cipher_api = tmp;
2927
2928 /* Alloc AEAD, can be used only in new format. */
2929 if (crypt_integrity_aead(cc)) {
2930 ret = crypt_ctr_auth_cipher(cc, cipher_api);
2931 if (ret < 0) {
2932 ti->error = "Invalid AEAD cipher spec";
2933 return ret;
2934 }
2935 }
2936
2937 if (*ivmode && !strcmp(*ivmode, "lmk"))
2938 cc->tfms_count = 64;
2939
2940 if (*ivmode && !strcmp(*ivmode, "essiv")) {
2941 if (!*ivopts) {
2942 ti->error = "Digest algorithm missing for ESSIV mode";
2943 return -EINVAL;
2944 }
2945 ret = snprintf(buf, CRYPTO_MAX_ALG_NAME, "essiv(%s,%s)",
2946 cipher_api, *ivopts);
2947 if (ret < 0 || ret >= CRYPTO_MAX_ALG_NAME) {
2948 ti->error = "Cannot allocate cipher string";
2949 return -ENOMEM;
2950 }
2951 cipher_api = buf;
2952 }
2953
2954 cc->key_parts = cc->tfms_count;
2955
2956 /* Allocate cipher */
2957 ret = crypt_alloc_tfms(cc, cipher_api);
2958 if (ret < 0) {
2959 ti->error = "Error allocating crypto tfm";
2960 return ret;
2961 }
2962
2963 if (crypt_integrity_aead(cc))
2964 cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
2965 else
2966 cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
2967
2968 return 0;
2969 }
2970
crypt_ctr_cipher_old(struct dm_target * ti,char * cipher_in,char * key,char ** ivmode,char ** ivopts)2971 static int crypt_ctr_cipher_old(struct dm_target *ti, char *cipher_in, char *key,
2972 char **ivmode, char **ivopts)
2973 {
2974 struct crypt_config *cc = ti->private;
2975 char *tmp, *cipher, *chainmode, *keycount;
2976 char *cipher_api = NULL;
2977 int ret = -EINVAL;
2978 char dummy;
2979
2980 if (strchr(cipher_in, '(') || crypt_integrity_aead(cc)) {
2981 ti->error = "Bad cipher specification";
2982 return -EINVAL;
2983 }
2984
2985 /*
2986 * Legacy dm-crypt cipher specification
2987 * cipher[:keycount]-mode-iv:ivopts
2988 */
2989 tmp = cipher_in;
2990 keycount = strsep(&tmp, "-");
2991 cipher = strsep(&keycount, ":");
2992
2993 if (!keycount)
2994 cc->tfms_count = 1;
2995 else if (sscanf(keycount, "%u%c", &cc->tfms_count, &dummy) != 1 ||
2996 !is_power_of_2(cc->tfms_count)) {
2997 ti->error = "Bad cipher key count specification";
2998 return -EINVAL;
2999 }
3000 cc->key_parts = cc->tfms_count;
3001
3002 chainmode = strsep(&tmp, "-");
3003 *ivmode = strsep(&tmp, ":");
3004 *ivopts = tmp;
3005
3006 /*
3007 * For compatibility with the original dm-crypt mapping format, if
3008 * only the cipher name is supplied, use cbc-plain.
3009 */
3010 if (!chainmode || (!strcmp(chainmode, "plain") && !*ivmode)) {
3011 chainmode = "cbc";
3012 *ivmode = "plain";
3013 }
3014
3015 if (strcmp(chainmode, "ecb") && !*ivmode) {
3016 ti->error = "IV mechanism required";
3017 return -EINVAL;
3018 }
3019
3020 cipher_api = kmalloc(CRYPTO_MAX_ALG_NAME, GFP_KERNEL);
3021 if (!cipher_api)
3022 goto bad_mem;
3023
3024 if (*ivmode && !strcmp(*ivmode, "essiv")) {
3025 if (!*ivopts) {
3026 ti->error = "Digest algorithm missing for ESSIV mode";
3027 kfree(cipher_api);
3028 return -EINVAL;
3029 }
3030 ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
3031 "essiv(%s(%s),%s)", chainmode, cipher, *ivopts);
3032 } else {
3033 ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
3034 "%s(%s)", chainmode, cipher);
3035 }
3036 if (ret < 0 || ret >= CRYPTO_MAX_ALG_NAME) {
3037 kfree(cipher_api);
3038 goto bad_mem;
3039 }
3040
3041 /* Allocate cipher */
3042 ret = crypt_alloc_tfms(cc, cipher_api);
3043 if (ret < 0) {
3044 ti->error = "Error allocating crypto tfm";
3045 kfree(cipher_api);
3046 return ret;
3047 }
3048 kfree(cipher_api);
3049
3050 return 0;
3051 bad_mem:
3052 ti->error = "Cannot allocate cipher strings";
3053 return -ENOMEM;
3054 }
3055
crypt_ctr_cipher(struct dm_target * ti,char * cipher_in,char * key)3056 static int crypt_ctr_cipher(struct dm_target *ti, char *cipher_in, char *key)
3057 {
3058 struct crypt_config *cc = ti->private;
3059 char *ivmode = NULL, *ivopts = NULL;
3060 int ret;
3061
3062 cc->cipher_string = kstrdup(cipher_in, GFP_KERNEL);
3063 if (!cc->cipher_string) {
3064 ti->error = "Cannot allocate cipher strings";
3065 return -ENOMEM;
3066 }
3067
3068 if (strstarts(cipher_in, "capi:"))
3069 ret = crypt_ctr_cipher_new(ti, cipher_in, key, &ivmode, &ivopts);
3070 else
3071 ret = crypt_ctr_cipher_old(ti, cipher_in, key, &ivmode, &ivopts);
3072 if (ret)
3073 return ret;
3074
3075 /* Initialize IV */
3076 ret = crypt_ctr_ivmode(ti, ivmode);
3077 if (ret < 0)
3078 return ret;
3079
3080 /* Initialize and set key */
3081 ret = crypt_set_key(cc, key);
3082 if (ret < 0) {
3083 ti->error = "Error decoding and setting key";
3084 return ret;
3085 }
3086
3087 /* Allocate IV */
3088 if (cc->iv_gen_ops && cc->iv_gen_ops->ctr) {
3089 ret = cc->iv_gen_ops->ctr(cc, ti, ivopts);
3090 if (ret < 0) {
3091 ti->error = "Error creating IV";
3092 return ret;
3093 }
3094 }
3095
3096 /* Initialize IV (set keys for ESSIV etc) */
3097 if (cc->iv_gen_ops && cc->iv_gen_ops->init) {
3098 ret = cc->iv_gen_ops->init(cc);
3099 if (ret < 0) {
3100 ti->error = "Error initialising IV";
3101 return ret;
3102 }
3103 }
3104
3105 /* wipe the kernel key payload copy */
3106 if (cc->key_string)
3107 memset(cc->key, 0, cc->key_size * sizeof(u8));
3108
3109 return ret;
3110 }
3111
crypt_ctr_optional(struct dm_target * ti,unsigned int argc,char ** argv)3112 static int crypt_ctr_optional(struct dm_target *ti, unsigned int argc, char **argv)
3113 {
3114 struct crypt_config *cc = ti->private;
3115 struct dm_arg_set as;
3116 static const struct dm_arg _args[] = {
3117 {0, 9, "Invalid number of feature args"},
3118 };
3119 unsigned int opt_params, val;
3120 const char *opt_string, *sval;
3121 char dummy;
3122 int ret;
3123
3124 /* Optional parameters */
3125 as.argc = argc;
3126 as.argv = argv;
3127
3128 ret = dm_read_arg_group(_args, &as, &opt_params, &ti->error);
3129 if (ret)
3130 return ret;
3131
3132 while (opt_params--) {
3133 opt_string = dm_shift_arg(&as);
3134 if (!opt_string) {
3135 ti->error = "Not enough feature arguments";
3136 return -EINVAL;
3137 }
3138
3139 if (!strcasecmp(opt_string, "allow_discards"))
3140 ti->num_discard_bios = 1;
3141
3142 else if (!strcasecmp(opt_string, "same_cpu_crypt"))
3143 set_bit(DM_CRYPT_SAME_CPU, &cc->flags);
3144 else if (!strcasecmp(opt_string, "high_priority"))
3145 set_bit(DM_CRYPT_HIGH_PRIORITY, &cc->flags);
3146
3147 else if (!strcasecmp(opt_string, "submit_from_crypt_cpus"))
3148 set_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
3149 else if (!strcasecmp(opt_string, "no_read_workqueue"))
3150 set_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags);
3151 else if (!strcasecmp(opt_string, "no_write_workqueue"))
3152 set_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags);
3153 else if (sscanf(opt_string, "integrity:%u:", &val) == 1) {
3154 if (val == 0 || val > MAX_TAG_SIZE) {
3155 ti->error = "Invalid integrity arguments";
3156 return -EINVAL;
3157 }
3158 cc->used_tag_size = val;
3159 sval = strchr(opt_string + strlen("integrity:"), ':') + 1;
3160 if (!strcasecmp(sval, "aead")) {
3161 set_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
3162 } else if (strcasecmp(sval, "none")) {
3163 ti->error = "Unknown integrity profile";
3164 return -EINVAL;
3165 }
3166
3167 cc->cipher_auth = kstrdup(sval, GFP_KERNEL);
3168 if (!cc->cipher_auth)
3169 return -ENOMEM;
3170 } else if (sscanf(opt_string, "integrity_key_size:%u%c", &val, &dummy) == 1) {
3171 if (!val) {
3172 ti->error = "Invalid integrity_key_size argument";
3173 return -EINVAL;
3174 }
3175 cc->key_mac_size = val;
3176 set_bit(CRYPT_KEY_MAC_SIZE_SET, &cc->cipher_flags);
3177 } else if (sscanf(opt_string, "sector_size:%hu%c", &cc->sector_size, &dummy) == 1) {
3178 if (cc->sector_size < (1 << SECTOR_SHIFT) ||
3179 cc->sector_size > 4096 ||
3180 (cc->sector_size & (cc->sector_size - 1))) {
3181 ti->error = "Invalid feature value for sector_size";
3182 return -EINVAL;
3183 }
3184 if (ti->len & ((cc->sector_size >> SECTOR_SHIFT) - 1)) {
3185 ti->error = "Device size is not multiple of sector_size feature";
3186 return -EINVAL;
3187 }
3188 cc->sector_shift = __ffs(cc->sector_size) - SECTOR_SHIFT;
3189 } else if (!strcasecmp(opt_string, "iv_large_sectors"))
3190 set_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
3191 else {
3192 ti->error = "Invalid feature arguments";
3193 return -EINVAL;
3194 }
3195 }
3196
3197 return 0;
3198 }
3199
3200 #ifdef CONFIG_BLK_DEV_ZONED
crypt_report_zones(struct dm_target * ti,struct dm_report_zones_args * args,unsigned int nr_zones)3201 static int crypt_report_zones(struct dm_target *ti,
3202 struct dm_report_zones_args *args, unsigned int nr_zones)
3203 {
3204 struct crypt_config *cc = ti->private;
3205
3206 return dm_report_zones(cc->dev->bdev, cc->start,
3207 cc->start + dm_target_offset(ti, args->next_sector),
3208 args, nr_zones);
3209 }
3210 #else
3211 #define crypt_report_zones NULL
3212 #endif
3213
3214 /*
3215 * Construct an encryption mapping:
3216 * <cipher> [<key>|:<key_size>:<user|logon>:<key_description>] <iv_offset> <dev_path> <start>
3217 */
crypt_ctr(struct dm_target * ti,unsigned int argc,char ** argv)3218 static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
3219 {
3220 struct crypt_config *cc;
3221 const char *devname = dm_table_device_name(ti->table);
3222 int key_size, wq_id;
3223 unsigned int align_mask;
3224 unsigned int common_wq_flags;
3225 unsigned long long tmpll;
3226 int ret;
3227 size_t iv_size_padding, additional_req_size;
3228 char dummy;
3229
3230 if (argc < 5) {
3231 ti->error = "Not enough arguments";
3232 return -EINVAL;
3233 }
3234
3235 key_size = get_key_size(&argv[1]);
3236 if (key_size < 0) {
3237 ti->error = "Cannot parse key size";
3238 return -EINVAL;
3239 }
3240
3241 cc = kzalloc(struct_size(cc, key, key_size), GFP_KERNEL);
3242 if (!cc) {
3243 ti->error = "Cannot allocate encryption context";
3244 return -ENOMEM;
3245 }
3246 cc->key_size = key_size;
3247 cc->sector_size = (1 << SECTOR_SHIFT);
3248 cc->sector_shift = 0;
3249
3250 ti->private = cc;
3251
3252 spin_lock(&dm_crypt_clients_lock);
3253 dm_crypt_clients_n++;
3254 crypt_calculate_pages_per_client();
3255 spin_unlock(&dm_crypt_clients_lock);
3256
3257 ret = percpu_counter_init(&cc->n_allocated_pages, 0, GFP_KERNEL);
3258 if (ret < 0)
3259 goto bad;
3260
3261 /* Optional parameters need to be read before cipher constructor */
3262 if (argc > 5) {
3263 ret = crypt_ctr_optional(ti, argc - 5, &argv[5]);
3264 if (ret)
3265 goto bad;
3266 }
3267
3268 ret = crypt_ctr_cipher(ti, argv[0], argv[1]);
3269 if (ret < 0)
3270 goto bad;
3271
3272 if (crypt_integrity_aead(cc)) {
3273 cc->dmreq_start = sizeof(struct aead_request);
3274 cc->dmreq_start += crypto_aead_reqsize(any_tfm_aead(cc));
3275 align_mask = crypto_aead_alignmask(any_tfm_aead(cc));
3276 } else {
3277 cc->dmreq_start = sizeof(struct skcipher_request);
3278 cc->dmreq_start += crypto_skcipher_reqsize(any_tfm(cc));
3279 align_mask = crypto_skcipher_alignmask(any_tfm(cc));
3280 }
3281 cc->dmreq_start = ALIGN(cc->dmreq_start, __alignof__(struct dm_crypt_request));
3282
3283 if (align_mask < CRYPTO_MINALIGN) {
3284 /* Allocate the padding exactly */
3285 iv_size_padding = -(cc->dmreq_start + sizeof(struct dm_crypt_request))
3286 & align_mask;
3287 } else {
3288 /*
3289 * If the cipher requires greater alignment than kmalloc
3290 * alignment, we don't know the exact position of the
3291 * initialization vector. We must assume worst case.
3292 */
3293 iv_size_padding = align_mask;
3294 }
3295
3296 /* ...| IV + padding | original IV | original sec. number | bio tag offset | */
3297 additional_req_size = sizeof(struct dm_crypt_request) +
3298 iv_size_padding + cc->iv_size +
3299 cc->iv_size +
3300 sizeof(uint64_t) +
3301 sizeof(unsigned int);
3302
3303 ret = mempool_init_kmalloc_pool(&cc->req_pool, MIN_IOS, cc->dmreq_start + additional_req_size);
3304 if (ret) {
3305 ti->error = "Cannot allocate crypt request mempool";
3306 goto bad;
3307 }
3308
3309 cc->per_bio_data_size = ti->per_io_data_size =
3310 ALIGN(sizeof(struct dm_crypt_io) + cc->dmreq_start + additional_req_size,
3311 ARCH_DMA_MINALIGN);
3312
3313 ret = mempool_init(&cc->page_pool, BIO_MAX_VECS, crypt_page_alloc, crypt_page_free, cc);
3314 if (ret) {
3315 ti->error = "Cannot allocate page mempool";
3316 goto bad;
3317 }
3318
3319 ret = bioset_init(&cc->bs, MIN_IOS, 0, BIOSET_NEED_BVECS);
3320 if (ret) {
3321 ti->error = "Cannot allocate crypt bioset";
3322 goto bad;
3323 }
3324
3325 mutex_init(&cc->bio_alloc_lock);
3326
3327 ret = -EINVAL;
3328 if ((sscanf(argv[2], "%llu%c", &tmpll, &dummy) != 1) ||
3329 (tmpll & ((cc->sector_size >> SECTOR_SHIFT) - 1))) {
3330 ti->error = "Invalid iv_offset sector";
3331 goto bad;
3332 }
3333 cc->iv_offset = tmpll;
3334
3335 ret = dm_get_device(ti, argv[3], dm_table_get_mode(ti->table), &cc->dev);
3336 if (ret) {
3337 ti->error = "Device lookup failed";
3338 goto bad;
3339 }
3340
3341 ret = -EINVAL;
3342 if (sscanf(argv[4], "%llu%c", &tmpll, &dummy) != 1 || tmpll != (sector_t)tmpll) {
3343 ti->error = "Invalid device sector";
3344 goto bad;
3345 }
3346 cc->start = tmpll;
3347
3348 if (bdev_is_zoned(cc->dev->bdev)) {
3349 /*
3350 * For zoned block devices, we need to preserve the issuer write
3351 * ordering. To do so, disable write workqueues and force inline
3352 * encryption completion.
3353 */
3354 set_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags);
3355 set_bit(DM_CRYPT_WRITE_INLINE, &cc->flags);
3356
3357 /*
3358 * All zone append writes to a zone of a zoned block device will
3359 * have the same BIO sector, the start of the zone. When the
3360 * cypher IV mode uses sector values, all data targeting a
3361 * zone will be encrypted using the first sector numbers of the
3362 * zone. This will not result in write errors but will
3363 * cause most reads to fail as reads will use the sector values
3364 * for the actual data locations, resulting in IV mismatch.
3365 * To avoid this problem, ask DM core to emulate zone append
3366 * operations with regular writes.
3367 */
3368 DMDEBUG("Zone append operations will be emulated");
3369 ti->emulate_zone_append = true;
3370 }
3371
3372 if (crypt_integrity_aead(cc) || cc->integrity_iv_size) {
3373 ret = crypt_integrity_ctr(cc, ti);
3374 if (ret)
3375 goto bad;
3376
3377 cc->tag_pool_max_sectors = POOL_ENTRY_SIZE / cc->tuple_size;
3378 if (!cc->tag_pool_max_sectors)
3379 cc->tag_pool_max_sectors = 1;
3380
3381 ret = mempool_init_kmalloc_pool(&cc->tag_pool, MIN_IOS,
3382 cc->tag_pool_max_sectors * cc->tuple_size);
3383 if (ret) {
3384 ti->error = "Cannot allocate integrity tags mempool";
3385 goto bad;
3386 }
3387
3388 cc->tag_pool_max_sectors <<= cc->sector_shift;
3389 }
3390
3391 wq_id = ida_alloc_min(&workqueue_ida, 1, GFP_KERNEL);
3392 if (wq_id < 0) {
3393 ti->error = "Couldn't get workqueue id";
3394 ret = wq_id;
3395 goto bad;
3396 }
3397 cc->workqueue_id = wq_id;
3398
3399 ret = -ENOMEM;
3400 common_wq_flags = WQ_MEM_RECLAIM | WQ_SYSFS;
3401 if (test_bit(DM_CRYPT_HIGH_PRIORITY, &cc->flags))
3402 common_wq_flags |= WQ_HIGHPRI;
3403
3404 cc->io_queue = alloc_workqueue("kcryptd_io-%s-%d",
3405 common_wq_flags | WQ_PERCPU, 1,
3406 devname, wq_id);
3407 if (!cc->io_queue) {
3408 ti->error = "Couldn't create kcryptd io queue";
3409 goto bad;
3410 }
3411
3412 if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags)) {
3413 cc->crypt_queue = alloc_workqueue("kcryptd-%s-%d",
3414 common_wq_flags | WQ_CPU_INTENSIVE | WQ_PERCPU,
3415 1, devname, wq_id);
3416 } else {
3417 /*
3418 * While crypt_queue is certainly CPU intensive, the use of
3419 * WQ_CPU_INTENSIVE is meaningless with WQ_UNBOUND.
3420 */
3421 cc->crypt_queue = alloc_workqueue("kcryptd-%s-%d",
3422 common_wq_flags | WQ_UNBOUND,
3423 num_online_cpus(), devname, wq_id);
3424 }
3425 if (!cc->crypt_queue) {
3426 ti->error = "Couldn't create kcryptd queue";
3427 goto bad;
3428 }
3429
3430 spin_lock_init(&cc->write_thread_lock);
3431 cc->write_tree = RB_ROOT;
3432
3433 cc->write_thread = kthread_run(dmcrypt_write, cc, "dmcrypt_write/%s", devname);
3434 if (IS_ERR(cc->write_thread)) {
3435 ret = PTR_ERR(cc->write_thread);
3436 cc->write_thread = NULL;
3437 ti->error = "Couldn't spawn write thread";
3438 goto bad;
3439 }
3440 if (test_bit(DM_CRYPT_HIGH_PRIORITY, &cc->flags))
3441 set_user_nice(cc->write_thread, MIN_NICE);
3442
3443 ti->num_flush_bios = 1;
3444 ti->limit_swap_bios = true;
3445 ti->accounts_remapped_io = true;
3446
3447 dm_audit_log_ctr(DM_MSG_PREFIX, ti, 1);
3448 return 0;
3449
3450 bad:
3451 dm_audit_log_ctr(DM_MSG_PREFIX, ti, 0);
3452 crypt_dtr(ti);
3453 return ret;
3454 }
3455
crypt_map(struct dm_target * ti,struct bio * bio)3456 static int crypt_map(struct dm_target *ti, struct bio *bio)
3457 {
3458 struct dm_crypt_io *io;
3459 struct crypt_config *cc = ti->private;
3460 unsigned max_sectors;
3461 bool no_split;
3462
3463 /*
3464 * If bio is REQ_PREFLUSH or REQ_OP_DISCARD, just bypass crypt queues.
3465 * - for REQ_PREFLUSH device-mapper core ensures that no IO is in-flight
3466 * - for REQ_OP_DISCARD caller must use flush if IO ordering matters
3467 */
3468 if (unlikely(bio->bi_opf & REQ_PREFLUSH ||
3469 bio_op(bio) == REQ_OP_DISCARD)) {
3470 bio_set_dev(bio, cc->dev->bdev);
3471 if (bio_sectors(bio))
3472 bio->bi_iter.bi_sector = cc->start +
3473 dm_target_offset(ti, bio->bi_iter.bi_sector);
3474 return DM_MAPIO_REMAPPED;
3475 }
3476
3477 /*
3478 * Check if bio is too large, split as needed.
3479 *
3480 * For zoned devices, splitting write operations creates the
3481 * risk of deadlocking queue freeze operations with zone write
3482 * plugging BIO work when the reminder of a split BIO is
3483 * issued. So always allow the entire BIO to proceed.
3484 */
3485 no_split = (ti->emulate_zone_append && op_is_write(bio_op(bio))) ||
3486 (bio->bi_opf & REQ_ATOMIC);
3487 max_sectors = get_max_request_sectors(ti, bio, no_split);
3488 if (unlikely(bio_sectors(bio) > max_sectors)) {
3489 if (unlikely(no_split))
3490 return DM_MAPIO_KILL;
3491 dm_accept_partial_bio(bio, max_sectors);
3492 }
3493
3494 /*
3495 * Ensure that bio is a multiple of internal sector encryption size
3496 * and is aligned to this size as defined in IO hints.
3497 */
3498 if (unlikely((bio->bi_iter.bi_sector & ((cc->sector_size >> SECTOR_SHIFT) - 1)) != 0))
3499 return DM_MAPIO_KILL;
3500
3501 if (unlikely(bio->bi_iter.bi_size & (cc->sector_size - 1)))
3502 return DM_MAPIO_KILL;
3503
3504 io = dm_per_bio_data(bio, cc->per_bio_data_size);
3505 crypt_io_init(io, cc, bio, dm_target_offset(ti, bio->bi_iter.bi_sector));
3506
3507 if (cc->tuple_size) {
3508 unsigned int tag_len = cc->tuple_size * (bio_sectors(bio) >> cc->sector_shift);
3509
3510 if (unlikely(tag_len > KMALLOC_MAX_SIZE))
3511 io->integrity_metadata = NULL;
3512 else
3513 io->integrity_metadata = kmalloc(tag_len, GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN);
3514
3515 if (unlikely(!io->integrity_metadata)) {
3516 if (bio_sectors(bio) > cc->tag_pool_max_sectors)
3517 dm_accept_partial_bio(bio, cc->tag_pool_max_sectors);
3518 io->integrity_metadata = mempool_alloc(&cc->tag_pool, GFP_NOIO);
3519 io->integrity_metadata_from_pool = true;
3520 }
3521 }
3522
3523 if (crypt_integrity_aead(cc))
3524 io->ctx.r.req_aead = (struct aead_request *)(io + 1);
3525 else
3526 io->ctx.r.req = (struct skcipher_request *)(io + 1);
3527
3528 if (bio_data_dir(io->base_bio) == READ) {
3529 if (kcryptd_io_read(io, CRYPT_MAP_READ_GFP))
3530 kcryptd_queue_read(io);
3531 } else
3532 kcryptd_queue_crypt(io);
3533
3534 return DM_MAPIO_SUBMITTED;
3535 }
3536
hex2asc(unsigned char c)3537 static char hex2asc(unsigned char c)
3538 {
3539 return c + '0' + ((unsigned int)(9 - c) >> 4 & 0x27);
3540 }
3541
crypt_status(struct dm_target * ti,status_type_t type,unsigned int status_flags,char * result,unsigned int maxlen)3542 static void crypt_status(struct dm_target *ti, status_type_t type,
3543 unsigned int status_flags, char *result, unsigned int maxlen)
3544 {
3545 struct crypt_config *cc = ti->private;
3546 unsigned int i, sz = 0;
3547 int num_feature_args = 0;
3548
3549 switch (type) {
3550 case STATUSTYPE_INFO:
3551 result[0] = '\0';
3552 break;
3553
3554 case STATUSTYPE_TABLE:
3555 DMEMIT("%s ", cc->cipher_string);
3556
3557 if (cc->key_size > 0) {
3558 if (cc->key_string)
3559 DMEMIT(":%u:%s", cc->key_size, cc->key_string);
3560 else {
3561 for (i = 0; i < cc->key_size; i++) {
3562 DMEMIT("%c%c", hex2asc(cc->key[i] >> 4),
3563 hex2asc(cc->key[i] & 0xf));
3564 }
3565 }
3566 } else
3567 DMEMIT("-");
3568
3569 DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
3570 cc->dev->name, (unsigned long long)cc->start);
3571
3572 num_feature_args += !!ti->num_discard_bios;
3573 num_feature_args += test_bit(DM_CRYPT_SAME_CPU, &cc->flags);
3574 num_feature_args += test_bit(DM_CRYPT_HIGH_PRIORITY, &cc->flags);
3575 num_feature_args += test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
3576 num_feature_args += test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags);
3577 num_feature_args += test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags);
3578 num_feature_args += !!cc->used_tag_size;
3579 num_feature_args += cc->sector_size != (1 << SECTOR_SHIFT);
3580 num_feature_args += test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
3581 num_feature_args += test_bit(CRYPT_KEY_MAC_SIZE_SET, &cc->cipher_flags);
3582 if (num_feature_args) {
3583 DMEMIT(" %d", num_feature_args);
3584 if (ti->num_discard_bios)
3585 DMEMIT(" allow_discards");
3586 if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
3587 DMEMIT(" same_cpu_crypt");
3588 if (test_bit(DM_CRYPT_HIGH_PRIORITY, &cc->flags))
3589 DMEMIT(" high_priority");
3590 if (test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags))
3591 DMEMIT(" submit_from_crypt_cpus");
3592 if (test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags))
3593 DMEMIT(" no_read_workqueue");
3594 if (test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags))
3595 DMEMIT(" no_write_workqueue");
3596 if (cc->used_tag_size)
3597 DMEMIT(" integrity:%u:%s", cc->used_tag_size, cc->cipher_auth);
3598 if (cc->sector_size != (1 << SECTOR_SHIFT))
3599 DMEMIT(" sector_size:%d", cc->sector_size);
3600 if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
3601 DMEMIT(" iv_large_sectors");
3602 if (test_bit(CRYPT_KEY_MAC_SIZE_SET, &cc->cipher_flags))
3603 DMEMIT(" integrity_key_size:%u", cc->key_mac_size);
3604 }
3605 break;
3606
3607 case STATUSTYPE_IMA:
3608 DMEMIT_TARGET_NAME_VERSION(ti->type);
3609 DMEMIT(",allow_discards=%c", ti->num_discard_bios ? 'y' : 'n');
3610 DMEMIT(",same_cpu_crypt=%c", test_bit(DM_CRYPT_SAME_CPU, &cc->flags) ? 'y' : 'n');
3611 DMEMIT(",high_priority=%c", test_bit(DM_CRYPT_HIGH_PRIORITY, &cc->flags) ? 'y' : 'n');
3612 DMEMIT(",submit_from_crypt_cpus=%c", test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags) ?
3613 'y' : 'n');
3614 DMEMIT(",no_read_workqueue=%c", test_bit(DM_CRYPT_NO_READ_WORKQUEUE, &cc->flags) ?
3615 'y' : 'n');
3616 DMEMIT(",no_write_workqueue=%c", test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags) ?
3617 'y' : 'n');
3618 DMEMIT(",iv_large_sectors=%c", test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags) ?
3619 'y' : 'n');
3620
3621 if (cc->used_tag_size)
3622 DMEMIT(",integrity_tag_size=%u,cipher_auth=%s",
3623 cc->used_tag_size, cc->cipher_auth);
3624 if (cc->sector_size != (1 << SECTOR_SHIFT))
3625 DMEMIT(",sector_size=%d", cc->sector_size);
3626 if (cc->cipher_string)
3627 DMEMIT(",cipher_string=%s", cc->cipher_string);
3628
3629 DMEMIT(",key_size=%u", cc->key_size);
3630 DMEMIT(",key_parts=%u", cc->key_parts);
3631 DMEMIT(",key_extra_size=%u", cc->key_extra_size);
3632 DMEMIT(",key_mac_size=%u", cc->key_mac_size);
3633 DMEMIT(";");
3634 break;
3635 }
3636 }
3637
crypt_postsuspend(struct dm_target * ti)3638 static void crypt_postsuspend(struct dm_target *ti)
3639 {
3640 struct crypt_config *cc = ti->private;
3641
3642 set_bit(DM_CRYPT_SUSPENDED, &cc->flags);
3643 }
3644
crypt_preresume(struct dm_target * ti)3645 static int crypt_preresume(struct dm_target *ti)
3646 {
3647 struct crypt_config *cc = ti->private;
3648
3649 if (!test_bit(DM_CRYPT_KEY_VALID, &cc->flags)) {
3650 DMERR("aborting resume - crypt key is not set.");
3651 return -EAGAIN;
3652 }
3653
3654 return 0;
3655 }
3656
crypt_resume(struct dm_target * ti)3657 static void crypt_resume(struct dm_target *ti)
3658 {
3659 struct crypt_config *cc = ti->private;
3660
3661 clear_bit(DM_CRYPT_SUSPENDED, &cc->flags);
3662 }
3663
3664 /* Message interface
3665 * key set <key>
3666 * key wipe
3667 */
crypt_message(struct dm_target * ti,unsigned int argc,char ** argv,char * result,unsigned int maxlen)3668 static int crypt_message(struct dm_target *ti, unsigned int argc, char **argv,
3669 char *result, unsigned int maxlen)
3670 {
3671 struct crypt_config *cc = ti->private;
3672 int key_size, ret = -EINVAL;
3673
3674 if (argc < 2)
3675 goto error;
3676
3677 if (!strcasecmp(argv[0], "key")) {
3678 if (!test_bit(DM_CRYPT_SUSPENDED, &cc->flags)) {
3679 DMWARN("not suspended during key manipulation.");
3680 return -EINVAL;
3681 }
3682 if (argc == 3 && !strcasecmp(argv[1], "set")) {
3683 /* The key size may not be changed. */
3684 key_size = get_key_size(&argv[2]);
3685 if (key_size < 0 || cc->key_size != key_size) {
3686 memset(argv[2], '0', strlen(argv[2]));
3687 return -EINVAL;
3688 }
3689
3690 ret = crypt_set_key(cc, argv[2]);
3691 if (ret)
3692 return ret;
3693 if (cc->iv_gen_ops && cc->iv_gen_ops->init)
3694 ret = cc->iv_gen_ops->init(cc);
3695 /* wipe the kernel key payload copy */
3696 if (cc->key_string)
3697 memset(cc->key, 0, cc->key_size * sizeof(u8));
3698 return ret;
3699 }
3700 if (argc == 2 && !strcasecmp(argv[1], "wipe"))
3701 return crypt_wipe_key(cc);
3702 }
3703
3704 error:
3705 DMWARN("unrecognised message received.");
3706 return -EINVAL;
3707 }
3708
crypt_iterate_devices(struct dm_target * ti,iterate_devices_callout_fn fn,void * data)3709 static int crypt_iterate_devices(struct dm_target *ti,
3710 iterate_devices_callout_fn fn, void *data)
3711 {
3712 struct crypt_config *cc = ti->private;
3713
3714 return fn(ti, cc->dev, cc->start, ti->len, data);
3715 }
3716
crypt_io_hints(struct dm_target * ti,struct queue_limits * limits)3717 static void crypt_io_hints(struct dm_target *ti, struct queue_limits *limits)
3718 {
3719 struct crypt_config *cc = ti->private;
3720
3721 limits->logical_block_size =
3722 max_t(unsigned int, limits->logical_block_size, cc->sector_size);
3723 limits->physical_block_size =
3724 max_t(unsigned int, limits->physical_block_size, cc->sector_size);
3725 limits->io_min = max_t(unsigned int, limits->io_min, cc->sector_size);
3726 limits->dma_alignment = limits->logical_block_size - 1;
3727
3728 /*
3729 * For zoned dm-crypt targets, there will be no internal splitting of
3730 * write BIOs to avoid exceeding BIO_MAX_VECS vectors per BIO. But
3731 * without respecting this limit, crypt_alloc_buffer() will trigger a
3732 * BUG(). Avoid this by forcing DM core to split write BIOs to this
3733 * limit.
3734 */
3735 if (ti->emulate_zone_append)
3736 limits->max_hw_sectors = min(limits->max_hw_sectors,
3737 BIO_MAX_VECS << PAGE_SECTORS_SHIFT);
3738
3739 limits->atomic_write_hw_unit_max = min(limits->atomic_write_hw_unit_max,
3740 BIO_MAX_VECS << PAGE_SHIFT);
3741 limits->atomic_write_hw_max = min(limits->atomic_write_hw_max,
3742 BIO_MAX_VECS << PAGE_SHIFT);
3743 }
3744
3745 static struct target_type crypt_target = {
3746 .name = "crypt",
3747 .version = {1, 29, 0},
3748 .module = THIS_MODULE,
3749 .ctr = crypt_ctr,
3750 .dtr = crypt_dtr,
3751 .features = DM_TARGET_ZONED_HM | DM_TARGET_ATOMIC_WRITES,
3752 .report_zones = crypt_report_zones,
3753 .map = crypt_map,
3754 .status = crypt_status,
3755 .postsuspend = crypt_postsuspend,
3756 .preresume = crypt_preresume,
3757 .resume = crypt_resume,
3758 .message = crypt_message,
3759 .iterate_devices = crypt_iterate_devices,
3760 .io_hints = crypt_io_hints,
3761 };
3762 module_dm(crypt);
3763
3764 MODULE_AUTHOR("Jana Saout <jana@saout.de>");
3765 MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
3766 MODULE_LICENSE("GPL");
3767