dm-crypt.c 24 KB

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