dm-crypt.c 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255
  1. /*
  2. * Copyright (C) 2003 Jana Saout <jana@saout.de>
  3. * Copyright (C) 2004 Clemens Fruhwirth <clemens@endorphin.org>
  4. * Copyright (C) 2006-2015 Red Hat, Inc. All rights reserved.
  5. * Copyright (C) 2013 Milan Broz <gmazyland@gmail.com>
  6. *
  7. * This file is released under the GPL.
  8. */
  9. #include <linux/completion.h>
  10. #include <linux/err.h>
  11. #include <linux/module.h>
  12. #include <linux/init.h>
  13. #include <linux/kernel.h>
  14. #include <linux/key.h>
  15. #include <linux/bio.h>
  16. #include <linux/blkdev.h>
  17. #include <linux/mempool.h>
  18. #include <linux/slab.h>
  19. #include <linux/crypto.h>
  20. #include <linux/workqueue.h>
  21. #include <linux/kthread.h>
  22. #include <linux/backing-dev.h>
  23. #include <linux/atomic.h>
  24. #include <linux/scatterlist.h>
  25. #include <linux/rbtree.h>
  26. #include <linux/ctype.h>
  27. #include <asm/page.h>
  28. #include <asm/unaligned.h>
  29. #include <crypto/hash.h>
  30. #include <crypto/md5.h>
  31. #include <crypto/algapi.h>
  32. #include <crypto/skcipher.h>
  33. #include <keys/user-type.h>
  34. #include <linux/device-mapper.h>
  35. #define DM_MSG_PREFIX "crypt"
  36. /*
  37. * context holding the current state of a multi-part conversion
  38. */
  39. struct convert_context {
  40. struct completion restart;
  41. struct bio *bio_in;
  42. struct bio *bio_out;
  43. struct bvec_iter iter_in;
  44. struct bvec_iter iter_out;
  45. sector_t cc_sector;
  46. atomic_t cc_pending;
  47. struct skcipher_request *req;
  48. };
  49. /*
  50. * per bio private data
  51. */
  52. struct dm_crypt_io {
  53. struct crypt_config *cc;
  54. struct bio *base_bio;
  55. struct work_struct work;
  56. struct convert_context ctx;
  57. atomic_t io_pending;
  58. int error;
  59. sector_t sector;
  60. struct rb_node rb_node;
  61. } CRYPTO_MINALIGN_ATTR;
  62. struct dm_crypt_request {
  63. struct convert_context *ctx;
  64. struct scatterlist sg_in;
  65. struct scatterlist sg_out;
  66. sector_t iv_sector;
  67. };
  68. struct crypt_config;
  69. struct crypt_iv_operations {
  70. int (*ctr)(struct crypt_config *cc, struct dm_target *ti,
  71. const char *opts);
  72. void (*dtr)(struct crypt_config *cc);
  73. int (*init)(struct crypt_config *cc);
  74. int (*wipe)(struct crypt_config *cc);
  75. int (*generator)(struct crypt_config *cc, u8 *iv,
  76. struct dm_crypt_request *dmreq);
  77. int (*post)(struct crypt_config *cc, u8 *iv,
  78. struct dm_crypt_request *dmreq);
  79. };
  80. struct iv_essiv_private {
  81. struct crypto_ahash *hash_tfm;
  82. u8 *salt;
  83. };
  84. struct iv_benbi_private {
  85. int shift;
  86. };
  87. #define LMK_SEED_SIZE 64 /* hash + 0 */
  88. struct iv_lmk_private {
  89. struct crypto_shash *hash_tfm;
  90. u8 *seed;
  91. };
  92. #define TCW_WHITENING_SIZE 16
  93. struct iv_tcw_private {
  94. struct crypto_shash *crc32_tfm;
  95. u8 *iv_seed;
  96. u8 *whitening;
  97. };
  98. /*
  99. * Crypt: maps a linear range of a block device
  100. * and encrypts / decrypts at the same time.
  101. */
  102. enum flags { DM_CRYPT_SUSPENDED, DM_CRYPT_KEY_VALID,
  103. DM_CRYPT_SAME_CPU, DM_CRYPT_NO_OFFLOAD };
  104. /*
  105. * The fields in here must be read only after initialization.
  106. */
  107. struct crypt_config {
  108. struct dm_dev *dev;
  109. sector_t start;
  110. /*
  111. * pool for per bio private data, crypto requests and
  112. * encryption requeusts/buffer pages
  113. */
  114. mempool_t *req_pool;
  115. mempool_t *page_pool;
  116. struct bio_set *bs;
  117. struct mutex bio_alloc_lock;
  118. struct workqueue_struct *io_queue;
  119. struct workqueue_struct *crypt_queue;
  120. struct task_struct *write_thread;
  121. wait_queue_head_t write_thread_wait;
  122. struct rb_root write_tree;
  123. char *cipher;
  124. char *cipher_string;
  125. char *key_string;
  126. const struct crypt_iv_operations *iv_gen_ops;
  127. union {
  128. struct iv_essiv_private essiv;
  129. struct iv_benbi_private benbi;
  130. struct iv_lmk_private lmk;
  131. struct iv_tcw_private tcw;
  132. } iv_gen_private;
  133. sector_t iv_offset;
  134. unsigned int iv_size;
  135. /* ESSIV: struct crypto_cipher *essiv_tfm */
  136. void *iv_private;
  137. struct crypto_skcipher **tfms;
  138. unsigned tfms_count;
  139. /*
  140. * Layout of each crypto request:
  141. *
  142. * struct skcipher_request
  143. * context
  144. * padding
  145. * struct dm_crypt_request
  146. * padding
  147. * IV
  148. *
  149. * The padding is added so that dm_crypt_request and the IV are
  150. * correctly aligned.
  151. */
  152. unsigned int dmreq_start;
  153. unsigned int per_bio_data_size;
  154. unsigned long flags;
  155. unsigned int key_size;
  156. unsigned int key_parts; /* independent parts in key buffer */
  157. unsigned int key_extra_size; /* additional keys length */
  158. u8 key[0];
  159. };
  160. #define MIN_IOS 64
  161. static void clone_init(struct dm_crypt_io *, struct bio *);
  162. static void kcryptd_queue_crypt(struct dm_crypt_io *io);
  163. static u8 *iv_of_dmreq(struct crypt_config *cc, struct dm_crypt_request *dmreq);
  164. /*
  165. * Use this to access cipher attributes that are the same for each CPU.
  166. */
  167. static struct crypto_skcipher *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. * tcw: Compatible implementation of the block chaining mode used
  205. * by the TrueCrypt device encryption system (prior to version 4.1).
  206. * For more info see: https://gitlab.com/cryptsetup/cryptsetup/wikis/TrueCryptOnDiskFormat
  207. * It operates on full 512 byte sectors and uses CBC
  208. * with an IV derived from initial key and the sector number.
  209. * In addition, whitening value is applied on every sector, whitening
  210. * is calculated from initial key, sector number and mixed using CRC32.
  211. * Note that this encryption scheme is vulnerable to watermarking attacks
  212. * and should be used for old compatible containers access only.
  213. *
  214. * plumb: unimplemented, see:
  215. * http://article.gmane.org/gmane.linux.kernel.device-mapper.dm-crypt/454
  216. */
  217. static int crypt_iv_plain_gen(struct crypt_config *cc, u8 *iv,
  218. struct dm_crypt_request *dmreq)
  219. {
  220. memset(iv, 0, cc->iv_size);
  221. *(__le32 *)iv = cpu_to_le32(dmreq->iv_sector & 0xffffffff);
  222. return 0;
  223. }
  224. static int crypt_iv_plain64_gen(struct crypt_config *cc, u8 *iv,
  225. struct dm_crypt_request *dmreq)
  226. {
  227. memset(iv, 0, cc->iv_size);
  228. *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
  229. return 0;
  230. }
  231. /* Initialise ESSIV - compute salt but no local memory allocations */
  232. static int crypt_iv_essiv_init(struct crypt_config *cc)
  233. {
  234. struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
  235. AHASH_REQUEST_ON_STACK(req, essiv->hash_tfm);
  236. struct scatterlist sg;
  237. struct crypto_cipher *essiv_tfm;
  238. int err;
  239. sg_init_one(&sg, cc->key, cc->key_size);
  240. ahash_request_set_tfm(req, essiv->hash_tfm);
  241. ahash_request_set_callback(req, CRYPTO_TFM_REQ_MAY_SLEEP, NULL, NULL);
  242. ahash_request_set_crypt(req, &sg, essiv->salt, cc->key_size);
  243. err = crypto_ahash_digest(req);
  244. ahash_request_zero(req);
  245. if (err)
  246. return err;
  247. essiv_tfm = cc->iv_private;
  248. err = crypto_cipher_setkey(essiv_tfm, essiv->salt,
  249. crypto_ahash_digestsize(essiv->hash_tfm));
  250. if (err)
  251. return err;
  252. return 0;
  253. }
  254. /* Wipe salt and reset key derived from volume key */
  255. static int crypt_iv_essiv_wipe(struct crypt_config *cc)
  256. {
  257. struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
  258. unsigned salt_size = crypto_ahash_digestsize(essiv->hash_tfm);
  259. struct crypto_cipher *essiv_tfm;
  260. int r, err = 0;
  261. memset(essiv->salt, 0, salt_size);
  262. essiv_tfm = cc->iv_private;
  263. r = crypto_cipher_setkey(essiv_tfm, essiv->salt, salt_size);
  264. if (r)
  265. err = r;
  266. return err;
  267. }
  268. /* Set up per cpu cipher state */
  269. static struct crypto_cipher *setup_essiv_cpu(struct crypt_config *cc,
  270. struct dm_target *ti,
  271. u8 *salt, unsigned saltsize)
  272. {
  273. struct crypto_cipher *essiv_tfm;
  274. int err;
  275. /* Setup the essiv_tfm with the given salt */
  276. essiv_tfm = crypto_alloc_cipher(cc->cipher, 0, CRYPTO_ALG_ASYNC);
  277. if (IS_ERR(essiv_tfm)) {
  278. ti->error = "Error allocating crypto tfm for ESSIV";
  279. return essiv_tfm;
  280. }
  281. if (crypto_cipher_blocksize(essiv_tfm) !=
  282. crypto_skcipher_ivsize(any_tfm(cc))) {
  283. ti->error = "Block size of ESSIV cipher does "
  284. "not match IV size of block cipher";
  285. crypto_free_cipher(essiv_tfm);
  286. return ERR_PTR(-EINVAL);
  287. }
  288. err = crypto_cipher_setkey(essiv_tfm, salt, saltsize);
  289. if (err) {
  290. ti->error = "Failed to set key for ESSIV cipher";
  291. crypto_free_cipher(essiv_tfm);
  292. return ERR_PTR(err);
  293. }
  294. return essiv_tfm;
  295. }
  296. static void crypt_iv_essiv_dtr(struct crypt_config *cc)
  297. {
  298. struct crypto_cipher *essiv_tfm;
  299. struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
  300. crypto_free_ahash(essiv->hash_tfm);
  301. essiv->hash_tfm = NULL;
  302. kzfree(essiv->salt);
  303. essiv->salt = NULL;
  304. essiv_tfm = cc->iv_private;
  305. if (essiv_tfm)
  306. crypto_free_cipher(essiv_tfm);
  307. cc->iv_private = NULL;
  308. }
  309. static int crypt_iv_essiv_ctr(struct crypt_config *cc, struct dm_target *ti,
  310. const char *opts)
  311. {
  312. struct crypto_cipher *essiv_tfm = NULL;
  313. struct crypto_ahash *hash_tfm = NULL;
  314. u8 *salt = NULL;
  315. int err;
  316. if (!opts) {
  317. ti->error = "Digest algorithm missing for ESSIV mode";
  318. return -EINVAL;
  319. }
  320. /* Allocate hash algorithm */
  321. hash_tfm = crypto_alloc_ahash(opts, 0, CRYPTO_ALG_ASYNC);
  322. if (IS_ERR(hash_tfm)) {
  323. ti->error = "Error initializing ESSIV hash";
  324. err = PTR_ERR(hash_tfm);
  325. goto bad;
  326. }
  327. salt = kzalloc(crypto_ahash_digestsize(hash_tfm), GFP_KERNEL);
  328. if (!salt) {
  329. ti->error = "Error kmallocing salt storage in ESSIV";
  330. err = -ENOMEM;
  331. goto bad;
  332. }
  333. cc->iv_gen_private.essiv.salt = salt;
  334. cc->iv_gen_private.essiv.hash_tfm = hash_tfm;
  335. essiv_tfm = setup_essiv_cpu(cc, ti, salt,
  336. crypto_ahash_digestsize(hash_tfm));
  337. if (IS_ERR(essiv_tfm)) {
  338. crypt_iv_essiv_dtr(cc);
  339. return PTR_ERR(essiv_tfm);
  340. }
  341. cc->iv_private = essiv_tfm;
  342. return 0;
  343. bad:
  344. if (hash_tfm && !IS_ERR(hash_tfm))
  345. crypto_free_ahash(hash_tfm);
  346. kfree(salt);
  347. return err;
  348. }
  349. static int crypt_iv_essiv_gen(struct crypt_config *cc, u8 *iv,
  350. struct dm_crypt_request *dmreq)
  351. {
  352. struct crypto_cipher *essiv_tfm = cc->iv_private;
  353. memset(iv, 0, cc->iv_size);
  354. *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
  355. crypto_cipher_encrypt_one(essiv_tfm, iv, iv);
  356. return 0;
  357. }
  358. static int crypt_iv_benbi_ctr(struct crypt_config *cc, struct dm_target *ti,
  359. const char *opts)
  360. {
  361. unsigned bs = crypto_skcipher_blocksize(any_tfm(cc));
  362. int log = ilog2(bs);
  363. /* we need to calculate how far we must shift the sector count
  364. * to get the cipher block count, we use this shift in _gen */
  365. if (1 << log != bs) {
  366. ti->error = "cypher blocksize is not a power of 2";
  367. return -EINVAL;
  368. }
  369. if (log > 9) {
  370. ti->error = "cypher blocksize is > 512";
  371. return -EINVAL;
  372. }
  373. cc->iv_gen_private.benbi.shift = 9 - log;
  374. return 0;
  375. }
  376. static void crypt_iv_benbi_dtr(struct crypt_config *cc)
  377. {
  378. }
  379. static int crypt_iv_benbi_gen(struct crypt_config *cc, u8 *iv,
  380. struct dm_crypt_request *dmreq)
  381. {
  382. __be64 val;
  383. memset(iv, 0, cc->iv_size - sizeof(u64)); /* rest is cleared below */
  384. val = cpu_to_be64(((u64)dmreq->iv_sector << cc->iv_gen_private.benbi.shift) + 1);
  385. put_unaligned(val, (__be64 *)(iv + cc->iv_size - sizeof(u64)));
  386. return 0;
  387. }
  388. static int crypt_iv_null_gen(struct crypt_config *cc, u8 *iv,
  389. struct dm_crypt_request *dmreq)
  390. {
  391. memset(iv, 0, cc->iv_size);
  392. return 0;
  393. }
  394. static void crypt_iv_lmk_dtr(struct crypt_config *cc)
  395. {
  396. struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
  397. if (lmk->hash_tfm && !IS_ERR(lmk->hash_tfm))
  398. crypto_free_shash(lmk->hash_tfm);
  399. lmk->hash_tfm = NULL;
  400. kzfree(lmk->seed);
  401. lmk->seed = NULL;
  402. }
  403. static int crypt_iv_lmk_ctr(struct crypt_config *cc, struct dm_target *ti,
  404. const char *opts)
  405. {
  406. struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
  407. lmk->hash_tfm = crypto_alloc_shash("md5", 0, 0);
  408. if (IS_ERR(lmk->hash_tfm)) {
  409. ti->error = "Error initializing LMK hash";
  410. return PTR_ERR(lmk->hash_tfm);
  411. }
  412. /* No seed in LMK version 2 */
  413. if (cc->key_parts == cc->tfms_count) {
  414. lmk->seed = NULL;
  415. return 0;
  416. }
  417. lmk->seed = kzalloc(LMK_SEED_SIZE, GFP_KERNEL);
  418. if (!lmk->seed) {
  419. crypt_iv_lmk_dtr(cc);
  420. ti->error = "Error kmallocing seed storage in LMK";
  421. return -ENOMEM;
  422. }
  423. return 0;
  424. }
  425. static int crypt_iv_lmk_init(struct crypt_config *cc)
  426. {
  427. struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
  428. int subkey_size = cc->key_size / cc->key_parts;
  429. /* LMK seed is on the position of LMK_KEYS + 1 key */
  430. if (lmk->seed)
  431. memcpy(lmk->seed, cc->key + (cc->tfms_count * subkey_size),
  432. crypto_shash_digestsize(lmk->hash_tfm));
  433. return 0;
  434. }
  435. static int crypt_iv_lmk_wipe(struct crypt_config *cc)
  436. {
  437. struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
  438. if (lmk->seed)
  439. memset(lmk->seed, 0, LMK_SEED_SIZE);
  440. return 0;
  441. }
  442. static int crypt_iv_lmk_one(struct crypt_config *cc, u8 *iv,
  443. struct dm_crypt_request *dmreq,
  444. u8 *data)
  445. {
  446. struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
  447. SHASH_DESC_ON_STACK(desc, lmk->hash_tfm);
  448. struct md5_state md5state;
  449. __le32 buf[4];
  450. int i, r;
  451. desc->tfm = lmk->hash_tfm;
  452. desc->flags = CRYPTO_TFM_REQ_MAY_SLEEP;
  453. r = crypto_shash_init(desc);
  454. if (r)
  455. return r;
  456. if (lmk->seed) {
  457. r = crypto_shash_update(desc, lmk->seed, LMK_SEED_SIZE);
  458. if (r)
  459. return r;
  460. }
  461. /* Sector is always 512B, block size 16, add data of blocks 1-31 */
  462. r = crypto_shash_update(desc, data + 16, 16 * 31);
  463. if (r)
  464. return r;
  465. /* Sector is cropped to 56 bits here */
  466. buf[0] = cpu_to_le32(dmreq->iv_sector & 0xFFFFFFFF);
  467. buf[1] = cpu_to_le32((((u64)dmreq->iv_sector >> 32) & 0x00FFFFFF) | 0x80000000);
  468. buf[2] = cpu_to_le32(4024);
  469. buf[3] = 0;
  470. r = crypto_shash_update(desc, (u8 *)buf, sizeof(buf));
  471. if (r)
  472. return r;
  473. /* No MD5 padding here */
  474. r = crypto_shash_export(desc, &md5state);
  475. if (r)
  476. return r;
  477. for (i = 0; i < MD5_HASH_WORDS; i++)
  478. __cpu_to_le32s(&md5state.hash[i]);
  479. memcpy(iv, &md5state.hash, cc->iv_size);
  480. return 0;
  481. }
  482. static int crypt_iv_lmk_gen(struct crypt_config *cc, u8 *iv,
  483. struct dm_crypt_request *dmreq)
  484. {
  485. u8 *src;
  486. int r = 0;
  487. if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
  488. src = kmap_atomic(sg_page(&dmreq->sg_in));
  489. r = crypt_iv_lmk_one(cc, iv, dmreq, src + dmreq->sg_in.offset);
  490. kunmap_atomic(src);
  491. } else
  492. memset(iv, 0, cc->iv_size);
  493. return r;
  494. }
  495. static int crypt_iv_lmk_post(struct crypt_config *cc, u8 *iv,
  496. struct dm_crypt_request *dmreq)
  497. {
  498. u8 *dst;
  499. int r;
  500. if (bio_data_dir(dmreq->ctx->bio_in) == WRITE)
  501. return 0;
  502. dst = kmap_atomic(sg_page(&dmreq->sg_out));
  503. r = crypt_iv_lmk_one(cc, iv, dmreq, dst + dmreq->sg_out.offset);
  504. /* Tweak the first block of plaintext sector */
  505. if (!r)
  506. crypto_xor(dst + dmreq->sg_out.offset, iv, cc->iv_size);
  507. kunmap_atomic(dst);
  508. return r;
  509. }
  510. static void crypt_iv_tcw_dtr(struct crypt_config *cc)
  511. {
  512. struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
  513. kzfree(tcw->iv_seed);
  514. tcw->iv_seed = NULL;
  515. kzfree(tcw->whitening);
  516. tcw->whitening = NULL;
  517. if (tcw->crc32_tfm && !IS_ERR(tcw->crc32_tfm))
  518. crypto_free_shash(tcw->crc32_tfm);
  519. tcw->crc32_tfm = NULL;
  520. }
  521. static int crypt_iv_tcw_ctr(struct crypt_config *cc, struct dm_target *ti,
  522. const char *opts)
  523. {
  524. struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
  525. if (cc->key_size <= (cc->iv_size + TCW_WHITENING_SIZE)) {
  526. ti->error = "Wrong key size for TCW";
  527. return -EINVAL;
  528. }
  529. tcw->crc32_tfm = crypto_alloc_shash("crc32", 0, 0);
  530. if (IS_ERR(tcw->crc32_tfm)) {
  531. ti->error = "Error initializing CRC32 in TCW";
  532. return PTR_ERR(tcw->crc32_tfm);
  533. }
  534. tcw->iv_seed = kzalloc(cc->iv_size, GFP_KERNEL);
  535. tcw->whitening = kzalloc(TCW_WHITENING_SIZE, GFP_KERNEL);
  536. if (!tcw->iv_seed || !tcw->whitening) {
  537. crypt_iv_tcw_dtr(cc);
  538. ti->error = "Error allocating seed storage in TCW";
  539. return -ENOMEM;
  540. }
  541. return 0;
  542. }
  543. static int crypt_iv_tcw_init(struct crypt_config *cc)
  544. {
  545. struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
  546. int key_offset = cc->key_size - cc->iv_size - TCW_WHITENING_SIZE;
  547. memcpy(tcw->iv_seed, &cc->key[key_offset], cc->iv_size);
  548. memcpy(tcw->whitening, &cc->key[key_offset + cc->iv_size],
  549. TCW_WHITENING_SIZE);
  550. return 0;
  551. }
  552. static int crypt_iv_tcw_wipe(struct crypt_config *cc)
  553. {
  554. struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
  555. memset(tcw->iv_seed, 0, cc->iv_size);
  556. memset(tcw->whitening, 0, TCW_WHITENING_SIZE);
  557. return 0;
  558. }
  559. static int crypt_iv_tcw_whitening(struct crypt_config *cc,
  560. struct dm_crypt_request *dmreq,
  561. u8 *data)
  562. {
  563. struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
  564. __le64 sector = cpu_to_le64(dmreq->iv_sector);
  565. u8 buf[TCW_WHITENING_SIZE];
  566. SHASH_DESC_ON_STACK(desc, tcw->crc32_tfm);
  567. int i, r;
  568. /* xor whitening with sector number */
  569. memcpy(buf, tcw->whitening, TCW_WHITENING_SIZE);
  570. crypto_xor(buf, (u8 *)&sector, 8);
  571. crypto_xor(&buf[8], (u8 *)&sector, 8);
  572. /* calculate crc32 for every 32bit part and xor it */
  573. desc->tfm = tcw->crc32_tfm;
  574. desc->flags = CRYPTO_TFM_REQ_MAY_SLEEP;
  575. for (i = 0; i < 4; i++) {
  576. r = crypto_shash_init(desc);
  577. if (r)
  578. goto out;
  579. r = crypto_shash_update(desc, &buf[i * 4], 4);
  580. if (r)
  581. goto out;
  582. r = crypto_shash_final(desc, &buf[i * 4]);
  583. if (r)
  584. goto out;
  585. }
  586. crypto_xor(&buf[0], &buf[12], 4);
  587. crypto_xor(&buf[4], &buf[8], 4);
  588. /* apply whitening (8 bytes) to whole sector */
  589. for (i = 0; i < ((1 << SECTOR_SHIFT) / 8); i++)
  590. crypto_xor(data + i * 8, buf, 8);
  591. out:
  592. memzero_explicit(buf, sizeof(buf));
  593. return r;
  594. }
  595. static int crypt_iv_tcw_gen(struct crypt_config *cc, u8 *iv,
  596. struct dm_crypt_request *dmreq)
  597. {
  598. struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
  599. __le64 sector = cpu_to_le64(dmreq->iv_sector);
  600. u8 *src;
  601. int r = 0;
  602. /* Remove whitening from ciphertext */
  603. if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
  604. src = kmap_atomic(sg_page(&dmreq->sg_in));
  605. r = crypt_iv_tcw_whitening(cc, dmreq, src + dmreq->sg_in.offset);
  606. kunmap_atomic(src);
  607. }
  608. /* Calculate IV */
  609. memcpy(iv, tcw->iv_seed, cc->iv_size);
  610. crypto_xor(iv, (u8 *)&sector, 8);
  611. if (cc->iv_size > 8)
  612. crypto_xor(&iv[8], (u8 *)&sector, cc->iv_size - 8);
  613. return r;
  614. }
  615. static int crypt_iv_tcw_post(struct crypt_config *cc, u8 *iv,
  616. struct dm_crypt_request *dmreq)
  617. {
  618. u8 *dst;
  619. int r;
  620. if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
  621. return 0;
  622. /* Apply whitening on ciphertext */
  623. dst = kmap_atomic(sg_page(&dmreq->sg_out));
  624. r = crypt_iv_tcw_whitening(cc, dmreq, dst + dmreq->sg_out.offset);
  625. kunmap_atomic(dst);
  626. return r;
  627. }
  628. static const struct crypt_iv_operations crypt_iv_plain_ops = {
  629. .generator = crypt_iv_plain_gen
  630. };
  631. static const struct crypt_iv_operations crypt_iv_plain64_ops = {
  632. .generator = crypt_iv_plain64_gen
  633. };
  634. static const struct crypt_iv_operations crypt_iv_essiv_ops = {
  635. .ctr = crypt_iv_essiv_ctr,
  636. .dtr = crypt_iv_essiv_dtr,
  637. .init = crypt_iv_essiv_init,
  638. .wipe = crypt_iv_essiv_wipe,
  639. .generator = crypt_iv_essiv_gen
  640. };
  641. static const struct crypt_iv_operations crypt_iv_benbi_ops = {
  642. .ctr = crypt_iv_benbi_ctr,
  643. .dtr = crypt_iv_benbi_dtr,
  644. .generator = crypt_iv_benbi_gen
  645. };
  646. static const struct crypt_iv_operations crypt_iv_null_ops = {
  647. .generator = crypt_iv_null_gen
  648. };
  649. static const struct crypt_iv_operations crypt_iv_lmk_ops = {
  650. .ctr = crypt_iv_lmk_ctr,
  651. .dtr = crypt_iv_lmk_dtr,
  652. .init = crypt_iv_lmk_init,
  653. .wipe = crypt_iv_lmk_wipe,
  654. .generator = crypt_iv_lmk_gen,
  655. .post = crypt_iv_lmk_post
  656. };
  657. static const struct crypt_iv_operations crypt_iv_tcw_ops = {
  658. .ctr = crypt_iv_tcw_ctr,
  659. .dtr = crypt_iv_tcw_dtr,
  660. .init = crypt_iv_tcw_init,
  661. .wipe = crypt_iv_tcw_wipe,
  662. .generator = crypt_iv_tcw_gen,
  663. .post = crypt_iv_tcw_post
  664. };
  665. static void crypt_convert_init(struct crypt_config *cc,
  666. struct convert_context *ctx,
  667. struct bio *bio_out, struct bio *bio_in,
  668. sector_t sector)
  669. {
  670. ctx->bio_in = bio_in;
  671. ctx->bio_out = bio_out;
  672. if (bio_in)
  673. ctx->iter_in = bio_in->bi_iter;
  674. if (bio_out)
  675. ctx->iter_out = bio_out->bi_iter;
  676. ctx->cc_sector = sector + cc->iv_offset;
  677. init_completion(&ctx->restart);
  678. }
  679. static struct dm_crypt_request *dmreq_of_req(struct crypt_config *cc,
  680. struct skcipher_request *req)
  681. {
  682. return (struct dm_crypt_request *)((char *)req + cc->dmreq_start);
  683. }
  684. static struct skcipher_request *req_of_dmreq(struct crypt_config *cc,
  685. struct dm_crypt_request *dmreq)
  686. {
  687. return (struct skcipher_request *)((char *)dmreq - cc->dmreq_start);
  688. }
  689. static u8 *iv_of_dmreq(struct crypt_config *cc,
  690. struct dm_crypt_request *dmreq)
  691. {
  692. return (u8 *)ALIGN((unsigned long)(dmreq + 1),
  693. crypto_skcipher_alignmask(any_tfm(cc)) + 1);
  694. }
  695. static int crypt_convert_block(struct crypt_config *cc,
  696. struct convert_context *ctx,
  697. struct skcipher_request *req)
  698. {
  699. struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
  700. struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
  701. struct dm_crypt_request *dmreq;
  702. u8 *iv;
  703. int r;
  704. dmreq = dmreq_of_req(cc, req);
  705. iv = iv_of_dmreq(cc, dmreq);
  706. dmreq->iv_sector = ctx->cc_sector;
  707. dmreq->ctx = ctx;
  708. sg_init_table(&dmreq->sg_in, 1);
  709. sg_set_page(&dmreq->sg_in, bv_in.bv_page, 1 << SECTOR_SHIFT,
  710. bv_in.bv_offset);
  711. sg_init_table(&dmreq->sg_out, 1);
  712. sg_set_page(&dmreq->sg_out, bv_out.bv_page, 1 << SECTOR_SHIFT,
  713. bv_out.bv_offset);
  714. bio_advance_iter(ctx->bio_in, &ctx->iter_in, 1 << SECTOR_SHIFT);
  715. bio_advance_iter(ctx->bio_out, &ctx->iter_out, 1 << SECTOR_SHIFT);
  716. if (cc->iv_gen_ops) {
  717. r = cc->iv_gen_ops->generator(cc, iv, dmreq);
  718. if (r < 0)
  719. return r;
  720. }
  721. skcipher_request_set_crypt(req, &dmreq->sg_in, &dmreq->sg_out,
  722. 1 << SECTOR_SHIFT, iv);
  723. if (bio_data_dir(ctx->bio_in) == WRITE)
  724. r = crypto_skcipher_encrypt(req);
  725. else
  726. r = crypto_skcipher_decrypt(req);
  727. if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
  728. r = cc->iv_gen_ops->post(cc, iv, dmreq);
  729. return r;
  730. }
  731. static void kcryptd_async_done(struct crypto_async_request *async_req,
  732. int error);
  733. static void crypt_alloc_req(struct crypt_config *cc,
  734. struct convert_context *ctx)
  735. {
  736. unsigned key_index = ctx->cc_sector & (cc->tfms_count - 1);
  737. if (!ctx->req)
  738. ctx->req = mempool_alloc(cc->req_pool, GFP_NOIO);
  739. skcipher_request_set_tfm(ctx->req, cc->tfms[key_index]);
  740. /*
  741. * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
  742. * requests if driver request queue is full.
  743. */
  744. skcipher_request_set_callback(ctx->req,
  745. CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
  746. kcryptd_async_done, dmreq_of_req(cc, ctx->req));
  747. }
  748. static void crypt_free_req(struct crypt_config *cc,
  749. struct skcipher_request *req, struct bio *base_bio)
  750. {
  751. struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
  752. if ((struct skcipher_request *)(io + 1) != req)
  753. mempool_free(req, cc->req_pool);
  754. }
  755. /*
  756. * Encrypt / decrypt data from one bio to another one (can be the same one)
  757. */
  758. static int crypt_convert(struct crypt_config *cc,
  759. struct convert_context *ctx)
  760. {
  761. int r;
  762. atomic_set(&ctx->cc_pending, 1);
  763. while (ctx->iter_in.bi_size && ctx->iter_out.bi_size) {
  764. crypt_alloc_req(cc, ctx);
  765. atomic_inc(&ctx->cc_pending);
  766. r = crypt_convert_block(cc, ctx, ctx->req);
  767. switch (r) {
  768. /*
  769. * The request was queued by a crypto driver
  770. * but the driver request queue is full, let's wait.
  771. */
  772. case -EBUSY:
  773. wait_for_completion(&ctx->restart);
  774. reinit_completion(&ctx->restart);
  775. /* fall through */
  776. /*
  777. * The request is queued and processed asynchronously,
  778. * completion function kcryptd_async_done() will be called.
  779. */
  780. case -EINPROGRESS:
  781. ctx->req = NULL;
  782. ctx->cc_sector++;
  783. continue;
  784. /*
  785. * The request was already processed (synchronously).
  786. */
  787. case 0:
  788. atomic_dec(&ctx->cc_pending);
  789. ctx->cc_sector++;
  790. cond_resched();
  791. continue;
  792. /* There was an error while processing the request. */
  793. default:
  794. atomic_dec(&ctx->cc_pending);
  795. return r;
  796. }
  797. }
  798. return 0;
  799. }
  800. static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone);
  801. /*
  802. * Generate a new unfragmented bio with the given size
  803. * This should never violate the device limitations (but only because
  804. * max_segment_size is being constrained to PAGE_SIZE).
  805. *
  806. * This function may be called concurrently. If we allocate from the mempool
  807. * concurrently, there is a possibility of deadlock. For example, if we have
  808. * mempool of 256 pages, two processes, each wanting 256, pages allocate from
  809. * the mempool concurrently, it may deadlock in a situation where both processes
  810. * have allocated 128 pages and the mempool is exhausted.
  811. *
  812. * In order to avoid this scenario we allocate the pages under a mutex.
  813. *
  814. * In order to not degrade performance with excessive locking, we try
  815. * non-blocking allocations without a mutex first but on failure we fallback
  816. * to blocking allocations with a mutex.
  817. */
  818. static struct bio *crypt_alloc_buffer(struct dm_crypt_io *io, unsigned size)
  819. {
  820. struct crypt_config *cc = io->cc;
  821. struct bio *clone;
  822. unsigned int nr_iovecs = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
  823. gfp_t gfp_mask = GFP_NOWAIT | __GFP_HIGHMEM;
  824. unsigned i, len, remaining_size;
  825. struct page *page;
  826. retry:
  827. if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
  828. mutex_lock(&cc->bio_alloc_lock);
  829. clone = bio_alloc_bioset(GFP_NOIO, nr_iovecs, cc->bs);
  830. if (!clone)
  831. goto return_clone;
  832. clone_init(io, clone);
  833. remaining_size = size;
  834. for (i = 0; i < nr_iovecs; i++) {
  835. page = mempool_alloc(cc->page_pool, gfp_mask);
  836. if (!page) {
  837. crypt_free_buffer_pages(cc, clone);
  838. bio_put(clone);
  839. gfp_mask |= __GFP_DIRECT_RECLAIM;
  840. goto retry;
  841. }
  842. len = (remaining_size > PAGE_SIZE) ? PAGE_SIZE : remaining_size;
  843. bio_add_page(clone, page, len, 0);
  844. remaining_size -= len;
  845. }
  846. return_clone:
  847. if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
  848. mutex_unlock(&cc->bio_alloc_lock);
  849. return clone;
  850. }
  851. static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone)
  852. {
  853. unsigned int i;
  854. struct bio_vec *bv;
  855. bio_for_each_segment_all(bv, clone, i) {
  856. BUG_ON(!bv->bv_page);
  857. mempool_free(bv->bv_page, cc->page_pool);
  858. bv->bv_page = NULL;
  859. }
  860. }
  861. static void crypt_io_init(struct dm_crypt_io *io, struct crypt_config *cc,
  862. struct bio *bio, sector_t sector)
  863. {
  864. io->cc = cc;
  865. io->base_bio = bio;
  866. io->sector = sector;
  867. io->error = 0;
  868. io->ctx.req = NULL;
  869. atomic_set(&io->io_pending, 0);
  870. }
  871. static void crypt_inc_pending(struct dm_crypt_io *io)
  872. {
  873. atomic_inc(&io->io_pending);
  874. }
  875. /*
  876. * One of the bios was finished. Check for completion of
  877. * the whole request and correctly clean up the buffer.
  878. */
  879. static void crypt_dec_pending(struct dm_crypt_io *io)
  880. {
  881. struct crypt_config *cc = io->cc;
  882. struct bio *base_bio = io->base_bio;
  883. int error = io->error;
  884. if (!atomic_dec_and_test(&io->io_pending))
  885. return;
  886. if (io->ctx.req)
  887. crypt_free_req(cc, io->ctx.req, base_bio);
  888. base_bio->bi_error = error;
  889. bio_endio(base_bio);
  890. }
  891. /*
  892. * kcryptd/kcryptd_io:
  893. *
  894. * Needed because it would be very unwise to do decryption in an
  895. * interrupt context.
  896. *
  897. * kcryptd performs the actual encryption or decryption.
  898. *
  899. * kcryptd_io performs the IO submission.
  900. *
  901. * They must be separated as otherwise the final stages could be
  902. * starved by new requests which can block in the first stages due
  903. * to memory allocation.
  904. *
  905. * The work is done per CPU global for all dm-crypt instances.
  906. * They should not depend on each other and do not block.
  907. */
  908. static void crypt_endio(struct bio *clone)
  909. {
  910. struct dm_crypt_io *io = clone->bi_private;
  911. struct crypt_config *cc = io->cc;
  912. unsigned rw = bio_data_dir(clone);
  913. int error;
  914. /*
  915. * free the processed pages
  916. */
  917. if (rw == WRITE)
  918. crypt_free_buffer_pages(cc, clone);
  919. error = clone->bi_error;
  920. bio_put(clone);
  921. if (rw == READ && !error) {
  922. kcryptd_queue_crypt(io);
  923. return;
  924. }
  925. if (unlikely(error))
  926. io->error = error;
  927. crypt_dec_pending(io);
  928. }
  929. static void clone_init(struct dm_crypt_io *io, struct bio *clone)
  930. {
  931. struct crypt_config *cc = io->cc;
  932. clone->bi_private = io;
  933. clone->bi_end_io = crypt_endio;
  934. clone->bi_bdev = cc->dev->bdev;
  935. clone->bi_opf = io->base_bio->bi_opf;
  936. }
  937. static int kcryptd_io_read(struct dm_crypt_io *io, gfp_t gfp)
  938. {
  939. struct crypt_config *cc = io->cc;
  940. struct bio *clone;
  941. /*
  942. * We need the original biovec array in order to decrypt
  943. * the whole bio data *afterwards* -- thanks to immutable
  944. * biovecs we don't need to worry about the block layer
  945. * modifying the biovec array; so leverage bio_clone_fast().
  946. */
  947. clone = bio_clone_fast(io->base_bio, gfp, cc->bs);
  948. if (!clone)
  949. return 1;
  950. crypt_inc_pending(io);
  951. clone_init(io, clone);
  952. clone->bi_iter.bi_sector = cc->start + io->sector;
  953. generic_make_request(clone);
  954. return 0;
  955. }
  956. static void kcryptd_io_read_work(struct work_struct *work)
  957. {
  958. struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
  959. crypt_inc_pending(io);
  960. if (kcryptd_io_read(io, GFP_NOIO))
  961. io->error = -ENOMEM;
  962. crypt_dec_pending(io);
  963. }
  964. static void kcryptd_queue_read(struct dm_crypt_io *io)
  965. {
  966. struct crypt_config *cc = io->cc;
  967. INIT_WORK(&io->work, kcryptd_io_read_work);
  968. queue_work(cc->io_queue, &io->work);
  969. }
  970. static void kcryptd_io_write(struct dm_crypt_io *io)
  971. {
  972. struct bio *clone = io->ctx.bio_out;
  973. generic_make_request(clone);
  974. }
  975. #define crypt_io_from_node(node) rb_entry((node), struct dm_crypt_io, rb_node)
  976. static int dmcrypt_write(void *data)
  977. {
  978. struct crypt_config *cc = data;
  979. struct dm_crypt_io *io;
  980. while (1) {
  981. struct rb_root write_tree;
  982. struct blk_plug plug;
  983. DECLARE_WAITQUEUE(wait, current);
  984. spin_lock_irq(&cc->write_thread_wait.lock);
  985. continue_locked:
  986. if (!RB_EMPTY_ROOT(&cc->write_tree))
  987. goto pop_from_list;
  988. set_current_state(TASK_INTERRUPTIBLE);
  989. __add_wait_queue(&cc->write_thread_wait, &wait);
  990. spin_unlock_irq(&cc->write_thread_wait.lock);
  991. if (unlikely(kthread_should_stop())) {
  992. set_task_state(current, TASK_RUNNING);
  993. remove_wait_queue(&cc->write_thread_wait, &wait);
  994. break;
  995. }
  996. schedule();
  997. set_task_state(current, TASK_RUNNING);
  998. spin_lock_irq(&cc->write_thread_wait.lock);
  999. __remove_wait_queue(&cc->write_thread_wait, &wait);
  1000. goto continue_locked;
  1001. pop_from_list:
  1002. write_tree = cc->write_tree;
  1003. cc->write_tree = RB_ROOT;
  1004. spin_unlock_irq(&cc->write_thread_wait.lock);
  1005. BUG_ON(rb_parent(write_tree.rb_node));
  1006. /*
  1007. * Note: we cannot walk the tree here with rb_next because
  1008. * the structures may be freed when kcryptd_io_write is called.
  1009. */
  1010. blk_start_plug(&plug);
  1011. do {
  1012. io = crypt_io_from_node(rb_first(&write_tree));
  1013. rb_erase(&io->rb_node, &write_tree);
  1014. kcryptd_io_write(io);
  1015. } while (!RB_EMPTY_ROOT(&write_tree));
  1016. blk_finish_plug(&plug);
  1017. }
  1018. return 0;
  1019. }
  1020. static void kcryptd_crypt_write_io_submit(struct dm_crypt_io *io, int async)
  1021. {
  1022. struct bio *clone = io->ctx.bio_out;
  1023. struct crypt_config *cc = io->cc;
  1024. unsigned long flags;
  1025. sector_t sector;
  1026. struct rb_node **rbp, *parent;
  1027. if (unlikely(io->error < 0)) {
  1028. crypt_free_buffer_pages(cc, clone);
  1029. bio_put(clone);
  1030. crypt_dec_pending(io);
  1031. return;
  1032. }
  1033. /* crypt_convert should have filled the clone bio */
  1034. BUG_ON(io->ctx.iter_out.bi_size);
  1035. clone->bi_iter.bi_sector = cc->start + io->sector;
  1036. if (likely(!async) && test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags)) {
  1037. generic_make_request(clone);
  1038. return;
  1039. }
  1040. spin_lock_irqsave(&cc->write_thread_wait.lock, flags);
  1041. rbp = &cc->write_tree.rb_node;
  1042. parent = NULL;
  1043. sector = io->sector;
  1044. while (*rbp) {
  1045. parent = *rbp;
  1046. if (sector < crypt_io_from_node(parent)->sector)
  1047. rbp = &(*rbp)->rb_left;
  1048. else
  1049. rbp = &(*rbp)->rb_right;
  1050. }
  1051. rb_link_node(&io->rb_node, parent, rbp);
  1052. rb_insert_color(&io->rb_node, &cc->write_tree);
  1053. wake_up_locked(&cc->write_thread_wait);
  1054. spin_unlock_irqrestore(&cc->write_thread_wait.lock, flags);
  1055. }
  1056. static void kcryptd_crypt_write_convert(struct dm_crypt_io *io)
  1057. {
  1058. struct crypt_config *cc = io->cc;
  1059. struct bio *clone;
  1060. int crypt_finished;
  1061. sector_t sector = io->sector;
  1062. int r;
  1063. /*
  1064. * Prevent io from disappearing until this function completes.
  1065. */
  1066. crypt_inc_pending(io);
  1067. crypt_convert_init(cc, &io->ctx, NULL, io->base_bio, sector);
  1068. clone = crypt_alloc_buffer(io, io->base_bio->bi_iter.bi_size);
  1069. if (unlikely(!clone)) {
  1070. io->error = -EIO;
  1071. goto dec;
  1072. }
  1073. io->ctx.bio_out = clone;
  1074. io->ctx.iter_out = clone->bi_iter;
  1075. sector += bio_sectors(clone);
  1076. crypt_inc_pending(io);
  1077. r = crypt_convert(cc, &io->ctx);
  1078. if (r)
  1079. io->error = -EIO;
  1080. crypt_finished = atomic_dec_and_test(&io->ctx.cc_pending);
  1081. /* Encryption was already finished, submit io now */
  1082. if (crypt_finished) {
  1083. kcryptd_crypt_write_io_submit(io, 0);
  1084. io->sector = sector;
  1085. }
  1086. dec:
  1087. crypt_dec_pending(io);
  1088. }
  1089. static void kcryptd_crypt_read_done(struct dm_crypt_io *io)
  1090. {
  1091. crypt_dec_pending(io);
  1092. }
  1093. static void kcryptd_crypt_read_convert(struct dm_crypt_io *io)
  1094. {
  1095. struct crypt_config *cc = io->cc;
  1096. int r = 0;
  1097. crypt_inc_pending(io);
  1098. crypt_convert_init(cc, &io->ctx, io->base_bio, io->base_bio,
  1099. io->sector);
  1100. r = crypt_convert(cc, &io->ctx);
  1101. if (r < 0)
  1102. io->error = -EIO;
  1103. if (atomic_dec_and_test(&io->ctx.cc_pending))
  1104. kcryptd_crypt_read_done(io);
  1105. crypt_dec_pending(io);
  1106. }
  1107. static void kcryptd_async_done(struct crypto_async_request *async_req,
  1108. int error)
  1109. {
  1110. struct dm_crypt_request *dmreq = async_req->data;
  1111. struct convert_context *ctx = dmreq->ctx;
  1112. struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
  1113. struct crypt_config *cc = io->cc;
  1114. /*
  1115. * A request from crypto driver backlog is going to be processed now,
  1116. * finish the completion and continue in crypt_convert().
  1117. * (Callback will be called for the second time for this request.)
  1118. */
  1119. if (error == -EINPROGRESS) {
  1120. complete(&ctx->restart);
  1121. return;
  1122. }
  1123. if (!error && cc->iv_gen_ops && cc->iv_gen_ops->post)
  1124. error = cc->iv_gen_ops->post(cc, iv_of_dmreq(cc, dmreq), dmreq);
  1125. if (error < 0)
  1126. io->error = -EIO;
  1127. crypt_free_req(cc, req_of_dmreq(cc, dmreq), io->base_bio);
  1128. if (!atomic_dec_and_test(&ctx->cc_pending))
  1129. return;
  1130. if (bio_data_dir(io->base_bio) == READ)
  1131. kcryptd_crypt_read_done(io);
  1132. else
  1133. kcryptd_crypt_write_io_submit(io, 1);
  1134. }
  1135. static void kcryptd_crypt(struct work_struct *work)
  1136. {
  1137. struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
  1138. if (bio_data_dir(io->base_bio) == READ)
  1139. kcryptd_crypt_read_convert(io);
  1140. else
  1141. kcryptd_crypt_write_convert(io);
  1142. }
  1143. static void kcryptd_queue_crypt(struct dm_crypt_io *io)
  1144. {
  1145. struct crypt_config *cc = io->cc;
  1146. INIT_WORK(&io->work, kcryptd_crypt);
  1147. queue_work(cc->crypt_queue, &io->work);
  1148. }
  1149. /*
  1150. * Decode key from its hex representation
  1151. */
  1152. static int crypt_decode_key(u8 *key, char *hex, unsigned int size)
  1153. {
  1154. char buffer[3];
  1155. unsigned int i;
  1156. buffer[2] = '\0';
  1157. for (i = 0; i < size; i++) {
  1158. buffer[0] = *hex++;
  1159. buffer[1] = *hex++;
  1160. if (kstrtou8(buffer, 16, &key[i]))
  1161. return -EINVAL;
  1162. }
  1163. if (*hex != '\0')
  1164. return -EINVAL;
  1165. return 0;
  1166. }
  1167. static void crypt_free_tfms(struct crypt_config *cc)
  1168. {
  1169. unsigned i;
  1170. if (!cc->tfms)
  1171. return;
  1172. for (i = 0; i < cc->tfms_count; i++)
  1173. if (cc->tfms[i] && !IS_ERR(cc->tfms[i])) {
  1174. crypto_free_skcipher(cc->tfms[i]);
  1175. cc->tfms[i] = NULL;
  1176. }
  1177. kfree(cc->tfms);
  1178. cc->tfms = NULL;
  1179. }
  1180. static int crypt_alloc_tfms(struct crypt_config *cc, char *ciphermode)
  1181. {
  1182. unsigned i;
  1183. int err;
  1184. cc->tfms = kzalloc(cc->tfms_count * sizeof(struct crypto_skcipher *),
  1185. GFP_KERNEL);
  1186. if (!cc->tfms)
  1187. return -ENOMEM;
  1188. for (i = 0; i < cc->tfms_count; i++) {
  1189. cc->tfms[i] = crypto_alloc_skcipher(ciphermode, 0, 0);
  1190. if (IS_ERR(cc->tfms[i])) {
  1191. err = PTR_ERR(cc->tfms[i]);
  1192. crypt_free_tfms(cc);
  1193. return err;
  1194. }
  1195. }
  1196. return 0;
  1197. }
  1198. static int crypt_setkey(struct crypt_config *cc)
  1199. {
  1200. unsigned subkey_size;
  1201. int err = 0, i, r;
  1202. /* Ignore extra keys (which are used for IV etc) */
  1203. subkey_size = (cc->key_size - cc->key_extra_size) >> ilog2(cc->tfms_count);
  1204. for (i = 0; i < cc->tfms_count; i++) {
  1205. r = crypto_skcipher_setkey(cc->tfms[i],
  1206. cc->key + (i * subkey_size),
  1207. subkey_size);
  1208. if (r)
  1209. err = r;
  1210. }
  1211. return err;
  1212. }
  1213. #ifdef CONFIG_KEYS
  1214. static bool contains_whitespace(const char *str)
  1215. {
  1216. while (*str)
  1217. if (isspace(*str++))
  1218. return true;
  1219. return false;
  1220. }
  1221. static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
  1222. {
  1223. char *new_key_string, *key_desc;
  1224. int ret;
  1225. struct key *key;
  1226. const struct user_key_payload *ukp;
  1227. /*
  1228. * Reject key_string with whitespace. dm core currently lacks code for
  1229. * proper whitespace escaping in arguments on DM_TABLE_STATUS path.
  1230. */
  1231. if (contains_whitespace(key_string)) {
  1232. DMERR("whitespace chars not allowed in key string");
  1233. return -EINVAL;
  1234. }
  1235. /* look for next ':' separating key_type from key_description */
  1236. key_desc = strpbrk(key_string, ":");
  1237. if (!key_desc || key_desc == key_string || !strlen(key_desc + 1))
  1238. return -EINVAL;
  1239. if (strncmp(key_string, "logon:", key_desc - key_string + 1) &&
  1240. strncmp(key_string, "user:", key_desc - key_string + 1))
  1241. return -EINVAL;
  1242. new_key_string = kstrdup(key_string, GFP_KERNEL);
  1243. if (!new_key_string)
  1244. return -ENOMEM;
  1245. key = request_key(key_string[0] == 'l' ? &key_type_logon : &key_type_user,
  1246. key_desc + 1, NULL);
  1247. if (IS_ERR(key)) {
  1248. kzfree(new_key_string);
  1249. return PTR_ERR(key);
  1250. }
  1251. rcu_read_lock();
  1252. ukp = user_key_payload(key);
  1253. if (!ukp) {
  1254. rcu_read_unlock();
  1255. key_put(key);
  1256. kzfree(new_key_string);
  1257. return -EKEYREVOKED;
  1258. }
  1259. if (cc->key_size != ukp->datalen) {
  1260. rcu_read_unlock();
  1261. key_put(key);
  1262. kzfree(new_key_string);
  1263. return -EINVAL;
  1264. }
  1265. memcpy(cc->key, ukp->data, cc->key_size);
  1266. rcu_read_unlock();
  1267. key_put(key);
  1268. /* clear the flag since following operations may invalidate previously valid key */
  1269. clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
  1270. ret = crypt_setkey(cc);
  1271. /* wipe the kernel key payload copy in each case */
  1272. memset(cc->key, 0, cc->key_size * sizeof(u8));
  1273. if (!ret) {
  1274. set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
  1275. kzfree(cc->key_string);
  1276. cc->key_string = new_key_string;
  1277. } else
  1278. kzfree(new_key_string);
  1279. return ret;
  1280. }
  1281. static int get_key_size(char **key_string)
  1282. {
  1283. char *colon, dummy;
  1284. int ret;
  1285. if (*key_string[0] != ':')
  1286. return strlen(*key_string) >> 1;
  1287. /* look for next ':' in key string */
  1288. colon = strpbrk(*key_string + 1, ":");
  1289. if (!colon)
  1290. return -EINVAL;
  1291. if (sscanf(*key_string + 1, "%u%c", &ret, &dummy) != 2 || dummy != ':')
  1292. return -EINVAL;
  1293. *key_string = colon;
  1294. /* remaining key string should be :<logon|user>:<key_desc> */
  1295. return ret;
  1296. }
  1297. #else
  1298. static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
  1299. {
  1300. return -EINVAL;
  1301. }
  1302. static int get_key_size(char **key_string)
  1303. {
  1304. return (*key_string[0] == ':') ? -EINVAL : strlen(*key_string) >> 1;
  1305. }
  1306. #endif
  1307. static int crypt_set_key(struct crypt_config *cc, char *key)
  1308. {
  1309. int r = -EINVAL;
  1310. int key_string_len = strlen(key);
  1311. /* Hyphen (which gives a key_size of zero) means there is no key. */
  1312. if (!cc->key_size && strcmp(key, "-"))
  1313. goto out;
  1314. /* ':' means the key is in kernel keyring, short-circuit normal key processing */
  1315. if (key[0] == ':') {
  1316. r = crypt_set_keyring_key(cc, key + 1);
  1317. goto out;
  1318. }
  1319. /* clear the flag since following operations may invalidate previously valid key */
  1320. clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
  1321. /* wipe references to any kernel keyring key */
  1322. kzfree(cc->key_string);
  1323. cc->key_string = NULL;
  1324. if (cc->key_size && crypt_decode_key(cc->key, key, cc->key_size) < 0)
  1325. goto out;
  1326. r = crypt_setkey(cc);
  1327. if (!r)
  1328. set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
  1329. out:
  1330. /* Hex key string not needed after here, so wipe it. */
  1331. memset(key, '0', key_string_len);
  1332. return r;
  1333. }
  1334. static int crypt_wipe_key(struct crypt_config *cc)
  1335. {
  1336. clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
  1337. memset(&cc->key, 0, cc->key_size * sizeof(u8));
  1338. kzfree(cc->key_string);
  1339. cc->key_string = NULL;
  1340. return crypt_setkey(cc);
  1341. }
  1342. static void crypt_dtr(struct dm_target *ti)
  1343. {
  1344. struct crypt_config *cc = ti->private;
  1345. ti->private = NULL;
  1346. if (!cc)
  1347. return;
  1348. if (cc->write_thread)
  1349. kthread_stop(cc->write_thread);
  1350. if (cc->io_queue)
  1351. destroy_workqueue(cc->io_queue);
  1352. if (cc->crypt_queue)
  1353. destroy_workqueue(cc->crypt_queue);
  1354. crypt_free_tfms(cc);
  1355. if (cc->bs)
  1356. bioset_free(cc->bs);
  1357. mempool_destroy(cc->page_pool);
  1358. mempool_destroy(cc->req_pool);
  1359. if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
  1360. cc->iv_gen_ops->dtr(cc);
  1361. if (cc->dev)
  1362. dm_put_device(ti, cc->dev);
  1363. kzfree(cc->cipher);
  1364. kzfree(cc->cipher_string);
  1365. kzfree(cc->key_string);
  1366. /* Must zero key material before freeing */
  1367. kzfree(cc);
  1368. }
  1369. static int crypt_ctr_cipher(struct dm_target *ti,
  1370. char *cipher_in, char *key)
  1371. {
  1372. struct crypt_config *cc = ti->private;
  1373. char *tmp, *cipher, *chainmode, *ivmode, *ivopts, *keycount;
  1374. char *cipher_api = NULL;
  1375. int ret = -EINVAL;
  1376. char dummy;
  1377. /* Convert to crypto api definition? */
  1378. if (strchr(cipher_in, '(')) {
  1379. ti->error = "Bad cipher specification";
  1380. return -EINVAL;
  1381. }
  1382. cc->cipher_string = kstrdup(cipher_in, GFP_KERNEL);
  1383. if (!cc->cipher_string)
  1384. goto bad_mem;
  1385. /*
  1386. * Legacy dm-crypt cipher specification
  1387. * cipher[:keycount]-mode-iv:ivopts
  1388. */
  1389. tmp = cipher_in;
  1390. keycount = strsep(&tmp, "-");
  1391. cipher = strsep(&keycount, ":");
  1392. if (!keycount)
  1393. cc->tfms_count = 1;
  1394. else if (sscanf(keycount, "%u%c", &cc->tfms_count, &dummy) != 1 ||
  1395. !is_power_of_2(cc->tfms_count)) {
  1396. ti->error = "Bad cipher key count specification";
  1397. return -EINVAL;
  1398. }
  1399. cc->key_parts = cc->tfms_count;
  1400. cc->key_extra_size = 0;
  1401. cc->cipher = kstrdup(cipher, GFP_KERNEL);
  1402. if (!cc->cipher)
  1403. goto bad_mem;
  1404. chainmode = strsep(&tmp, "-");
  1405. ivopts = strsep(&tmp, "-");
  1406. ivmode = strsep(&ivopts, ":");
  1407. if (tmp)
  1408. DMWARN("Ignoring unexpected additional cipher options");
  1409. /*
  1410. * For compatibility with the original dm-crypt mapping format, if
  1411. * only the cipher name is supplied, use cbc-plain.
  1412. */
  1413. if (!chainmode || (!strcmp(chainmode, "plain") && !ivmode)) {
  1414. chainmode = "cbc";
  1415. ivmode = "plain";
  1416. }
  1417. if (strcmp(chainmode, "ecb") && !ivmode) {
  1418. ti->error = "IV mechanism required";
  1419. return -EINVAL;
  1420. }
  1421. cipher_api = kmalloc(CRYPTO_MAX_ALG_NAME, GFP_KERNEL);
  1422. if (!cipher_api)
  1423. goto bad_mem;
  1424. ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
  1425. "%s(%s)", chainmode, cipher);
  1426. if (ret < 0) {
  1427. kfree(cipher_api);
  1428. goto bad_mem;
  1429. }
  1430. /* Allocate cipher */
  1431. ret = crypt_alloc_tfms(cc, cipher_api);
  1432. if (ret < 0) {
  1433. ti->error = "Error allocating crypto tfm";
  1434. goto bad;
  1435. }
  1436. /* Initialize IV */
  1437. cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
  1438. if (cc->iv_size)
  1439. /* at least a 64 bit sector number should fit in our buffer */
  1440. cc->iv_size = max(cc->iv_size,
  1441. (unsigned int)(sizeof(u64) / sizeof(u8)));
  1442. else if (ivmode) {
  1443. DMWARN("Selected cipher does not support IVs");
  1444. ivmode = NULL;
  1445. }
  1446. /* Choose ivmode, see comments at iv code. */
  1447. if (ivmode == NULL)
  1448. cc->iv_gen_ops = NULL;
  1449. else if (strcmp(ivmode, "plain") == 0)
  1450. cc->iv_gen_ops = &crypt_iv_plain_ops;
  1451. else if (strcmp(ivmode, "plain64") == 0)
  1452. cc->iv_gen_ops = &crypt_iv_plain64_ops;
  1453. else if (strcmp(ivmode, "essiv") == 0)
  1454. cc->iv_gen_ops = &crypt_iv_essiv_ops;
  1455. else if (strcmp(ivmode, "benbi") == 0)
  1456. cc->iv_gen_ops = &crypt_iv_benbi_ops;
  1457. else if (strcmp(ivmode, "null") == 0)
  1458. cc->iv_gen_ops = &crypt_iv_null_ops;
  1459. else if (strcmp(ivmode, "lmk") == 0) {
  1460. cc->iv_gen_ops = &crypt_iv_lmk_ops;
  1461. /*
  1462. * Version 2 and 3 is recognised according
  1463. * to length of provided multi-key string.
  1464. * If present (version 3), last key is used as IV seed.
  1465. * All keys (including IV seed) are always the same size.
  1466. */
  1467. if (cc->key_size % cc->key_parts) {
  1468. cc->key_parts++;
  1469. cc->key_extra_size = cc->key_size / cc->key_parts;
  1470. }
  1471. } else if (strcmp(ivmode, "tcw") == 0) {
  1472. cc->iv_gen_ops = &crypt_iv_tcw_ops;
  1473. cc->key_parts += 2; /* IV + whitening */
  1474. cc->key_extra_size = cc->iv_size + TCW_WHITENING_SIZE;
  1475. } else {
  1476. ret = -EINVAL;
  1477. ti->error = "Invalid IV mode";
  1478. goto bad;
  1479. }
  1480. /* Initialize and set key */
  1481. ret = crypt_set_key(cc, key);
  1482. if (ret < 0) {
  1483. ti->error = "Error decoding and setting key";
  1484. goto bad;
  1485. }
  1486. /* Allocate IV */
  1487. if (cc->iv_gen_ops && cc->iv_gen_ops->ctr) {
  1488. ret = cc->iv_gen_ops->ctr(cc, ti, ivopts);
  1489. if (ret < 0) {
  1490. ti->error = "Error creating IV";
  1491. goto bad;
  1492. }
  1493. }
  1494. /* Initialize IV (set keys for ESSIV etc) */
  1495. if (cc->iv_gen_ops && cc->iv_gen_ops->init) {
  1496. ret = cc->iv_gen_ops->init(cc);
  1497. if (ret < 0) {
  1498. ti->error = "Error initialising IV";
  1499. goto bad;
  1500. }
  1501. }
  1502. ret = 0;
  1503. bad:
  1504. kfree(cipher_api);
  1505. return ret;
  1506. bad_mem:
  1507. ti->error = "Cannot allocate cipher strings";
  1508. return -ENOMEM;
  1509. }
  1510. /*
  1511. * Construct an encryption mapping:
  1512. * <cipher> [<key>|:<key_size>:<user|logon>:<key_description>] <iv_offset> <dev_path> <start>
  1513. */
  1514. static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
  1515. {
  1516. struct crypt_config *cc;
  1517. int key_size;
  1518. unsigned int opt_params;
  1519. unsigned long long tmpll;
  1520. int ret;
  1521. size_t iv_size_padding;
  1522. struct dm_arg_set as;
  1523. const char *opt_string;
  1524. char dummy;
  1525. static struct dm_arg _args[] = {
  1526. {0, 3, "Invalid number of feature args"},
  1527. };
  1528. if (argc < 5) {
  1529. ti->error = "Not enough arguments";
  1530. return -EINVAL;
  1531. }
  1532. key_size = get_key_size(&argv[1]);
  1533. if (key_size < 0) {
  1534. ti->error = "Cannot parse key size";
  1535. return -EINVAL;
  1536. }
  1537. cc = kzalloc(sizeof(*cc) + key_size * sizeof(u8), GFP_KERNEL);
  1538. if (!cc) {
  1539. ti->error = "Cannot allocate encryption context";
  1540. return -ENOMEM;
  1541. }
  1542. cc->key_size = key_size;
  1543. ti->private = cc;
  1544. ret = crypt_ctr_cipher(ti, argv[0], argv[1]);
  1545. if (ret < 0)
  1546. goto bad;
  1547. cc->dmreq_start = sizeof(struct skcipher_request);
  1548. cc->dmreq_start += crypto_skcipher_reqsize(any_tfm(cc));
  1549. cc->dmreq_start = ALIGN(cc->dmreq_start, __alignof__(struct dm_crypt_request));
  1550. if (crypto_skcipher_alignmask(any_tfm(cc)) < CRYPTO_MINALIGN) {
  1551. /* Allocate the padding exactly */
  1552. iv_size_padding = -(cc->dmreq_start + sizeof(struct dm_crypt_request))
  1553. & crypto_skcipher_alignmask(any_tfm(cc));
  1554. } else {
  1555. /*
  1556. * If the cipher requires greater alignment than kmalloc
  1557. * alignment, we don't know the exact position of the
  1558. * initialization vector. We must assume worst case.
  1559. */
  1560. iv_size_padding = crypto_skcipher_alignmask(any_tfm(cc));
  1561. }
  1562. ret = -ENOMEM;
  1563. cc->req_pool = mempool_create_kmalloc_pool(MIN_IOS, cc->dmreq_start +
  1564. sizeof(struct dm_crypt_request) + iv_size_padding + cc->iv_size);
  1565. if (!cc->req_pool) {
  1566. ti->error = "Cannot allocate crypt request mempool";
  1567. goto bad;
  1568. }
  1569. cc->per_bio_data_size = ti->per_io_data_size =
  1570. ALIGN(sizeof(struct dm_crypt_io) + cc->dmreq_start +
  1571. sizeof(struct dm_crypt_request) + iv_size_padding + cc->iv_size,
  1572. ARCH_KMALLOC_MINALIGN);
  1573. cc->page_pool = mempool_create_page_pool(BIO_MAX_PAGES, 0);
  1574. if (!cc->page_pool) {
  1575. ti->error = "Cannot allocate page mempool";
  1576. goto bad;
  1577. }
  1578. cc->bs = bioset_create(MIN_IOS, 0);
  1579. if (!cc->bs) {
  1580. ti->error = "Cannot allocate crypt bioset";
  1581. goto bad;
  1582. }
  1583. mutex_init(&cc->bio_alloc_lock);
  1584. ret = -EINVAL;
  1585. if (sscanf(argv[2], "%llu%c", &tmpll, &dummy) != 1) {
  1586. ti->error = "Invalid iv_offset sector";
  1587. goto bad;
  1588. }
  1589. cc->iv_offset = tmpll;
  1590. ret = dm_get_device(ti, argv[3], dm_table_get_mode(ti->table), &cc->dev);
  1591. if (ret) {
  1592. ti->error = "Device lookup failed";
  1593. goto bad;
  1594. }
  1595. ret = -EINVAL;
  1596. if (sscanf(argv[4], "%llu%c", &tmpll, &dummy) != 1) {
  1597. ti->error = "Invalid device sector";
  1598. goto bad;
  1599. }
  1600. cc->start = tmpll;
  1601. argv += 5;
  1602. argc -= 5;
  1603. /* Optional parameters */
  1604. if (argc) {
  1605. as.argc = argc;
  1606. as.argv = argv;
  1607. ret = dm_read_arg_group(_args, &as, &opt_params, &ti->error);
  1608. if (ret)
  1609. goto bad;
  1610. ret = -EINVAL;
  1611. while (opt_params--) {
  1612. opt_string = dm_shift_arg(&as);
  1613. if (!opt_string) {
  1614. ti->error = "Not enough feature arguments";
  1615. goto bad;
  1616. }
  1617. if (!strcasecmp(opt_string, "allow_discards"))
  1618. ti->num_discard_bios = 1;
  1619. else if (!strcasecmp(opt_string, "same_cpu_crypt"))
  1620. set_bit(DM_CRYPT_SAME_CPU, &cc->flags);
  1621. else if (!strcasecmp(opt_string, "submit_from_crypt_cpus"))
  1622. set_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
  1623. else {
  1624. ti->error = "Invalid feature arguments";
  1625. goto bad;
  1626. }
  1627. }
  1628. }
  1629. ret = -ENOMEM;
  1630. cc->io_queue = alloc_workqueue("kcryptd_io", WQ_MEM_RECLAIM, 1);
  1631. if (!cc->io_queue) {
  1632. ti->error = "Couldn't create kcryptd io queue";
  1633. goto bad;
  1634. }
  1635. if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
  1636. cc->crypt_queue = alloc_workqueue("kcryptd", WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM, 1);
  1637. else
  1638. cc->crypt_queue = alloc_workqueue("kcryptd", WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM | WQ_UNBOUND,
  1639. num_online_cpus());
  1640. if (!cc->crypt_queue) {
  1641. ti->error = "Couldn't create kcryptd queue";
  1642. goto bad;
  1643. }
  1644. init_waitqueue_head(&cc->write_thread_wait);
  1645. cc->write_tree = RB_ROOT;
  1646. cc->write_thread = kthread_create(dmcrypt_write, cc, "dmcrypt_write");
  1647. if (IS_ERR(cc->write_thread)) {
  1648. ret = PTR_ERR(cc->write_thread);
  1649. cc->write_thread = NULL;
  1650. ti->error = "Couldn't spawn write thread";
  1651. goto bad;
  1652. }
  1653. wake_up_process(cc->write_thread);
  1654. ti->num_flush_bios = 1;
  1655. ti->discard_zeroes_data_unsupported = true;
  1656. return 0;
  1657. bad:
  1658. crypt_dtr(ti);
  1659. return ret;
  1660. }
  1661. static int crypt_map(struct dm_target *ti, struct bio *bio)
  1662. {
  1663. struct dm_crypt_io *io;
  1664. struct crypt_config *cc = ti->private;
  1665. /*
  1666. * If bio is REQ_PREFLUSH or REQ_OP_DISCARD, just bypass crypt queues.
  1667. * - for REQ_PREFLUSH device-mapper core ensures that no IO is in-flight
  1668. * - for REQ_OP_DISCARD caller must use flush if IO ordering matters
  1669. */
  1670. if (unlikely(bio->bi_opf & REQ_PREFLUSH ||
  1671. bio_op(bio) == REQ_OP_DISCARD)) {
  1672. bio->bi_bdev = cc->dev->bdev;
  1673. if (bio_sectors(bio))
  1674. bio->bi_iter.bi_sector = cc->start +
  1675. dm_target_offset(ti, bio->bi_iter.bi_sector);
  1676. return DM_MAPIO_REMAPPED;
  1677. }
  1678. /*
  1679. * Check if bio is too large, split as needed.
  1680. */
  1681. if (unlikely(bio->bi_iter.bi_size > (BIO_MAX_PAGES << PAGE_SHIFT)) &&
  1682. bio_data_dir(bio) == WRITE)
  1683. dm_accept_partial_bio(bio, ((BIO_MAX_PAGES << PAGE_SHIFT) >> SECTOR_SHIFT));
  1684. io = dm_per_bio_data(bio, cc->per_bio_data_size);
  1685. crypt_io_init(io, cc, bio, dm_target_offset(ti, bio->bi_iter.bi_sector));
  1686. io->ctx.req = (struct skcipher_request *)(io + 1);
  1687. if (bio_data_dir(io->base_bio) == READ) {
  1688. if (kcryptd_io_read(io, GFP_NOWAIT))
  1689. kcryptd_queue_read(io);
  1690. } else
  1691. kcryptd_queue_crypt(io);
  1692. return DM_MAPIO_SUBMITTED;
  1693. }
  1694. static void crypt_status(struct dm_target *ti, status_type_t type,
  1695. unsigned status_flags, char *result, unsigned maxlen)
  1696. {
  1697. struct crypt_config *cc = ti->private;
  1698. unsigned i, sz = 0;
  1699. int num_feature_args = 0;
  1700. switch (type) {
  1701. case STATUSTYPE_INFO:
  1702. result[0] = '\0';
  1703. break;
  1704. case STATUSTYPE_TABLE:
  1705. DMEMIT("%s ", cc->cipher_string);
  1706. if (cc->key_size > 0) {
  1707. if (cc->key_string)
  1708. DMEMIT(":%u:%s", cc->key_size, cc->key_string);
  1709. else
  1710. for (i = 0; i < cc->key_size; i++)
  1711. DMEMIT("%02x", cc->key[i]);
  1712. } else
  1713. DMEMIT("-");
  1714. DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
  1715. cc->dev->name, (unsigned long long)cc->start);
  1716. num_feature_args += !!ti->num_discard_bios;
  1717. num_feature_args += test_bit(DM_CRYPT_SAME_CPU, &cc->flags);
  1718. num_feature_args += test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
  1719. if (num_feature_args) {
  1720. DMEMIT(" %d", num_feature_args);
  1721. if (ti->num_discard_bios)
  1722. DMEMIT(" allow_discards");
  1723. if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
  1724. DMEMIT(" same_cpu_crypt");
  1725. if (test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags))
  1726. DMEMIT(" submit_from_crypt_cpus");
  1727. }
  1728. break;
  1729. }
  1730. }
  1731. static void crypt_postsuspend(struct dm_target *ti)
  1732. {
  1733. struct crypt_config *cc = ti->private;
  1734. set_bit(DM_CRYPT_SUSPENDED, &cc->flags);
  1735. }
  1736. static int crypt_preresume(struct dm_target *ti)
  1737. {
  1738. struct crypt_config *cc = ti->private;
  1739. if (!test_bit(DM_CRYPT_KEY_VALID, &cc->flags)) {
  1740. DMERR("aborting resume - crypt key is not set.");
  1741. return -EAGAIN;
  1742. }
  1743. return 0;
  1744. }
  1745. static void crypt_resume(struct dm_target *ti)
  1746. {
  1747. struct crypt_config *cc = ti->private;
  1748. clear_bit(DM_CRYPT_SUSPENDED, &cc->flags);
  1749. }
  1750. /* Message interface
  1751. * key set <key>
  1752. * key wipe
  1753. */
  1754. static int crypt_message(struct dm_target *ti, unsigned argc, char **argv)
  1755. {
  1756. struct crypt_config *cc = ti->private;
  1757. int key_size, ret = -EINVAL;
  1758. if (argc < 2)
  1759. goto error;
  1760. if (!strcasecmp(argv[0], "key")) {
  1761. if (!test_bit(DM_CRYPT_SUSPENDED, &cc->flags)) {
  1762. DMWARN("not suspended during key manipulation.");
  1763. return -EINVAL;
  1764. }
  1765. if (argc == 3 && !strcasecmp(argv[1], "set")) {
  1766. /* The key size may not be changed. */
  1767. key_size = get_key_size(&argv[2]);
  1768. if (key_size < 0 || cc->key_size != key_size) {
  1769. memset(argv[2], '0', strlen(argv[2]));
  1770. return -EINVAL;
  1771. }
  1772. ret = crypt_set_key(cc, argv[2]);
  1773. if (ret)
  1774. return ret;
  1775. if (cc->iv_gen_ops && cc->iv_gen_ops->init)
  1776. ret = cc->iv_gen_ops->init(cc);
  1777. return ret;
  1778. }
  1779. if (argc == 2 && !strcasecmp(argv[1], "wipe")) {
  1780. if (cc->iv_gen_ops && cc->iv_gen_ops->wipe) {
  1781. ret = cc->iv_gen_ops->wipe(cc);
  1782. if (ret)
  1783. return ret;
  1784. }
  1785. return crypt_wipe_key(cc);
  1786. }
  1787. }
  1788. error:
  1789. DMWARN("unrecognised message received.");
  1790. return -EINVAL;
  1791. }
  1792. static int crypt_iterate_devices(struct dm_target *ti,
  1793. iterate_devices_callout_fn fn, void *data)
  1794. {
  1795. struct crypt_config *cc = ti->private;
  1796. return fn(ti, cc->dev, cc->start, ti->len, data);
  1797. }
  1798. static void crypt_io_hints(struct dm_target *ti, struct queue_limits *limits)
  1799. {
  1800. /*
  1801. * Unfortunate constraint that is required to avoid the potential
  1802. * for exceeding underlying device's max_segments limits -- due to
  1803. * crypt_alloc_buffer() possibly allocating pages for the encryption
  1804. * bio that are not as physically contiguous as the original bio.
  1805. */
  1806. limits->max_segment_size = PAGE_SIZE;
  1807. }
  1808. static struct target_type crypt_target = {
  1809. .name = "crypt",
  1810. .version = {1, 15, 0},
  1811. .module = THIS_MODULE,
  1812. .ctr = crypt_ctr,
  1813. .dtr = crypt_dtr,
  1814. .map = crypt_map,
  1815. .status = crypt_status,
  1816. .postsuspend = crypt_postsuspend,
  1817. .preresume = crypt_preresume,
  1818. .resume = crypt_resume,
  1819. .message = crypt_message,
  1820. .iterate_devices = crypt_iterate_devices,
  1821. .io_hints = crypt_io_hints,
  1822. };
  1823. static int __init dm_crypt_init(void)
  1824. {
  1825. int r;
  1826. r = dm_register_target(&crypt_target);
  1827. if (r < 0)
  1828. DMERR("register failed %d", r);
  1829. return r;
  1830. }
  1831. static void __exit dm_crypt_exit(void)
  1832. {
  1833. dm_unregister_target(&crypt_target);
  1834. }
  1835. module_init(dm_crypt_init);
  1836. module_exit(dm_crypt_exit);
  1837. MODULE_AUTHOR("Jana Saout <jana@saout.de>");
  1838. MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
  1839. MODULE_LICENSE("GPL");