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