dm-crypt.c 25 KB

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