dm-crypt.c 25 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066
  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 struct kmem_cache *_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(struct work_struct *work);
  394. static void kcryptd_queue_io(struct crypt_io *io)
  395. {
  396. INIT_WORK(&io->work, kcryptd_do_work);
  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(struct work_struct *work)
  523. {
  524. struct crypt_io *io = container_of(work, struct crypt_io, work);
  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. unsigned int sz = 0;
  769. switch (type) {
  770. case STATUSTYPE_INFO:
  771. result[0] = '\0';
  772. break;
  773. case STATUSTYPE_TABLE:
  774. if (cc->iv_mode)
  775. DMEMIT("%s-%s-%s ", cc->cipher, cc->chainmode,
  776. cc->iv_mode);
  777. else
  778. DMEMIT("%s-%s ", cc->cipher, cc->chainmode);
  779. if (cc->key_size > 0) {
  780. if ((maxlen - sz) < ((cc->key_size << 1) + 1))
  781. return -ENOMEM;
  782. crypt_encode_key(result + sz, cc->key, cc->key_size);
  783. sz += cc->key_size << 1;
  784. } else {
  785. if (sz >= maxlen)
  786. return -ENOMEM;
  787. result[sz++] = '-';
  788. }
  789. DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
  790. cc->dev->name, (unsigned long long)cc->start);
  791. break;
  792. }
  793. return 0;
  794. }
  795. static void crypt_postsuspend(struct dm_target *ti)
  796. {
  797. struct crypt_config *cc = ti->private;
  798. set_bit(DM_CRYPT_SUSPENDED, &cc->flags);
  799. }
  800. static int crypt_preresume(struct dm_target *ti)
  801. {
  802. struct crypt_config *cc = ti->private;
  803. if (!test_bit(DM_CRYPT_KEY_VALID, &cc->flags)) {
  804. DMERR("aborting resume - crypt key is not set.");
  805. return -EAGAIN;
  806. }
  807. return 0;
  808. }
  809. static void crypt_resume(struct dm_target *ti)
  810. {
  811. struct crypt_config *cc = ti->private;
  812. clear_bit(DM_CRYPT_SUSPENDED, &cc->flags);
  813. }
  814. /* Message interface
  815. * key set <key>
  816. * key wipe
  817. */
  818. static int crypt_message(struct dm_target *ti, unsigned argc, char **argv)
  819. {
  820. struct crypt_config *cc = ti->private;
  821. if (argc < 2)
  822. goto error;
  823. if (!strnicmp(argv[0], MESG_STR("key"))) {
  824. if (!test_bit(DM_CRYPT_SUSPENDED, &cc->flags)) {
  825. DMWARN("not suspended during key manipulation.");
  826. return -EINVAL;
  827. }
  828. if (argc == 3 && !strnicmp(argv[1], MESG_STR("set")))
  829. return crypt_set_key(cc, argv[2]);
  830. if (argc == 2 && !strnicmp(argv[1], MESG_STR("wipe")))
  831. return crypt_wipe_key(cc);
  832. }
  833. error:
  834. DMWARN("unrecognised message received.");
  835. return -EINVAL;
  836. }
  837. static struct target_type crypt_target = {
  838. .name = "crypt",
  839. .version= {1, 3, 0},
  840. .module = THIS_MODULE,
  841. .ctr = crypt_ctr,
  842. .dtr = crypt_dtr,
  843. .map = crypt_map,
  844. .status = crypt_status,
  845. .postsuspend = crypt_postsuspend,
  846. .preresume = crypt_preresume,
  847. .resume = crypt_resume,
  848. .message = crypt_message,
  849. };
  850. static int __init dm_crypt_init(void)
  851. {
  852. int r;
  853. _crypt_io_pool = kmem_cache_create("dm-crypt_io",
  854. sizeof(struct crypt_io),
  855. 0, 0, NULL, NULL);
  856. if (!_crypt_io_pool)
  857. return -ENOMEM;
  858. _kcryptd_workqueue = create_workqueue("kcryptd");
  859. if (!_kcryptd_workqueue) {
  860. r = -ENOMEM;
  861. DMERR("couldn't create kcryptd");
  862. goto bad1;
  863. }
  864. r = dm_register_target(&crypt_target);
  865. if (r < 0) {
  866. DMERR("register failed %d", r);
  867. goto bad2;
  868. }
  869. return 0;
  870. bad2:
  871. destroy_workqueue(_kcryptd_workqueue);
  872. bad1:
  873. kmem_cache_destroy(_crypt_io_pool);
  874. return r;
  875. }
  876. static void __exit dm_crypt_exit(void)
  877. {
  878. int r = dm_unregister_target(&crypt_target);
  879. if (r < 0)
  880. DMERR("unregister failed %d", r);
  881. destroy_workqueue(_kcryptd_workqueue);
  882. kmem_cache_destroy(_crypt_io_pool);
  883. }
  884. module_init(dm_crypt_init);
  885. module_exit(dm_crypt_exit);
  886. MODULE_AUTHOR("Christophe Saout <christophe@saout.de>");
  887. MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
  888. MODULE_LICENSE("GPL");