dm-crypt.c 26 KB

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