dm-crypt.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113
  1. /*
  2. * Copyright (C) 2003 Christophe Saout <christophe@saout.de>
  3. * Copyright (C) 2004 Clemens Fruhwirth <clemens@endorphin.org>
  4. * Copyright (C) 2006 Red Hat, Inc. All rights reserved.
  5. *
  6. * This file is released under the GPL.
  7. */
  8. #include <linux/err.h>
  9. #include <linux/module.h>
  10. #include <linux/init.h>
  11. #include <linux/kernel.h>
  12. #include <linux/bio.h>
  13. #include <linux/blkdev.h>
  14. #include <linux/mempool.h>
  15. #include <linux/slab.h>
  16. #include <linux/crypto.h>
  17. #include <linux/workqueue.h>
  18. #include <linux/backing-dev.h>
  19. #include <asm/atomic.h>
  20. #include <linux/scatterlist.h>
  21. #include <asm/page.h>
  22. #include <asm/unaligned.h>
  23. #include "dm.h"
  24. #define DM_MSG_PREFIX "crypt"
  25. #define MESG_STR(x) x, sizeof(x)
  26. /*
  27. * per bio private data
  28. */
  29. struct dm_crypt_io {
  30. struct dm_target *target;
  31. struct bio *base_bio;
  32. struct work_struct work;
  33. atomic_t pending;
  34. int error;
  35. };
  36. /*
  37. * context holding the current state of a multi-part conversion
  38. */
  39. struct convert_context {
  40. struct bio *bio_in;
  41. struct bio *bio_out;
  42. unsigned int offset_in;
  43. unsigned int offset_out;
  44. unsigned int idx_in;
  45. unsigned int idx_out;
  46. sector_t sector;
  47. int write;
  48. };
  49. struct crypt_config;
  50. struct crypt_iv_operations {
  51. int (*ctr)(struct crypt_config *cc, struct dm_target *ti,
  52. const char *opts);
  53. void (*dtr)(struct crypt_config *cc);
  54. const char *(*status)(struct crypt_config *cc);
  55. int (*generator)(struct crypt_config *cc, u8 *iv, sector_t sector);
  56. };
  57. /*
  58. * Crypt: maps a linear range of a block device
  59. * and encrypts / decrypts at the same time.
  60. */
  61. enum flags { DM_CRYPT_SUSPENDED, DM_CRYPT_KEY_VALID };
  62. struct crypt_config {
  63. struct dm_dev *dev;
  64. sector_t start;
  65. /*
  66. * pool for per bio private data and
  67. * for encryption buffer pages
  68. */
  69. mempool_t *io_pool;
  70. mempool_t *page_pool;
  71. struct bio_set *bs;
  72. struct workqueue_struct *io_queue;
  73. struct workqueue_struct *crypt_queue;
  74. /*
  75. * crypto related data
  76. */
  77. struct crypt_iv_operations *iv_gen_ops;
  78. char *iv_mode;
  79. union {
  80. struct crypto_cipher *essiv_tfm;
  81. int benbi_shift;
  82. } iv_gen_private;
  83. sector_t iv_offset;
  84. unsigned int iv_size;
  85. char cipher[CRYPTO_MAX_ALG_NAME];
  86. char chainmode[CRYPTO_MAX_ALG_NAME];
  87. struct crypto_blkcipher *tfm;
  88. unsigned long flags;
  89. unsigned int key_size;
  90. u8 key[0];
  91. };
  92. #define MIN_IOS 16
  93. #define MIN_POOL_PAGES 32
  94. #define MIN_BIO_PAGES 8
  95. static struct kmem_cache *_crypt_io_pool;
  96. static void clone_init(struct dm_crypt_io *, struct bio *);
  97. /*
  98. * Different IV generation algorithms:
  99. *
  100. * plain: the initial vector is the 32-bit little-endian version of the sector
  101. * number, padded with zeros if necessary.
  102. *
  103. * essiv: "encrypted sector|salt initial vector", the sector number is
  104. * encrypted with the bulk cipher using a salt as key. The salt
  105. * should be derived from the bulk cipher's key via hashing.
  106. *
  107. * benbi: the 64-bit "big-endian 'narrow block'-count", starting at 1
  108. * (needed for LRW-32-AES and possible other narrow block modes)
  109. *
  110. * null: the initial vector is always zero. Provides compatibility with
  111. * obsolete loop_fish2 devices. Do not use for new devices.
  112. *
  113. * plumb: unimplemented, see:
  114. * http://article.gmane.org/gmane.linux.kernel.device-mapper.dm-crypt/454
  115. */
  116. static int crypt_iv_plain_gen(struct crypt_config *cc, u8 *iv, sector_t sector)
  117. {
  118. memset(iv, 0, cc->iv_size);
  119. *(u32 *)iv = cpu_to_le32(sector & 0xffffffff);
  120. return 0;
  121. }
  122. static int crypt_iv_essiv_ctr(struct crypt_config *cc, struct dm_target *ti,
  123. const char *opts)
  124. {
  125. struct crypto_cipher *essiv_tfm;
  126. struct crypto_hash *hash_tfm;
  127. struct hash_desc desc;
  128. struct scatterlist sg;
  129. unsigned int saltsize;
  130. u8 *salt;
  131. int err;
  132. if (opts == NULL) {
  133. ti->error = "Digest algorithm missing for ESSIV mode";
  134. return -EINVAL;
  135. }
  136. /* Hash the cipher key with the given hash algorithm */
  137. hash_tfm = crypto_alloc_hash(opts, 0, CRYPTO_ALG_ASYNC);
  138. if (IS_ERR(hash_tfm)) {
  139. ti->error = "Error initializing ESSIV hash";
  140. return PTR_ERR(hash_tfm);
  141. }
  142. saltsize = crypto_hash_digestsize(hash_tfm);
  143. salt = kmalloc(saltsize, GFP_KERNEL);
  144. if (salt == NULL) {
  145. ti->error = "Error kmallocing salt storage in ESSIV";
  146. crypto_free_hash(hash_tfm);
  147. return -ENOMEM;
  148. }
  149. sg_set_buf(&sg, cc->key, cc->key_size);
  150. desc.tfm = hash_tfm;
  151. desc.flags = CRYPTO_TFM_REQ_MAY_SLEEP;
  152. err = crypto_hash_digest(&desc, &sg, cc->key_size, salt);
  153. crypto_free_hash(hash_tfm);
  154. if (err) {
  155. ti->error = "Error calculating hash in ESSIV";
  156. kfree(salt);
  157. return err;
  158. }
  159. /* Setup the essiv_tfm with the given salt */
  160. essiv_tfm = crypto_alloc_cipher(cc->cipher, 0, CRYPTO_ALG_ASYNC);
  161. if (IS_ERR(essiv_tfm)) {
  162. ti->error = "Error allocating crypto tfm for ESSIV";
  163. kfree(salt);
  164. return PTR_ERR(essiv_tfm);
  165. }
  166. if (crypto_cipher_blocksize(essiv_tfm) !=
  167. crypto_blkcipher_ivsize(cc->tfm)) {
  168. ti->error = "Block size of ESSIV cipher does "
  169. "not match IV size of block cipher";
  170. crypto_free_cipher(essiv_tfm);
  171. kfree(salt);
  172. return -EINVAL;
  173. }
  174. err = crypto_cipher_setkey(essiv_tfm, salt, saltsize);
  175. if (err) {
  176. ti->error = "Failed to set key for ESSIV cipher";
  177. crypto_free_cipher(essiv_tfm);
  178. kfree(salt);
  179. return err;
  180. }
  181. kfree(salt);
  182. cc->iv_gen_private.essiv_tfm = essiv_tfm;
  183. return 0;
  184. }
  185. static void crypt_iv_essiv_dtr(struct crypt_config *cc)
  186. {
  187. crypto_free_cipher(cc->iv_gen_private.essiv_tfm);
  188. cc->iv_gen_private.essiv_tfm = NULL;
  189. }
  190. static int crypt_iv_essiv_gen(struct crypt_config *cc, u8 *iv, sector_t sector)
  191. {
  192. memset(iv, 0, cc->iv_size);
  193. *(u64 *)iv = cpu_to_le64(sector);
  194. crypto_cipher_encrypt_one(cc->iv_gen_private.essiv_tfm, iv, iv);
  195. return 0;
  196. }
  197. static int crypt_iv_benbi_ctr(struct crypt_config *cc, struct dm_target *ti,
  198. const char *opts)
  199. {
  200. unsigned int bs = crypto_blkcipher_blocksize(cc->tfm);
  201. int log = ilog2(bs);
  202. /* we need to calculate how far we must shift the sector count
  203. * to get the cipher block count, we use this shift in _gen */
  204. if (1 << log != bs) {
  205. ti->error = "cypher blocksize is not a power of 2";
  206. return -EINVAL;
  207. }
  208. if (log > 9) {
  209. ti->error = "cypher blocksize is > 512";
  210. return -EINVAL;
  211. }
  212. cc->iv_gen_private.benbi_shift = 9 - log;
  213. return 0;
  214. }
  215. static void crypt_iv_benbi_dtr(struct crypt_config *cc)
  216. {
  217. }
  218. static int crypt_iv_benbi_gen(struct crypt_config *cc, u8 *iv, sector_t sector)
  219. {
  220. __be64 val;
  221. memset(iv, 0, cc->iv_size - sizeof(u64)); /* rest is cleared below */
  222. val = cpu_to_be64(((u64)sector << cc->iv_gen_private.benbi_shift) + 1);
  223. put_unaligned(val, (__be64 *)(iv + cc->iv_size - sizeof(u64)));
  224. return 0;
  225. }
  226. static int crypt_iv_null_gen(struct crypt_config *cc, u8 *iv, sector_t sector)
  227. {
  228. memset(iv, 0, cc->iv_size);
  229. return 0;
  230. }
  231. static struct crypt_iv_operations crypt_iv_plain_ops = {
  232. .generator = crypt_iv_plain_gen
  233. };
  234. static struct crypt_iv_operations crypt_iv_essiv_ops = {
  235. .ctr = crypt_iv_essiv_ctr,
  236. .dtr = crypt_iv_essiv_dtr,
  237. .generator = crypt_iv_essiv_gen
  238. };
  239. static struct crypt_iv_operations crypt_iv_benbi_ops = {
  240. .ctr = crypt_iv_benbi_ctr,
  241. .dtr = crypt_iv_benbi_dtr,
  242. .generator = crypt_iv_benbi_gen
  243. };
  244. static struct crypt_iv_operations crypt_iv_null_ops = {
  245. .generator = crypt_iv_null_gen
  246. };
  247. static int
  248. crypt_convert_scatterlist(struct crypt_config *cc, struct scatterlist *out,
  249. struct scatterlist *in, unsigned int length,
  250. int write, sector_t sector)
  251. {
  252. u8 iv[cc->iv_size] __attribute__ ((aligned(__alignof__(u64))));
  253. struct blkcipher_desc desc = {
  254. .tfm = cc->tfm,
  255. .info = iv,
  256. .flags = CRYPTO_TFM_REQ_MAY_SLEEP,
  257. };
  258. int r;
  259. if (cc->iv_gen_ops) {
  260. r = cc->iv_gen_ops->generator(cc, iv, sector);
  261. if (r < 0)
  262. return r;
  263. if (write)
  264. r = crypto_blkcipher_encrypt_iv(&desc, out, in, length);
  265. else
  266. r = crypto_blkcipher_decrypt_iv(&desc, out, in, length);
  267. } else {
  268. if (write)
  269. r = crypto_blkcipher_encrypt(&desc, out, in, length);
  270. else
  271. r = crypto_blkcipher_decrypt(&desc, out, in, length);
  272. }
  273. return r;
  274. }
  275. static void crypt_convert_init(struct crypt_config *cc,
  276. struct convert_context *ctx,
  277. struct bio *bio_out, struct bio *bio_in,
  278. sector_t sector, int write)
  279. {
  280. ctx->bio_in = bio_in;
  281. ctx->bio_out = bio_out;
  282. ctx->offset_in = 0;
  283. ctx->offset_out = 0;
  284. ctx->idx_in = bio_in ? bio_in->bi_idx : 0;
  285. ctx->idx_out = bio_out ? bio_out->bi_idx : 0;
  286. ctx->sector = sector + cc->iv_offset;
  287. ctx->write = write;
  288. }
  289. /*
  290. * Encrypt / decrypt data from one bio to another one (can be the same one)
  291. */
  292. static int crypt_convert(struct crypt_config *cc,
  293. struct convert_context *ctx)
  294. {
  295. int r = 0;
  296. while(ctx->idx_in < ctx->bio_in->bi_vcnt &&
  297. ctx->idx_out < ctx->bio_out->bi_vcnt) {
  298. struct bio_vec *bv_in = bio_iovec_idx(ctx->bio_in, ctx->idx_in);
  299. struct bio_vec *bv_out = bio_iovec_idx(ctx->bio_out, ctx->idx_out);
  300. struct scatterlist sg_in, sg_out;
  301. sg_init_table(&sg_in, 1);
  302. sg_set_page(&sg_in, bv_in->bv_page);
  303. sg_in.offset = bv_in->bv_offset + ctx->offset_in;
  304. sg_in.length = 1 << SECTOR_SHIFT;
  305. sg_init_table(&sg_out, 1);
  306. sg_set_page(&sg_out, bv_out->bv_page);
  307. sg_out.offset = bv_out->bv_offset + ctx->offset_out;
  308. sg_out.length = 1 << SECTOR_SHIFT;
  309. ctx->offset_in += sg_in.length;
  310. if (ctx->offset_in >= bv_in->bv_len) {
  311. ctx->offset_in = 0;
  312. ctx->idx_in++;
  313. }
  314. ctx->offset_out += sg_out.length;
  315. if (ctx->offset_out >= bv_out->bv_len) {
  316. ctx->offset_out = 0;
  317. ctx->idx_out++;
  318. }
  319. r = crypt_convert_scatterlist(cc, &sg_out, &sg_in, sg_in.length,
  320. ctx->write, ctx->sector);
  321. if (r < 0)
  322. break;
  323. ctx->sector++;
  324. }
  325. return r;
  326. }
  327. static void dm_crypt_bio_destructor(struct bio *bio)
  328. {
  329. struct dm_crypt_io *io = bio->bi_private;
  330. struct crypt_config *cc = io->target->private;
  331. bio_free(bio, cc->bs);
  332. }
  333. /*
  334. * Generate a new unfragmented bio with the given size
  335. * This should never violate the device limitations
  336. * May return a smaller bio when running out of pages
  337. */
  338. static struct bio *crypt_alloc_buffer(struct dm_crypt_io *io, unsigned size)
  339. {
  340. struct crypt_config *cc = io->target->private;
  341. struct bio *clone;
  342. unsigned int nr_iovecs = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
  343. gfp_t gfp_mask = GFP_NOIO | __GFP_HIGHMEM;
  344. unsigned int i;
  345. clone = bio_alloc_bioset(GFP_NOIO, nr_iovecs, cc->bs);
  346. if (!clone)
  347. return NULL;
  348. clone_init(io, clone);
  349. for (i = 0; i < nr_iovecs; i++) {
  350. struct bio_vec *bv = bio_iovec_idx(clone, i);
  351. bv->bv_page = mempool_alloc(cc->page_pool, gfp_mask);
  352. if (!bv->bv_page)
  353. break;
  354. /*
  355. * if additional pages cannot be allocated without waiting,
  356. * return a partially allocated bio, the caller will then try
  357. * to allocate additional bios while submitting this partial bio
  358. */
  359. if (i == (MIN_BIO_PAGES - 1))
  360. gfp_mask = (gfp_mask | __GFP_NOWARN) & ~__GFP_WAIT;
  361. bv->bv_offset = 0;
  362. if (size > PAGE_SIZE)
  363. bv->bv_len = PAGE_SIZE;
  364. else
  365. bv->bv_len = size;
  366. clone->bi_size += bv->bv_len;
  367. clone->bi_vcnt++;
  368. size -= bv->bv_len;
  369. }
  370. if (!clone->bi_size) {
  371. bio_put(clone);
  372. return NULL;
  373. }
  374. return clone;
  375. }
  376. static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone)
  377. {
  378. unsigned int i;
  379. struct bio_vec *bv;
  380. for (i = 0; i < clone->bi_vcnt; i++) {
  381. bv = bio_iovec_idx(clone, i);
  382. BUG_ON(!bv->bv_page);
  383. mempool_free(bv->bv_page, cc->page_pool);
  384. bv->bv_page = NULL;
  385. }
  386. }
  387. /*
  388. * One of the bios was finished. Check for completion of
  389. * the whole request and correctly clean up the buffer.
  390. */
  391. static void crypt_dec_pending(struct dm_crypt_io *io, int error)
  392. {
  393. struct crypt_config *cc = (struct crypt_config *) io->target->private;
  394. if (error < 0)
  395. io->error = error;
  396. if (!atomic_dec_and_test(&io->pending))
  397. return;
  398. bio_endio(io->base_bio, io->error);
  399. mempool_free(io, cc->io_pool);
  400. }
  401. /*
  402. * kcryptd/kcryptd_io:
  403. *
  404. * Needed because it would be very unwise to do decryption in an
  405. * interrupt context.
  406. *
  407. * kcryptd performs the actual encryption or decryption.
  408. *
  409. * kcryptd_io performs the IO submission.
  410. *
  411. * They must be separated as otherwise the final stages could be
  412. * starved by new requests which can block in the first stages due
  413. * to memory allocation.
  414. */
  415. static void kcryptd_do_work(struct work_struct *work);
  416. static void kcryptd_do_crypt(struct work_struct *work);
  417. static void kcryptd_queue_io(struct dm_crypt_io *io)
  418. {
  419. struct crypt_config *cc = io->target->private;
  420. INIT_WORK(&io->work, kcryptd_do_work);
  421. queue_work(cc->io_queue, &io->work);
  422. }
  423. static void kcryptd_queue_crypt(struct dm_crypt_io *io)
  424. {
  425. struct crypt_config *cc = io->target->private;
  426. INIT_WORK(&io->work, kcryptd_do_crypt);
  427. queue_work(cc->crypt_queue, &io->work);
  428. }
  429. static void crypt_endio(struct bio *clone, int error)
  430. {
  431. struct dm_crypt_io *io = clone->bi_private;
  432. struct crypt_config *cc = io->target->private;
  433. unsigned read_io = bio_data_dir(clone) == READ;
  434. /*
  435. * free the processed pages
  436. */
  437. if (!read_io) {
  438. crypt_free_buffer_pages(cc, clone);
  439. goto out;
  440. }
  441. if (unlikely(!bio_flagged(clone, BIO_UPTODATE))) {
  442. error = -EIO;
  443. goto out;
  444. }
  445. bio_put(clone);
  446. kcryptd_queue_crypt(io);
  447. return;
  448. out:
  449. bio_put(clone);
  450. crypt_dec_pending(io, error);
  451. }
  452. static void clone_init(struct dm_crypt_io *io, struct bio *clone)
  453. {
  454. struct crypt_config *cc = io->target->private;
  455. clone->bi_private = io;
  456. clone->bi_end_io = crypt_endio;
  457. clone->bi_bdev = cc->dev->bdev;
  458. clone->bi_rw = io->base_bio->bi_rw;
  459. clone->bi_destructor = dm_crypt_bio_destructor;
  460. }
  461. static void process_read(struct dm_crypt_io *io)
  462. {
  463. struct crypt_config *cc = io->target->private;
  464. struct bio *base_bio = io->base_bio;
  465. struct bio *clone;
  466. sector_t sector = base_bio->bi_sector - io->target->begin;
  467. atomic_inc(&io->pending);
  468. /*
  469. * The block layer might modify the bvec array, so always
  470. * copy the required bvecs because we need the original
  471. * one in order to decrypt the whole bio data *afterwards*.
  472. */
  473. clone = bio_alloc_bioset(GFP_NOIO, bio_segments(base_bio), cc->bs);
  474. if (unlikely(!clone)) {
  475. crypt_dec_pending(io, -ENOMEM);
  476. return;
  477. }
  478. clone_init(io, clone);
  479. clone->bi_idx = 0;
  480. clone->bi_vcnt = bio_segments(base_bio);
  481. clone->bi_size = base_bio->bi_size;
  482. clone->bi_sector = cc->start + sector;
  483. memcpy(clone->bi_io_vec, bio_iovec(base_bio),
  484. sizeof(struct bio_vec) * clone->bi_vcnt);
  485. generic_make_request(clone);
  486. }
  487. static void process_write(struct dm_crypt_io *io)
  488. {
  489. struct crypt_config *cc = io->target->private;
  490. struct bio *base_bio = io->base_bio;
  491. struct bio *clone;
  492. struct convert_context ctx;
  493. unsigned remaining = base_bio->bi_size;
  494. sector_t sector = base_bio->bi_sector - io->target->begin;
  495. atomic_inc(&io->pending);
  496. crypt_convert_init(cc, &ctx, NULL, base_bio, sector, 1);
  497. /*
  498. * The allocated buffers can be smaller than the whole bio,
  499. * so repeat the whole process until all the data can be handled.
  500. */
  501. while (remaining) {
  502. clone = crypt_alloc_buffer(io, remaining);
  503. if (unlikely(!clone)) {
  504. crypt_dec_pending(io, -ENOMEM);
  505. return;
  506. }
  507. ctx.bio_out = clone;
  508. ctx.idx_out = 0;
  509. if (unlikely(crypt_convert(cc, &ctx) < 0)) {
  510. crypt_free_buffer_pages(cc, clone);
  511. bio_put(clone);
  512. crypt_dec_pending(io, -EIO);
  513. return;
  514. }
  515. /* crypt_convert should have filled the clone bio */
  516. BUG_ON(ctx.idx_out < clone->bi_vcnt);
  517. clone->bi_sector = cc->start + sector;
  518. remaining -= clone->bi_size;
  519. sector += bio_sectors(clone);
  520. /* Grab another reference to the io struct
  521. * before we kick off the request */
  522. if (remaining)
  523. atomic_inc(&io->pending);
  524. generic_make_request(clone);
  525. /* Do not reference clone after this - it
  526. * may be gone already. */
  527. /* out of memory -> run queues */
  528. if (remaining)
  529. congestion_wait(WRITE, HZ/100);
  530. }
  531. }
  532. static void process_read_endio(struct dm_crypt_io *io)
  533. {
  534. struct crypt_config *cc = io->target->private;
  535. struct convert_context ctx;
  536. crypt_convert_init(cc, &ctx, io->base_bio, io->base_bio,
  537. io->base_bio->bi_sector - io->target->begin, 0);
  538. crypt_dec_pending(io, crypt_convert(cc, &ctx));
  539. }
  540. static void kcryptd_do_work(struct work_struct *work)
  541. {
  542. struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
  543. if (bio_data_dir(io->base_bio) == READ)
  544. process_read(io);
  545. }
  546. static void kcryptd_do_crypt(struct work_struct *work)
  547. {
  548. struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
  549. if (bio_data_dir(io->base_bio) == READ)
  550. process_read_endio(io);
  551. else
  552. process_write(io);
  553. }
  554. /*
  555. * Decode key from its hex representation
  556. */
  557. static int crypt_decode_key(u8 *key, char *hex, unsigned int size)
  558. {
  559. char buffer[3];
  560. char *endp;
  561. unsigned int i;
  562. buffer[2] = '\0';
  563. for (i = 0; i < size; i++) {
  564. buffer[0] = *hex++;
  565. buffer[1] = *hex++;
  566. key[i] = (u8)simple_strtoul(buffer, &endp, 16);
  567. if (endp != &buffer[2])
  568. return -EINVAL;
  569. }
  570. if (*hex != '\0')
  571. return -EINVAL;
  572. return 0;
  573. }
  574. /*
  575. * Encode key into its hex representation
  576. */
  577. static void crypt_encode_key(char *hex, u8 *key, unsigned int size)
  578. {
  579. unsigned int i;
  580. for (i = 0; i < size; i++) {
  581. sprintf(hex, "%02x", *key);
  582. hex += 2;
  583. key++;
  584. }
  585. }
  586. static int crypt_set_key(struct crypt_config *cc, char *key)
  587. {
  588. unsigned key_size = strlen(key) >> 1;
  589. if (cc->key_size && cc->key_size != key_size)
  590. return -EINVAL;
  591. cc->key_size = key_size; /* initial settings */
  592. if ((!key_size && strcmp(key, "-")) ||
  593. (key_size && crypt_decode_key(cc->key, key, key_size) < 0))
  594. return -EINVAL;
  595. set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
  596. return 0;
  597. }
  598. static int crypt_wipe_key(struct crypt_config *cc)
  599. {
  600. clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
  601. memset(&cc->key, 0, cc->key_size * sizeof(u8));
  602. return 0;
  603. }
  604. /*
  605. * Construct an encryption mapping:
  606. * <cipher> <key> <iv_offset> <dev_path> <start>
  607. */
  608. static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
  609. {
  610. struct crypt_config *cc;
  611. struct crypto_blkcipher *tfm;
  612. char *tmp;
  613. char *cipher;
  614. char *chainmode;
  615. char *ivmode;
  616. char *ivopts;
  617. unsigned int key_size;
  618. unsigned long long tmpll;
  619. if (argc != 5) {
  620. ti->error = "Not enough arguments";
  621. return -EINVAL;
  622. }
  623. tmp = argv[0];
  624. cipher = strsep(&tmp, "-");
  625. chainmode = strsep(&tmp, "-");
  626. ivopts = strsep(&tmp, "-");
  627. ivmode = strsep(&ivopts, ":");
  628. if (tmp)
  629. DMWARN("Unexpected additional cipher options");
  630. key_size = strlen(argv[1]) >> 1;
  631. cc = kzalloc(sizeof(*cc) + key_size * sizeof(u8), GFP_KERNEL);
  632. if (cc == NULL) {
  633. ti->error =
  634. "Cannot allocate transparent encryption context";
  635. return -ENOMEM;
  636. }
  637. if (crypt_set_key(cc, argv[1])) {
  638. ti->error = "Error decoding key";
  639. goto bad_cipher;
  640. }
  641. /* Compatiblity mode for old dm-crypt cipher strings */
  642. if (!chainmode || (strcmp(chainmode, "plain") == 0 && !ivmode)) {
  643. chainmode = "cbc";
  644. ivmode = "plain";
  645. }
  646. if (strcmp(chainmode, "ecb") && !ivmode) {
  647. ti->error = "This chaining mode requires an IV mechanism";
  648. goto bad_cipher;
  649. }
  650. if (snprintf(cc->cipher, CRYPTO_MAX_ALG_NAME, "%s(%s)",
  651. chainmode, cipher) >= CRYPTO_MAX_ALG_NAME) {
  652. ti->error = "Chain mode + cipher name is too long";
  653. goto bad_cipher;
  654. }
  655. tfm = crypto_alloc_blkcipher(cc->cipher, 0, CRYPTO_ALG_ASYNC);
  656. if (IS_ERR(tfm)) {
  657. ti->error = "Error allocating crypto tfm";
  658. goto bad_cipher;
  659. }
  660. strcpy(cc->cipher, cipher);
  661. strcpy(cc->chainmode, chainmode);
  662. cc->tfm = tfm;
  663. /*
  664. * Choose ivmode. Valid modes: "plain", "essiv:<esshash>", "benbi".
  665. * See comments at iv code
  666. */
  667. if (ivmode == NULL)
  668. cc->iv_gen_ops = NULL;
  669. else if (strcmp(ivmode, "plain") == 0)
  670. cc->iv_gen_ops = &crypt_iv_plain_ops;
  671. else if (strcmp(ivmode, "essiv") == 0)
  672. cc->iv_gen_ops = &crypt_iv_essiv_ops;
  673. else if (strcmp(ivmode, "benbi") == 0)
  674. cc->iv_gen_ops = &crypt_iv_benbi_ops;
  675. else if (strcmp(ivmode, "null") == 0)
  676. cc->iv_gen_ops = &crypt_iv_null_ops;
  677. else {
  678. ti->error = "Invalid IV mode";
  679. goto bad_ivmode;
  680. }
  681. if (cc->iv_gen_ops && cc->iv_gen_ops->ctr &&
  682. cc->iv_gen_ops->ctr(cc, ti, ivopts) < 0)
  683. goto bad_ivmode;
  684. cc->iv_size = crypto_blkcipher_ivsize(tfm);
  685. if (cc->iv_size)
  686. /* at least a 64 bit sector number should fit in our buffer */
  687. cc->iv_size = max(cc->iv_size,
  688. (unsigned int)(sizeof(u64) / sizeof(u8)));
  689. else {
  690. if (cc->iv_gen_ops) {
  691. DMWARN("Selected cipher does not support IVs");
  692. if (cc->iv_gen_ops->dtr)
  693. cc->iv_gen_ops->dtr(cc);
  694. cc->iv_gen_ops = NULL;
  695. }
  696. }
  697. cc->io_pool = mempool_create_slab_pool(MIN_IOS, _crypt_io_pool);
  698. if (!cc->io_pool) {
  699. ti->error = "Cannot allocate crypt io mempool";
  700. goto bad_slab_pool;
  701. }
  702. cc->page_pool = mempool_create_page_pool(MIN_POOL_PAGES, 0);
  703. if (!cc->page_pool) {
  704. ti->error = "Cannot allocate page mempool";
  705. goto bad_page_pool;
  706. }
  707. cc->bs = bioset_create(MIN_IOS, MIN_IOS);
  708. if (!cc->bs) {
  709. ti->error = "Cannot allocate crypt bioset";
  710. goto bad_bs;
  711. }
  712. if (crypto_blkcipher_setkey(tfm, cc->key, key_size) < 0) {
  713. ti->error = "Error setting key";
  714. goto bad_device;
  715. }
  716. if (sscanf(argv[2], "%llu", &tmpll) != 1) {
  717. ti->error = "Invalid iv_offset sector";
  718. goto bad_device;
  719. }
  720. cc->iv_offset = tmpll;
  721. if (sscanf(argv[4], "%llu", &tmpll) != 1) {
  722. ti->error = "Invalid device sector";
  723. goto bad_device;
  724. }
  725. cc->start = tmpll;
  726. if (dm_get_device(ti, argv[3], cc->start, ti->len,
  727. dm_table_get_mode(ti->table), &cc->dev)) {
  728. ti->error = "Device lookup failed";
  729. goto bad_device;
  730. }
  731. if (ivmode && cc->iv_gen_ops) {
  732. if (ivopts)
  733. *(ivopts - 1) = ':';
  734. cc->iv_mode = kmalloc(strlen(ivmode) + 1, GFP_KERNEL);
  735. if (!cc->iv_mode) {
  736. ti->error = "Error kmallocing iv_mode string";
  737. goto bad_ivmode_string;
  738. }
  739. strcpy(cc->iv_mode, ivmode);
  740. } else
  741. cc->iv_mode = NULL;
  742. cc->io_queue = create_singlethread_workqueue("kcryptd_io");
  743. if (!cc->io_queue) {
  744. ti->error = "Couldn't create kcryptd io queue";
  745. goto bad_io_queue;
  746. }
  747. cc->crypt_queue = create_singlethread_workqueue("kcryptd");
  748. if (!cc->crypt_queue) {
  749. ti->error = "Couldn't create kcryptd queue";
  750. goto bad_crypt_queue;
  751. }
  752. ti->private = cc;
  753. return 0;
  754. bad_crypt_queue:
  755. destroy_workqueue(cc->io_queue);
  756. bad_io_queue:
  757. kfree(cc->iv_mode);
  758. bad_ivmode_string:
  759. dm_put_device(ti, cc->dev);
  760. bad_device:
  761. bioset_free(cc->bs);
  762. bad_bs:
  763. mempool_destroy(cc->page_pool);
  764. bad_page_pool:
  765. mempool_destroy(cc->io_pool);
  766. bad_slab_pool:
  767. if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
  768. cc->iv_gen_ops->dtr(cc);
  769. bad_ivmode:
  770. crypto_free_blkcipher(tfm);
  771. bad_cipher:
  772. /* Must zero key material before freeing */
  773. memset(cc, 0, sizeof(*cc) + cc->key_size * sizeof(u8));
  774. kfree(cc);
  775. return -EINVAL;
  776. }
  777. static void crypt_dtr(struct dm_target *ti)
  778. {
  779. struct crypt_config *cc = (struct crypt_config *) ti->private;
  780. destroy_workqueue(cc->io_queue);
  781. destroy_workqueue(cc->crypt_queue);
  782. bioset_free(cc->bs);
  783. mempool_destroy(cc->page_pool);
  784. mempool_destroy(cc->io_pool);
  785. kfree(cc->iv_mode);
  786. if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
  787. cc->iv_gen_ops->dtr(cc);
  788. crypto_free_blkcipher(cc->tfm);
  789. dm_put_device(ti, cc->dev);
  790. /* Must zero key material before freeing */
  791. memset(cc, 0, sizeof(*cc) + cc->key_size * sizeof(u8));
  792. kfree(cc);
  793. }
  794. static int crypt_map(struct dm_target *ti, struct bio *bio,
  795. union map_info *map_context)
  796. {
  797. struct crypt_config *cc = ti->private;
  798. struct dm_crypt_io *io;
  799. io = mempool_alloc(cc->io_pool, GFP_NOIO);
  800. io->target = ti;
  801. io->base_bio = bio;
  802. io->error = 0;
  803. atomic_set(&io->pending, 0);
  804. if (bio_data_dir(io->base_bio) == READ)
  805. kcryptd_queue_io(io);
  806. else
  807. kcryptd_queue_crypt(io);
  808. return DM_MAPIO_SUBMITTED;
  809. }
  810. static int crypt_status(struct dm_target *ti, status_type_t type,
  811. char *result, unsigned int maxlen)
  812. {
  813. struct crypt_config *cc = (struct crypt_config *) ti->private;
  814. unsigned int sz = 0;
  815. switch (type) {
  816. case STATUSTYPE_INFO:
  817. result[0] = '\0';
  818. break;
  819. case STATUSTYPE_TABLE:
  820. if (cc->iv_mode)
  821. DMEMIT("%s-%s-%s ", cc->cipher, cc->chainmode,
  822. cc->iv_mode);
  823. else
  824. DMEMIT("%s-%s ", cc->cipher, cc->chainmode);
  825. if (cc->key_size > 0) {
  826. if ((maxlen - sz) < ((cc->key_size << 1) + 1))
  827. return -ENOMEM;
  828. crypt_encode_key(result + sz, cc->key, cc->key_size);
  829. sz += cc->key_size << 1;
  830. } else {
  831. if (sz >= maxlen)
  832. return -ENOMEM;
  833. result[sz++] = '-';
  834. }
  835. DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
  836. cc->dev->name, (unsigned long long)cc->start);
  837. break;
  838. }
  839. return 0;
  840. }
  841. static void crypt_postsuspend(struct dm_target *ti)
  842. {
  843. struct crypt_config *cc = ti->private;
  844. set_bit(DM_CRYPT_SUSPENDED, &cc->flags);
  845. }
  846. static int crypt_preresume(struct dm_target *ti)
  847. {
  848. struct crypt_config *cc = ti->private;
  849. if (!test_bit(DM_CRYPT_KEY_VALID, &cc->flags)) {
  850. DMERR("aborting resume - crypt key is not set.");
  851. return -EAGAIN;
  852. }
  853. return 0;
  854. }
  855. static void crypt_resume(struct dm_target *ti)
  856. {
  857. struct crypt_config *cc = ti->private;
  858. clear_bit(DM_CRYPT_SUSPENDED, &cc->flags);
  859. }
  860. /* Message interface
  861. * key set <key>
  862. * key wipe
  863. */
  864. static int crypt_message(struct dm_target *ti, unsigned argc, char **argv)
  865. {
  866. struct crypt_config *cc = ti->private;
  867. if (argc < 2)
  868. goto error;
  869. if (!strnicmp(argv[0], MESG_STR("key"))) {
  870. if (!test_bit(DM_CRYPT_SUSPENDED, &cc->flags)) {
  871. DMWARN("not suspended during key manipulation.");
  872. return -EINVAL;
  873. }
  874. if (argc == 3 && !strnicmp(argv[1], MESG_STR("set")))
  875. return crypt_set_key(cc, argv[2]);
  876. if (argc == 2 && !strnicmp(argv[1], MESG_STR("wipe")))
  877. return crypt_wipe_key(cc);
  878. }
  879. error:
  880. DMWARN("unrecognised message received.");
  881. return -EINVAL;
  882. }
  883. static struct target_type crypt_target = {
  884. .name = "crypt",
  885. .version= {1, 5, 0},
  886. .module = THIS_MODULE,
  887. .ctr = crypt_ctr,
  888. .dtr = crypt_dtr,
  889. .map = crypt_map,
  890. .status = crypt_status,
  891. .postsuspend = crypt_postsuspend,
  892. .preresume = crypt_preresume,
  893. .resume = crypt_resume,
  894. .message = crypt_message,
  895. };
  896. static int __init dm_crypt_init(void)
  897. {
  898. int r;
  899. _crypt_io_pool = KMEM_CACHE(dm_crypt_io, 0);
  900. if (!_crypt_io_pool)
  901. return -ENOMEM;
  902. r = dm_register_target(&crypt_target);
  903. if (r < 0) {
  904. DMERR("register failed %d", r);
  905. kmem_cache_destroy(_crypt_io_pool);
  906. }
  907. return r;
  908. }
  909. static void __exit dm_crypt_exit(void)
  910. {
  911. int r = dm_unregister_target(&crypt_target);
  912. if (r < 0)
  913. DMERR("unregister failed %d", r);
  914. kmem_cache_destroy(_crypt_io_pool);
  915. }
  916. module_init(dm_crypt_init);
  917. module_exit(dm_crypt_exit);
  918. MODULE_AUTHOR("Christophe Saout <christophe@saout.de>");
  919. MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
  920. MODULE_LICENSE("GPL");