dm-crypt.c 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125
  1. /*
  2. * Copyright (C) 2003 Jana Saout <jana@saout.de>
  3. * Copyright (C) 2004 Clemens Fruhwirth <clemens@endorphin.org>
  4. * Copyright (C) 2006-2017 Red Hat, Inc. All rights reserved.
  5. * Copyright (C) 2013-2017 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 <crypto/aead.h>
  34. #include <crypto/authenc.h>
  35. #include <linux/rtnetlink.h> /* for struct rtattr and RTA macros only */
  36. #include <keys/user-type.h>
  37. #include <linux/device-mapper.h>
  38. #define DM_MSG_PREFIX "crypt"
  39. /*
  40. * context holding the current state of a multi-part conversion
  41. */
  42. struct convert_context {
  43. struct completion restart;
  44. struct bio *bio_in;
  45. struct bio *bio_out;
  46. struct bvec_iter iter_in;
  47. struct bvec_iter iter_out;
  48. u64 cc_sector;
  49. atomic_t cc_pending;
  50. union {
  51. struct skcipher_request *req;
  52. struct aead_request *req_aead;
  53. } r;
  54. };
  55. /*
  56. * per bio private data
  57. */
  58. struct dm_crypt_io {
  59. struct crypt_config *cc;
  60. struct bio *base_bio;
  61. u8 *integrity_metadata;
  62. bool integrity_metadata_from_pool;
  63. struct work_struct work;
  64. struct convert_context ctx;
  65. atomic_t io_pending;
  66. blk_status_t error;
  67. sector_t sector;
  68. struct rb_node rb_node;
  69. } CRYPTO_MINALIGN_ATTR;
  70. struct dm_crypt_request {
  71. struct convert_context *ctx;
  72. struct scatterlist sg_in[4];
  73. struct scatterlist sg_out[4];
  74. u64 iv_sector;
  75. };
  76. struct crypt_config;
  77. struct crypt_iv_operations {
  78. int (*ctr)(struct crypt_config *cc, struct dm_target *ti,
  79. const char *opts);
  80. void (*dtr)(struct crypt_config *cc);
  81. int (*init)(struct crypt_config *cc);
  82. int (*wipe)(struct crypt_config *cc);
  83. int (*generator)(struct crypt_config *cc, u8 *iv,
  84. struct dm_crypt_request *dmreq);
  85. int (*post)(struct crypt_config *cc, u8 *iv,
  86. struct dm_crypt_request *dmreq);
  87. };
  88. struct iv_essiv_private {
  89. struct crypto_shash *hash_tfm;
  90. u8 *salt;
  91. };
  92. struct iv_benbi_private {
  93. int shift;
  94. };
  95. #define LMK_SEED_SIZE 64 /* hash + 0 */
  96. struct iv_lmk_private {
  97. struct crypto_shash *hash_tfm;
  98. u8 *seed;
  99. };
  100. #define TCW_WHITENING_SIZE 16
  101. struct iv_tcw_private {
  102. struct crypto_shash *crc32_tfm;
  103. u8 *iv_seed;
  104. u8 *whitening;
  105. };
  106. /*
  107. * Crypt: maps a linear range of a block device
  108. * and encrypts / decrypts at the same time.
  109. */
  110. enum flags { DM_CRYPT_SUSPENDED, DM_CRYPT_KEY_VALID,
  111. DM_CRYPT_SAME_CPU, DM_CRYPT_NO_OFFLOAD };
  112. enum cipher_flags {
  113. CRYPT_MODE_INTEGRITY_AEAD, /* Use authenticated mode for cihper */
  114. CRYPT_IV_LARGE_SECTORS, /* Calculate IV from sector_size, not 512B sectors */
  115. };
  116. /*
  117. * The fields in here must be read only after initialization.
  118. */
  119. struct crypt_config {
  120. struct dm_dev *dev;
  121. sector_t start;
  122. struct percpu_counter n_allocated_pages;
  123. struct workqueue_struct *io_queue;
  124. struct workqueue_struct *crypt_queue;
  125. spinlock_t write_thread_lock;
  126. struct task_struct *write_thread;
  127. struct rb_root write_tree;
  128. char *cipher;
  129. char *cipher_string;
  130. char *cipher_auth;
  131. char *key_string;
  132. const struct crypt_iv_operations *iv_gen_ops;
  133. union {
  134. struct iv_essiv_private essiv;
  135. struct iv_benbi_private benbi;
  136. struct iv_lmk_private lmk;
  137. struct iv_tcw_private tcw;
  138. } iv_gen_private;
  139. u64 iv_offset;
  140. unsigned int iv_size;
  141. unsigned short int sector_size;
  142. unsigned char sector_shift;
  143. /* ESSIV: struct crypto_cipher *essiv_tfm */
  144. void *iv_private;
  145. union {
  146. struct crypto_skcipher **tfms;
  147. struct crypto_aead **tfms_aead;
  148. } cipher_tfm;
  149. unsigned tfms_count;
  150. unsigned long cipher_flags;
  151. /*
  152. * Layout of each crypto request:
  153. *
  154. * struct skcipher_request
  155. * context
  156. * padding
  157. * struct dm_crypt_request
  158. * padding
  159. * IV
  160. *
  161. * The padding is added so that dm_crypt_request and the IV are
  162. * correctly aligned.
  163. */
  164. unsigned int dmreq_start;
  165. unsigned int per_bio_data_size;
  166. unsigned long flags;
  167. unsigned int key_size;
  168. unsigned int key_parts; /* independent parts in key buffer */
  169. unsigned int key_extra_size; /* additional keys length */
  170. unsigned int key_mac_size; /* MAC key size for authenc(...) */
  171. unsigned int integrity_tag_size;
  172. unsigned int integrity_iv_size;
  173. unsigned int on_disk_tag_size;
  174. /*
  175. * pool for per bio private data, crypto requests,
  176. * encryption requeusts/buffer pages and integrity tags
  177. */
  178. unsigned tag_pool_max_sectors;
  179. mempool_t tag_pool;
  180. mempool_t req_pool;
  181. mempool_t page_pool;
  182. struct bio_set bs;
  183. struct mutex bio_alloc_lock;
  184. u8 *authenc_key; /* space for keys in authenc() format (if used) */
  185. u8 key[0];
  186. };
  187. #define MIN_IOS 64
  188. #define MAX_TAG_SIZE 480
  189. #define POOL_ENTRY_SIZE 512
  190. static DEFINE_SPINLOCK(dm_crypt_clients_lock);
  191. static unsigned dm_crypt_clients_n = 0;
  192. static volatile unsigned long dm_crypt_pages_per_client;
  193. #define DM_CRYPT_MEMORY_PERCENT 2
  194. #define DM_CRYPT_MIN_PAGES_PER_CLIENT (BIO_MAX_PAGES * 16)
  195. static void clone_init(struct dm_crypt_io *, struct bio *);
  196. static void kcryptd_queue_crypt(struct dm_crypt_io *io);
  197. static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
  198. struct scatterlist *sg);
  199. /*
  200. * Use this to access cipher attributes that are independent of the key.
  201. */
  202. static struct crypto_skcipher *any_tfm(struct crypt_config *cc)
  203. {
  204. return cc->cipher_tfm.tfms[0];
  205. }
  206. static struct crypto_aead *any_tfm_aead(struct crypt_config *cc)
  207. {
  208. return cc->cipher_tfm.tfms_aead[0];
  209. }
  210. /*
  211. * Different IV generation algorithms:
  212. *
  213. * plain: the initial vector is the 32-bit little-endian version of the sector
  214. * number, padded with zeros if necessary.
  215. *
  216. * plain64: the initial vector is the 64-bit little-endian version of the sector
  217. * number, padded with zeros if necessary.
  218. *
  219. * plain64be: the initial vector is the 64-bit big-endian version of the sector
  220. * number, padded with zeros if necessary.
  221. *
  222. * essiv: "encrypted sector|salt initial vector", the sector number is
  223. * encrypted with the bulk cipher using a salt as key. The salt
  224. * should be derived from the bulk cipher's key via hashing.
  225. *
  226. * benbi: the 64-bit "big-endian 'narrow block'-count", starting at 1
  227. * (needed for LRW-32-AES and possible other narrow block modes)
  228. *
  229. * null: the initial vector is always zero. Provides compatibility with
  230. * obsolete loop_fish2 devices. Do not use for new devices.
  231. *
  232. * lmk: Compatible implementation of the block chaining mode used
  233. * by the Loop-AES block device encryption system
  234. * designed by Jari Ruusu. See http://loop-aes.sourceforge.net/
  235. * It operates on full 512 byte sectors and uses CBC
  236. * with an IV derived from the sector number, the data and
  237. * optionally extra IV seed.
  238. * This means that after decryption the first block
  239. * of sector must be tweaked according to decrypted data.
  240. * Loop-AES can use three encryption schemes:
  241. * version 1: is plain aes-cbc mode
  242. * version 2: uses 64 multikey scheme with lmk IV generator
  243. * version 3: the same as version 2 with additional IV seed
  244. * (it uses 65 keys, last key is used as IV seed)
  245. *
  246. * tcw: Compatible implementation of the block chaining mode used
  247. * by the TrueCrypt device encryption system (prior to version 4.1).
  248. * For more info see: https://gitlab.com/cryptsetup/cryptsetup/wikis/TrueCryptOnDiskFormat
  249. * It operates on full 512 byte sectors and uses CBC
  250. * with an IV derived from initial key and the sector number.
  251. * In addition, whitening value is applied on every sector, whitening
  252. * is calculated from initial key, sector number and mixed using CRC32.
  253. * Note that this encryption scheme is vulnerable to watermarking attacks
  254. * and should be used for old compatible containers access only.
  255. *
  256. * plumb: unimplemented, see:
  257. * http://article.gmane.org/gmane.linux.kernel.device-mapper.dm-crypt/454
  258. */
  259. static int crypt_iv_plain_gen(struct crypt_config *cc, u8 *iv,
  260. struct dm_crypt_request *dmreq)
  261. {
  262. memset(iv, 0, cc->iv_size);
  263. *(__le32 *)iv = cpu_to_le32(dmreq->iv_sector & 0xffffffff);
  264. return 0;
  265. }
  266. static int crypt_iv_plain64_gen(struct crypt_config *cc, u8 *iv,
  267. struct dm_crypt_request *dmreq)
  268. {
  269. memset(iv, 0, cc->iv_size);
  270. *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
  271. return 0;
  272. }
  273. static int crypt_iv_plain64be_gen(struct crypt_config *cc, u8 *iv,
  274. struct dm_crypt_request *dmreq)
  275. {
  276. memset(iv, 0, cc->iv_size);
  277. /* iv_size is at least of size u64; usually it is 16 bytes */
  278. *(__be64 *)&iv[cc->iv_size - sizeof(u64)] = cpu_to_be64(dmreq->iv_sector);
  279. return 0;
  280. }
  281. /* Initialise ESSIV - compute salt but no local memory allocations */
  282. static int crypt_iv_essiv_init(struct crypt_config *cc)
  283. {
  284. struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
  285. SHASH_DESC_ON_STACK(desc, essiv->hash_tfm);
  286. struct crypto_cipher *essiv_tfm;
  287. int err;
  288. desc->tfm = essiv->hash_tfm;
  289. desc->flags = 0;
  290. err = crypto_shash_digest(desc, cc->key, cc->key_size, essiv->salt);
  291. shash_desc_zero(desc);
  292. if (err)
  293. return err;
  294. essiv_tfm = cc->iv_private;
  295. err = crypto_cipher_setkey(essiv_tfm, essiv->salt,
  296. crypto_shash_digestsize(essiv->hash_tfm));
  297. if (err)
  298. return err;
  299. return 0;
  300. }
  301. /* Wipe salt and reset key derived from volume key */
  302. static int crypt_iv_essiv_wipe(struct crypt_config *cc)
  303. {
  304. struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
  305. unsigned salt_size = crypto_shash_digestsize(essiv->hash_tfm);
  306. struct crypto_cipher *essiv_tfm;
  307. int r, err = 0;
  308. memset(essiv->salt, 0, salt_size);
  309. essiv_tfm = cc->iv_private;
  310. r = crypto_cipher_setkey(essiv_tfm, essiv->salt, salt_size);
  311. if (r)
  312. err = r;
  313. return err;
  314. }
  315. /* Allocate the cipher for ESSIV */
  316. static struct crypto_cipher *alloc_essiv_cipher(struct crypt_config *cc,
  317. struct dm_target *ti,
  318. const u8 *salt,
  319. unsigned int saltsize)
  320. {
  321. struct crypto_cipher *essiv_tfm;
  322. int err;
  323. /* Setup the essiv_tfm with the given salt */
  324. essiv_tfm = crypto_alloc_cipher(cc->cipher, 0, CRYPTO_ALG_ASYNC);
  325. if (IS_ERR(essiv_tfm)) {
  326. ti->error = "Error allocating crypto tfm for ESSIV";
  327. return essiv_tfm;
  328. }
  329. if (crypto_cipher_blocksize(essiv_tfm) != cc->iv_size) {
  330. ti->error = "Block size of ESSIV cipher does "
  331. "not match IV size of block cipher";
  332. crypto_free_cipher(essiv_tfm);
  333. return ERR_PTR(-EINVAL);
  334. }
  335. err = crypto_cipher_setkey(essiv_tfm, salt, saltsize);
  336. if (err) {
  337. ti->error = "Failed to set key for ESSIV cipher";
  338. crypto_free_cipher(essiv_tfm);
  339. return ERR_PTR(err);
  340. }
  341. return essiv_tfm;
  342. }
  343. static void crypt_iv_essiv_dtr(struct crypt_config *cc)
  344. {
  345. struct crypto_cipher *essiv_tfm;
  346. struct iv_essiv_private *essiv = &cc->iv_gen_private.essiv;
  347. crypto_free_shash(essiv->hash_tfm);
  348. essiv->hash_tfm = NULL;
  349. kzfree(essiv->salt);
  350. essiv->salt = NULL;
  351. essiv_tfm = cc->iv_private;
  352. if (essiv_tfm)
  353. crypto_free_cipher(essiv_tfm);
  354. cc->iv_private = NULL;
  355. }
  356. static int crypt_iv_essiv_ctr(struct crypt_config *cc, struct dm_target *ti,
  357. const char *opts)
  358. {
  359. struct crypto_cipher *essiv_tfm = NULL;
  360. struct crypto_shash *hash_tfm = NULL;
  361. u8 *salt = NULL;
  362. int err;
  363. if (!opts) {
  364. ti->error = "Digest algorithm missing for ESSIV mode";
  365. return -EINVAL;
  366. }
  367. /* Allocate hash algorithm */
  368. hash_tfm = crypto_alloc_shash(opts, 0, 0);
  369. if (IS_ERR(hash_tfm)) {
  370. ti->error = "Error initializing ESSIV hash";
  371. err = PTR_ERR(hash_tfm);
  372. goto bad;
  373. }
  374. salt = kzalloc(crypto_shash_digestsize(hash_tfm), GFP_KERNEL);
  375. if (!salt) {
  376. ti->error = "Error kmallocing salt storage in ESSIV";
  377. err = -ENOMEM;
  378. goto bad;
  379. }
  380. cc->iv_gen_private.essiv.salt = salt;
  381. cc->iv_gen_private.essiv.hash_tfm = hash_tfm;
  382. essiv_tfm = alloc_essiv_cipher(cc, ti, salt,
  383. crypto_shash_digestsize(hash_tfm));
  384. if (IS_ERR(essiv_tfm)) {
  385. crypt_iv_essiv_dtr(cc);
  386. return PTR_ERR(essiv_tfm);
  387. }
  388. cc->iv_private = essiv_tfm;
  389. return 0;
  390. bad:
  391. if (hash_tfm && !IS_ERR(hash_tfm))
  392. crypto_free_shash(hash_tfm);
  393. kfree(salt);
  394. return err;
  395. }
  396. static int crypt_iv_essiv_gen(struct crypt_config *cc, u8 *iv,
  397. struct dm_crypt_request *dmreq)
  398. {
  399. struct crypto_cipher *essiv_tfm = cc->iv_private;
  400. memset(iv, 0, cc->iv_size);
  401. *(__le64 *)iv = cpu_to_le64(dmreq->iv_sector);
  402. crypto_cipher_encrypt_one(essiv_tfm, iv, iv);
  403. return 0;
  404. }
  405. static int crypt_iv_benbi_ctr(struct crypt_config *cc, struct dm_target *ti,
  406. const char *opts)
  407. {
  408. unsigned bs;
  409. int log;
  410. if (test_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags))
  411. bs = crypto_aead_blocksize(any_tfm_aead(cc));
  412. else
  413. bs = crypto_skcipher_blocksize(any_tfm(cc));
  414. log = ilog2(bs);
  415. /* we need to calculate how far we must shift the sector count
  416. * to get the cipher block count, we use this shift in _gen */
  417. if (1 << log != bs) {
  418. ti->error = "cypher blocksize is not a power of 2";
  419. return -EINVAL;
  420. }
  421. if (log > 9) {
  422. ti->error = "cypher blocksize is > 512";
  423. return -EINVAL;
  424. }
  425. cc->iv_gen_private.benbi.shift = 9 - log;
  426. return 0;
  427. }
  428. static void crypt_iv_benbi_dtr(struct crypt_config *cc)
  429. {
  430. }
  431. static int crypt_iv_benbi_gen(struct crypt_config *cc, u8 *iv,
  432. struct dm_crypt_request *dmreq)
  433. {
  434. __be64 val;
  435. memset(iv, 0, cc->iv_size - sizeof(u64)); /* rest is cleared below */
  436. val = cpu_to_be64(((u64)dmreq->iv_sector << cc->iv_gen_private.benbi.shift) + 1);
  437. put_unaligned(val, (__be64 *)(iv + cc->iv_size - sizeof(u64)));
  438. return 0;
  439. }
  440. static int crypt_iv_null_gen(struct crypt_config *cc, u8 *iv,
  441. struct dm_crypt_request *dmreq)
  442. {
  443. memset(iv, 0, cc->iv_size);
  444. return 0;
  445. }
  446. static void crypt_iv_lmk_dtr(struct crypt_config *cc)
  447. {
  448. struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
  449. if (lmk->hash_tfm && !IS_ERR(lmk->hash_tfm))
  450. crypto_free_shash(lmk->hash_tfm);
  451. lmk->hash_tfm = NULL;
  452. kzfree(lmk->seed);
  453. lmk->seed = NULL;
  454. }
  455. static int crypt_iv_lmk_ctr(struct crypt_config *cc, struct dm_target *ti,
  456. const char *opts)
  457. {
  458. struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
  459. if (cc->sector_size != (1 << SECTOR_SHIFT)) {
  460. ti->error = "Unsupported sector size for LMK";
  461. return -EINVAL;
  462. }
  463. lmk->hash_tfm = crypto_alloc_shash("md5", 0, 0);
  464. if (IS_ERR(lmk->hash_tfm)) {
  465. ti->error = "Error initializing LMK hash";
  466. return PTR_ERR(lmk->hash_tfm);
  467. }
  468. /* No seed in LMK version 2 */
  469. if (cc->key_parts == cc->tfms_count) {
  470. lmk->seed = NULL;
  471. return 0;
  472. }
  473. lmk->seed = kzalloc(LMK_SEED_SIZE, GFP_KERNEL);
  474. if (!lmk->seed) {
  475. crypt_iv_lmk_dtr(cc);
  476. ti->error = "Error kmallocing seed storage in LMK";
  477. return -ENOMEM;
  478. }
  479. return 0;
  480. }
  481. static int crypt_iv_lmk_init(struct crypt_config *cc)
  482. {
  483. struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
  484. int subkey_size = cc->key_size / cc->key_parts;
  485. /* LMK seed is on the position of LMK_KEYS + 1 key */
  486. if (lmk->seed)
  487. memcpy(lmk->seed, cc->key + (cc->tfms_count * subkey_size),
  488. crypto_shash_digestsize(lmk->hash_tfm));
  489. return 0;
  490. }
  491. static int crypt_iv_lmk_wipe(struct crypt_config *cc)
  492. {
  493. struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
  494. if (lmk->seed)
  495. memset(lmk->seed, 0, LMK_SEED_SIZE);
  496. return 0;
  497. }
  498. static int crypt_iv_lmk_one(struct crypt_config *cc, u8 *iv,
  499. struct dm_crypt_request *dmreq,
  500. u8 *data)
  501. {
  502. struct iv_lmk_private *lmk = &cc->iv_gen_private.lmk;
  503. SHASH_DESC_ON_STACK(desc, lmk->hash_tfm);
  504. struct md5_state md5state;
  505. __le32 buf[4];
  506. int i, r;
  507. desc->tfm = lmk->hash_tfm;
  508. desc->flags = 0;
  509. r = crypto_shash_init(desc);
  510. if (r)
  511. return r;
  512. if (lmk->seed) {
  513. r = crypto_shash_update(desc, lmk->seed, LMK_SEED_SIZE);
  514. if (r)
  515. return r;
  516. }
  517. /* Sector is always 512B, block size 16, add data of blocks 1-31 */
  518. r = crypto_shash_update(desc, data + 16, 16 * 31);
  519. if (r)
  520. return r;
  521. /* Sector is cropped to 56 bits here */
  522. buf[0] = cpu_to_le32(dmreq->iv_sector & 0xFFFFFFFF);
  523. buf[1] = cpu_to_le32((((u64)dmreq->iv_sector >> 32) & 0x00FFFFFF) | 0x80000000);
  524. buf[2] = cpu_to_le32(4024);
  525. buf[3] = 0;
  526. r = crypto_shash_update(desc, (u8 *)buf, sizeof(buf));
  527. if (r)
  528. return r;
  529. /* No MD5 padding here */
  530. r = crypto_shash_export(desc, &md5state);
  531. if (r)
  532. return r;
  533. for (i = 0; i < MD5_HASH_WORDS; i++)
  534. __cpu_to_le32s(&md5state.hash[i]);
  535. memcpy(iv, &md5state.hash, cc->iv_size);
  536. return 0;
  537. }
  538. static int crypt_iv_lmk_gen(struct crypt_config *cc, u8 *iv,
  539. struct dm_crypt_request *dmreq)
  540. {
  541. struct scatterlist *sg;
  542. u8 *src;
  543. int r = 0;
  544. if (bio_data_dir(dmreq->ctx->bio_in) == WRITE) {
  545. sg = crypt_get_sg_data(cc, dmreq->sg_in);
  546. src = kmap_atomic(sg_page(sg));
  547. r = crypt_iv_lmk_one(cc, iv, dmreq, src + sg->offset);
  548. kunmap_atomic(src);
  549. } else
  550. memset(iv, 0, cc->iv_size);
  551. return r;
  552. }
  553. static int crypt_iv_lmk_post(struct crypt_config *cc, u8 *iv,
  554. struct dm_crypt_request *dmreq)
  555. {
  556. struct scatterlist *sg;
  557. u8 *dst;
  558. int r;
  559. if (bio_data_dir(dmreq->ctx->bio_in) == WRITE)
  560. return 0;
  561. sg = crypt_get_sg_data(cc, dmreq->sg_out);
  562. dst = kmap_atomic(sg_page(sg));
  563. r = crypt_iv_lmk_one(cc, iv, dmreq, dst + sg->offset);
  564. /* Tweak the first block of plaintext sector */
  565. if (!r)
  566. crypto_xor(dst + sg->offset, iv, cc->iv_size);
  567. kunmap_atomic(dst);
  568. return r;
  569. }
  570. static void crypt_iv_tcw_dtr(struct crypt_config *cc)
  571. {
  572. struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
  573. kzfree(tcw->iv_seed);
  574. tcw->iv_seed = NULL;
  575. kzfree(tcw->whitening);
  576. tcw->whitening = NULL;
  577. if (tcw->crc32_tfm && !IS_ERR(tcw->crc32_tfm))
  578. crypto_free_shash(tcw->crc32_tfm);
  579. tcw->crc32_tfm = NULL;
  580. }
  581. static int crypt_iv_tcw_ctr(struct crypt_config *cc, struct dm_target *ti,
  582. const char *opts)
  583. {
  584. struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
  585. if (cc->sector_size != (1 << SECTOR_SHIFT)) {
  586. ti->error = "Unsupported sector size for TCW";
  587. return -EINVAL;
  588. }
  589. if (cc->key_size <= (cc->iv_size + TCW_WHITENING_SIZE)) {
  590. ti->error = "Wrong key size for TCW";
  591. return -EINVAL;
  592. }
  593. tcw->crc32_tfm = crypto_alloc_shash("crc32", 0, 0);
  594. if (IS_ERR(tcw->crc32_tfm)) {
  595. ti->error = "Error initializing CRC32 in TCW";
  596. return PTR_ERR(tcw->crc32_tfm);
  597. }
  598. tcw->iv_seed = kzalloc(cc->iv_size, GFP_KERNEL);
  599. tcw->whitening = kzalloc(TCW_WHITENING_SIZE, GFP_KERNEL);
  600. if (!tcw->iv_seed || !tcw->whitening) {
  601. crypt_iv_tcw_dtr(cc);
  602. ti->error = "Error allocating seed storage in TCW";
  603. return -ENOMEM;
  604. }
  605. return 0;
  606. }
  607. static int crypt_iv_tcw_init(struct crypt_config *cc)
  608. {
  609. struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
  610. int key_offset = cc->key_size - cc->iv_size - TCW_WHITENING_SIZE;
  611. memcpy(tcw->iv_seed, &cc->key[key_offset], cc->iv_size);
  612. memcpy(tcw->whitening, &cc->key[key_offset + cc->iv_size],
  613. TCW_WHITENING_SIZE);
  614. return 0;
  615. }
  616. static int crypt_iv_tcw_wipe(struct crypt_config *cc)
  617. {
  618. struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
  619. memset(tcw->iv_seed, 0, cc->iv_size);
  620. memset(tcw->whitening, 0, TCW_WHITENING_SIZE);
  621. return 0;
  622. }
  623. static int crypt_iv_tcw_whitening(struct crypt_config *cc,
  624. struct dm_crypt_request *dmreq,
  625. u8 *data)
  626. {
  627. struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
  628. __le64 sector = cpu_to_le64(dmreq->iv_sector);
  629. u8 buf[TCW_WHITENING_SIZE];
  630. SHASH_DESC_ON_STACK(desc, tcw->crc32_tfm);
  631. int i, r;
  632. /* xor whitening with sector number */
  633. crypto_xor_cpy(buf, tcw->whitening, (u8 *)&sector, 8);
  634. crypto_xor_cpy(&buf[8], tcw->whitening + 8, (u8 *)&sector, 8);
  635. /* calculate crc32 for every 32bit part and xor it */
  636. desc->tfm = tcw->crc32_tfm;
  637. desc->flags = 0;
  638. for (i = 0; i < 4; i++) {
  639. r = crypto_shash_init(desc);
  640. if (r)
  641. goto out;
  642. r = crypto_shash_update(desc, &buf[i * 4], 4);
  643. if (r)
  644. goto out;
  645. r = crypto_shash_final(desc, &buf[i * 4]);
  646. if (r)
  647. goto out;
  648. }
  649. crypto_xor(&buf[0], &buf[12], 4);
  650. crypto_xor(&buf[4], &buf[8], 4);
  651. /* apply whitening (8 bytes) to whole sector */
  652. for (i = 0; i < ((1 << SECTOR_SHIFT) / 8); i++)
  653. crypto_xor(data + i * 8, buf, 8);
  654. out:
  655. memzero_explicit(buf, sizeof(buf));
  656. return r;
  657. }
  658. static int crypt_iv_tcw_gen(struct crypt_config *cc, u8 *iv,
  659. struct dm_crypt_request *dmreq)
  660. {
  661. struct scatterlist *sg;
  662. struct iv_tcw_private *tcw = &cc->iv_gen_private.tcw;
  663. __le64 sector = cpu_to_le64(dmreq->iv_sector);
  664. u8 *src;
  665. int r = 0;
  666. /* Remove whitening from ciphertext */
  667. if (bio_data_dir(dmreq->ctx->bio_in) != WRITE) {
  668. sg = crypt_get_sg_data(cc, dmreq->sg_in);
  669. src = kmap_atomic(sg_page(sg));
  670. r = crypt_iv_tcw_whitening(cc, dmreq, src + sg->offset);
  671. kunmap_atomic(src);
  672. }
  673. /* Calculate IV */
  674. crypto_xor_cpy(iv, tcw->iv_seed, (u8 *)&sector, 8);
  675. if (cc->iv_size > 8)
  676. crypto_xor_cpy(&iv[8], tcw->iv_seed + 8, (u8 *)&sector,
  677. cc->iv_size - 8);
  678. return r;
  679. }
  680. static int crypt_iv_tcw_post(struct crypt_config *cc, u8 *iv,
  681. struct dm_crypt_request *dmreq)
  682. {
  683. struct scatterlist *sg;
  684. u8 *dst;
  685. int r;
  686. if (bio_data_dir(dmreq->ctx->bio_in) != WRITE)
  687. return 0;
  688. /* Apply whitening on ciphertext */
  689. sg = crypt_get_sg_data(cc, dmreq->sg_out);
  690. dst = kmap_atomic(sg_page(sg));
  691. r = crypt_iv_tcw_whitening(cc, dmreq, dst + sg->offset);
  692. kunmap_atomic(dst);
  693. return r;
  694. }
  695. static int crypt_iv_random_gen(struct crypt_config *cc, u8 *iv,
  696. struct dm_crypt_request *dmreq)
  697. {
  698. /* Used only for writes, there must be an additional space to store IV */
  699. get_random_bytes(iv, cc->iv_size);
  700. return 0;
  701. }
  702. static const struct crypt_iv_operations crypt_iv_plain_ops = {
  703. .generator = crypt_iv_plain_gen
  704. };
  705. static const struct crypt_iv_operations crypt_iv_plain64_ops = {
  706. .generator = crypt_iv_plain64_gen
  707. };
  708. static const struct crypt_iv_operations crypt_iv_plain64be_ops = {
  709. .generator = crypt_iv_plain64be_gen
  710. };
  711. static const struct crypt_iv_operations crypt_iv_essiv_ops = {
  712. .ctr = crypt_iv_essiv_ctr,
  713. .dtr = crypt_iv_essiv_dtr,
  714. .init = crypt_iv_essiv_init,
  715. .wipe = crypt_iv_essiv_wipe,
  716. .generator = crypt_iv_essiv_gen
  717. };
  718. static const struct crypt_iv_operations crypt_iv_benbi_ops = {
  719. .ctr = crypt_iv_benbi_ctr,
  720. .dtr = crypt_iv_benbi_dtr,
  721. .generator = crypt_iv_benbi_gen
  722. };
  723. static const struct crypt_iv_operations crypt_iv_null_ops = {
  724. .generator = crypt_iv_null_gen
  725. };
  726. static const struct crypt_iv_operations crypt_iv_lmk_ops = {
  727. .ctr = crypt_iv_lmk_ctr,
  728. .dtr = crypt_iv_lmk_dtr,
  729. .init = crypt_iv_lmk_init,
  730. .wipe = crypt_iv_lmk_wipe,
  731. .generator = crypt_iv_lmk_gen,
  732. .post = crypt_iv_lmk_post
  733. };
  734. static const struct crypt_iv_operations crypt_iv_tcw_ops = {
  735. .ctr = crypt_iv_tcw_ctr,
  736. .dtr = crypt_iv_tcw_dtr,
  737. .init = crypt_iv_tcw_init,
  738. .wipe = crypt_iv_tcw_wipe,
  739. .generator = crypt_iv_tcw_gen,
  740. .post = crypt_iv_tcw_post
  741. };
  742. static struct crypt_iv_operations crypt_iv_random_ops = {
  743. .generator = crypt_iv_random_gen
  744. };
  745. /*
  746. * Integrity extensions
  747. */
  748. static bool crypt_integrity_aead(struct crypt_config *cc)
  749. {
  750. return test_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
  751. }
  752. static bool crypt_integrity_hmac(struct crypt_config *cc)
  753. {
  754. return crypt_integrity_aead(cc) && cc->key_mac_size;
  755. }
  756. /* Get sg containing data */
  757. static struct scatterlist *crypt_get_sg_data(struct crypt_config *cc,
  758. struct scatterlist *sg)
  759. {
  760. if (unlikely(crypt_integrity_aead(cc)))
  761. return &sg[2];
  762. return sg;
  763. }
  764. static int dm_crypt_integrity_io_alloc(struct dm_crypt_io *io, struct bio *bio)
  765. {
  766. struct bio_integrity_payload *bip;
  767. unsigned int tag_len;
  768. int ret;
  769. if (!bio_sectors(bio) || !io->cc->on_disk_tag_size)
  770. return 0;
  771. bip = bio_integrity_alloc(bio, GFP_NOIO, 1);
  772. if (IS_ERR(bip))
  773. return PTR_ERR(bip);
  774. tag_len = io->cc->on_disk_tag_size * (bio_sectors(bio) >> io->cc->sector_shift);
  775. bip->bip_iter.bi_size = tag_len;
  776. bip->bip_iter.bi_sector = io->cc->start + io->sector;
  777. ret = bio_integrity_add_page(bio, virt_to_page(io->integrity_metadata),
  778. tag_len, offset_in_page(io->integrity_metadata));
  779. if (unlikely(ret != tag_len))
  780. return -ENOMEM;
  781. return 0;
  782. }
  783. static int crypt_integrity_ctr(struct crypt_config *cc, struct dm_target *ti)
  784. {
  785. #ifdef CONFIG_BLK_DEV_INTEGRITY
  786. struct blk_integrity *bi = blk_get_integrity(cc->dev->bdev->bd_disk);
  787. struct mapped_device *md = dm_table_get_md(ti->table);
  788. /* From now we require underlying device with our integrity profile */
  789. if (!bi || strcasecmp(bi->profile->name, "DM-DIF-EXT-TAG")) {
  790. ti->error = "Integrity profile not supported.";
  791. return -EINVAL;
  792. }
  793. if (bi->tag_size != cc->on_disk_tag_size ||
  794. bi->tuple_size != cc->on_disk_tag_size) {
  795. ti->error = "Integrity profile tag size mismatch.";
  796. return -EINVAL;
  797. }
  798. if (1 << bi->interval_exp != cc->sector_size) {
  799. ti->error = "Integrity profile sector size mismatch.";
  800. return -EINVAL;
  801. }
  802. if (crypt_integrity_aead(cc)) {
  803. cc->integrity_tag_size = cc->on_disk_tag_size - cc->integrity_iv_size;
  804. DMDEBUG("%s: Integrity AEAD, tag size %u, IV size %u.", dm_device_name(md),
  805. cc->integrity_tag_size, cc->integrity_iv_size);
  806. if (crypto_aead_setauthsize(any_tfm_aead(cc), cc->integrity_tag_size)) {
  807. ti->error = "Integrity AEAD auth tag size is not supported.";
  808. return -EINVAL;
  809. }
  810. } else if (cc->integrity_iv_size)
  811. DMDEBUG("%s: Additional per-sector space %u bytes for IV.", dm_device_name(md),
  812. cc->integrity_iv_size);
  813. if ((cc->integrity_tag_size + cc->integrity_iv_size) != bi->tag_size) {
  814. ti->error = "Not enough space for integrity tag in the profile.";
  815. return -EINVAL;
  816. }
  817. return 0;
  818. #else
  819. ti->error = "Integrity profile not supported.";
  820. return -EINVAL;
  821. #endif
  822. }
  823. static void crypt_convert_init(struct crypt_config *cc,
  824. struct convert_context *ctx,
  825. struct bio *bio_out, struct bio *bio_in,
  826. sector_t sector)
  827. {
  828. ctx->bio_in = bio_in;
  829. ctx->bio_out = bio_out;
  830. if (bio_in)
  831. ctx->iter_in = bio_in->bi_iter;
  832. if (bio_out)
  833. ctx->iter_out = bio_out->bi_iter;
  834. ctx->cc_sector = sector + cc->iv_offset;
  835. init_completion(&ctx->restart);
  836. }
  837. static struct dm_crypt_request *dmreq_of_req(struct crypt_config *cc,
  838. void *req)
  839. {
  840. return (struct dm_crypt_request *)((char *)req + cc->dmreq_start);
  841. }
  842. static void *req_of_dmreq(struct crypt_config *cc, struct dm_crypt_request *dmreq)
  843. {
  844. return (void *)((char *)dmreq - cc->dmreq_start);
  845. }
  846. static u8 *iv_of_dmreq(struct crypt_config *cc,
  847. struct dm_crypt_request *dmreq)
  848. {
  849. if (crypt_integrity_aead(cc))
  850. return (u8 *)ALIGN((unsigned long)(dmreq + 1),
  851. crypto_aead_alignmask(any_tfm_aead(cc)) + 1);
  852. else
  853. return (u8 *)ALIGN((unsigned long)(dmreq + 1),
  854. crypto_skcipher_alignmask(any_tfm(cc)) + 1);
  855. }
  856. static u8 *org_iv_of_dmreq(struct crypt_config *cc,
  857. struct dm_crypt_request *dmreq)
  858. {
  859. return iv_of_dmreq(cc, dmreq) + cc->iv_size;
  860. }
  861. static uint64_t *org_sector_of_dmreq(struct crypt_config *cc,
  862. struct dm_crypt_request *dmreq)
  863. {
  864. u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size + cc->iv_size;
  865. return (uint64_t*) ptr;
  866. }
  867. static unsigned int *org_tag_of_dmreq(struct crypt_config *cc,
  868. struct dm_crypt_request *dmreq)
  869. {
  870. u8 *ptr = iv_of_dmreq(cc, dmreq) + cc->iv_size +
  871. cc->iv_size + sizeof(uint64_t);
  872. return (unsigned int*)ptr;
  873. }
  874. static void *tag_from_dmreq(struct crypt_config *cc,
  875. struct dm_crypt_request *dmreq)
  876. {
  877. struct convert_context *ctx = dmreq->ctx;
  878. struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
  879. return &io->integrity_metadata[*org_tag_of_dmreq(cc, dmreq) *
  880. cc->on_disk_tag_size];
  881. }
  882. static void *iv_tag_from_dmreq(struct crypt_config *cc,
  883. struct dm_crypt_request *dmreq)
  884. {
  885. return tag_from_dmreq(cc, dmreq) + cc->integrity_tag_size;
  886. }
  887. static int crypt_convert_block_aead(struct crypt_config *cc,
  888. struct convert_context *ctx,
  889. struct aead_request *req,
  890. unsigned int tag_offset)
  891. {
  892. struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
  893. struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
  894. struct dm_crypt_request *dmreq;
  895. u8 *iv, *org_iv, *tag_iv, *tag;
  896. uint64_t *sector;
  897. int r = 0;
  898. BUG_ON(cc->integrity_iv_size && cc->integrity_iv_size != cc->iv_size);
  899. /* Reject unexpected unaligned bio. */
  900. if (unlikely(bv_in.bv_len & (cc->sector_size - 1)))
  901. return -EIO;
  902. dmreq = dmreq_of_req(cc, req);
  903. dmreq->iv_sector = ctx->cc_sector;
  904. if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
  905. dmreq->iv_sector >>= cc->sector_shift;
  906. dmreq->ctx = ctx;
  907. *org_tag_of_dmreq(cc, dmreq) = tag_offset;
  908. sector = org_sector_of_dmreq(cc, dmreq);
  909. *sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
  910. iv = iv_of_dmreq(cc, dmreq);
  911. org_iv = org_iv_of_dmreq(cc, dmreq);
  912. tag = tag_from_dmreq(cc, dmreq);
  913. tag_iv = iv_tag_from_dmreq(cc, dmreq);
  914. /* AEAD request:
  915. * |----- AAD -------|------ DATA -------|-- AUTH TAG --|
  916. * | (authenticated) | (auth+encryption) | |
  917. * | sector_LE | IV | sector in/out | tag in/out |
  918. */
  919. sg_init_table(dmreq->sg_in, 4);
  920. sg_set_buf(&dmreq->sg_in[0], sector, sizeof(uint64_t));
  921. sg_set_buf(&dmreq->sg_in[1], org_iv, cc->iv_size);
  922. sg_set_page(&dmreq->sg_in[2], bv_in.bv_page, cc->sector_size, bv_in.bv_offset);
  923. sg_set_buf(&dmreq->sg_in[3], tag, cc->integrity_tag_size);
  924. sg_init_table(dmreq->sg_out, 4);
  925. sg_set_buf(&dmreq->sg_out[0], sector, sizeof(uint64_t));
  926. sg_set_buf(&dmreq->sg_out[1], org_iv, cc->iv_size);
  927. sg_set_page(&dmreq->sg_out[2], bv_out.bv_page, cc->sector_size, bv_out.bv_offset);
  928. sg_set_buf(&dmreq->sg_out[3], tag, cc->integrity_tag_size);
  929. if (cc->iv_gen_ops) {
  930. /* For READs use IV stored in integrity metadata */
  931. if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
  932. memcpy(org_iv, tag_iv, cc->iv_size);
  933. } else {
  934. r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
  935. if (r < 0)
  936. return r;
  937. /* Store generated IV in integrity metadata */
  938. if (cc->integrity_iv_size)
  939. memcpy(tag_iv, org_iv, cc->iv_size);
  940. }
  941. /* Working copy of IV, to be modified in crypto API */
  942. memcpy(iv, org_iv, cc->iv_size);
  943. }
  944. aead_request_set_ad(req, sizeof(uint64_t) + cc->iv_size);
  945. if (bio_data_dir(ctx->bio_in) == WRITE) {
  946. aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
  947. cc->sector_size, iv);
  948. r = crypto_aead_encrypt(req);
  949. if (cc->integrity_tag_size + cc->integrity_iv_size != cc->on_disk_tag_size)
  950. memset(tag + cc->integrity_tag_size + cc->integrity_iv_size, 0,
  951. cc->on_disk_tag_size - (cc->integrity_tag_size + cc->integrity_iv_size));
  952. } else {
  953. aead_request_set_crypt(req, dmreq->sg_in, dmreq->sg_out,
  954. cc->sector_size + cc->integrity_tag_size, iv);
  955. r = crypto_aead_decrypt(req);
  956. }
  957. if (r == -EBADMSG)
  958. DMERR_LIMIT("INTEGRITY AEAD ERROR, sector %llu",
  959. (unsigned long long)le64_to_cpu(*sector));
  960. if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
  961. r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
  962. bio_advance_iter(ctx->bio_in, &ctx->iter_in, cc->sector_size);
  963. bio_advance_iter(ctx->bio_out, &ctx->iter_out, cc->sector_size);
  964. return r;
  965. }
  966. static int crypt_convert_block_skcipher(struct crypt_config *cc,
  967. struct convert_context *ctx,
  968. struct skcipher_request *req,
  969. unsigned int tag_offset)
  970. {
  971. struct bio_vec bv_in = bio_iter_iovec(ctx->bio_in, ctx->iter_in);
  972. struct bio_vec bv_out = bio_iter_iovec(ctx->bio_out, ctx->iter_out);
  973. struct scatterlist *sg_in, *sg_out;
  974. struct dm_crypt_request *dmreq;
  975. u8 *iv, *org_iv, *tag_iv;
  976. uint64_t *sector;
  977. int r = 0;
  978. /* Reject unexpected unaligned bio. */
  979. if (unlikely(bv_in.bv_len & (cc->sector_size - 1)))
  980. return -EIO;
  981. dmreq = dmreq_of_req(cc, req);
  982. dmreq->iv_sector = ctx->cc_sector;
  983. if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
  984. dmreq->iv_sector >>= cc->sector_shift;
  985. dmreq->ctx = ctx;
  986. *org_tag_of_dmreq(cc, dmreq) = tag_offset;
  987. iv = iv_of_dmreq(cc, dmreq);
  988. org_iv = org_iv_of_dmreq(cc, dmreq);
  989. tag_iv = iv_tag_from_dmreq(cc, dmreq);
  990. sector = org_sector_of_dmreq(cc, dmreq);
  991. *sector = cpu_to_le64(ctx->cc_sector - cc->iv_offset);
  992. /* For skcipher we use only the first sg item */
  993. sg_in = &dmreq->sg_in[0];
  994. sg_out = &dmreq->sg_out[0];
  995. sg_init_table(sg_in, 1);
  996. sg_set_page(sg_in, bv_in.bv_page, cc->sector_size, bv_in.bv_offset);
  997. sg_init_table(sg_out, 1);
  998. sg_set_page(sg_out, bv_out.bv_page, cc->sector_size, bv_out.bv_offset);
  999. if (cc->iv_gen_ops) {
  1000. /* For READs use IV stored in integrity metadata */
  1001. if (cc->integrity_iv_size && bio_data_dir(ctx->bio_in) != WRITE) {
  1002. memcpy(org_iv, tag_iv, cc->integrity_iv_size);
  1003. } else {
  1004. r = cc->iv_gen_ops->generator(cc, org_iv, dmreq);
  1005. if (r < 0)
  1006. return r;
  1007. /* Store generated IV in integrity metadata */
  1008. if (cc->integrity_iv_size)
  1009. memcpy(tag_iv, org_iv, cc->integrity_iv_size);
  1010. }
  1011. /* Working copy of IV, to be modified in crypto API */
  1012. memcpy(iv, org_iv, cc->iv_size);
  1013. }
  1014. skcipher_request_set_crypt(req, sg_in, sg_out, cc->sector_size, iv);
  1015. if (bio_data_dir(ctx->bio_in) == WRITE)
  1016. r = crypto_skcipher_encrypt(req);
  1017. else
  1018. r = crypto_skcipher_decrypt(req);
  1019. if (!r && cc->iv_gen_ops && cc->iv_gen_ops->post)
  1020. r = cc->iv_gen_ops->post(cc, org_iv, dmreq);
  1021. bio_advance_iter(ctx->bio_in, &ctx->iter_in, cc->sector_size);
  1022. bio_advance_iter(ctx->bio_out, &ctx->iter_out, cc->sector_size);
  1023. return r;
  1024. }
  1025. static void kcryptd_async_done(struct crypto_async_request *async_req,
  1026. int error);
  1027. static void crypt_alloc_req_skcipher(struct crypt_config *cc,
  1028. struct convert_context *ctx)
  1029. {
  1030. unsigned key_index = ctx->cc_sector & (cc->tfms_count - 1);
  1031. if (!ctx->r.req)
  1032. ctx->r.req = mempool_alloc(&cc->req_pool, GFP_NOIO);
  1033. skcipher_request_set_tfm(ctx->r.req, cc->cipher_tfm.tfms[key_index]);
  1034. /*
  1035. * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
  1036. * requests if driver request queue is full.
  1037. */
  1038. skcipher_request_set_callback(ctx->r.req,
  1039. CRYPTO_TFM_REQ_MAY_BACKLOG,
  1040. kcryptd_async_done, dmreq_of_req(cc, ctx->r.req));
  1041. }
  1042. static void crypt_alloc_req_aead(struct crypt_config *cc,
  1043. struct convert_context *ctx)
  1044. {
  1045. if (!ctx->r.req_aead)
  1046. ctx->r.req_aead = mempool_alloc(&cc->req_pool, GFP_NOIO);
  1047. aead_request_set_tfm(ctx->r.req_aead, cc->cipher_tfm.tfms_aead[0]);
  1048. /*
  1049. * Use REQ_MAY_BACKLOG so a cipher driver internally backlogs
  1050. * requests if driver request queue is full.
  1051. */
  1052. aead_request_set_callback(ctx->r.req_aead,
  1053. CRYPTO_TFM_REQ_MAY_BACKLOG,
  1054. kcryptd_async_done, dmreq_of_req(cc, ctx->r.req_aead));
  1055. }
  1056. static void crypt_alloc_req(struct crypt_config *cc,
  1057. struct convert_context *ctx)
  1058. {
  1059. if (crypt_integrity_aead(cc))
  1060. crypt_alloc_req_aead(cc, ctx);
  1061. else
  1062. crypt_alloc_req_skcipher(cc, ctx);
  1063. }
  1064. static void crypt_free_req_skcipher(struct crypt_config *cc,
  1065. struct skcipher_request *req, struct bio *base_bio)
  1066. {
  1067. struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
  1068. if ((struct skcipher_request *)(io + 1) != req)
  1069. mempool_free(req, &cc->req_pool);
  1070. }
  1071. static void crypt_free_req_aead(struct crypt_config *cc,
  1072. struct aead_request *req, struct bio *base_bio)
  1073. {
  1074. struct dm_crypt_io *io = dm_per_bio_data(base_bio, cc->per_bio_data_size);
  1075. if ((struct aead_request *)(io + 1) != req)
  1076. mempool_free(req, &cc->req_pool);
  1077. }
  1078. static void crypt_free_req(struct crypt_config *cc, void *req, struct bio *base_bio)
  1079. {
  1080. if (crypt_integrity_aead(cc))
  1081. crypt_free_req_aead(cc, req, base_bio);
  1082. else
  1083. crypt_free_req_skcipher(cc, req, base_bio);
  1084. }
  1085. /*
  1086. * Encrypt / decrypt data from one bio to another one (can be the same one)
  1087. */
  1088. static blk_status_t crypt_convert(struct crypt_config *cc,
  1089. struct convert_context *ctx)
  1090. {
  1091. unsigned int tag_offset = 0;
  1092. unsigned int sector_step = cc->sector_size >> SECTOR_SHIFT;
  1093. int r;
  1094. atomic_set(&ctx->cc_pending, 1);
  1095. while (ctx->iter_in.bi_size && ctx->iter_out.bi_size) {
  1096. crypt_alloc_req(cc, ctx);
  1097. atomic_inc(&ctx->cc_pending);
  1098. if (crypt_integrity_aead(cc))
  1099. r = crypt_convert_block_aead(cc, ctx, ctx->r.req_aead, tag_offset);
  1100. else
  1101. r = crypt_convert_block_skcipher(cc, ctx, ctx->r.req, tag_offset);
  1102. switch (r) {
  1103. /*
  1104. * The request was queued by a crypto driver
  1105. * but the driver request queue is full, let's wait.
  1106. */
  1107. case -EBUSY:
  1108. wait_for_completion(&ctx->restart);
  1109. reinit_completion(&ctx->restart);
  1110. /* fall through */
  1111. /*
  1112. * The request is queued and processed asynchronously,
  1113. * completion function kcryptd_async_done() will be called.
  1114. */
  1115. case -EINPROGRESS:
  1116. ctx->r.req = NULL;
  1117. ctx->cc_sector += sector_step;
  1118. tag_offset++;
  1119. continue;
  1120. /*
  1121. * The request was already processed (synchronously).
  1122. */
  1123. case 0:
  1124. atomic_dec(&ctx->cc_pending);
  1125. ctx->cc_sector += sector_step;
  1126. tag_offset++;
  1127. cond_resched();
  1128. continue;
  1129. /*
  1130. * There was a data integrity error.
  1131. */
  1132. case -EBADMSG:
  1133. atomic_dec(&ctx->cc_pending);
  1134. return BLK_STS_PROTECTION;
  1135. /*
  1136. * There was an error while processing the request.
  1137. */
  1138. default:
  1139. atomic_dec(&ctx->cc_pending);
  1140. return BLK_STS_IOERR;
  1141. }
  1142. }
  1143. return 0;
  1144. }
  1145. static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone);
  1146. /*
  1147. * Generate a new unfragmented bio with the given size
  1148. * This should never violate the device limitations (but only because
  1149. * max_segment_size is being constrained to PAGE_SIZE).
  1150. *
  1151. * This function may be called concurrently. If we allocate from the mempool
  1152. * concurrently, there is a possibility of deadlock. For example, if we have
  1153. * mempool of 256 pages, two processes, each wanting 256, pages allocate from
  1154. * the mempool concurrently, it may deadlock in a situation where both processes
  1155. * have allocated 128 pages and the mempool is exhausted.
  1156. *
  1157. * In order to avoid this scenario we allocate the pages under a mutex.
  1158. *
  1159. * In order to not degrade performance with excessive locking, we try
  1160. * non-blocking allocations without a mutex first but on failure we fallback
  1161. * to blocking allocations with a mutex.
  1162. */
  1163. static struct bio *crypt_alloc_buffer(struct dm_crypt_io *io, unsigned size)
  1164. {
  1165. struct crypt_config *cc = io->cc;
  1166. struct bio *clone;
  1167. unsigned int nr_iovecs = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
  1168. gfp_t gfp_mask = GFP_NOWAIT | __GFP_HIGHMEM;
  1169. unsigned i, len, remaining_size;
  1170. struct page *page;
  1171. retry:
  1172. if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
  1173. mutex_lock(&cc->bio_alloc_lock);
  1174. clone = bio_alloc_bioset(GFP_NOIO, nr_iovecs, &cc->bs);
  1175. if (!clone)
  1176. goto out;
  1177. clone_init(io, clone);
  1178. remaining_size = size;
  1179. for (i = 0; i < nr_iovecs; i++) {
  1180. page = mempool_alloc(&cc->page_pool, gfp_mask);
  1181. if (!page) {
  1182. crypt_free_buffer_pages(cc, clone);
  1183. bio_put(clone);
  1184. gfp_mask |= __GFP_DIRECT_RECLAIM;
  1185. goto retry;
  1186. }
  1187. len = (remaining_size > PAGE_SIZE) ? PAGE_SIZE : remaining_size;
  1188. bio_add_page(clone, page, len, 0);
  1189. remaining_size -= len;
  1190. }
  1191. /* Allocate space for integrity tags */
  1192. if (dm_crypt_integrity_io_alloc(io, clone)) {
  1193. crypt_free_buffer_pages(cc, clone);
  1194. bio_put(clone);
  1195. clone = NULL;
  1196. }
  1197. out:
  1198. if (unlikely(gfp_mask & __GFP_DIRECT_RECLAIM))
  1199. mutex_unlock(&cc->bio_alloc_lock);
  1200. return clone;
  1201. }
  1202. static void crypt_free_buffer_pages(struct crypt_config *cc, struct bio *clone)
  1203. {
  1204. unsigned int i;
  1205. struct bio_vec *bv;
  1206. bio_for_each_segment_all(bv, clone, i) {
  1207. BUG_ON(!bv->bv_page);
  1208. mempool_free(bv->bv_page, &cc->page_pool);
  1209. }
  1210. }
  1211. static void crypt_io_init(struct dm_crypt_io *io, struct crypt_config *cc,
  1212. struct bio *bio, sector_t sector)
  1213. {
  1214. io->cc = cc;
  1215. io->base_bio = bio;
  1216. io->sector = sector;
  1217. io->error = 0;
  1218. io->ctx.r.req = NULL;
  1219. io->integrity_metadata = NULL;
  1220. io->integrity_metadata_from_pool = false;
  1221. atomic_set(&io->io_pending, 0);
  1222. }
  1223. static void crypt_inc_pending(struct dm_crypt_io *io)
  1224. {
  1225. atomic_inc(&io->io_pending);
  1226. }
  1227. /*
  1228. * One of the bios was finished. Check for completion of
  1229. * the whole request and correctly clean up the buffer.
  1230. */
  1231. static void crypt_dec_pending(struct dm_crypt_io *io)
  1232. {
  1233. struct crypt_config *cc = io->cc;
  1234. struct bio *base_bio = io->base_bio;
  1235. blk_status_t error = io->error;
  1236. if (!atomic_dec_and_test(&io->io_pending))
  1237. return;
  1238. if (io->ctx.r.req)
  1239. crypt_free_req(cc, io->ctx.r.req, base_bio);
  1240. if (unlikely(io->integrity_metadata_from_pool))
  1241. mempool_free(io->integrity_metadata, &io->cc->tag_pool);
  1242. else
  1243. kfree(io->integrity_metadata);
  1244. base_bio->bi_status = error;
  1245. bio_endio(base_bio);
  1246. }
  1247. /*
  1248. * kcryptd/kcryptd_io:
  1249. *
  1250. * Needed because it would be very unwise to do decryption in an
  1251. * interrupt context.
  1252. *
  1253. * kcryptd performs the actual encryption or decryption.
  1254. *
  1255. * kcryptd_io performs the IO submission.
  1256. *
  1257. * They must be separated as otherwise the final stages could be
  1258. * starved by new requests which can block in the first stages due
  1259. * to memory allocation.
  1260. *
  1261. * The work is done per CPU global for all dm-crypt instances.
  1262. * They should not depend on each other and do not block.
  1263. */
  1264. static void crypt_endio(struct bio *clone)
  1265. {
  1266. struct dm_crypt_io *io = clone->bi_private;
  1267. struct crypt_config *cc = io->cc;
  1268. unsigned rw = bio_data_dir(clone);
  1269. blk_status_t error;
  1270. /*
  1271. * free the processed pages
  1272. */
  1273. if (rw == WRITE)
  1274. crypt_free_buffer_pages(cc, clone);
  1275. error = clone->bi_status;
  1276. bio_put(clone);
  1277. if (rw == READ && !error) {
  1278. kcryptd_queue_crypt(io);
  1279. return;
  1280. }
  1281. if (unlikely(error))
  1282. io->error = error;
  1283. crypt_dec_pending(io);
  1284. }
  1285. static void clone_init(struct dm_crypt_io *io, struct bio *clone)
  1286. {
  1287. struct crypt_config *cc = io->cc;
  1288. clone->bi_private = io;
  1289. clone->bi_end_io = crypt_endio;
  1290. bio_set_dev(clone, cc->dev->bdev);
  1291. clone->bi_opf = io->base_bio->bi_opf;
  1292. }
  1293. static int kcryptd_io_read(struct dm_crypt_io *io, gfp_t gfp)
  1294. {
  1295. struct crypt_config *cc = io->cc;
  1296. struct bio *clone;
  1297. /*
  1298. * We need the original biovec array in order to decrypt
  1299. * the whole bio data *afterwards* -- thanks to immutable
  1300. * biovecs we don't need to worry about the block layer
  1301. * modifying the biovec array; so leverage bio_clone_fast().
  1302. */
  1303. clone = bio_clone_fast(io->base_bio, gfp, &cc->bs);
  1304. if (!clone)
  1305. return 1;
  1306. crypt_inc_pending(io);
  1307. clone_init(io, clone);
  1308. clone->bi_iter.bi_sector = cc->start + io->sector;
  1309. if (dm_crypt_integrity_io_alloc(io, clone)) {
  1310. crypt_dec_pending(io);
  1311. bio_put(clone);
  1312. return 1;
  1313. }
  1314. generic_make_request(clone);
  1315. return 0;
  1316. }
  1317. static void kcryptd_io_read_work(struct work_struct *work)
  1318. {
  1319. struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
  1320. crypt_inc_pending(io);
  1321. if (kcryptd_io_read(io, GFP_NOIO))
  1322. io->error = BLK_STS_RESOURCE;
  1323. crypt_dec_pending(io);
  1324. }
  1325. static void kcryptd_queue_read(struct dm_crypt_io *io)
  1326. {
  1327. struct crypt_config *cc = io->cc;
  1328. INIT_WORK(&io->work, kcryptd_io_read_work);
  1329. queue_work(cc->io_queue, &io->work);
  1330. }
  1331. static void kcryptd_io_write(struct dm_crypt_io *io)
  1332. {
  1333. struct bio *clone = io->ctx.bio_out;
  1334. generic_make_request(clone);
  1335. }
  1336. #define crypt_io_from_node(node) rb_entry((node), struct dm_crypt_io, rb_node)
  1337. static int dmcrypt_write(void *data)
  1338. {
  1339. struct crypt_config *cc = data;
  1340. struct dm_crypt_io *io;
  1341. while (1) {
  1342. struct rb_root write_tree;
  1343. struct blk_plug plug;
  1344. spin_lock_irq(&cc->write_thread_lock);
  1345. continue_locked:
  1346. if (!RB_EMPTY_ROOT(&cc->write_tree))
  1347. goto pop_from_list;
  1348. set_current_state(TASK_INTERRUPTIBLE);
  1349. spin_unlock_irq(&cc->write_thread_lock);
  1350. if (unlikely(kthread_should_stop())) {
  1351. set_current_state(TASK_RUNNING);
  1352. break;
  1353. }
  1354. schedule();
  1355. set_current_state(TASK_RUNNING);
  1356. spin_lock_irq(&cc->write_thread_lock);
  1357. goto continue_locked;
  1358. pop_from_list:
  1359. write_tree = cc->write_tree;
  1360. cc->write_tree = RB_ROOT;
  1361. spin_unlock_irq(&cc->write_thread_lock);
  1362. BUG_ON(rb_parent(write_tree.rb_node));
  1363. /*
  1364. * Note: we cannot walk the tree here with rb_next because
  1365. * the structures may be freed when kcryptd_io_write is called.
  1366. */
  1367. blk_start_plug(&plug);
  1368. do {
  1369. io = crypt_io_from_node(rb_first(&write_tree));
  1370. rb_erase(&io->rb_node, &write_tree);
  1371. kcryptd_io_write(io);
  1372. } while (!RB_EMPTY_ROOT(&write_tree));
  1373. blk_finish_plug(&plug);
  1374. }
  1375. return 0;
  1376. }
  1377. static void kcryptd_crypt_write_io_submit(struct dm_crypt_io *io, int async)
  1378. {
  1379. struct bio *clone = io->ctx.bio_out;
  1380. struct crypt_config *cc = io->cc;
  1381. unsigned long flags;
  1382. sector_t sector;
  1383. struct rb_node **rbp, *parent;
  1384. if (unlikely(io->error)) {
  1385. crypt_free_buffer_pages(cc, clone);
  1386. bio_put(clone);
  1387. crypt_dec_pending(io);
  1388. return;
  1389. }
  1390. /* crypt_convert should have filled the clone bio */
  1391. BUG_ON(io->ctx.iter_out.bi_size);
  1392. clone->bi_iter.bi_sector = cc->start + io->sector;
  1393. if (likely(!async) && test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags)) {
  1394. generic_make_request(clone);
  1395. return;
  1396. }
  1397. spin_lock_irqsave(&cc->write_thread_lock, flags);
  1398. if (RB_EMPTY_ROOT(&cc->write_tree))
  1399. wake_up_process(cc->write_thread);
  1400. rbp = &cc->write_tree.rb_node;
  1401. parent = NULL;
  1402. sector = io->sector;
  1403. while (*rbp) {
  1404. parent = *rbp;
  1405. if (sector < crypt_io_from_node(parent)->sector)
  1406. rbp = &(*rbp)->rb_left;
  1407. else
  1408. rbp = &(*rbp)->rb_right;
  1409. }
  1410. rb_link_node(&io->rb_node, parent, rbp);
  1411. rb_insert_color(&io->rb_node, &cc->write_tree);
  1412. spin_unlock_irqrestore(&cc->write_thread_lock, flags);
  1413. }
  1414. static void kcryptd_crypt_write_convert(struct dm_crypt_io *io)
  1415. {
  1416. struct crypt_config *cc = io->cc;
  1417. struct bio *clone;
  1418. int crypt_finished;
  1419. sector_t sector = io->sector;
  1420. blk_status_t r;
  1421. /*
  1422. * Prevent io from disappearing until this function completes.
  1423. */
  1424. crypt_inc_pending(io);
  1425. crypt_convert_init(cc, &io->ctx, NULL, io->base_bio, sector);
  1426. clone = crypt_alloc_buffer(io, io->base_bio->bi_iter.bi_size);
  1427. if (unlikely(!clone)) {
  1428. io->error = BLK_STS_IOERR;
  1429. goto dec;
  1430. }
  1431. io->ctx.bio_out = clone;
  1432. io->ctx.iter_out = clone->bi_iter;
  1433. sector += bio_sectors(clone);
  1434. crypt_inc_pending(io);
  1435. r = crypt_convert(cc, &io->ctx);
  1436. if (r)
  1437. io->error = r;
  1438. crypt_finished = atomic_dec_and_test(&io->ctx.cc_pending);
  1439. /* Encryption was already finished, submit io now */
  1440. if (crypt_finished) {
  1441. kcryptd_crypt_write_io_submit(io, 0);
  1442. io->sector = sector;
  1443. }
  1444. dec:
  1445. crypt_dec_pending(io);
  1446. }
  1447. static void kcryptd_crypt_read_done(struct dm_crypt_io *io)
  1448. {
  1449. crypt_dec_pending(io);
  1450. }
  1451. static void kcryptd_crypt_read_convert(struct dm_crypt_io *io)
  1452. {
  1453. struct crypt_config *cc = io->cc;
  1454. blk_status_t r;
  1455. crypt_inc_pending(io);
  1456. crypt_convert_init(cc, &io->ctx, io->base_bio, io->base_bio,
  1457. io->sector);
  1458. r = crypt_convert(cc, &io->ctx);
  1459. if (r)
  1460. io->error = r;
  1461. if (atomic_dec_and_test(&io->ctx.cc_pending))
  1462. kcryptd_crypt_read_done(io);
  1463. crypt_dec_pending(io);
  1464. }
  1465. static void kcryptd_async_done(struct crypto_async_request *async_req,
  1466. int error)
  1467. {
  1468. struct dm_crypt_request *dmreq = async_req->data;
  1469. struct convert_context *ctx = dmreq->ctx;
  1470. struct dm_crypt_io *io = container_of(ctx, struct dm_crypt_io, ctx);
  1471. struct crypt_config *cc = io->cc;
  1472. /*
  1473. * A request from crypto driver backlog is going to be processed now,
  1474. * finish the completion and continue in crypt_convert().
  1475. * (Callback will be called for the second time for this request.)
  1476. */
  1477. if (error == -EINPROGRESS) {
  1478. complete(&ctx->restart);
  1479. return;
  1480. }
  1481. if (!error && cc->iv_gen_ops && cc->iv_gen_ops->post)
  1482. error = cc->iv_gen_ops->post(cc, org_iv_of_dmreq(cc, dmreq), dmreq);
  1483. if (error == -EBADMSG) {
  1484. DMERR_LIMIT("INTEGRITY AEAD ERROR, sector %llu",
  1485. (unsigned long long)le64_to_cpu(*org_sector_of_dmreq(cc, dmreq)));
  1486. io->error = BLK_STS_PROTECTION;
  1487. } else if (error < 0)
  1488. io->error = BLK_STS_IOERR;
  1489. crypt_free_req(cc, req_of_dmreq(cc, dmreq), io->base_bio);
  1490. if (!atomic_dec_and_test(&ctx->cc_pending))
  1491. return;
  1492. if (bio_data_dir(io->base_bio) == READ)
  1493. kcryptd_crypt_read_done(io);
  1494. else
  1495. kcryptd_crypt_write_io_submit(io, 1);
  1496. }
  1497. static void kcryptd_crypt(struct work_struct *work)
  1498. {
  1499. struct dm_crypt_io *io = container_of(work, struct dm_crypt_io, work);
  1500. if (bio_data_dir(io->base_bio) == READ)
  1501. kcryptd_crypt_read_convert(io);
  1502. else
  1503. kcryptd_crypt_write_convert(io);
  1504. }
  1505. static void kcryptd_queue_crypt(struct dm_crypt_io *io)
  1506. {
  1507. struct crypt_config *cc = io->cc;
  1508. INIT_WORK(&io->work, kcryptd_crypt);
  1509. queue_work(cc->crypt_queue, &io->work);
  1510. }
  1511. static void crypt_free_tfms_aead(struct crypt_config *cc)
  1512. {
  1513. if (!cc->cipher_tfm.tfms_aead)
  1514. return;
  1515. if (cc->cipher_tfm.tfms_aead[0] && !IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
  1516. crypto_free_aead(cc->cipher_tfm.tfms_aead[0]);
  1517. cc->cipher_tfm.tfms_aead[0] = NULL;
  1518. }
  1519. kfree(cc->cipher_tfm.tfms_aead);
  1520. cc->cipher_tfm.tfms_aead = NULL;
  1521. }
  1522. static void crypt_free_tfms_skcipher(struct crypt_config *cc)
  1523. {
  1524. unsigned i;
  1525. if (!cc->cipher_tfm.tfms)
  1526. return;
  1527. for (i = 0; i < cc->tfms_count; i++)
  1528. if (cc->cipher_tfm.tfms[i] && !IS_ERR(cc->cipher_tfm.tfms[i])) {
  1529. crypto_free_skcipher(cc->cipher_tfm.tfms[i]);
  1530. cc->cipher_tfm.tfms[i] = NULL;
  1531. }
  1532. kfree(cc->cipher_tfm.tfms);
  1533. cc->cipher_tfm.tfms = NULL;
  1534. }
  1535. static void crypt_free_tfms(struct crypt_config *cc)
  1536. {
  1537. if (crypt_integrity_aead(cc))
  1538. crypt_free_tfms_aead(cc);
  1539. else
  1540. crypt_free_tfms_skcipher(cc);
  1541. }
  1542. static int crypt_alloc_tfms_skcipher(struct crypt_config *cc, char *ciphermode)
  1543. {
  1544. unsigned i;
  1545. int err;
  1546. cc->cipher_tfm.tfms = kcalloc(cc->tfms_count,
  1547. sizeof(struct crypto_skcipher *),
  1548. GFP_KERNEL);
  1549. if (!cc->cipher_tfm.tfms)
  1550. return -ENOMEM;
  1551. for (i = 0; i < cc->tfms_count; i++) {
  1552. cc->cipher_tfm.tfms[i] = crypto_alloc_skcipher(ciphermode, 0, 0);
  1553. if (IS_ERR(cc->cipher_tfm.tfms[i])) {
  1554. err = PTR_ERR(cc->cipher_tfm.tfms[i]);
  1555. crypt_free_tfms(cc);
  1556. return err;
  1557. }
  1558. }
  1559. return 0;
  1560. }
  1561. static int crypt_alloc_tfms_aead(struct crypt_config *cc, char *ciphermode)
  1562. {
  1563. int err;
  1564. cc->cipher_tfm.tfms = kmalloc(sizeof(struct crypto_aead *), GFP_KERNEL);
  1565. if (!cc->cipher_tfm.tfms)
  1566. return -ENOMEM;
  1567. cc->cipher_tfm.tfms_aead[0] = crypto_alloc_aead(ciphermode, 0, 0);
  1568. if (IS_ERR(cc->cipher_tfm.tfms_aead[0])) {
  1569. err = PTR_ERR(cc->cipher_tfm.tfms_aead[0]);
  1570. crypt_free_tfms(cc);
  1571. return err;
  1572. }
  1573. return 0;
  1574. }
  1575. static int crypt_alloc_tfms(struct crypt_config *cc, char *ciphermode)
  1576. {
  1577. if (crypt_integrity_aead(cc))
  1578. return crypt_alloc_tfms_aead(cc, ciphermode);
  1579. else
  1580. return crypt_alloc_tfms_skcipher(cc, ciphermode);
  1581. }
  1582. static unsigned crypt_subkey_size(struct crypt_config *cc)
  1583. {
  1584. return (cc->key_size - cc->key_extra_size) >> ilog2(cc->tfms_count);
  1585. }
  1586. static unsigned crypt_authenckey_size(struct crypt_config *cc)
  1587. {
  1588. return crypt_subkey_size(cc) + RTA_SPACE(sizeof(struct crypto_authenc_key_param));
  1589. }
  1590. /*
  1591. * If AEAD is composed like authenc(hmac(sha256),xts(aes)),
  1592. * the key must be for some reason in special format.
  1593. * This funcion converts cc->key to this special format.
  1594. */
  1595. static void crypt_copy_authenckey(char *p, const void *key,
  1596. unsigned enckeylen, unsigned authkeylen)
  1597. {
  1598. struct crypto_authenc_key_param *param;
  1599. struct rtattr *rta;
  1600. rta = (struct rtattr *)p;
  1601. param = RTA_DATA(rta);
  1602. param->enckeylen = cpu_to_be32(enckeylen);
  1603. rta->rta_len = RTA_LENGTH(sizeof(*param));
  1604. rta->rta_type = CRYPTO_AUTHENC_KEYA_PARAM;
  1605. p += RTA_SPACE(sizeof(*param));
  1606. memcpy(p, key + enckeylen, authkeylen);
  1607. p += authkeylen;
  1608. memcpy(p, key, enckeylen);
  1609. }
  1610. static int crypt_setkey(struct crypt_config *cc)
  1611. {
  1612. unsigned subkey_size;
  1613. int err = 0, i, r;
  1614. /* Ignore extra keys (which are used for IV etc) */
  1615. subkey_size = crypt_subkey_size(cc);
  1616. if (crypt_integrity_hmac(cc)) {
  1617. if (subkey_size < cc->key_mac_size)
  1618. return -EINVAL;
  1619. crypt_copy_authenckey(cc->authenc_key, cc->key,
  1620. subkey_size - cc->key_mac_size,
  1621. cc->key_mac_size);
  1622. }
  1623. for (i = 0; i < cc->tfms_count; i++) {
  1624. if (crypt_integrity_hmac(cc))
  1625. r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
  1626. cc->authenc_key, crypt_authenckey_size(cc));
  1627. else if (crypt_integrity_aead(cc))
  1628. r = crypto_aead_setkey(cc->cipher_tfm.tfms_aead[i],
  1629. cc->key + (i * subkey_size),
  1630. subkey_size);
  1631. else
  1632. r = crypto_skcipher_setkey(cc->cipher_tfm.tfms[i],
  1633. cc->key + (i * subkey_size),
  1634. subkey_size);
  1635. if (r)
  1636. err = r;
  1637. }
  1638. if (crypt_integrity_hmac(cc))
  1639. memzero_explicit(cc->authenc_key, crypt_authenckey_size(cc));
  1640. return err;
  1641. }
  1642. #ifdef CONFIG_KEYS
  1643. static bool contains_whitespace(const char *str)
  1644. {
  1645. while (*str)
  1646. if (isspace(*str++))
  1647. return true;
  1648. return false;
  1649. }
  1650. static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
  1651. {
  1652. char *new_key_string, *key_desc;
  1653. int ret;
  1654. struct key *key;
  1655. const struct user_key_payload *ukp;
  1656. /*
  1657. * Reject key_string with whitespace. dm core currently lacks code for
  1658. * proper whitespace escaping in arguments on DM_TABLE_STATUS path.
  1659. */
  1660. if (contains_whitespace(key_string)) {
  1661. DMERR("whitespace chars not allowed in key string");
  1662. return -EINVAL;
  1663. }
  1664. /* look for next ':' separating key_type from key_description */
  1665. key_desc = strpbrk(key_string, ":");
  1666. if (!key_desc || key_desc == key_string || !strlen(key_desc + 1))
  1667. return -EINVAL;
  1668. if (strncmp(key_string, "logon:", key_desc - key_string + 1) &&
  1669. strncmp(key_string, "user:", key_desc - key_string + 1))
  1670. return -EINVAL;
  1671. new_key_string = kstrdup(key_string, GFP_KERNEL);
  1672. if (!new_key_string)
  1673. return -ENOMEM;
  1674. key = request_key(key_string[0] == 'l' ? &key_type_logon : &key_type_user,
  1675. key_desc + 1, NULL);
  1676. if (IS_ERR(key)) {
  1677. kzfree(new_key_string);
  1678. return PTR_ERR(key);
  1679. }
  1680. down_read(&key->sem);
  1681. ukp = user_key_payload_locked(key);
  1682. if (!ukp) {
  1683. up_read(&key->sem);
  1684. key_put(key);
  1685. kzfree(new_key_string);
  1686. return -EKEYREVOKED;
  1687. }
  1688. if (cc->key_size != ukp->datalen) {
  1689. up_read(&key->sem);
  1690. key_put(key);
  1691. kzfree(new_key_string);
  1692. return -EINVAL;
  1693. }
  1694. memcpy(cc->key, ukp->data, cc->key_size);
  1695. up_read(&key->sem);
  1696. key_put(key);
  1697. /* clear the flag since following operations may invalidate previously valid key */
  1698. clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
  1699. ret = crypt_setkey(cc);
  1700. if (!ret) {
  1701. set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
  1702. kzfree(cc->key_string);
  1703. cc->key_string = new_key_string;
  1704. } else
  1705. kzfree(new_key_string);
  1706. return ret;
  1707. }
  1708. static int get_key_size(char **key_string)
  1709. {
  1710. char *colon, dummy;
  1711. int ret;
  1712. if (*key_string[0] != ':')
  1713. return strlen(*key_string) >> 1;
  1714. /* look for next ':' in key string */
  1715. colon = strpbrk(*key_string + 1, ":");
  1716. if (!colon)
  1717. return -EINVAL;
  1718. if (sscanf(*key_string + 1, "%u%c", &ret, &dummy) != 2 || dummy != ':')
  1719. return -EINVAL;
  1720. *key_string = colon;
  1721. /* remaining key string should be :<logon|user>:<key_desc> */
  1722. return ret;
  1723. }
  1724. #else
  1725. static int crypt_set_keyring_key(struct crypt_config *cc, const char *key_string)
  1726. {
  1727. return -EINVAL;
  1728. }
  1729. static int get_key_size(char **key_string)
  1730. {
  1731. return (*key_string[0] == ':') ? -EINVAL : strlen(*key_string) >> 1;
  1732. }
  1733. #endif
  1734. static int crypt_set_key(struct crypt_config *cc, char *key)
  1735. {
  1736. int r = -EINVAL;
  1737. int key_string_len = strlen(key);
  1738. /* Hyphen (which gives a key_size of zero) means there is no key. */
  1739. if (!cc->key_size && strcmp(key, "-"))
  1740. goto out;
  1741. /* ':' means the key is in kernel keyring, short-circuit normal key processing */
  1742. if (key[0] == ':') {
  1743. r = crypt_set_keyring_key(cc, key + 1);
  1744. goto out;
  1745. }
  1746. /* clear the flag since following operations may invalidate previously valid key */
  1747. clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
  1748. /* wipe references to any kernel keyring key */
  1749. kzfree(cc->key_string);
  1750. cc->key_string = NULL;
  1751. /* Decode key from its hex representation. */
  1752. if (cc->key_size && hex2bin(cc->key, key, cc->key_size) < 0)
  1753. goto out;
  1754. r = crypt_setkey(cc);
  1755. if (!r)
  1756. set_bit(DM_CRYPT_KEY_VALID, &cc->flags);
  1757. out:
  1758. /* Hex key string not needed after here, so wipe it. */
  1759. memset(key, '0', key_string_len);
  1760. return r;
  1761. }
  1762. static int crypt_wipe_key(struct crypt_config *cc)
  1763. {
  1764. int r;
  1765. clear_bit(DM_CRYPT_KEY_VALID, &cc->flags);
  1766. get_random_bytes(&cc->key, cc->key_size);
  1767. kzfree(cc->key_string);
  1768. cc->key_string = NULL;
  1769. r = crypt_setkey(cc);
  1770. memset(&cc->key, 0, cc->key_size * sizeof(u8));
  1771. return r;
  1772. }
  1773. static void crypt_calculate_pages_per_client(void)
  1774. {
  1775. unsigned long pages = (totalram_pages - totalhigh_pages) * DM_CRYPT_MEMORY_PERCENT / 100;
  1776. if (!dm_crypt_clients_n)
  1777. return;
  1778. pages /= dm_crypt_clients_n;
  1779. if (pages < DM_CRYPT_MIN_PAGES_PER_CLIENT)
  1780. pages = DM_CRYPT_MIN_PAGES_PER_CLIENT;
  1781. dm_crypt_pages_per_client = pages;
  1782. }
  1783. static void *crypt_page_alloc(gfp_t gfp_mask, void *pool_data)
  1784. {
  1785. struct crypt_config *cc = pool_data;
  1786. struct page *page;
  1787. if (unlikely(percpu_counter_compare(&cc->n_allocated_pages, dm_crypt_pages_per_client) >= 0) &&
  1788. likely(gfp_mask & __GFP_NORETRY))
  1789. return NULL;
  1790. page = alloc_page(gfp_mask);
  1791. if (likely(page != NULL))
  1792. percpu_counter_add(&cc->n_allocated_pages, 1);
  1793. return page;
  1794. }
  1795. static void crypt_page_free(void *page, void *pool_data)
  1796. {
  1797. struct crypt_config *cc = pool_data;
  1798. __free_page(page);
  1799. percpu_counter_sub(&cc->n_allocated_pages, 1);
  1800. }
  1801. static void crypt_dtr(struct dm_target *ti)
  1802. {
  1803. struct crypt_config *cc = ti->private;
  1804. ti->private = NULL;
  1805. if (!cc)
  1806. return;
  1807. if (cc->write_thread)
  1808. kthread_stop(cc->write_thread);
  1809. if (cc->io_queue)
  1810. destroy_workqueue(cc->io_queue);
  1811. if (cc->crypt_queue)
  1812. destroy_workqueue(cc->crypt_queue);
  1813. crypt_free_tfms(cc);
  1814. bioset_exit(&cc->bs);
  1815. mempool_exit(&cc->page_pool);
  1816. mempool_exit(&cc->req_pool);
  1817. mempool_exit(&cc->tag_pool);
  1818. WARN_ON(percpu_counter_sum(&cc->n_allocated_pages) != 0);
  1819. percpu_counter_destroy(&cc->n_allocated_pages);
  1820. if (cc->iv_gen_ops && cc->iv_gen_ops->dtr)
  1821. cc->iv_gen_ops->dtr(cc);
  1822. if (cc->dev)
  1823. dm_put_device(ti, cc->dev);
  1824. kzfree(cc->cipher);
  1825. kzfree(cc->cipher_string);
  1826. kzfree(cc->key_string);
  1827. kzfree(cc->cipher_auth);
  1828. kzfree(cc->authenc_key);
  1829. mutex_destroy(&cc->bio_alloc_lock);
  1830. /* Must zero key material before freeing */
  1831. kzfree(cc);
  1832. spin_lock(&dm_crypt_clients_lock);
  1833. WARN_ON(!dm_crypt_clients_n);
  1834. dm_crypt_clients_n--;
  1835. crypt_calculate_pages_per_client();
  1836. spin_unlock(&dm_crypt_clients_lock);
  1837. }
  1838. static int crypt_ctr_ivmode(struct dm_target *ti, const char *ivmode)
  1839. {
  1840. struct crypt_config *cc = ti->private;
  1841. if (crypt_integrity_aead(cc))
  1842. cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
  1843. else
  1844. cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
  1845. if (cc->iv_size)
  1846. /* at least a 64 bit sector number should fit in our buffer */
  1847. cc->iv_size = max(cc->iv_size,
  1848. (unsigned int)(sizeof(u64) / sizeof(u8)));
  1849. else if (ivmode) {
  1850. DMWARN("Selected cipher does not support IVs");
  1851. ivmode = NULL;
  1852. }
  1853. /* Choose ivmode, see comments at iv code. */
  1854. if (ivmode == NULL)
  1855. cc->iv_gen_ops = NULL;
  1856. else if (strcmp(ivmode, "plain") == 0)
  1857. cc->iv_gen_ops = &crypt_iv_plain_ops;
  1858. else if (strcmp(ivmode, "plain64") == 0)
  1859. cc->iv_gen_ops = &crypt_iv_plain64_ops;
  1860. else if (strcmp(ivmode, "plain64be") == 0)
  1861. cc->iv_gen_ops = &crypt_iv_plain64be_ops;
  1862. else if (strcmp(ivmode, "essiv") == 0)
  1863. cc->iv_gen_ops = &crypt_iv_essiv_ops;
  1864. else if (strcmp(ivmode, "benbi") == 0)
  1865. cc->iv_gen_ops = &crypt_iv_benbi_ops;
  1866. else if (strcmp(ivmode, "null") == 0)
  1867. cc->iv_gen_ops = &crypt_iv_null_ops;
  1868. else if (strcmp(ivmode, "lmk") == 0) {
  1869. cc->iv_gen_ops = &crypt_iv_lmk_ops;
  1870. /*
  1871. * Version 2 and 3 is recognised according
  1872. * to length of provided multi-key string.
  1873. * If present (version 3), last key is used as IV seed.
  1874. * All keys (including IV seed) are always the same size.
  1875. */
  1876. if (cc->key_size % cc->key_parts) {
  1877. cc->key_parts++;
  1878. cc->key_extra_size = cc->key_size / cc->key_parts;
  1879. }
  1880. } else if (strcmp(ivmode, "tcw") == 0) {
  1881. cc->iv_gen_ops = &crypt_iv_tcw_ops;
  1882. cc->key_parts += 2; /* IV + whitening */
  1883. cc->key_extra_size = cc->iv_size + TCW_WHITENING_SIZE;
  1884. } else if (strcmp(ivmode, "random") == 0) {
  1885. cc->iv_gen_ops = &crypt_iv_random_ops;
  1886. /* Need storage space in integrity fields. */
  1887. cc->integrity_iv_size = cc->iv_size;
  1888. } else {
  1889. ti->error = "Invalid IV mode";
  1890. return -EINVAL;
  1891. }
  1892. return 0;
  1893. }
  1894. /*
  1895. * Workaround to parse cipher algorithm from crypto API spec.
  1896. * The cc->cipher is currently used only in ESSIV.
  1897. * This should be probably done by crypto-api calls (once available...)
  1898. */
  1899. static int crypt_ctr_blkdev_cipher(struct crypt_config *cc)
  1900. {
  1901. const char *alg_name = NULL;
  1902. char *start, *end;
  1903. if (crypt_integrity_aead(cc)) {
  1904. alg_name = crypto_tfm_alg_name(crypto_aead_tfm(any_tfm_aead(cc)));
  1905. if (!alg_name)
  1906. return -EINVAL;
  1907. if (crypt_integrity_hmac(cc)) {
  1908. alg_name = strchr(alg_name, ',');
  1909. if (!alg_name)
  1910. return -EINVAL;
  1911. }
  1912. alg_name++;
  1913. } else {
  1914. alg_name = crypto_tfm_alg_name(crypto_skcipher_tfm(any_tfm(cc)));
  1915. if (!alg_name)
  1916. return -EINVAL;
  1917. }
  1918. start = strchr(alg_name, '(');
  1919. end = strchr(alg_name, ')');
  1920. if (!start && !end) {
  1921. cc->cipher = kstrdup(alg_name, GFP_KERNEL);
  1922. return cc->cipher ? 0 : -ENOMEM;
  1923. }
  1924. if (!start || !end || ++start >= end)
  1925. return -EINVAL;
  1926. cc->cipher = kzalloc(end - start + 1, GFP_KERNEL);
  1927. if (!cc->cipher)
  1928. return -ENOMEM;
  1929. strncpy(cc->cipher, start, end - start);
  1930. return 0;
  1931. }
  1932. /*
  1933. * Workaround to parse HMAC algorithm from AEAD crypto API spec.
  1934. * The HMAC is needed to calculate tag size (HMAC digest size).
  1935. * This should be probably done by crypto-api calls (once available...)
  1936. */
  1937. static int crypt_ctr_auth_cipher(struct crypt_config *cc, char *cipher_api)
  1938. {
  1939. char *start, *end, *mac_alg = NULL;
  1940. struct crypto_ahash *mac;
  1941. if (!strstarts(cipher_api, "authenc("))
  1942. return 0;
  1943. start = strchr(cipher_api, '(');
  1944. end = strchr(cipher_api, ',');
  1945. if (!start || !end || ++start > end)
  1946. return -EINVAL;
  1947. mac_alg = kzalloc(end - start + 1, GFP_KERNEL);
  1948. if (!mac_alg)
  1949. return -ENOMEM;
  1950. strncpy(mac_alg, start, end - start);
  1951. mac = crypto_alloc_ahash(mac_alg, 0, 0);
  1952. kfree(mac_alg);
  1953. if (IS_ERR(mac))
  1954. return PTR_ERR(mac);
  1955. cc->key_mac_size = crypto_ahash_digestsize(mac);
  1956. crypto_free_ahash(mac);
  1957. cc->authenc_key = kmalloc(crypt_authenckey_size(cc), GFP_KERNEL);
  1958. if (!cc->authenc_key)
  1959. return -ENOMEM;
  1960. return 0;
  1961. }
  1962. static int crypt_ctr_cipher_new(struct dm_target *ti, char *cipher_in, char *key,
  1963. char **ivmode, char **ivopts)
  1964. {
  1965. struct crypt_config *cc = ti->private;
  1966. char *tmp, *cipher_api;
  1967. int ret = -EINVAL;
  1968. cc->tfms_count = 1;
  1969. /*
  1970. * New format (capi: prefix)
  1971. * capi:cipher_api_spec-iv:ivopts
  1972. */
  1973. tmp = &cipher_in[strlen("capi:")];
  1974. /* Separate IV options if present, it can contain another '-' in hash name */
  1975. *ivopts = strrchr(tmp, ':');
  1976. if (*ivopts) {
  1977. **ivopts = '\0';
  1978. (*ivopts)++;
  1979. }
  1980. /* Parse IV mode */
  1981. *ivmode = strrchr(tmp, '-');
  1982. if (*ivmode) {
  1983. **ivmode = '\0';
  1984. (*ivmode)++;
  1985. }
  1986. /* The rest is crypto API spec */
  1987. cipher_api = tmp;
  1988. if (*ivmode && !strcmp(*ivmode, "lmk"))
  1989. cc->tfms_count = 64;
  1990. cc->key_parts = cc->tfms_count;
  1991. /* Allocate cipher */
  1992. ret = crypt_alloc_tfms(cc, cipher_api);
  1993. if (ret < 0) {
  1994. ti->error = "Error allocating crypto tfm";
  1995. return ret;
  1996. }
  1997. /* Alloc AEAD, can be used only in new format. */
  1998. if (crypt_integrity_aead(cc)) {
  1999. ret = crypt_ctr_auth_cipher(cc, cipher_api);
  2000. if (ret < 0) {
  2001. ti->error = "Invalid AEAD cipher spec";
  2002. return -ENOMEM;
  2003. }
  2004. cc->iv_size = crypto_aead_ivsize(any_tfm_aead(cc));
  2005. } else
  2006. cc->iv_size = crypto_skcipher_ivsize(any_tfm(cc));
  2007. ret = crypt_ctr_blkdev_cipher(cc);
  2008. if (ret < 0) {
  2009. ti->error = "Cannot allocate cipher string";
  2010. return -ENOMEM;
  2011. }
  2012. return 0;
  2013. }
  2014. static int crypt_ctr_cipher_old(struct dm_target *ti, char *cipher_in, char *key,
  2015. char **ivmode, char **ivopts)
  2016. {
  2017. struct crypt_config *cc = ti->private;
  2018. char *tmp, *cipher, *chainmode, *keycount;
  2019. char *cipher_api = NULL;
  2020. int ret = -EINVAL;
  2021. char dummy;
  2022. if (strchr(cipher_in, '(') || crypt_integrity_aead(cc)) {
  2023. ti->error = "Bad cipher specification";
  2024. return -EINVAL;
  2025. }
  2026. /*
  2027. * Legacy dm-crypt cipher specification
  2028. * cipher[:keycount]-mode-iv:ivopts
  2029. */
  2030. tmp = cipher_in;
  2031. keycount = strsep(&tmp, "-");
  2032. cipher = strsep(&keycount, ":");
  2033. if (!keycount)
  2034. cc->tfms_count = 1;
  2035. else if (sscanf(keycount, "%u%c", &cc->tfms_count, &dummy) != 1 ||
  2036. !is_power_of_2(cc->tfms_count)) {
  2037. ti->error = "Bad cipher key count specification";
  2038. return -EINVAL;
  2039. }
  2040. cc->key_parts = cc->tfms_count;
  2041. cc->cipher = kstrdup(cipher, GFP_KERNEL);
  2042. if (!cc->cipher)
  2043. goto bad_mem;
  2044. chainmode = strsep(&tmp, "-");
  2045. *ivmode = strsep(&tmp, ":");
  2046. *ivopts = tmp;
  2047. /*
  2048. * For compatibility with the original dm-crypt mapping format, if
  2049. * only the cipher name is supplied, use cbc-plain.
  2050. */
  2051. if (!chainmode || (!strcmp(chainmode, "plain") && !*ivmode)) {
  2052. chainmode = "cbc";
  2053. *ivmode = "plain";
  2054. }
  2055. if (strcmp(chainmode, "ecb") && !*ivmode) {
  2056. ti->error = "IV mechanism required";
  2057. return -EINVAL;
  2058. }
  2059. cipher_api = kmalloc(CRYPTO_MAX_ALG_NAME, GFP_KERNEL);
  2060. if (!cipher_api)
  2061. goto bad_mem;
  2062. ret = snprintf(cipher_api, CRYPTO_MAX_ALG_NAME,
  2063. "%s(%s)", chainmode, cipher);
  2064. if (ret < 0) {
  2065. kfree(cipher_api);
  2066. goto bad_mem;
  2067. }
  2068. /* Allocate cipher */
  2069. ret = crypt_alloc_tfms(cc, cipher_api);
  2070. if (ret < 0) {
  2071. ti->error = "Error allocating crypto tfm";
  2072. kfree(cipher_api);
  2073. return ret;
  2074. }
  2075. kfree(cipher_api);
  2076. return 0;
  2077. bad_mem:
  2078. ti->error = "Cannot allocate cipher strings";
  2079. return -ENOMEM;
  2080. }
  2081. static int crypt_ctr_cipher(struct dm_target *ti, char *cipher_in, char *key)
  2082. {
  2083. struct crypt_config *cc = ti->private;
  2084. char *ivmode = NULL, *ivopts = NULL;
  2085. int ret;
  2086. cc->cipher_string = kstrdup(cipher_in, GFP_KERNEL);
  2087. if (!cc->cipher_string) {
  2088. ti->error = "Cannot allocate cipher strings";
  2089. return -ENOMEM;
  2090. }
  2091. if (strstarts(cipher_in, "capi:"))
  2092. ret = crypt_ctr_cipher_new(ti, cipher_in, key, &ivmode, &ivopts);
  2093. else
  2094. ret = crypt_ctr_cipher_old(ti, cipher_in, key, &ivmode, &ivopts);
  2095. if (ret)
  2096. return ret;
  2097. /* Initialize IV */
  2098. ret = crypt_ctr_ivmode(ti, ivmode);
  2099. if (ret < 0)
  2100. return ret;
  2101. /* Initialize and set key */
  2102. ret = crypt_set_key(cc, key);
  2103. if (ret < 0) {
  2104. ti->error = "Error decoding and setting key";
  2105. return ret;
  2106. }
  2107. /* Allocate IV */
  2108. if (cc->iv_gen_ops && cc->iv_gen_ops->ctr) {
  2109. ret = cc->iv_gen_ops->ctr(cc, ti, ivopts);
  2110. if (ret < 0) {
  2111. ti->error = "Error creating IV";
  2112. return ret;
  2113. }
  2114. }
  2115. /* Initialize IV (set keys for ESSIV etc) */
  2116. if (cc->iv_gen_ops && cc->iv_gen_ops->init) {
  2117. ret = cc->iv_gen_ops->init(cc);
  2118. if (ret < 0) {
  2119. ti->error = "Error initialising IV";
  2120. return ret;
  2121. }
  2122. }
  2123. /* wipe the kernel key payload copy */
  2124. if (cc->key_string)
  2125. memset(cc->key, 0, cc->key_size * sizeof(u8));
  2126. return ret;
  2127. }
  2128. static int crypt_ctr_optional(struct dm_target *ti, unsigned int argc, char **argv)
  2129. {
  2130. struct crypt_config *cc = ti->private;
  2131. struct dm_arg_set as;
  2132. static const struct dm_arg _args[] = {
  2133. {0, 6, "Invalid number of feature args"},
  2134. };
  2135. unsigned int opt_params, val;
  2136. const char *opt_string, *sval;
  2137. char dummy;
  2138. int ret;
  2139. /* Optional parameters */
  2140. as.argc = argc;
  2141. as.argv = argv;
  2142. ret = dm_read_arg_group(_args, &as, &opt_params, &ti->error);
  2143. if (ret)
  2144. return ret;
  2145. while (opt_params--) {
  2146. opt_string = dm_shift_arg(&as);
  2147. if (!opt_string) {
  2148. ti->error = "Not enough feature arguments";
  2149. return -EINVAL;
  2150. }
  2151. if (!strcasecmp(opt_string, "allow_discards"))
  2152. ti->num_discard_bios = 1;
  2153. else if (!strcasecmp(opt_string, "same_cpu_crypt"))
  2154. set_bit(DM_CRYPT_SAME_CPU, &cc->flags);
  2155. else if (!strcasecmp(opt_string, "submit_from_crypt_cpus"))
  2156. set_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
  2157. else if (sscanf(opt_string, "integrity:%u:", &val) == 1) {
  2158. if (val == 0 || val > MAX_TAG_SIZE) {
  2159. ti->error = "Invalid integrity arguments";
  2160. return -EINVAL;
  2161. }
  2162. cc->on_disk_tag_size = val;
  2163. sval = strchr(opt_string + strlen("integrity:"), ':') + 1;
  2164. if (!strcasecmp(sval, "aead")) {
  2165. set_bit(CRYPT_MODE_INTEGRITY_AEAD, &cc->cipher_flags);
  2166. } else if (strcasecmp(sval, "none")) {
  2167. ti->error = "Unknown integrity profile";
  2168. return -EINVAL;
  2169. }
  2170. cc->cipher_auth = kstrdup(sval, GFP_KERNEL);
  2171. if (!cc->cipher_auth)
  2172. return -ENOMEM;
  2173. } else if (sscanf(opt_string, "sector_size:%hu%c", &cc->sector_size, &dummy) == 1) {
  2174. if (cc->sector_size < (1 << SECTOR_SHIFT) ||
  2175. cc->sector_size > 4096 ||
  2176. (cc->sector_size & (cc->sector_size - 1))) {
  2177. ti->error = "Invalid feature value for sector_size";
  2178. return -EINVAL;
  2179. }
  2180. if (ti->len & ((cc->sector_size >> SECTOR_SHIFT) - 1)) {
  2181. ti->error = "Device size is not multiple of sector_size feature";
  2182. return -EINVAL;
  2183. }
  2184. cc->sector_shift = __ffs(cc->sector_size) - SECTOR_SHIFT;
  2185. } else if (!strcasecmp(opt_string, "iv_large_sectors"))
  2186. set_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
  2187. else {
  2188. ti->error = "Invalid feature arguments";
  2189. return -EINVAL;
  2190. }
  2191. }
  2192. return 0;
  2193. }
  2194. /*
  2195. * Construct an encryption mapping:
  2196. * <cipher> [<key>|:<key_size>:<user|logon>:<key_description>] <iv_offset> <dev_path> <start>
  2197. */
  2198. static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv)
  2199. {
  2200. struct crypt_config *cc;
  2201. int key_size;
  2202. unsigned int align_mask;
  2203. unsigned long long tmpll;
  2204. int ret;
  2205. size_t iv_size_padding, additional_req_size;
  2206. char dummy;
  2207. if (argc < 5) {
  2208. ti->error = "Not enough arguments";
  2209. return -EINVAL;
  2210. }
  2211. key_size = get_key_size(&argv[1]);
  2212. if (key_size < 0) {
  2213. ti->error = "Cannot parse key size";
  2214. return -EINVAL;
  2215. }
  2216. cc = kzalloc(sizeof(*cc) + key_size * sizeof(u8), GFP_KERNEL);
  2217. if (!cc) {
  2218. ti->error = "Cannot allocate encryption context";
  2219. return -ENOMEM;
  2220. }
  2221. cc->key_size = key_size;
  2222. cc->sector_size = (1 << SECTOR_SHIFT);
  2223. cc->sector_shift = 0;
  2224. ti->private = cc;
  2225. spin_lock(&dm_crypt_clients_lock);
  2226. dm_crypt_clients_n++;
  2227. crypt_calculate_pages_per_client();
  2228. spin_unlock(&dm_crypt_clients_lock);
  2229. ret = percpu_counter_init(&cc->n_allocated_pages, 0, GFP_KERNEL);
  2230. if (ret < 0)
  2231. goto bad;
  2232. /* Optional parameters need to be read before cipher constructor */
  2233. if (argc > 5) {
  2234. ret = crypt_ctr_optional(ti, argc - 5, &argv[5]);
  2235. if (ret)
  2236. goto bad;
  2237. }
  2238. ret = crypt_ctr_cipher(ti, argv[0], argv[1]);
  2239. if (ret < 0)
  2240. goto bad;
  2241. if (crypt_integrity_aead(cc)) {
  2242. cc->dmreq_start = sizeof(struct aead_request);
  2243. cc->dmreq_start += crypto_aead_reqsize(any_tfm_aead(cc));
  2244. align_mask = crypto_aead_alignmask(any_tfm_aead(cc));
  2245. } else {
  2246. cc->dmreq_start = sizeof(struct skcipher_request);
  2247. cc->dmreq_start += crypto_skcipher_reqsize(any_tfm(cc));
  2248. align_mask = crypto_skcipher_alignmask(any_tfm(cc));
  2249. }
  2250. cc->dmreq_start = ALIGN(cc->dmreq_start, __alignof__(struct dm_crypt_request));
  2251. if (align_mask < CRYPTO_MINALIGN) {
  2252. /* Allocate the padding exactly */
  2253. iv_size_padding = -(cc->dmreq_start + sizeof(struct dm_crypt_request))
  2254. & align_mask;
  2255. } else {
  2256. /*
  2257. * If the cipher requires greater alignment than kmalloc
  2258. * alignment, we don't know the exact position of the
  2259. * initialization vector. We must assume worst case.
  2260. */
  2261. iv_size_padding = align_mask;
  2262. }
  2263. /* ...| IV + padding | original IV | original sec. number | bio tag offset | */
  2264. additional_req_size = sizeof(struct dm_crypt_request) +
  2265. iv_size_padding + cc->iv_size +
  2266. cc->iv_size +
  2267. sizeof(uint64_t) +
  2268. sizeof(unsigned int);
  2269. ret = mempool_init_kmalloc_pool(&cc->req_pool, MIN_IOS, cc->dmreq_start + additional_req_size);
  2270. if (ret) {
  2271. ti->error = "Cannot allocate crypt request mempool";
  2272. goto bad;
  2273. }
  2274. cc->per_bio_data_size = ti->per_io_data_size =
  2275. ALIGN(sizeof(struct dm_crypt_io) + cc->dmreq_start + additional_req_size,
  2276. ARCH_KMALLOC_MINALIGN);
  2277. ret = mempool_init(&cc->page_pool, BIO_MAX_PAGES, crypt_page_alloc, crypt_page_free, cc);
  2278. if (ret) {
  2279. ti->error = "Cannot allocate page mempool";
  2280. goto bad;
  2281. }
  2282. ret = bioset_init(&cc->bs, MIN_IOS, 0, BIOSET_NEED_BVECS);
  2283. if (ret) {
  2284. ti->error = "Cannot allocate crypt bioset";
  2285. goto bad;
  2286. }
  2287. mutex_init(&cc->bio_alloc_lock);
  2288. ret = -EINVAL;
  2289. if ((sscanf(argv[2], "%llu%c", &tmpll, &dummy) != 1) ||
  2290. (tmpll & ((cc->sector_size >> SECTOR_SHIFT) - 1))) {
  2291. ti->error = "Invalid iv_offset sector";
  2292. goto bad;
  2293. }
  2294. cc->iv_offset = tmpll;
  2295. ret = dm_get_device(ti, argv[3], dm_table_get_mode(ti->table), &cc->dev);
  2296. if (ret) {
  2297. ti->error = "Device lookup failed";
  2298. goto bad;
  2299. }
  2300. ret = -EINVAL;
  2301. if (sscanf(argv[4], "%llu%c", &tmpll, &dummy) != 1 || tmpll != (sector_t)tmpll) {
  2302. ti->error = "Invalid device sector";
  2303. goto bad;
  2304. }
  2305. cc->start = tmpll;
  2306. if (crypt_integrity_aead(cc) || cc->integrity_iv_size) {
  2307. ret = crypt_integrity_ctr(cc, ti);
  2308. if (ret)
  2309. goto bad;
  2310. cc->tag_pool_max_sectors = POOL_ENTRY_SIZE / cc->on_disk_tag_size;
  2311. if (!cc->tag_pool_max_sectors)
  2312. cc->tag_pool_max_sectors = 1;
  2313. ret = mempool_init_kmalloc_pool(&cc->tag_pool, MIN_IOS,
  2314. cc->tag_pool_max_sectors * cc->on_disk_tag_size);
  2315. if (ret) {
  2316. ti->error = "Cannot allocate integrity tags mempool";
  2317. goto bad;
  2318. }
  2319. cc->tag_pool_max_sectors <<= cc->sector_shift;
  2320. }
  2321. ret = -ENOMEM;
  2322. cc->io_queue = alloc_workqueue("kcryptd_io", WQ_HIGHPRI | WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM, 1);
  2323. if (!cc->io_queue) {
  2324. ti->error = "Couldn't create kcryptd io queue";
  2325. goto bad;
  2326. }
  2327. if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
  2328. cc->crypt_queue = alloc_workqueue("kcryptd", WQ_HIGHPRI | WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM, 1);
  2329. else
  2330. cc->crypt_queue = alloc_workqueue("kcryptd",
  2331. WQ_HIGHPRI | WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM | WQ_UNBOUND,
  2332. num_online_cpus());
  2333. if (!cc->crypt_queue) {
  2334. ti->error = "Couldn't create kcryptd queue";
  2335. goto bad;
  2336. }
  2337. spin_lock_init(&cc->write_thread_lock);
  2338. cc->write_tree = RB_ROOT;
  2339. cc->write_thread = kthread_create(dmcrypt_write, cc, "dmcrypt_write");
  2340. if (IS_ERR(cc->write_thread)) {
  2341. ret = PTR_ERR(cc->write_thread);
  2342. cc->write_thread = NULL;
  2343. ti->error = "Couldn't spawn write thread";
  2344. goto bad;
  2345. }
  2346. wake_up_process(cc->write_thread);
  2347. ti->num_flush_bios = 1;
  2348. return 0;
  2349. bad:
  2350. crypt_dtr(ti);
  2351. return ret;
  2352. }
  2353. static int crypt_map(struct dm_target *ti, struct bio *bio)
  2354. {
  2355. struct dm_crypt_io *io;
  2356. struct crypt_config *cc = ti->private;
  2357. /*
  2358. * If bio is REQ_PREFLUSH or REQ_OP_DISCARD, just bypass crypt queues.
  2359. * - for REQ_PREFLUSH device-mapper core ensures that no IO is in-flight
  2360. * - for REQ_OP_DISCARD caller must use flush if IO ordering matters
  2361. */
  2362. if (unlikely(bio->bi_opf & REQ_PREFLUSH ||
  2363. bio_op(bio) == REQ_OP_DISCARD)) {
  2364. bio_set_dev(bio, cc->dev->bdev);
  2365. if (bio_sectors(bio))
  2366. bio->bi_iter.bi_sector = cc->start +
  2367. dm_target_offset(ti, bio->bi_iter.bi_sector);
  2368. return DM_MAPIO_REMAPPED;
  2369. }
  2370. /*
  2371. * Check if bio is too large, split as needed.
  2372. */
  2373. if (unlikely(bio->bi_iter.bi_size > (BIO_MAX_PAGES << PAGE_SHIFT)) &&
  2374. (bio_data_dir(bio) == WRITE || cc->on_disk_tag_size))
  2375. dm_accept_partial_bio(bio, ((BIO_MAX_PAGES << PAGE_SHIFT) >> SECTOR_SHIFT));
  2376. /*
  2377. * Ensure that bio is a multiple of internal sector encryption size
  2378. * and is aligned to this size as defined in IO hints.
  2379. */
  2380. if (unlikely((bio->bi_iter.bi_sector & ((cc->sector_size >> SECTOR_SHIFT) - 1)) != 0))
  2381. return DM_MAPIO_KILL;
  2382. if (unlikely(bio->bi_iter.bi_size & (cc->sector_size - 1)))
  2383. return DM_MAPIO_KILL;
  2384. io = dm_per_bio_data(bio, cc->per_bio_data_size);
  2385. crypt_io_init(io, cc, bio, dm_target_offset(ti, bio->bi_iter.bi_sector));
  2386. if (cc->on_disk_tag_size) {
  2387. unsigned tag_len = cc->on_disk_tag_size * (bio_sectors(bio) >> cc->sector_shift);
  2388. if (unlikely(tag_len > KMALLOC_MAX_SIZE) ||
  2389. unlikely(!(io->integrity_metadata = kmalloc(tag_len,
  2390. GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN)))) {
  2391. if (bio_sectors(bio) > cc->tag_pool_max_sectors)
  2392. dm_accept_partial_bio(bio, cc->tag_pool_max_sectors);
  2393. io->integrity_metadata = mempool_alloc(&cc->tag_pool, GFP_NOIO);
  2394. io->integrity_metadata_from_pool = true;
  2395. }
  2396. }
  2397. if (crypt_integrity_aead(cc))
  2398. io->ctx.r.req_aead = (struct aead_request *)(io + 1);
  2399. else
  2400. io->ctx.r.req = (struct skcipher_request *)(io + 1);
  2401. if (bio_data_dir(io->base_bio) == READ) {
  2402. if (kcryptd_io_read(io, GFP_NOWAIT))
  2403. kcryptd_queue_read(io);
  2404. } else
  2405. kcryptd_queue_crypt(io);
  2406. return DM_MAPIO_SUBMITTED;
  2407. }
  2408. static void crypt_status(struct dm_target *ti, status_type_t type,
  2409. unsigned status_flags, char *result, unsigned maxlen)
  2410. {
  2411. struct crypt_config *cc = ti->private;
  2412. unsigned i, sz = 0;
  2413. int num_feature_args = 0;
  2414. switch (type) {
  2415. case STATUSTYPE_INFO:
  2416. result[0] = '\0';
  2417. break;
  2418. case STATUSTYPE_TABLE:
  2419. DMEMIT("%s ", cc->cipher_string);
  2420. if (cc->key_size > 0) {
  2421. if (cc->key_string)
  2422. DMEMIT(":%u:%s", cc->key_size, cc->key_string);
  2423. else
  2424. for (i = 0; i < cc->key_size; i++)
  2425. DMEMIT("%02x", cc->key[i]);
  2426. } else
  2427. DMEMIT("-");
  2428. DMEMIT(" %llu %s %llu", (unsigned long long)cc->iv_offset,
  2429. cc->dev->name, (unsigned long long)cc->start);
  2430. num_feature_args += !!ti->num_discard_bios;
  2431. num_feature_args += test_bit(DM_CRYPT_SAME_CPU, &cc->flags);
  2432. num_feature_args += test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags);
  2433. num_feature_args += cc->sector_size != (1 << SECTOR_SHIFT);
  2434. num_feature_args += test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags);
  2435. if (cc->on_disk_tag_size)
  2436. num_feature_args++;
  2437. if (num_feature_args) {
  2438. DMEMIT(" %d", num_feature_args);
  2439. if (ti->num_discard_bios)
  2440. DMEMIT(" allow_discards");
  2441. if (test_bit(DM_CRYPT_SAME_CPU, &cc->flags))
  2442. DMEMIT(" same_cpu_crypt");
  2443. if (test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags))
  2444. DMEMIT(" submit_from_crypt_cpus");
  2445. if (cc->on_disk_tag_size)
  2446. DMEMIT(" integrity:%u:%s", cc->on_disk_tag_size, cc->cipher_auth);
  2447. if (cc->sector_size != (1 << SECTOR_SHIFT))
  2448. DMEMIT(" sector_size:%d", cc->sector_size);
  2449. if (test_bit(CRYPT_IV_LARGE_SECTORS, &cc->cipher_flags))
  2450. DMEMIT(" iv_large_sectors");
  2451. }
  2452. break;
  2453. }
  2454. }
  2455. static void crypt_postsuspend(struct dm_target *ti)
  2456. {
  2457. struct crypt_config *cc = ti->private;
  2458. set_bit(DM_CRYPT_SUSPENDED, &cc->flags);
  2459. }
  2460. static int crypt_preresume(struct dm_target *ti)
  2461. {
  2462. struct crypt_config *cc = ti->private;
  2463. if (!test_bit(DM_CRYPT_KEY_VALID, &cc->flags)) {
  2464. DMERR("aborting resume - crypt key is not set.");
  2465. return -EAGAIN;
  2466. }
  2467. return 0;
  2468. }
  2469. static void crypt_resume(struct dm_target *ti)
  2470. {
  2471. struct crypt_config *cc = ti->private;
  2472. clear_bit(DM_CRYPT_SUSPENDED, &cc->flags);
  2473. }
  2474. /* Message interface
  2475. * key set <key>
  2476. * key wipe
  2477. */
  2478. static int crypt_message(struct dm_target *ti, unsigned argc, char **argv,
  2479. char *result, unsigned maxlen)
  2480. {
  2481. struct crypt_config *cc = ti->private;
  2482. int key_size, ret = -EINVAL;
  2483. if (argc < 2)
  2484. goto error;
  2485. if (!strcasecmp(argv[0], "key")) {
  2486. if (!test_bit(DM_CRYPT_SUSPENDED, &cc->flags)) {
  2487. DMWARN("not suspended during key manipulation.");
  2488. return -EINVAL;
  2489. }
  2490. if (argc == 3 && !strcasecmp(argv[1], "set")) {
  2491. /* The key size may not be changed. */
  2492. key_size = get_key_size(&argv[2]);
  2493. if (key_size < 0 || cc->key_size != key_size) {
  2494. memset(argv[2], '0', strlen(argv[2]));
  2495. return -EINVAL;
  2496. }
  2497. ret = crypt_set_key(cc, argv[2]);
  2498. if (ret)
  2499. return ret;
  2500. if (cc->iv_gen_ops && cc->iv_gen_ops->init)
  2501. ret = cc->iv_gen_ops->init(cc);
  2502. /* wipe the kernel key payload copy */
  2503. if (cc->key_string)
  2504. memset(cc->key, 0, cc->key_size * sizeof(u8));
  2505. return ret;
  2506. }
  2507. if (argc == 2 && !strcasecmp(argv[1], "wipe")) {
  2508. if (cc->iv_gen_ops && cc->iv_gen_ops->wipe) {
  2509. ret = cc->iv_gen_ops->wipe(cc);
  2510. if (ret)
  2511. return ret;
  2512. }
  2513. return crypt_wipe_key(cc);
  2514. }
  2515. }
  2516. error:
  2517. DMWARN("unrecognised message received.");
  2518. return -EINVAL;
  2519. }
  2520. static int crypt_iterate_devices(struct dm_target *ti,
  2521. iterate_devices_callout_fn fn, void *data)
  2522. {
  2523. struct crypt_config *cc = ti->private;
  2524. return fn(ti, cc->dev, cc->start, ti->len, data);
  2525. }
  2526. static void crypt_io_hints(struct dm_target *ti, struct queue_limits *limits)
  2527. {
  2528. struct crypt_config *cc = ti->private;
  2529. /*
  2530. * Unfortunate constraint that is required to avoid the potential
  2531. * for exceeding underlying device's max_segments limits -- due to
  2532. * crypt_alloc_buffer() possibly allocating pages for the encryption
  2533. * bio that are not as physically contiguous as the original bio.
  2534. */
  2535. limits->max_segment_size = PAGE_SIZE;
  2536. limits->logical_block_size =
  2537. max_t(unsigned short, limits->logical_block_size, cc->sector_size);
  2538. limits->physical_block_size =
  2539. max_t(unsigned, limits->physical_block_size, cc->sector_size);
  2540. limits->io_min = max_t(unsigned, limits->io_min, cc->sector_size);
  2541. }
  2542. static struct target_type crypt_target = {
  2543. .name = "crypt",
  2544. .version = {1, 18, 1},
  2545. .module = THIS_MODULE,
  2546. .ctr = crypt_ctr,
  2547. .dtr = crypt_dtr,
  2548. .map = crypt_map,
  2549. .status = crypt_status,
  2550. .postsuspend = crypt_postsuspend,
  2551. .preresume = crypt_preresume,
  2552. .resume = crypt_resume,
  2553. .message = crypt_message,
  2554. .iterate_devices = crypt_iterate_devices,
  2555. .io_hints = crypt_io_hints,
  2556. };
  2557. static int __init dm_crypt_init(void)
  2558. {
  2559. int r;
  2560. r = dm_register_target(&crypt_target);
  2561. if (r < 0)
  2562. DMERR("register failed %d", r);
  2563. return r;
  2564. }
  2565. static void __exit dm_crypt_exit(void)
  2566. {
  2567. dm_unregister_target(&crypt_target);
  2568. }
  2569. module_init(dm_crypt_init);
  2570. module_exit(dm_crypt_exit);
  2571. MODULE_AUTHOR("Jana Saout <jana@saout.de>");
  2572. MODULE_DESCRIPTION(DM_NAME " target for transparent encryption / decryption");
  2573. MODULE_LICENSE("GPL");