dm-crypt.c 25 KB

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