dm-crypt.c 95 KB

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