dm-crypt.c 79 KB

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