dm-crypt.c 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869
  1. /*
  2. * Copyright (C) 2003 Christophe Saout <christophe@saout.de>
  3. * Copyright (C) 2004 Clemens Fruhwirth <clemens@endorphin.org>
  4. * Copyright (C) 2006-2009 Red Hat, Inc. All rights reserved.
  5. *
  6. * This file is released under the GPL.
  7. */
  8. #include <linux/completion.h>
  9. #include <linux/err.h>
  10. #include <linux/module.h>
  11. #include <linux/init.h>
  12. #include <linux/kernel.h>
  13. #include <linux/bio.h>
  14. #include <linux/blkdev.h>
  15. #include <linux/mempool.h>
  16. #include <linux/slab.h>
  17. #include <linux/crypto.h>
  18. #include <linux/workqueue.h>
  19. #include <linux/backing-dev.h>
  20. #include <linux/percpu.h>
  21. #include <linux/atomic.h>
  22. #include <linux/scatterlist.h>
  23. #include <asm/page.h>
  24. #include <asm/unaligned.h>
  25. #include <crypto/hash.h>
  26. #include <crypto/md5.h>
  27. #include <crypto/algapi.h>
  28. #include <linux/device-mapper.h>
  29. #define DM_MSG_PREFIX "crypt"
  30. /*
  31. * context holding the current state of a multi-part conversion
  32. */
  33. struct convert_context {
  34. struct completion restart;
  35. struct bio *bio_in;
  36. struct bio *bio_out;
  37. unsigned int offset_in;
  38. unsigned int offset_out;
  39. unsigned int idx_in;
  40. unsigned int idx_out;
  41. sector_t cc_sector;
  42. atomic_t cc_pending;
  43. };
  44. /*
  45. * per bio private data
  46. */
  47. struct dm_crypt_io {
  48. struct crypt_config *cc;
  49. struct bio *base_bio;
  50. struct work_struct work;
  51. struct convert_context ctx;
  52. atomic_t io_pending;
  53. int error;
  54. sector_t sector;
  55. struct dm_crypt_io *base_io;
  56. };
  57. struct dm_crypt_request {
  58. struct convert_context *ctx;
  59. struct scatterlist sg_in;
  60. struct scatterlist sg_out;
  61. sector_t iv_sector;
  62. };
  63. struct crypt_config;
  64. struct crypt_iv_operations {
  65. int (*ctr)(struct crypt_config *cc, struct dm_target *ti,
  66. const char *opts);
  67. void (*dtr)(struct crypt_config *cc);
  68. int (*init)(struct crypt_config *cc);
  69. int (*wipe)(struct crypt_config *cc);
  70. int (*generator)(struct crypt_config *cc, u8 *iv,
  71. struct dm_crypt_request *dmreq);
  72. int (*post)(struct crypt_config *cc, u8 *iv,
  73. struct dm_crypt_request *dmreq);
  74. };
  75. struct iv_essiv_private {
  76. struct crypto_hash *hash_tfm;
  77. u8 *salt;
  78. };
  79. struct iv_benbi_private {
  80. int shift;
  81. };
  82. #define LMK_SEED_SIZE 64 /* hash + 0 */
  83. struct iv_lmk_private {
  84. struct crypto_shash *hash_tfm;
  85. u8 *seed;
  86. };
  87. /*
  88. * Crypt: maps a linear range of a block device
  89. * and encrypts / decrypts at the same time.
  90. */
  91. enum flags { DM_CRYPT_SUSPENDED, DM_CRYPT_KEY_VALID };
  92. /*
  93. * Duplicated per-CPU state for cipher.
  94. */
  95. struct crypt_cpu {
  96. struct ablkcipher_request *req;
  97. };
  98. /*
  99. * The fields in here must be read only after initialization,
  100. * changing state should be in crypt_cpu.
  101. */
  102. struct crypt_config {
  103. struct dm_dev *dev;
  104. sector_t start;
  105. /*
  106. * pool for per bio private data, crypto requests and
  107. * encryption requeusts/buffer pages
  108. */
  109. mempool_t *io_pool;
  110. mempool_t *req_pool;
  111. mempool_t *page_pool;
  112. struct bio_set *bs;
  113. struct workqueue_struct *io_queue;
  114. struct workqueue_struct *crypt_queue;
  115. char *cipher;
  116. char *cipher_string;
  117. struct crypt_iv_operations *iv_gen_ops;
  118. union {
  119. struct iv_essiv_private essiv;
  120. struct iv_benbi_private benbi;
  121. struct iv_lmk_private lmk;
  122. } iv_gen_private;
  123. sector_t iv_offset;
  124. unsigned int iv_size;
  125. /*
  126. * Duplicated per cpu state. Access through
  127. * per_cpu_ptr() only.
  128. */
  129. struct crypt_cpu __percpu *cpu;
  130. /* ESSIV: struct crypto_cipher *essiv_tfm */
  131. void *iv_private;
  132. struct crypto_ablkcipher **tfms;
  133. unsigned tfms_count;
  134. /*
  135. * Layout of each crypto request:
  136. *
  137. * struct ablkcipher_request
  138. * context
  139. * padding
  140. * struct dm_crypt_request
  141. * padding
  142. * IV
  143. *
  144. * The padding is added so that dm_crypt_request and the IV are
  145. * correctly aligned.
  146. */
  147. unsigned int dmreq_start;
  148. unsigned long flags;
  149. unsigned int key_size;
  150. unsigned int key_parts; /* independent parts in key buffer */
  151. unsigned int key_extra_size; /* additional keys length */
  152. u8 key[0];
  153. };
  154. #define MIN_IOS 16
  155. #define MIN_POOL_PAGES 32
  156. static struct kmem_cache *_crypt_io_pool;
  157. static void clone_init(struct dm_crypt_io *, struct bio *);
  158. static void kcryptd_queue_crypt(struct dm_crypt_io *io);
  159. static u8 *iv_of_dmreq(struct crypt_config *cc, struct dm_crypt_request *dmreq);
  160. static struct crypt_cpu *this_crypt_config(struct crypt_config *cc)
  161. {
  162. return this_cpu_ptr(cc->cpu);
  163. }
  164. /*
  165. * Use this to access cipher attributes that are the same for each CPU.
  166. */
  167. static struct crypto_ablkcipher *any_tfm(struct crypt_config *cc)
  168. {
  169. return cc->tfms[0];
  170. }
  171. /*
  172. * Different IV generation algorithms:
  173. *
  174. * plain: the initial vector is the 32-bit little-endian version of the sector
  175. * number, padded with zeros if necessary.
  176. *
  177. * plain64: the initial vector is the 64-bit little-endian version of the sector
  178. * number, padded with zeros if necessary.
  179. *
  180. * essiv: "encrypted sector|salt initial vector", the sector number is
  181. * encrypted with the bulk cipher using a salt as key. The salt
  182. * should be derived from the bulk cipher's key via hashing.
  183. *
  184. * benbi: the 64-bit "big-endian 'narrow block'-count", starting at 1
  185. * (needed for LRW-32-AES and possible other narrow block modes)
  186. *
  187. * null: the initial vector is always zero. Provides compatibility with
  188. * obsolete loop_fish2 devices. Do not use for new devices.
  189. *
  190. * lmk: Compatible implementation of the block chaining mode used
  191. * by the Loop-AES block device encryption system
  192. * designed by Jari Ruusu. See http://loop-aes.sourceforge.net/
  193. * It operates on full 512 byte sectors and uses CBC
  194. * with an IV derived from the sector number, the data and
  195. * optionally extra IV seed.
  196. * This means that after decryption the first block
  197. * of sector must be tweaked according to decrypted data.
  198. * Loop-AES can use three encryption schemes:
  199. * version 1: is plain aes-cbc mode
  200. * version 2: uses 64 multikey scheme with lmk IV generator
  201. * version 3: the same as version 2 with additional IV seed
  202. * (it uses 65 keys, last key is used as IV seed)
  203. *
  204. * plumb: unimplemented, see:
  205. * http://article.gmane.org/gmane.linux.kernel.device-mapper.dm-crypt/454
  206. */
  207. static int crypt_iv_plain_gen(struct crypt_config *cc, u8 *iv,
  208. struct dm_crypt_request *dmreq)
  209. {
  210. memset(iv, 0, cc->iv_size);
  211. *(__le32 *)iv = cpu_to_le32(dmreq->iv_sector & 0xffffffff);
  212. return 0;
  213. }
  214. static int crypt_iv_plain64_gen(struct crypt_config *cc, u8 *iv,
  215. struct dm_crypt_request *dmreq)
  216. {
  217. memset(iv, 0, cc->iv_size);
  218. *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
  219. return 0;
  220. }
  221. /* Initialise ESSIV - compute salt but no local memory allocations */
  222. static int crypt_iv_essiv_init(struct crypt_config *cc)
  223. {
  224. struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
  225. struct hash_desc desc;
  226. struct scatterlist sg;
  227. struct crypto_cipher *essiv_tfm;
  228. int err;
  229. sg_init_one(&sg, cc->key, cc->key_size);
  230. desc.tfm = essiv->hash_tfm;
  231. desc.flags = CRYPTO_TFM_REQ_MAY_SLEEP;
  232. err = crypto_hash_digest(&desc, &sg, cc->key_size, essiv->salt);
  233. if (err)
  234. return err;
  235. essiv_tfm = cc->iv_private;
  236. err = crypto_cipher_setkey(essiv_tfm, essiv->salt,
  237. crypto_hash_digestsize(essiv->hash_tfm));
  238. if (err)
  239. return err;
  240. return 0;
  241. }
  242. /* Wipe salt and reset key derived from volume key */
  243. static int crypt_iv_essiv_wipe(struct crypt_config *cc)
  244. {
  245. struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
  246. unsigned salt_size = crypto_hash_digestsize(essiv->hash_tfm);
  247. struct crypto_cipher *essiv_tfm;
  248. int r, err = 0;
  249. memset(essiv->salt, 0, salt_size);
  250. essiv_tfm = cc->iv_private;
  251. r = crypto_cipher_setkey(essiv_tfm, essiv->salt, salt_size);
  252. if (r)
  253. err = r;
  254. return err;
  255. }
  256. /* Set up per cpu cipher state */
  257. static struct crypto_cipher *setup_essiv_cpu(struct crypt_config *cc,
  258. struct dm_target *ti,
  259. u8 *salt, unsigned saltsize)
  260. {
  261. struct crypto_cipher *essiv_tfm;
  262. int err;
  263. /* Setup the essiv_tfm with the given salt */
  264. essiv_tfm = crypto_alloc_cipher(cc->cipher, 0, CRYPTO_ALG_ASYNC);
  265. if (IS_ERR(essiv_tfm)) {
  266. ti->error = "Error allocating crypto tfm for ESSIV";
  267. return essiv_tfm;
  268. }
  269. if (crypto_cipher_blocksize(essiv_tfm) !=
  270. crypto_ablkcipher_ivsize(any_tfm(cc))) {
  271. ti->error = "Block size of ESSIV cipher does "
  272. "not match IV size of block cipher";
  273. crypto_free_cipher(essiv_tfm);
  274. return ERR_PTR(-EINVAL);
  275. }
  276. err = crypto_cipher_setkey(essiv_tfm, salt, saltsize);
  277. if (err) {
  278. ti->error = "Failed to set key for ESSIV cipher";
  279. crypto_free_cipher(essiv_tfm);
  280. return ERR_PTR(err);
  281. }
  282. return essiv_tfm;
  283. }
  284. static void crypt_iv_essiv_dtr(struct crypt_config *cc)
  285. {
  286. struct crypto_cipher *essiv_tfm;
  287. struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
  288. crypto_free_hash(essiv->hash_tfm);
  289. essiv->hash_tfm = NULL;
  290. kzfree(essiv->salt);
  291. essiv->salt = NULL;
  292. essiv_tfm = cc->iv_private;
  293. if (essiv_tfm)
  294. crypto_free_cipher(essiv_tfm);
  295. cc->iv_private = NULL;
  296. }
  297. static int crypt_iv_essiv_ctr(struct crypt_config *cc, struct dm_target *ti,
  298. const char *opts)
  299. {
  300. struct crypto_cipher *essiv_tfm = NULL;
  301. struct crypto_hash *hash_tfm = NULL;
  302. u8 *salt = NULL;
  303. int err;
  304. if (!opts) {
  305. ti->error = "Digest algorithm missing for ESSIV mode";
  306. return -EINVAL;
  307. }
  308. /* Allocate hash algorithm */
  309. hash_tfm = crypto_alloc_hash(opts, 0, CRYPTO_ALG_ASYNC);
  310. if (IS_ERR(hash_tfm)) {
  311. ti->error = "Error initializing ESSIV hash";
  312. err = PTR_ERR(hash_tfm);
  313. goto bad;
  314. }
  315. salt = kzalloc(crypto_hash_digestsize(hash_tfm), GFP_KERNEL);
  316. if (!salt) {
  317. ti->error = "Error kmallocing salt storage in ESSIV";
  318. err = -ENOMEM;
  319. goto bad;
  320. }
  321. cc->iv_gen_private.essiv.salt = salt;
  322. cc->iv_gen_private.essiv.hash_tfm = hash_tfm;
  323. essiv_tfm = setup_essiv_cpu(cc, ti, salt,
  324. crypto_hash_digestsize(hash_tfm));
  325. if (IS_ERR(essiv_tfm)) {
  326. crypt_iv_essiv_dtr(cc);
  327. return PTR_ERR(essiv_tfm);
  328. }
  329. cc->iv_private = essiv_tfm;
  330. return 0;
  331. bad:
  332. if (hash_tfm && !IS_ERR(hash_tfm))
  333. crypto_free_hash(hash_tfm);
  334. kfree(salt);
  335. return err;
  336. }
  337. static int crypt_iv_essiv_gen(struct crypt_config *cc, u8 *iv,
  338. struct dm_crypt_request *dmreq)
  339. {
  340. struct crypto_cipher *essiv_tfm = cc->iv_private;
  341. memset(iv, 0, cc->iv_size);
  342. *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
  343. crypto_cipher_encrypt_one(essiv_tfm, iv, iv);
  344. return 0;
  345. }
  346. static int crypt_iv_benbi_ctr(struct crypt_config *cc, struct dm_target *ti,
  347. const char *opts)
  348. {
  349. unsigned bs = crypto_ablkcipher_blocksize(any_tfm(cc));
  350. int log = ilog2(bs);
  351. /* we need to calculate how far we must shift the sector count
  352. * to get the cipher block count, we use this shift in _gen */
  353. if (1 << log != bs) {
  354. ti->error = "cypher blocksize is not a power of 2";
  355. return -EINVAL;
  356. }
  357. if (log > 9) {
  358. ti->error = "cypher blocksize is > 512";
  359. return -EINVAL;
  360. }
  361. cc->iv_gen_private.benbi.shift = 9 - log;
  362. return 0;
  363. }
  364. static void crypt_iv_benbi_dtr(struct crypt_config *cc)
  365. {
  366. }
  367. static int crypt_iv_benbi_gen(struct crypt_config *cc, u8 *iv,
  368. struct dm_crypt_request *dmreq)
  369. {
  370. __be64 val;
  371. memset(iv, 0, cc->iv_size - sizeof(u64)); /* rest is cleared below */
  372. val = cpu_to_be64(((u64)dmreq->iv_sector << cc->iv_gen_private.benbi.shift) + 1);
  373. put_unaligned(val, (__be64 *)(iv + cc->iv_size - sizeof(u64)));
  374. return 0;
  375. }
  376. static int crypt_iv_null_gen(struct crypt_config *cc, u8 *iv,
  377. struct dm_crypt_request *dmreq)
  378. {
  379. memset(iv, 0, cc->iv_size);
  380. return 0;
  381. }
  382. static void crypt_iv_lmk_dtr(struct crypt_config *cc)
  383. {
  384. struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
  385. if (lmk->hash_tfm && !IS_ERR(lmk->hash_tfm))
  386. crypto_free_shash(lmk->hash_tfm);
  387. lmk->hash_tfm = NULL;
  388. kzfree(lmk->seed);
  389. lmk->seed = NULL;
  390. }
  391. static int crypt_iv_lmk_ctr(struct crypt_config *cc, struct dm_target *ti,
  392. const char *opts)
  393. {
  394. struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
  395. lmk->hash_tfm = crypto_alloc_shash("md5", 0, 0);
  396. if (IS_ERR(lmk->hash_tfm)) {
  397. ti->error = "Error initializing LMK hash";
  398. return PTR_ERR(lmk->hash_tfm);
  399. }
  400. /* No seed in LMK version 2 */
  401. if (cc->key_parts == cc->tfms_count) {
  402. lmk->seed = NULL;
  403. return 0;
  404. }
  405. lmk->seed = kzalloc(LMK_SEED_SIZE, GFP_KERNEL);
  406. if (!lmk->seed) {
  407. crypt_iv_lmk_dtr(cc);
  408. ti->error = "Error kmallocing seed storage in LMK";
  409. return -ENOMEM;
  410. }
  411. return 0;
  412. }
  413. static int crypt_iv_lmk_init(struct crypt_config *cc)
  414. {
  415. struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
  416. int subkey_size = cc->key_size / cc->key_parts;
  417. /* LMK seed is on the position of LMK_KEYS + 1 key */
  418. if (lmk->seed)
  419. memcpy(lmk->seed, cc->key + (cc->tfms_count * subkey_size),
  420. crypto_shash_digestsize(lmk->hash_tfm));
  421. return 0;
  422. }
  423. static int crypt_iv_lmk_wipe(struct crypt_config *cc)
  424. {
  425. struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
  426. if (lmk->seed)
  427. memset(lmk->seed, 0, LMK_SEED_SIZE);
  428. return 0;
  429. }
  430. static int crypt_iv_lmk_one(struct crypt_config *cc, u8 *iv,
  431. struct dm_crypt_request *dmreq,
  432. u8 *data)
  433. {
  434. struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
  435. struct {
  436. struct shash_desc desc;
  437. char ctx[crypto_shash_descsize(lmk->hash_tfm)];
  438. } sdesc;
  439. struct md5_state md5state;
  440. __le32 buf[4];
  441. int i, r;
  442. sdesc.desc.tfm = lmk->hash_tfm;
  443. sdesc.desc.flags = CRYPTO_TFM_REQ_MAY_SLEEP;
  444. r = crypto_shash_init(&sdesc.desc);
  445. if (r)
  446. return r;
  447. if (lmk->seed) {
  448. r = crypto_shash_update(&sdesc.desc, lmk->seed, LMK_SEED_SIZE);
  449. if (r)
  450. return r;
  451. }
  452. /* Sector is always 512B, block size 16, add data of blocks 1-31 */
  453. r = crypto_shash_update(&sdesc.desc, data + 16, 16 * 31);
  454. if (r)
  455. return r;
  456. /* Sector is cropped to 56 bits here */
  457. buf[0] = cpu_to_le32(dmreq->iv_sector & 0xFFFFFFFF);
  458. buf[1] = cpu_to_le32((((u64)dmreq->iv_sector >> 32) & 0x00FFFFFF) | 0x80000000);
  459. buf[2] = cpu_to_le32(4024);
  460. buf[3] = 0;
  461. r = crypto_shash_update(&sdesc.desc, (u8 *)buf, sizeof(buf));
  462. if (r)
  463. return r;
  464. /* No MD5 padding here */
  465. r = crypto_shash_export(&sdesc.desc, &md5state);
  466. if (r)
  467. return r;
  468. for (i = 0; i < MD5_HASH_WORDS; i++)
  469. __cpu_to_le32s(&md5state.hash[i]);
  470. memcpy(iv, &md5state.hash, cc->iv_size);
  471. return 0;
  472. }
  473. static int crypt_iv_lmk_gen(struct crypt_config *cc, u8 *iv,
  474. struct dm_crypt_request *dmreq)
  475. {
  476. u8 *src;
  477. int r = 0;
  478. if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
  479. src = kmap_atomic(sg_page(&dmreq->sg_in));
  480. r = crypt_iv_lmk_one(cc, iv, dmreq, src + dmreq->sg_in.offset);
  481. kunmap_atomic(src);
  482. } else
  483. memset(iv, 0, cc->iv_size);
  484. return r;
  485. }
  486. static int crypt_iv_lmk_post(struct crypt_config *cc, u8 *iv,
  487. struct dm_crypt_request *dmreq)
  488. {
  489. u8 *dst;
  490. int r;
  491. if (bio_data_dir(dmreq->ctx->bio_in) == WRITE)
  492. return 0;
  493. dst = kmap_atomic(sg_page(&dmreq->sg_out));
  494. r = crypt_iv_lmk_one(cc, iv, dmreq, dst + dmreq->sg_out.offset);
  495. /* Tweak the first block of plaintext sector */
  496. if (!r)
  497. crypto_xor(dst + dmreq->sg_out.offset, iv, cc->iv_size);
  498. kunmap_atomic(dst);
  499. return r;
  500. }
  501. static struct crypt_iv_operations crypt_iv_plain_ops = {
  502. .generator = crypt_iv_plain_gen
  503. };
  504. static struct crypt_iv_operations crypt_iv_plain64_ops = {
  505. .generator = crypt_iv_plain64_gen
  506. };
  507. static struct crypt_iv_operations crypt_iv_essiv_ops = {
  508. .ctr = crypt_iv_essiv_ctr,
  509. .dtr = crypt_iv_essiv_dtr,
  510. .init = crypt_iv_essiv_init,
  511. .wipe = crypt_iv_essiv_wipe,
  512. .generator = crypt_iv_essiv_gen
  513. };
  514. static struct crypt_iv_operations crypt_iv_benbi_ops = {
  515. .ctr = crypt_iv_benbi_ctr,
  516. .dtr = crypt_iv_benbi_dtr,
  517. .generator = crypt_iv_benbi_gen
  518. };
  519. static struct crypt_iv_operations crypt_iv_null_ops = {
  520. .generator = crypt_iv_null_gen
  521. };
  522. static struct crypt_iv_operations crypt_iv_lmk_ops = {
  523. .ctr = crypt_iv_lmk_ctr,
  524. .dtr = crypt_iv_lmk_dtr,
  525. .init = crypt_iv_lmk_init,
  526. .wipe = crypt_iv_lmk_wipe,
  527. .generator = crypt_iv_lmk_gen,
  528. .post = crypt_iv_lmk_post
  529. };
  530. static void crypt_convert_init(struct crypt_config *cc,
  531. struct convert_context *ctx,
  532. struct bio *bio_out, struct bio *bio_in,
  533. sector_t sector)
  534. {
  535. ctx->bio_in = bio_in;
  536. ctx->bio_out = bio_out;
  537. ctx->offset_in = 0;
  538. ctx->offset_out = 0;
  539. ctx->idx_in = bio_in ? bio_in->bi_idx : 0;
  540. ctx->idx_out = bio_out ? bio_out->bi_idx : 0;
  541. ctx->cc_sector = sector + cc->iv_offset;
  542. init_completion(&ctx->restart);
  543. }
  544. static struct dm_crypt_request *dmreq_of_req(struct crypt_config *cc,
  545. struct ablkcipher_request *req)
  546. {
  547. return (struct dm_crypt_request *)((char *)req + cc->dmreq_start);
  548. }
  549. static struct ablkcipher_request *req_of_dmreq(struct crypt_config *cc,
  550. struct dm_crypt_request *dmreq)
  551. {
  552. return (struct ablkcipher_request *)((char *)dmreq - cc->dmreq_start);
  553. }
  554. static u8 *iv_of_dmreq(struct crypt_config *cc,
  555. struct dm_crypt_request *dmreq)
  556. {
  557. return (u8 *)ALIGN((unsigned long)(dmreq + 1),
  558. crypto_ablkcipher_alignmask(any_tfm(cc)) + 1);
  559. }
  560. static int crypt_convert_block(struct crypt_config *cc,
  561. struct convert_context *ctx,
  562. struct ablkcipher_request *req)
  563. {
  564. struct bio_vec *bv_in = bio_iovec_idx(ctx->bio_in, ctx->idx_in);
  565. struct bio_vec *bv_out = bio_iovec_idx(ctx->bio_out, ctx->idx_out);
  566. struct dm_crypt_request *dmreq;
  567. u8 *iv;
  568. int r;
  569. dmreq = dmreq_of_req(cc, req);
  570. iv = iv_of_dmreq(cc, dmreq);
  571. dmreq->iv_sector = ctx->cc_sector;
  572. dmreq->ctx = ctx;
  573. sg_init_table(&dmreq->sg_in, 1);
  574. sg_set_page(&dmreq->sg_in, bv_in->bv_page, 1 << SECTOR_SHIFT,
  575. bv_in->bv_offset + ctx->offset_in);
  576. sg_init_table(&dmreq->sg_out, 1);
  577. sg_set_page(&dmreq->sg_out, bv_out->bv_page, 1 << SECTOR_SHIFT,
  578. bv_out->bv_offset + ctx->offset_out);
  579. ctx->offset_in += 1 << SECTOR_SHIFT;
  580. if (ctx->offset_in >= bv_in->bv_len) {
  581. ctx->offset_in = 0;
  582. ctx->idx_in++;
  583. }
  584. ctx->offset_out += 1 << SECTOR_SHIFT;
  585. if (ctx->offset_out >= bv_out->bv_len) {
  586. ctx->offset_out = 0;
  587. ctx->idx_out++;
  588. }
  589. if (cc->iv_gen_ops) {
  590. r = cc->iv_gen_ops->generator(cc, iv, dmreq);
  591. if (r < 0)
  592. return r;
  593. }
  594. ablkcipher_request_set_crypt(req, &dmreq->sg_in, &dmreq->sg_out,
  595. 1 << SECTOR_SHIFT, iv);
  596. if (bio_data_dir(ctx->bio_in) == WRITE)
  597. r = crypto_ablkcipher_encrypt(req);
  598. else
  599. r = crypto_ablkcipher_decrypt(req);
  600. if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
  601. r = cc->iv_gen_ops->post(cc, iv, dmreq);
  602. return r;
  603. }
  604. static void kcryptd_async_done(struct crypto_async_request *async_req,
  605. int error);
  606. static void crypt_alloc_req(struct crypt_config *cc,
  607. struct convert_context *ctx)
  608. {
  609. struct crypt_cpu *this_cc = this_crypt_config(cc);
  610. unsigned key_index = ctx->cc_sector & (cc->tfms_count - 1);
  611. if (!this_cc->req)
  612. this_cc->req = mempool_alloc(cc->req_pool, GFP_NOIO);
  613. ablkcipher_request_set_tfm(this_cc->req, cc->tfms[key_index]);
  614. ablkcipher_request_set_callback(this_cc->req,
  615. CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
  616. kcryptd_async_done, dmreq_of_req(cc, this_cc->req));
  617. }
  618. /*
  619. * Encrypt / decrypt data from one bio to another one (can be the same one)
  620. */
  621. static int crypt_convert(struct crypt_config *cc,
  622. struct convert_context *ctx)
  623. {
  624. struct crypt_cpu *this_cc = this_crypt_config(cc);
  625. int r;
  626. atomic_set(&ctx->cc_pending, 1);
  627. while(ctx->idx_in < ctx->bio_in->bi_vcnt &&
  628. ctx->idx_out < ctx->bio_out->bi_vcnt) {
  629. crypt_alloc_req(cc, ctx);
  630. atomic_inc(&ctx->cc_pending);
  631. r = crypt_convert_block(cc, ctx, this_cc->req);
  632. switch (r) {
  633. /* async */
  634. case -EBUSY:
  635. wait_for_completion(&ctx->restart);
  636. INIT_COMPLETION(ctx->restart);
  637. /* fall through*/
  638. case -EINPROGRESS:
  639. this_cc->req = NULL;
  640. ctx->cc_sector++;
  641. continue;
  642. /* sync */
  643. case 0:
  644. atomic_dec(&ctx->cc_pending);
  645. ctx->cc_sector++;
  646. cond_resched();
  647. continue;
  648. /* error */
  649. default:
  650. atomic_dec(&ctx->cc_pending);
  651. return r;
  652. }
  653. }
  654. return 0;
  655. }
  656. /*
  657. * Generate a new unfragmented bio with the given size
  658. * This should never violate the device limitations
  659. * May return a smaller bio when running out of pages, indicated by
  660. * *out_of_pages set to 1.
  661. */
  662. static struct bio *crypt_alloc_buffer(struct dm_crypt_io *io, unsigned size,
  663. unsigned *out_of_pages)
  664. {
  665. struct crypt_config *cc = io->cc;
  666. struct bio *clone;
  667. unsigned int nr_iovecs = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
  668. gfp_t gfp_mask = GFP_NOIO | __GFP_HIGHMEM;
  669. unsigned i, len;
  670. struct page *page;
  671. clone = bio_alloc_bioset(GFP_NOIO, nr_iovecs, cc->bs);
  672. if (!clone)
  673. return NULL;
  674. clone_init(io, clone);
  675. *out_of_pages = 0;
  676. for (i = 0; i < nr_iovecs; i++) {
  677. page = mempool_alloc(cc->page_pool, gfp_mask);
  678. if (!page) {
  679. *out_of_pages = 1;
  680. break;
  681. }
  682. /*
  683. * If additional pages cannot be allocated without waiting,
  684. * return a partially-allocated bio. The caller will then try
  685. * to allocate more bios while submitting this partial bio.
  686. */
  687. gfp_mask = (gfp_mask | __GFP_NOWARN) & ~__GFP_WAIT;
  688. len = (size > PAGE_SIZE) ? PAGE_SIZE : size;
  689. if (!bio_add_page(clone, page, len, 0)) {
  690. mempool_free(page, cc->page_pool);
  691. break;
  692. }
  693. size -= len;
  694. }
  695. if (!clone->bi_size) {
  696. bio_put(clone);
  697. return NULL;
  698. }
  699. return clone;
  700. }
  701. static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone)
  702. {
  703. unsigned int i;
  704. struct bio_vec *bv;
  705. bio_for_each_segment_all(bv, clone, i) {
  706. BUG_ON(!bv->bv_page);
  707. mempool_free(bv->bv_page, cc->page_pool);
  708. bv->bv_page = NULL;
  709. }
  710. }
  711. static struct dm_crypt_io *crypt_io_alloc(struct crypt_config *cc,
  712. struct bio *bio, sector_t sector)
  713. {
  714. struct dm_crypt_io *io;
  715. io = mempool_alloc(cc->io_pool, GFP_NOIO);
  716. io->cc = cc;
  717. io->base_bio = bio;
  718. io->sector = sector;
  719. io->error = 0;
  720. io->base_io = NULL;
  721. atomic_set(&io->io_pending, 0);
  722. return io;
  723. }
  724. static void crypt_inc_pending(struct dm_crypt_io *io)
  725. {
  726. atomic_inc(&io->io_pending);
  727. }
  728. /*
  729. * One of the bios was finished. Check for completion of
  730. * the whole request and correctly clean up the buffer.
  731. * If base_io is set, wait for the last fragment to complete.
  732. */
  733. static void crypt_dec_pending(struct dm_crypt_io *io)
  734. {
  735. struct crypt_config *cc = io->cc;
  736. struct bio *base_bio = io->base_bio;
  737. struct dm_crypt_io *base_io = io->base_io;
  738. int error = io->error;
  739. if (!atomic_dec_and_test(&io->io_pending))
  740. return;
  741. mempool_free(io, cc->io_pool);
  742. if (likely(!base_io))
  743. bio_endio(base_bio, error);
  744. else {
  745. if (error && !base_io->error)
  746. base_io->error = error;
  747. crypt_dec_pending(base_io);
  748. }
  749. }
  750. /*
  751. * kcryptd/kcryptd_io:
  752. *
  753. * Needed because it would be very unwise to do decryption in an
  754. * interrupt context.
  755. *
  756. * kcryptd performs the actual encryption or decryption.
  757. *
  758. * kcryptd_io performs the IO submission.
  759. *
  760. * They must be separated as otherwise the final stages could be
  761. * starved by new requests which can block in the first stages due
  762. * to memory allocation.
  763. *
  764. * The work is done per CPU global for all dm-crypt instances.
  765. * They should not depend on each other and do not block.
  766. */
  767. static void crypt_endio(struct bio *clone, int error)
  768. {
  769. struct dm_crypt_io *io = clone->bi_private;
  770. struct crypt_config *cc = io->cc;
  771. unsigned rw = bio_data_dir(clone);
  772. if (unlikely(!bio_flagged(clone, BIO_UPTODATE) && !error))
  773. error = -EIO;
  774. /*
  775. * free the processed pages
  776. */
  777. if (rw == WRITE)
  778. crypt_free_buffer_pages(cc, clone);
  779. bio_put(clone);
  780. if (rw == READ && !error) {
  781. kcryptd_queue_crypt(io);
  782. return;
  783. }
  784. if (unlikely(error))
  785. io->error = error;
  786. crypt_dec_pending(io);
  787. }
  788. static void clone_init(struct dm_crypt_io *io, struct bio *clone)
  789. {
  790. struct crypt_config *cc = io->cc;
  791. clone->bi_private = io;
  792. clone->bi_end_io = crypt_endio;
  793. clone->bi_bdev = cc->dev->bdev;
  794. clone->bi_rw = io->base_bio->bi_rw;
  795. }
  796. static int kcryptd_io_read(struct dm_crypt_io *io, gfp_t gfp)
  797. {
  798. struct crypt_config *cc = io->cc;
  799. struct bio *base_bio = io->base_bio;
  800. struct bio *clone;
  801. /*
  802. * The block layer might modify the bvec array, so always
  803. * copy the required bvecs because we need the original
  804. * one in order to decrypt the whole bio data *afterwards*.
  805. */
  806. clone = bio_clone_bioset(base_bio, gfp, cc->bs);
  807. if (!clone)
  808. return 1;
  809. crypt_inc_pending(io);
  810. clone_init(io, clone);
  811. clone->bi_sector = cc->start + io->sector;
  812. generic_make_request(clone);
  813. return 0;
  814. }
  815. static void kcryptd_io_write(struct dm_crypt_io *io)
  816. {
  817. struct bio *clone = io->ctx.bio_out;
  818. generic_make_request(clone);
  819. }
  820. static void kcryptd_io(struct work_struct *work)
  821. {
  822. struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
  823. if (bio_data_dir(io->base_bio) == READ) {
  824. crypt_inc_pending(io);
  825. if (kcryptd_io_read(io, GFP_NOIO))
  826. io->error = -ENOMEM;
  827. crypt_dec_pending(io);
  828. } else
  829. kcryptd_io_write(io);
  830. }
  831. static void kcryptd_queue_io(struct dm_crypt_io *io)
  832. {
  833. struct crypt_config *cc = io->cc;
  834. INIT_WORK(&io->work, kcryptd_io);
  835. queue_work(cc->io_queue, &io->work);
  836. }
  837. static void kcryptd_crypt_write_io_submit(struct dm_crypt_io *io, int async)
  838. {
  839. struct bio *clone = io->ctx.bio_out;
  840. struct crypt_config *cc = io->cc;
  841. if (unlikely(io->error < 0)) {
  842. crypt_free_buffer_pages(cc, clone);
  843. bio_put(clone);
  844. crypt_dec_pending(io);
  845. return;
  846. }
  847. /* crypt_convert should have filled the clone bio */
  848. BUG_ON(io->ctx.idx_out < clone->bi_vcnt);
  849. clone->bi_sector = cc->start + io->sector;
  850. if (async)
  851. kcryptd_queue_io(io);
  852. else
  853. generic_make_request(clone);
  854. }
  855. static void kcryptd_crypt_write_convert(struct dm_crypt_io *io)
  856. {
  857. struct crypt_config *cc = io->cc;
  858. struct bio *clone;
  859. struct dm_crypt_io *new_io;
  860. int crypt_finished;
  861. unsigned out_of_pages = 0;
  862. unsigned remaining = io->base_bio->bi_size;
  863. sector_t sector = io->sector;
  864. int r;
  865. /*
  866. * Prevent io from disappearing until this function completes.
  867. */
  868. crypt_inc_pending(io);
  869. crypt_convert_init(cc, &io->ctx, NULL, io->base_bio, sector);
  870. /*
  871. * The allocated buffers can be smaller than the whole bio,
  872. * so repeat the whole process until all the data can be handled.
  873. */
  874. while (remaining) {
  875. clone = crypt_alloc_buffer(io, remaining, &out_of_pages);
  876. if (unlikely(!clone)) {
  877. io->error = -ENOMEM;
  878. break;
  879. }
  880. io->ctx.bio_out = clone;
  881. io->ctx.idx_out = 0;
  882. remaining -= clone->bi_size;
  883. sector += bio_sectors(clone);
  884. crypt_inc_pending(io);
  885. r = crypt_convert(cc, &io->ctx);
  886. if (r < 0)
  887. io->error = -EIO;
  888. crypt_finished = atomic_dec_and_test(&io->ctx.cc_pending);
  889. /* Encryption was already finished, submit io now */
  890. if (crypt_finished) {
  891. kcryptd_crypt_write_io_submit(io, 0);
  892. /*
  893. * If there was an error, do not try next fragments.
  894. * For async, error is processed in async handler.
  895. */
  896. if (unlikely(r < 0))
  897. break;
  898. io->sector = sector;
  899. }
  900. /*
  901. * Out of memory -> run queues
  902. * But don't wait if split was due to the io size restriction
  903. */
  904. if (unlikely(out_of_pages))
  905. congestion_wait(BLK_RW_ASYNC, HZ/100);
  906. /*
  907. * With async crypto it is unsafe to share the crypto context
  908. * between fragments, so switch to a new dm_crypt_io structure.
  909. */
  910. if (unlikely(!crypt_finished && remaining)) {
  911. new_io = crypt_io_alloc(io->cc, io->base_bio,
  912. sector);
  913. crypt_inc_pending(new_io);
  914. crypt_convert_init(cc, &new_io->ctx, NULL,
  915. io->base_bio, sector);
  916. new_io->ctx.idx_in = io->ctx.idx_in;
  917. new_io->ctx.offset_in = io->ctx.offset_in;
  918. /*
  919. * Fragments after the first use the base_io
  920. * pending count.
  921. */
  922. if (!io->base_io)
  923. new_io->base_io = io;
  924. else {
  925. new_io->base_io = io->base_io;
  926. crypt_inc_pending(io->base_io);
  927. crypt_dec_pending(io);
  928. }
  929. io = new_io;
  930. }
  931. }
  932. crypt_dec_pending(io);
  933. }
  934. static void kcryptd_crypt_read_done(struct dm_crypt_io *io)
  935. {
  936. crypt_dec_pending(io);
  937. }
  938. static void kcryptd_crypt_read_convert(struct dm_crypt_io *io)
  939. {
  940. struct crypt_config *cc = io->cc;
  941. int r = 0;
  942. crypt_inc_pending(io);
  943. crypt_convert_init(cc, &io->ctx, io->base_bio, io->base_bio,
  944. io->sector);
  945. r = crypt_convert(cc, &io->ctx);
  946. if (r < 0)
  947. io->error = -EIO;
  948. if (atomic_dec_and_test(&io->ctx.cc_pending))
  949. kcryptd_crypt_read_done(io);
  950. crypt_dec_pending(io);
  951. }
  952. static void kcryptd_async_done(struct crypto_async_request *async_req,
  953. int error)
  954. {
  955. struct dm_crypt_request *dmreq = async_req->data;
  956. struct convert_context *ctx = dmreq->ctx;
  957. struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
  958. struct crypt_config *cc = io->cc;
  959. if (error == -EINPROGRESS) {
  960. complete(&ctx->restart);
  961. return;
  962. }
  963. if (!error && cc->iv_gen_ops && cc->iv_gen_ops->post)
  964. error = cc->iv_gen_ops->post(cc, iv_of_dmreq(cc, dmreq), dmreq);
  965. if (error < 0)
  966. io->error = -EIO;
  967. mempool_free(req_of_dmreq(cc, dmreq), cc->req_pool);
  968. if (!atomic_dec_and_test(&ctx->cc_pending))
  969. return;
  970. if (bio_data_dir(io->base_bio) == READ)
  971. kcryptd_crypt_read_done(io);
  972. else
  973. kcryptd_crypt_write_io_submit(io, 1);
  974. }
  975. static void kcryptd_crypt(struct work_struct *work)
  976. {
  977. struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
  978. if (bio_data_dir(io->base_bio) == READ)
  979. kcryptd_crypt_read_convert(io);
  980. else
  981. kcryptd_crypt_write_convert(io);
  982. }
  983. static void kcryptd_queue_crypt(struct dm_crypt_io *io)
  984. {
  985. struct crypt_config *cc = io->cc;
  986. INIT_WORK(&io->work, kcryptd_crypt);
  987. queue_work(cc->crypt_queue, &io->work);
  988. }
  989. /*
  990. * Decode key from its hex representation
  991. */
  992. static int crypt_decode_key(u8 *key, char *hex, unsigned int size)
  993. {
  994. char buffer[3];
  995. unsigned int i;
  996. buffer[2] = '\0';
  997. for (i = 0; i < size; i++) {
  998. buffer[0] = *hex++;
  999. buffer[1] = *hex++;
  1000. if (kstrtou8(buffer, 16, &key[i]))
  1001. return -EINVAL;
  1002. }
  1003. if (*hex != '\0')
  1004. return -EINVAL;
  1005. return 0;
  1006. }
  1007. static void crypt_free_tfms(struct crypt_config *cc)
  1008. {
  1009. unsigned i;
  1010. if (!cc->tfms)
  1011. return;
  1012. for (i = 0; i < cc->tfms_count; i++)
  1013. if (cc->tfms[i] && !IS_ERR(cc->tfms[i])) {
  1014. crypto_free_ablkcipher(cc->tfms[i]);
  1015. cc->tfms[i] = NULL;
  1016. }
  1017. kfree(cc->tfms);
  1018. cc->tfms = NULL;
  1019. }
  1020. static int crypt_alloc_tfms(struct crypt_config *cc, char *ciphermode)
  1021. {
  1022. unsigned i;
  1023. int err;
  1024. cc->tfms = kmalloc(cc->tfms_count * sizeof(struct crypto_ablkcipher *),
  1025. GFP_KERNEL);
  1026. if (!cc->tfms)
  1027. return -ENOMEM;
  1028. for (i = 0; i < cc->tfms_count; i++) {
  1029. cc->tfms[i] = crypto_alloc_ablkcipher(ciphermode, 0, 0);
  1030. if (IS_ERR(cc->tfms[i])) {
  1031. err = PTR_ERR(cc->tfms[i]);
  1032. crypt_free_tfms(cc);
  1033. return err;
  1034. }
  1035. }
  1036. return 0;
  1037. }
  1038. static int crypt_setkey_allcpus(struct crypt_config *cc)
  1039. {
  1040. unsigned subkey_size;
  1041. int err = 0, i, r;
  1042. /* Ignore extra keys (which are used for IV etc) */
  1043. subkey_size = (cc->key_size - cc->key_extra_size) >> ilog2(cc->tfms_count);
  1044. for (i = 0; i < cc->tfms_count; i++) {
  1045. r = crypto_ablkcipher_setkey(cc->tfms[i],
  1046. cc->key + (i * subkey_size),
  1047. subkey_size);
  1048. if (r)
  1049. err = r;
  1050. }
  1051. return err;
  1052. }
  1053. static int crypt_set_key(struct crypt_config *cc, char *key)
  1054. {
  1055. int r = -EINVAL;
  1056. int key_string_len = strlen(key);
  1057. /* The key size may not be changed. */
  1058. if (cc->key_size != (key_string_len >> 1))
  1059. goto out;
  1060. /* Hyphen (which gives a key_size of zero) means there is no key. */
  1061. if (!cc->key_size && strcmp(key, "-"))
  1062. goto out;
  1063. if (cc->key_size && crypt_decode_key(cc->key, key, cc->key_size) < 0)
  1064. goto out;
  1065. set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
  1066. r = crypt_setkey_allcpus(cc);
  1067. out:
  1068. /* Hex key string not needed after here, so wipe it. */
  1069. memset(key, '0', key_string_len);
  1070. return r;
  1071. }
  1072. static int crypt_wipe_key(struct crypt_config *cc)
  1073. {
  1074. clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
  1075. memset(&cc->key, 0, cc->key_size * sizeof(u8));
  1076. return crypt_setkey_allcpus(cc);
  1077. }
  1078. static void crypt_dtr(struct dm_target *ti)
  1079. {
  1080. struct crypt_config *cc = ti->private;
  1081. struct crypt_cpu *cpu_cc;
  1082. int cpu;
  1083. ti->private = NULL;
  1084. if (!cc)
  1085. return;
  1086. if (cc->io_queue)
  1087. destroy_workqueue(cc->io_queue);
  1088. if (cc->crypt_queue)
  1089. destroy_workqueue(cc->crypt_queue);
  1090. if (cc->cpu)
  1091. for_each_possible_cpu(cpu) {
  1092. cpu_cc = per_cpu_ptr(cc->cpu, cpu);
  1093. if (cpu_cc->req)
  1094. mempool_free(cpu_cc->req, cc->req_pool);
  1095. }
  1096. crypt_free_tfms(cc);
  1097. if (cc->bs)
  1098. bioset_free(cc->bs);
  1099. if (cc->page_pool)
  1100. mempool_destroy(cc->page_pool);
  1101. if (cc->req_pool)
  1102. mempool_destroy(cc->req_pool);
  1103. if (cc->io_pool)
  1104. mempool_destroy(cc->io_pool);
  1105. if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
  1106. cc->iv_gen_ops->dtr(cc);
  1107. if (cc->dev)
  1108. dm_put_device(ti, cc->dev);
  1109. if (cc->cpu)
  1110. free_percpu(cc->cpu);
  1111. kzfree(cc->cipher);
  1112. kzfree(cc->cipher_string);
  1113. /* Must zero key material before freeing */
  1114. kzfree(cc);
  1115. }
  1116. static int crypt_ctr_cipher(struct dm_target *ti,
  1117. char *cipher_in, char *key)
  1118. {
  1119. struct crypt_config *cc = ti->private;
  1120. char *tmp, *cipher, *chainmode, *ivmode, *ivopts, *keycount;
  1121. char *cipher_api = NULL;
  1122. int ret = -EINVAL;
  1123. char dummy;
  1124. /* Convert to crypto api definition? */
  1125. if (strchr(cipher_in, '(')) {
  1126. ti->error = "Bad cipher specification";
  1127. return -EINVAL;
  1128. }
  1129. cc->cipher_string = kstrdup(cipher_in, GFP_KERNEL);
  1130. if (!cc->cipher_string)
  1131. goto bad_mem;
  1132. /*
  1133. * Legacy dm-crypt cipher specification
  1134. * cipher[:keycount]-mode-iv:ivopts
  1135. */
  1136. tmp = cipher_in;
  1137. keycount = strsep(&tmp, "-");
  1138. cipher = strsep(&keycount, ":");
  1139. if (!keycount)
  1140. cc->tfms_count = 1;
  1141. else if (sscanf(keycount, "%u%c", &cc->tfms_count, &dummy) != 1 ||
  1142. !is_power_of_2(cc->tfms_count)) {
  1143. ti->error = "Bad cipher key count specification";
  1144. return -EINVAL;
  1145. }
  1146. cc->key_parts = cc->tfms_count;
  1147. cc->key_extra_size = 0;
  1148. cc->cipher = kstrdup(cipher, GFP_KERNEL);
  1149. if (!cc->cipher)
  1150. goto bad_mem;
  1151. chainmode = strsep(&tmp, "-");
  1152. ivopts = strsep(&tmp, "-");
  1153. ivmode = strsep(&ivopts, ":");
  1154. if (tmp)
  1155. DMWARN("Ignoring unexpected additional cipher options");
  1156. cc->cpu = __alloc_percpu(sizeof(*(cc->cpu)),
  1157. __alignof__(struct crypt_cpu));
  1158. if (!cc->cpu) {
  1159. ti->error = "Cannot allocate per cpu state";
  1160. goto bad_mem;
  1161. }
  1162. /*
  1163. * For compatibility with the original dm-crypt mapping format, if
  1164. * only the cipher name is supplied, use cbc-plain.
  1165. */
  1166. if (!chainmode || (!strcmp(chainmode, "plain") && !ivmode)) {
  1167. chainmode = "cbc";
  1168. ivmode = "plain";
  1169. }
  1170. if (strcmp(chainmode, "ecb") && !ivmode) {
  1171. ti->error = "IV mechanism required";
  1172. return -EINVAL;
  1173. }
  1174. cipher_api = kmalloc(CRYPTO_MAX_ALG_NAME, GFP_KERNEL);
  1175. if (!cipher_api)
  1176. goto bad_mem;
  1177. ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
  1178. "%s(%s)", chainmode, cipher);
  1179. if (ret < 0) {
  1180. kfree(cipher_api);
  1181. goto bad_mem;
  1182. }
  1183. /* Allocate cipher */
  1184. ret = crypt_alloc_tfms(cc, cipher_api);
  1185. if (ret < 0) {
  1186. ti->error = "Error allocating crypto tfm";
  1187. goto bad;
  1188. }
  1189. /* Initialize IV */
  1190. cc->iv_size = crypto_ablkcipher_ivsize(any_tfm(cc));
  1191. if (cc->iv_size)
  1192. /* at least a 64 bit sector number should fit in our buffer */
  1193. cc->iv_size = max(cc->iv_size,
  1194. (unsigned int)(sizeof(u64) / sizeof(u8)));
  1195. else if (ivmode) {
  1196. DMWARN("Selected cipher does not support IVs");
  1197. ivmode = NULL;
  1198. }
  1199. /* Choose ivmode, see comments at iv code. */
  1200. if (ivmode == NULL)
  1201. cc->iv_gen_ops = NULL;
  1202. else if (strcmp(ivmode, "plain") == 0)
  1203. cc->iv_gen_ops = &crypt_iv_plain_ops;
  1204. else if (strcmp(ivmode, "plain64") == 0)
  1205. cc->iv_gen_ops = &crypt_iv_plain64_ops;
  1206. else if (strcmp(ivmode, "essiv") == 0)
  1207. cc->iv_gen_ops = &crypt_iv_essiv_ops;
  1208. else if (strcmp(ivmode, "benbi") == 0)
  1209. cc->iv_gen_ops = &crypt_iv_benbi_ops;
  1210. else if (strcmp(ivmode, "null") == 0)
  1211. cc->iv_gen_ops = &crypt_iv_null_ops;
  1212. else if (strcmp(ivmode, "lmk") == 0) {
  1213. cc->iv_gen_ops = &crypt_iv_lmk_ops;
  1214. /* Version 2 and 3 is recognised according
  1215. * to length of provided multi-key string.
  1216. * If present (version 3), last key is used as IV seed.
  1217. */
  1218. if (cc->key_size % cc->key_parts) {
  1219. cc->key_parts++;
  1220. cc->key_extra_size = cc->key_size / cc->key_parts;
  1221. }
  1222. } else {
  1223. ret = -EINVAL;
  1224. ti->error = "Invalid IV mode";
  1225. goto bad;
  1226. }
  1227. /* Initialize and set key */
  1228. ret = crypt_set_key(cc, key);
  1229. if (ret < 0) {
  1230. ti->error = "Error decoding and setting key";
  1231. goto bad;
  1232. }
  1233. /* Allocate IV */
  1234. if (cc->iv_gen_ops && cc->iv_gen_ops->ctr) {
  1235. ret = cc->iv_gen_ops->ctr(cc, ti, ivopts);
  1236. if (ret < 0) {
  1237. ti->error = "Error creating IV";
  1238. goto bad;
  1239. }
  1240. }
  1241. /* Initialize IV (set keys for ESSIV etc) */
  1242. if (cc->iv_gen_ops && cc->iv_gen_ops->init) {
  1243. ret = cc->iv_gen_ops->init(cc);
  1244. if (ret < 0) {
  1245. ti->error = "Error initialising IV";
  1246. goto bad;
  1247. }
  1248. }
  1249. ret = 0;
  1250. bad:
  1251. kfree(cipher_api);
  1252. return ret;
  1253. bad_mem:
  1254. ti->error = "Cannot allocate cipher strings";
  1255. return -ENOMEM;
  1256. }
  1257. /*
  1258. * Construct an encryption mapping:
  1259. * <cipher> <key> <iv_offset> <dev_path> <start>
  1260. */
  1261. static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
  1262. {
  1263. struct crypt_config *cc;
  1264. unsigned int key_size, opt_params;
  1265. unsigned long long tmpll;
  1266. int ret;
  1267. struct dm_arg_set as;
  1268. const char *opt_string;
  1269. char dummy;
  1270. static struct dm_arg _args[] = {
  1271. {0, 1, "Invalid number of feature args"},
  1272. };
  1273. if (argc < 5) {
  1274. ti->error = "Not enough arguments";
  1275. return -EINVAL;
  1276. }
  1277. key_size = strlen(argv[1]) >> 1;
  1278. cc = kzalloc(sizeof(*cc) + key_size * sizeof(u8), GFP_KERNEL);
  1279. if (!cc) {
  1280. ti->error = "Cannot allocate encryption context";
  1281. return -ENOMEM;
  1282. }
  1283. cc->key_size = key_size;
  1284. ti->private = cc;
  1285. ret = crypt_ctr_cipher(ti, argv[0], argv[1]);
  1286. if (ret < 0)
  1287. goto bad;
  1288. ret = -ENOMEM;
  1289. cc->io_pool = mempool_create_slab_pool(MIN_IOS, _crypt_io_pool);
  1290. if (!cc->io_pool) {
  1291. ti->error = "Cannot allocate crypt io mempool";
  1292. goto bad;
  1293. }
  1294. cc->dmreq_start = sizeof(struct ablkcipher_request);
  1295. cc->dmreq_start += crypto_ablkcipher_reqsize(any_tfm(cc));
  1296. cc->dmreq_start = ALIGN(cc->dmreq_start, crypto_tfm_ctx_alignment());
  1297. cc->dmreq_start += crypto_ablkcipher_alignmask(any_tfm(cc)) &
  1298. ~(crypto_tfm_ctx_alignment() - 1);
  1299. cc->req_pool = mempool_create_kmalloc_pool(MIN_IOS, cc->dmreq_start +
  1300. sizeof(struct dm_crypt_request) + cc->iv_size);
  1301. if (!cc->req_pool) {
  1302. ti->error = "Cannot allocate crypt request mempool";
  1303. goto bad;
  1304. }
  1305. cc->page_pool = mempool_create_page_pool(MIN_POOL_PAGES, 0);
  1306. if (!cc->page_pool) {
  1307. ti->error = "Cannot allocate page mempool";
  1308. goto bad;
  1309. }
  1310. cc->bs = bioset_create(MIN_IOS, 0);
  1311. if (!cc->bs) {
  1312. ti->error = "Cannot allocate crypt bioset";
  1313. goto bad;
  1314. }
  1315. ret = -EINVAL;
  1316. if (sscanf(argv[2], "%llu%c", &tmpll, &dummy) != 1) {
  1317. ti->error = "Invalid iv_offset sector";
  1318. goto bad;
  1319. }
  1320. cc->iv_offset = tmpll;
  1321. if (dm_get_device(ti, argv[3], dm_table_get_mode(ti->table), &cc->dev)) {
  1322. ti->error = "Device lookup failed";
  1323. goto bad;
  1324. }
  1325. if (sscanf(argv[4], "%llu%c", &tmpll, &dummy) != 1) {
  1326. ti->error = "Invalid device sector";
  1327. goto bad;
  1328. }
  1329. cc->start = tmpll;
  1330. argv += 5;
  1331. argc -= 5;
  1332. /* Optional parameters */
  1333. if (argc) {
  1334. as.argc = argc;
  1335. as.argv = argv;
  1336. ret = dm_read_arg_group(_args, &as, &opt_params, &ti->error);
  1337. if (ret)
  1338. goto bad;
  1339. opt_string = dm_shift_arg(&as);
  1340. if (opt_params == 1 && opt_string &&
  1341. !strcasecmp(opt_string, "allow_discards"))
  1342. ti->num_discard_bios = 1;
  1343. else if (opt_params) {
  1344. ret = -EINVAL;
  1345. ti->error = "Invalid feature arguments";
  1346. goto bad;
  1347. }
  1348. }
  1349. ret = -ENOMEM;
  1350. cc->io_queue = alloc_workqueue("kcryptd_io", WQ_MEM_RECLAIM, 1);
  1351. if (!cc->io_queue) {
  1352. ti->error = "Couldn't create kcryptd io queue";
  1353. goto bad;
  1354. }
  1355. cc->crypt_queue = alloc_workqueue("kcryptd",
  1356. WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM, 1);
  1357. if (!cc->crypt_queue) {
  1358. ti->error = "Couldn't create kcryptd queue";
  1359. goto bad;
  1360. }
  1361. ti->num_flush_bios = 1;
  1362. ti->discard_zeroes_data_unsupported = true;
  1363. return 0;
  1364. bad:
  1365. crypt_dtr(ti);
  1366. return ret;
  1367. }
  1368. static int crypt_map(struct dm_target *ti, struct bio *bio)
  1369. {
  1370. struct dm_crypt_io *io;
  1371. struct crypt_config *cc = ti->private;
  1372. /*
  1373. * If bio is REQ_FLUSH or REQ_DISCARD, just bypass crypt queues.
  1374. * - for REQ_FLUSH device-mapper core ensures that no IO is in-flight
  1375. * - for REQ_DISCARD caller must use flush if IO ordering matters
  1376. */
  1377. if (unlikely(bio->bi_rw & (REQ_FLUSH | REQ_DISCARD))) {
  1378. bio->bi_bdev = cc->dev->bdev;
  1379. if (bio_sectors(bio))
  1380. bio->bi_sector = cc->start + dm_target_offset(ti, bio->bi_sector);
  1381. return DM_MAPIO_REMAPPED;
  1382. }
  1383. io = crypt_io_alloc(cc, bio, dm_target_offset(ti, bio->bi_sector));
  1384. if (bio_data_dir(io->base_bio) == READ) {
  1385. if (kcryptd_io_read(io, GFP_NOWAIT))
  1386. kcryptd_queue_io(io);
  1387. } else
  1388. kcryptd_queue_crypt(io);
  1389. return DM_MAPIO_SUBMITTED;
  1390. }
  1391. static void crypt_status(struct dm_target *ti, status_type_t type,
  1392. unsigned status_flags, char *result, unsigned maxlen)
  1393. {
  1394. struct crypt_config *cc = ti->private;
  1395. unsigned i, sz = 0;
  1396. switch (type) {
  1397. case STATUSTYPE_INFO:
  1398. result[0] = '\0';
  1399. break;
  1400. case STATUSTYPE_TABLE:
  1401. DMEMIT("%s ", cc->cipher_string);
  1402. if (cc->key_size > 0)
  1403. for (i = 0; i < cc->key_size; i++)
  1404. DMEMIT("%02x", cc->key[i]);
  1405. else
  1406. DMEMIT("-");
  1407. DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
  1408. cc->dev->name, (unsigned long long)cc->start);
  1409. if (ti->num_discard_bios)
  1410. DMEMIT(" 1 allow_discards");
  1411. break;
  1412. }
  1413. }
  1414. static void crypt_postsuspend(struct dm_target *ti)
  1415. {
  1416. struct crypt_config *cc = ti->private;
  1417. set_bit(DM_CRYPT_SUSPENDED, &cc->flags);
  1418. }
  1419. static int crypt_preresume(struct dm_target *ti)
  1420. {
  1421. struct crypt_config *cc = ti->private;
  1422. if (!test_bit(DM_CRYPT_KEY_VALID, &cc->flags)) {
  1423. DMERR("aborting resume - crypt key is not set.");
  1424. return -EAGAIN;
  1425. }
  1426. return 0;
  1427. }
  1428. static void crypt_resume(struct dm_target *ti)
  1429. {
  1430. struct crypt_config *cc = ti->private;
  1431. clear_bit(DM_CRYPT_SUSPENDED, &cc->flags);
  1432. }
  1433. /* Message interface
  1434. * key set <key>
  1435. * key wipe
  1436. */
  1437. static int crypt_message(struct dm_target *ti, unsigned argc, char **argv)
  1438. {
  1439. struct crypt_config *cc = ti->private;
  1440. int ret = -EINVAL;
  1441. if (argc < 2)
  1442. goto error;
  1443. if (!strcasecmp(argv[0], "key")) {
  1444. if (!test_bit(DM_CRYPT_SUSPENDED, &cc->flags)) {
  1445. DMWARN("not suspended during key manipulation.");
  1446. return -EINVAL;
  1447. }
  1448. if (argc == 3 && !strcasecmp(argv[1], "set")) {
  1449. ret = crypt_set_key(cc, argv[2]);
  1450. if (ret)
  1451. return ret;
  1452. if (cc->iv_gen_ops && cc->iv_gen_ops->init)
  1453. ret = cc->iv_gen_ops->init(cc);
  1454. return ret;
  1455. }
  1456. if (argc == 2 && !strcasecmp(argv[1], "wipe")) {
  1457. if (cc->iv_gen_ops && cc->iv_gen_ops->wipe) {
  1458. ret = cc->iv_gen_ops->wipe(cc);
  1459. if (ret)
  1460. return ret;
  1461. }
  1462. return crypt_wipe_key(cc);
  1463. }
  1464. }
  1465. error:
  1466. DMWARN("unrecognised message received.");
  1467. return -EINVAL;
  1468. }
  1469. static int crypt_merge(struct dm_target *ti, struct bvec_merge_data *bvm,
  1470. struct bio_vec *biovec, int max_size)
  1471. {
  1472. struct crypt_config *cc = ti->private;
  1473. struct request_queue *q = bdev_get_queue(cc->dev->bdev);
  1474. if (!q->merge_bvec_fn)
  1475. return max_size;
  1476. bvm->bi_bdev = cc->dev->bdev;
  1477. bvm->bi_sector = cc->start + dm_target_offset(ti, bvm->bi_sector);
  1478. return min(max_size, q->merge_bvec_fn(q, bvm, biovec));
  1479. }
  1480. static int crypt_iterate_devices(struct dm_target *ti,
  1481. iterate_devices_callout_fn fn, void *data)
  1482. {
  1483. struct crypt_config *cc = ti->private;
  1484. return fn(ti, cc->dev, cc->start, ti->len, data);
  1485. }
  1486. static struct target_type crypt_target = {
  1487. .name = "crypt",
  1488. .version = {1, 12, 1},
  1489. .module = THIS_MODULE,
  1490. .ctr = crypt_ctr,
  1491. .dtr = crypt_dtr,
  1492. .map = crypt_map,
  1493. .status = crypt_status,
  1494. .postsuspend = crypt_postsuspend,
  1495. .preresume = crypt_preresume,
  1496. .resume = crypt_resume,
  1497. .message = crypt_message,
  1498. .merge = crypt_merge,
  1499. .iterate_devices = crypt_iterate_devices,
  1500. };
  1501. static int __init dm_crypt_init(void)
  1502. {
  1503. int r;
  1504. _crypt_io_pool = KMEM_CACHE(dm_crypt_io, 0);
  1505. if (!_crypt_io_pool)
  1506. return -ENOMEM;
  1507. r = dm_register_target(&crypt_target);
  1508. if (r < 0) {
  1509. DMERR("register failed %d", r);
  1510. kmem_cache_destroy(_crypt_io_pool);
  1511. }
  1512. return r;
  1513. }
  1514. static void __exit dm_crypt_exit(void)
  1515. {
  1516. dm_unregister_target(&crypt_target);
  1517. kmem_cache_destroy(_crypt_io_pool);
  1518. }
  1519. module_init(dm_crypt_init);
  1520. module_exit(dm_crypt_exit);
  1521. MODULE_AUTHOR("Christophe Saout <christophe@saout.de>");
  1522. MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
  1523. MODULE_LICENSE("GPL");