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