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