dm-crypt.c 26 KB

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