dm-crypt.c 24 KB

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