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