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