dm-crypt.c 79 KB

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