Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

lua_cryptobox.c 72KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973
  1. /*-
  2. * Copyright 2016 Vsevolod Stakhov
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. /***
  17. * @module rspamd_cryptobox
  18. * Rspamd cryptobox is a module that operates with digital signatures and
  19. * hashes.
  20. * @example
  21. * local hash = require "rspamd_cryptobox_hash"
  22. *
  23. * local h = hash.create()
  24. * h:update('hello world')
  25. * print(h:hex())
  26. */
  27. #include "lua_common.h"
  28. #include "libcryptobox/cryptobox.h"
  29. #include "libcryptobox/keypair.h"
  30. #include "libcryptobox/keypair_private.h"
  31. #include "unix-std.h"
  32. #include "contrib/libottery/ottery.h"
  33. #include "libutil/ref.h"
  34. #include <stdalign.h>
  35. #include <openssl/hmac.h>
  36. enum lua_cryptobox_hash_type {
  37. LUA_CRYPTOBOX_HASH_BLAKE2 = 0,
  38. LUA_CRYPTOBOX_HASH_SSL,
  39. LUA_CRYPTOBOX_HASH_HMAC,
  40. LUA_CRYPTOBOX_HASH_XXHASH64,
  41. LUA_CRYPTOBOX_HASH_XXHASH32,
  42. LUA_CRYPTOBOX_HASH_MUM,
  43. LUA_CRYPTOBOX_HASH_T1HA,
  44. };
  45. struct rspamd_lua_cryptobox_hash {
  46. union {
  47. rspamd_cryptobox_hash_state_t *h;
  48. EVP_MD_CTX *c;
  49. HMAC_CTX *hmac_c;
  50. rspamd_cryptobox_fast_hash_state_t *fh;
  51. } content;
  52. unsigned char out[rspamd_cryptobox_HASHBYTES];
  53. uint8_t type;
  54. uint8_t out_len;
  55. uint8_t is_finished;
  56. ref_entry_t ref;
  57. };
  58. LUA_FUNCTION_DEF (cryptobox_pubkey, load);
  59. LUA_FUNCTION_DEF (cryptobox_pubkey, create);
  60. LUA_FUNCTION_DEF (cryptobox_pubkey, gc);
  61. LUA_FUNCTION_DEF (cryptobox_keypair, load);
  62. LUA_FUNCTION_DEF (cryptobox_keypair, create);
  63. LUA_FUNCTION_DEF (cryptobox_keypair, gc);
  64. LUA_FUNCTION_DEF (cryptobox_keypair, totable);
  65. LUA_FUNCTION_DEF (cryptobox_keypair, get_type);
  66. LUA_FUNCTION_DEF (cryptobox_keypair, get_alg);
  67. LUA_FUNCTION_DEF (cryptobox_keypair, get_pk);
  68. LUA_FUNCTION_DEF (cryptobox_signature, create);
  69. LUA_FUNCTION_DEF (cryptobox_signature, load);
  70. LUA_FUNCTION_DEF (cryptobox_signature, save);
  71. LUA_FUNCTION_DEF (cryptobox_signature, gc);
  72. LUA_FUNCTION_DEF (cryptobox_signature, hex);
  73. LUA_FUNCTION_DEF (cryptobox_signature, base32);
  74. LUA_FUNCTION_DEF (cryptobox_signature, base64);
  75. LUA_FUNCTION_DEF (cryptobox_signature, bin);
  76. LUA_FUNCTION_DEF (cryptobox_hash, create);
  77. LUA_FUNCTION_DEF (cryptobox_hash, create_specific);
  78. LUA_FUNCTION_DEF (cryptobox_hash, create_specific_keyed);
  79. LUA_FUNCTION_DEF (cryptobox_hash, create_keyed);
  80. LUA_FUNCTION_DEF (cryptobox_hash, update);
  81. LUA_FUNCTION_DEF (cryptobox_hash, reset);
  82. LUA_FUNCTION_DEF (cryptobox_hash, hex);
  83. LUA_FUNCTION_DEF (cryptobox_hash, base32);
  84. LUA_FUNCTION_DEF (cryptobox_hash, base64);
  85. LUA_FUNCTION_DEF (cryptobox_hash, bin);
  86. LUA_FUNCTION_DEF (cryptobox_hash, gc);
  87. LUA_FUNCTION_DEF (cryptobox, verify_memory);
  88. LUA_FUNCTION_DEF (cryptobox, verify_file);
  89. LUA_FUNCTION_DEF (cryptobox, sign_file);
  90. LUA_FUNCTION_DEF (cryptobox, sign_memory);
  91. LUA_FUNCTION_DEF (cryptobox, encrypt_memory);
  92. LUA_FUNCTION_DEF (cryptobox, encrypt_file);
  93. LUA_FUNCTION_DEF (cryptobox, decrypt_memory);
  94. LUA_FUNCTION_DEF (cryptobox, decrypt_file);
  95. LUA_FUNCTION_DEF (cryptobox, encrypt_cookie);
  96. LUA_FUNCTION_DEF (cryptobox, decrypt_cookie);
  97. LUA_FUNCTION_DEF (cryptobox, pbkdf);
  98. LUA_FUNCTION_DEF (cryptobox, gen_dkim_keypair);
  99. /* Secretbox API: uses libsodium secretbox and blake2b for key derivation */
  100. LUA_FUNCTION_DEF (cryptobox_secretbox, create);
  101. LUA_FUNCTION_DEF (cryptobox_secretbox, encrypt);
  102. LUA_FUNCTION_DEF (cryptobox_secretbox, decrypt);
  103. LUA_FUNCTION_DEF (cryptobox_secretbox, gc);
  104. static const struct luaL_reg cryptoboxlib_f[] = {
  105. LUA_INTERFACE_DEF (cryptobox, verify_memory),
  106. LUA_INTERFACE_DEF (cryptobox, verify_file),
  107. LUA_INTERFACE_DEF (cryptobox, sign_memory),
  108. LUA_INTERFACE_DEF (cryptobox, sign_file),
  109. LUA_INTERFACE_DEF (cryptobox, encrypt_memory),
  110. LUA_INTERFACE_DEF (cryptobox, encrypt_file),
  111. LUA_INTERFACE_DEF (cryptobox, decrypt_memory),
  112. LUA_INTERFACE_DEF (cryptobox, decrypt_file),
  113. LUA_INTERFACE_DEF (cryptobox, encrypt_cookie),
  114. LUA_INTERFACE_DEF (cryptobox, decrypt_cookie),
  115. LUA_INTERFACE_DEF (cryptobox, pbkdf),
  116. LUA_INTERFACE_DEF (cryptobox, gen_dkim_keypair),
  117. {NULL, NULL}
  118. };
  119. static const struct luaL_reg cryptoboxpubkeylib_f[] = {
  120. LUA_INTERFACE_DEF (cryptobox_pubkey, load),
  121. LUA_INTERFACE_DEF (cryptobox_pubkey, create),
  122. {NULL, NULL}
  123. };
  124. static const struct luaL_reg cryptoboxpubkeylib_m[] = {
  125. {"__tostring", rspamd_lua_class_tostring},
  126. {"__gc", lua_cryptobox_pubkey_gc},
  127. {NULL, NULL}
  128. };
  129. static const struct luaL_reg cryptoboxkeypairlib_f[] = {
  130. LUA_INTERFACE_DEF (cryptobox_keypair, load),
  131. LUA_INTERFACE_DEF (cryptobox_keypair, create),
  132. {NULL, NULL}
  133. };
  134. static const struct luaL_reg cryptoboxkeypairlib_m[] = {
  135. {"__tostring", rspamd_lua_class_tostring},
  136. {"totable", lua_cryptobox_keypair_totable},
  137. {"get_type", lua_cryptobox_keypair_get_type},
  138. {"get_alg", lua_cryptobox_keypair_get_alg},
  139. {"type", lua_cryptobox_keypair_get_type},
  140. {"alg", lua_cryptobox_keypair_get_alg},
  141. {"pk", lua_cryptobox_keypair_get_pk},
  142. {"pubkey", lua_cryptobox_keypair_get_pk},
  143. {"__gc", lua_cryptobox_keypair_gc},
  144. {NULL, NULL}
  145. };
  146. static const struct luaL_reg cryptoboxsignlib_f[] = {
  147. LUA_INTERFACE_DEF (cryptobox_signature, load),
  148. LUA_INTERFACE_DEF (cryptobox_signature, create),
  149. {NULL, NULL}
  150. };
  151. static const struct luaL_reg cryptoboxsignlib_m[] = {
  152. LUA_INTERFACE_DEF (cryptobox_signature, save),
  153. LUA_INTERFACE_DEF (cryptobox_signature, hex),
  154. LUA_INTERFACE_DEF (cryptobox_signature, base32),
  155. LUA_INTERFACE_DEF (cryptobox_signature, base64),
  156. LUA_INTERFACE_DEF (cryptobox_signature, bin),
  157. {"__tostring", rspamd_lua_class_tostring},
  158. {"__gc", lua_cryptobox_signature_gc},
  159. {NULL, NULL}
  160. };
  161. static const struct luaL_reg cryptoboxhashlib_f[] = {
  162. LUA_INTERFACE_DEF (cryptobox_hash, create),
  163. LUA_INTERFACE_DEF (cryptobox_hash, create_keyed),
  164. LUA_INTERFACE_DEF (cryptobox_hash, create_specific),
  165. LUA_INTERFACE_DEF (cryptobox_hash, create_specific_keyed),
  166. {NULL, NULL}
  167. };
  168. static const struct luaL_reg cryptoboxhashlib_m[] = {
  169. LUA_INTERFACE_DEF (cryptobox_hash, update),
  170. LUA_INTERFACE_DEF (cryptobox_hash, reset),
  171. LUA_INTERFACE_DEF (cryptobox_hash, hex),
  172. LUA_INTERFACE_DEF (cryptobox_hash, base32),
  173. LUA_INTERFACE_DEF (cryptobox_hash, base64),
  174. LUA_INTERFACE_DEF (cryptobox_hash, bin),
  175. {"__tostring", rspamd_lua_class_tostring},
  176. {"__gc", lua_cryptobox_hash_gc},
  177. {NULL, NULL}
  178. };
  179. static const struct luaL_reg cryptoboxsecretboxlib_f[] = {
  180. LUA_INTERFACE_DEF (cryptobox_secretbox, create),
  181. {NULL, NULL},
  182. };
  183. static const struct luaL_reg cryptoboxsecretboxlib_m[] = {
  184. LUA_INTERFACE_DEF (cryptobox_secretbox, encrypt),
  185. LUA_INTERFACE_DEF (cryptobox_secretbox, decrypt),
  186. {"__gc", lua_cryptobox_secretbox_gc},
  187. {NULL, NULL},
  188. };
  189. struct rspamd_lua_cryptobox_secretbox {
  190. guchar sk[crypto_secretbox_KEYBYTES];
  191. };
  192. static struct rspamd_cryptobox_pubkey *
  193. lua_check_cryptobox_pubkey (lua_State * L, int pos)
  194. {
  195. void *ud = rspamd_lua_check_udata (L, pos, "rspamd{cryptobox_pubkey}");
  196. luaL_argcheck (L, ud != NULL, 1, "'cryptobox_pubkey' expected");
  197. return ud ? *((struct rspamd_cryptobox_pubkey **)ud) : NULL;
  198. }
  199. static struct rspamd_cryptobox_keypair *
  200. lua_check_cryptobox_keypair (lua_State * L, int pos)
  201. {
  202. void *ud = rspamd_lua_check_udata (L, pos, "rspamd{cryptobox_keypair}");
  203. luaL_argcheck (L, ud != NULL, 1, "'cryptobox_keypair' expected");
  204. return ud ? *((struct rspamd_cryptobox_keypair **)ud) : NULL;
  205. }
  206. static rspamd_fstring_t *
  207. lua_check_cryptobox_sign (lua_State * L, int pos)
  208. {
  209. void *ud = rspamd_lua_check_udata (L, pos, "rspamd{cryptobox_signature}");
  210. luaL_argcheck (L, ud != NULL, 1, "'cryptobox_signature' expected");
  211. return ud ? *((rspamd_fstring_t **)ud) : NULL;
  212. }
  213. struct rspamd_lua_cryptobox_hash *
  214. lua_check_cryptobox_hash (lua_State * L, int pos)
  215. {
  216. void *ud = rspamd_lua_check_udata (L, pos, "rspamd{cryptobox_hash}");
  217. luaL_argcheck (L, ud != NULL, 1, "'cryptobox_hash' expected");
  218. return ud ? *((struct rspamd_lua_cryptobox_hash **)ud) : NULL;
  219. }
  220. static struct rspamd_lua_cryptobox_secretbox *
  221. lua_check_cryptobox_secretbox (lua_State * L, int pos)
  222. {
  223. void *ud = rspamd_lua_check_udata (L, pos, "rspamd{cryptobox_secretbox}");
  224. luaL_argcheck (L, ud != NULL, 1, "'cryptobox_secretbox' expected");
  225. return ud ? *((struct rspamd_lua_cryptobox_secretbox **)ud) : NULL;
  226. }
  227. /***
  228. * @function rspamd_cryptobox_pubkey.load(file[, type[, alg]])
  229. * Loads public key from base32 encoded file
  230. * @param {string} file filename to load
  231. * @param {string} type optional 'sign' or 'kex' for signing and encryption
  232. * @param {string} alg optional 'default' or 'nist' for curve25519/nistp256 keys
  233. * @return {cryptobox_pubkey} new public key
  234. */
  235. static gint
  236. lua_cryptobox_pubkey_load (lua_State *L)
  237. {
  238. LUA_TRACE_POINT;
  239. struct rspamd_cryptobox_pubkey *pkey = NULL, **ppkey;
  240. const gchar *filename, *arg;
  241. gint type = RSPAMD_KEYPAIR_SIGN;
  242. gint alg = RSPAMD_CRYPTOBOX_MODE_25519;
  243. guchar *map;
  244. gsize len;
  245. filename = luaL_checkstring (L, 1);
  246. if (filename != NULL) {
  247. map = rspamd_file_xmap (filename, PROT_READ, &len, TRUE);
  248. if (map == NULL) {
  249. msg_err ("cannot open pubkey from file: %s, %s",
  250. filename,
  251. strerror (errno));
  252. lua_pushnil (L);
  253. }
  254. else {
  255. if (lua_type (L, 2) == LUA_TSTRING) {
  256. /* keypair type */
  257. arg = lua_tostring (L, 2);
  258. if (strcmp (arg, "sign") == 0) {
  259. type = RSPAMD_KEYPAIR_SIGN;
  260. }
  261. else if (strcmp (arg, "kex") == 0) {
  262. type = RSPAMD_KEYPAIR_KEX;
  263. }
  264. }
  265. if (lua_type (L, 3) == LUA_TSTRING) {
  266. /* algorithm */
  267. arg = lua_tostring (L, 3);
  268. if (strcmp (arg, "default") == 0 || strcmp (arg, "curve25519") == 0) {
  269. type = RSPAMD_CRYPTOBOX_MODE_25519;
  270. }
  271. else if (strcmp (arg, "nist") == 0) {
  272. type = RSPAMD_CRYPTOBOX_MODE_NIST;
  273. }
  274. }
  275. pkey = rspamd_pubkey_from_base32 (map, len, type, alg);
  276. if (pkey == NULL) {
  277. msg_err ("cannot open pubkey from file: %s", filename);
  278. munmap (map, len);
  279. lua_pushnil (L);
  280. }
  281. else {
  282. munmap (map, len);
  283. ppkey = lua_newuserdata (L, sizeof (void *));
  284. rspamd_lua_setclass (L, "rspamd{cryptobox_pubkey}", -1);
  285. *ppkey = pkey;
  286. }
  287. }
  288. }
  289. else {
  290. return luaL_error (L, "bad input arguments");
  291. }
  292. return 1;
  293. }
  294. /***
  295. * @function rspamd_cryptobox_pubkey.create(data[, type[, alg]])
  296. * Loads public key from base32 encoded string
  297. * @param {base32 string} base32 string with the key
  298. * @param {string} type optional 'sign' or 'kex' for signing and encryption
  299. * @param {string} alg optional 'default' or 'nist' for curve25519/nistp256 keys
  300. * @return {cryptobox_pubkey} new public key
  301. */
  302. static gint
  303. lua_cryptobox_pubkey_create (lua_State *L)
  304. {
  305. LUA_TRACE_POINT;
  306. struct rspamd_cryptobox_pubkey *pkey = NULL, **ppkey;
  307. const gchar *buf, *arg;
  308. gsize len;
  309. gint type = RSPAMD_KEYPAIR_SIGN;
  310. gint alg = RSPAMD_CRYPTOBOX_MODE_25519;
  311. buf = luaL_checklstring (L, 1, &len);
  312. if (buf != NULL) {
  313. if (lua_type (L, 2) == LUA_TSTRING) {
  314. /* keypair type */
  315. arg = lua_tostring (L, 2);
  316. if (strcmp (arg, "sign") == 0) {
  317. type = RSPAMD_KEYPAIR_SIGN;
  318. }
  319. else if (strcmp (arg, "kex") == 0) {
  320. type = RSPAMD_KEYPAIR_KEX;
  321. }
  322. }
  323. if (lua_type (L, 3) == LUA_TSTRING) {
  324. /* algorithm */
  325. arg = lua_tostring (L, 3);
  326. if (strcmp (arg, "default") == 0 || strcmp (arg, "curve25519") == 0) {
  327. type = RSPAMD_CRYPTOBOX_MODE_25519;
  328. }
  329. else if (strcmp (arg, "nist") == 0) {
  330. type = RSPAMD_CRYPTOBOX_MODE_NIST;
  331. }
  332. }
  333. pkey = rspamd_pubkey_from_base32 (buf, len, type, alg);
  334. if (pkey == NULL) {
  335. msg_err ("cannot load pubkey from string");
  336. lua_pushnil (L);
  337. }
  338. else {
  339. ppkey = lua_newuserdata (L, sizeof (void *));
  340. rspamd_lua_setclass (L, "rspamd{cryptobox_pubkey}", -1);
  341. *ppkey = pkey;
  342. }
  343. }
  344. else {
  345. return luaL_error (L, "bad input arguments");
  346. }
  347. return 1;
  348. }
  349. static gint
  350. lua_cryptobox_pubkey_gc (lua_State *L)
  351. {
  352. LUA_TRACE_POINT;
  353. struct rspamd_cryptobox_pubkey *pkey = lua_check_cryptobox_pubkey (L, 1);
  354. if (pkey != NULL) {
  355. rspamd_pubkey_unref (pkey);
  356. }
  357. return 0;
  358. }
  359. /***
  360. * @function rspamd_cryptobox_keypair.load(file|table)
  361. * Loads public key from UCL file or directly from Lua
  362. * @param {string} file filename to load
  363. * @return {cryptobox_keypair} new keypair
  364. */
  365. static gint
  366. lua_cryptobox_keypair_load (lua_State *L)
  367. {
  368. LUA_TRACE_POINT;
  369. struct rspamd_cryptobox_keypair *kp, **pkp;
  370. const gchar *buf;
  371. gsize len;
  372. struct ucl_parser *parser;
  373. ucl_object_t *obj;
  374. if (lua_type (L, 1) == LUA_TSTRING) {
  375. buf = luaL_checklstring (L, 1, &len);
  376. if (buf != NULL) {
  377. parser = ucl_parser_new (0);
  378. if (!ucl_parser_add_chunk (parser, buf, len)) {
  379. msg_err ("cannot open keypair from data: %s",
  380. ucl_parser_get_error (parser));
  381. ucl_parser_free (parser);
  382. lua_pushnil (L);
  383. }
  384. else {
  385. obj = ucl_parser_get_object (parser);
  386. kp = rspamd_keypair_from_ucl (obj);
  387. ucl_parser_free (parser);
  388. if (kp == NULL) {
  389. msg_err ("cannot load keypair from data");
  390. ucl_object_unref (obj);
  391. lua_pushnil (L);
  392. }
  393. else {
  394. pkp = lua_newuserdata (L, sizeof (gpointer));
  395. *pkp = kp;
  396. rspamd_lua_setclass (L, "rspamd{cryptobox_keypair}", -1);
  397. ucl_object_unref (obj);
  398. }
  399. }
  400. }
  401. else {
  402. luaL_error (L, "bad input arguments");
  403. }
  404. }
  405. else {
  406. /* Directly import from lua */
  407. obj = ucl_object_lua_import (L, 1);
  408. kp = rspamd_keypair_from_ucl (obj);
  409. if (kp == NULL) {
  410. msg_err ("cannot load keypair from data");
  411. ucl_object_unref (obj);
  412. lua_pushnil (L);
  413. }
  414. else {
  415. pkp = lua_newuserdata (L, sizeof (gpointer));
  416. *pkp = kp;
  417. rspamd_lua_setclass (L, "rspamd{cryptobox_keypair}", -1);
  418. ucl_object_unref (obj);
  419. }
  420. }
  421. return 1;
  422. }
  423. /***
  424. * @function rspamd_cryptobox_keypair.create([type='encryption'[, alg='curve25519']])
  425. * Generates new keypair
  426. * @param {string} type type of keypair: 'encryption' (default) or 'sign'
  427. * @param {string} alg algorithm of keypair: 'curve25519' (default) or 'nist'
  428. * @return {cryptobox_keypair} new keypair
  429. */
  430. static gint
  431. lua_cryptobox_keypair_create (lua_State *L)
  432. {
  433. LUA_TRACE_POINT;
  434. struct rspamd_cryptobox_keypair *kp, **pkp;
  435. enum rspamd_cryptobox_keypair_type type = RSPAMD_KEYPAIR_KEX;
  436. enum rspamd_cryptobox_mode alg = RSPAMD_CRYPTOBOX_MODE_25519;
  437. if (lua_isstring (L, 1)) {
  438. const gchar *str = lua_tostring (L, 1);
  439. if (strcmp (str, "sign") == 0) {
  440. type = RSPAMD_KEYPAIR_SIGN;
  441. }
  442. else if (strcmp (str, "encryption") == 0) {
  443. type = RSPAMD_KEYPAIR_KEX;
  444. }
  445. else {
  446. return luaL_error (L, "invalid keypair type: %s", str);
  447. }
  448. }
  449. if (lua_isstring (L, 2)) {
  450. const gchar *str = lua_tostring (L, 2);
  451. if (strcmp (str, "nist") == 0 || strcmp (str, "openssl") == 0) {
  452. alg = RSPAMD_CRYPTOBOX_MODE_NIST;
  453. }
  454. else if (strcmp (str, "curve25519") == 0 || strcmp (str, "default") == 0) {
  455. alg = RSPAMD_CRYPTOBOX_MODE_25519;
  456. }
  457. else {
  458. return luaL_error (L, "invalid keypair algorithm: %s", str);
  459. }
  460. }
  461. kp = rspamd_keypair_new (type, alg);
  462. pkp = lua_newuserdata (L, sizeof (gpointer));
  463. *pkp = kp;
  464. rspamd_lua_setclass (L, "rspamd{cryptobox_keypair}", -1);
  465. return 1;
  466. }
  467. static gint
  468. lua_cryptobox_keypair_gc (lua_State *L)
  469. {
  470. LUA_TRACE_POINT;
  471. struct rspamd_cryptobox_keypair *kp = lua_check_cryptobox_keypair (L, 1);
  472. if (kp != NULL) {
  473. rspamd_keypair_unref (kp);
  474. }
  475. return 0;
  476. }
  477. /***
  478. * @method keypair:totable([hex=false]])
  479. * Converts keypair to table (not very safe due to memory leftovers)
  480. */
  481. static gint
  482. lua_cryptobox_keypair_totable (lua_State *L)
  483. {
  484. LUA_TRACE_POINT;
  485. struct rspamd_cryptobox_keypair *kp = lua_check_cryptobox_keypair (L, 1);
  486. ucl_object_t *obj;
  487. gboolean hex = FALSE;
  488. gint ret = 1;
  489. if (kp != NULL) {
  490. if (lua_isboolean (L, 2)) {
  491. hex = lua_toboolean (L, 2);
  492. }
  493. obj = rspamd_keypair_to_ucl (kp, hex);
  494. ret = ucl_object_push_lua (L, obj, true);
  495. ucl_object_unref (obj);
  496. }
  497. else {
  498. return luaL_error (L, "invalid arguments");
  499. }
  500. return ret;
  501. }
  502. /***
  503. * @method keypair:type()
  504. * Returns type of keypair as a string: 'encryption' or 'sign'
  505. * @return {string} type of keypair as a string
  506. */
  507. static gint
  508. lua_cryptobox_keypair_get_type (lua_State *L)
  509. {
  510. LUA_TRACE_POINT;
  511. struct rspamd_cryptobox_keypair *kp = lua_check_cryptobox_keypair (L, 1);
  512. if (kp) {
  513. if (kp->type == RSPAMD_KEYPAIR_KEX) {
  514. lua_pushstring (L, "encryption");
  515. }
  516. else {
  517. lua_pushstring (L, "sign");
  518. }
  519. }
  520. else {
  521. return luaL_error (L, "invalid arguments");
  522. }
  523. return 1;
  524. }
  525. /***
  526. * @method keypair:alg()
  527. * Returns algorithm of keypair as a string: 'encryption' or 'sign'
  528. * @return {string} type of keypair as a string
  529. */
  530. static gint
  531. lua_cryptobox_keypair_get_alg (lua_State *L)
  532. {
  533. LUA_TRACE_POINT;
  534. struct rspamd_cryptobox_keypair *kp = lua_check_cryptobox_keypair (L, 1);
  535. if (kp) {
  536. if (kp->alg == RSPAMD_CRYPTOBOX_MODE_25519) {
  537. lua_pushstring (L, "curve25519");
  538. }
  539. else {
  540. lua_pushstring (L, "nist");
  541. }
  542. }
  543. else {
  544. return luaL_error (L, "invalid arguments");
  545. }
  546. return 1;
  547. }
  548. /***
  549. * @method keypair:pk()
  550. * Returns pubkey for a specific keypair
  551. * @return {rspamd_pubkey} pubkey for a keypair
  552. */
  553. static gint
  554. lua_cryptobox_keypair_get_pk (lua_State *L)
  555. {
  556. LUA_TRACE_POINT;
  557. struct rspamd_cryptobox_keypair *kp = lua_check_cryptobox_keypair (L, 1);
  558. struct rspamd_cryptobox_pubkey *pk, **ppk;
  559. const guchar *data;
  560. guint dlen;
  561. if (kp) {
  562. data = rspamd_keypair_component (kp, RSPAMD_KEYPAIR_COMPONENT_PK, &dlen);
  563. pk = rspamd_pubkey_from_bin (data, dlen, kp->type, kp->alg);
  564. if (pk == NULL) {
  565. return luaL_error (L, "invalid keypair");
  566. }
  567. ppk = lua_newuserdata (L, sizeof (*ppk));
  568. *ppk = pk;
  569. rspamd_lua_setclass (L, "rspamd{cryptobox_pubkey}", -1);
  570. }
  571. else {
  572. return luaL_error (L, "invalid arguments");
  573. }
  574. return 1;
  575. }
  576. /***
  577. * @function rspamd_cryptobox_signature.load(file, [alg = 'curve25519'])
  578. * Loads signature from raw file
  579. * @param {string} file filename to load
  580. * @return {cryptobox_signature} new signature
  581. */
  582. static gint
  583. lua_cryptobox_signature_load (lua_State *L)
  584. {
  585. LUA_TRACE_POINT;
  586. rspamd_fstring_t *sig, **psig;
  587. const gchar *filename;
  588. gpointer data;
  589. int fd;
  590. struct stat st;
  591. enum rspamd_cryptobox_mode alg = RSPAMD_CRYPTOBOX_MODE_25519;
  592. filename = luaL_checkstring (L, 1);
  593. if (filename != NULL) {
  594. fd = open (filename, O_RDONLY);
  595. if (fd == -1) {
  596. msg_err ("cannot open signature file: %s, %s", filename,
  597. strerror (errno));
  598. lua_pushnil (L);
  599. }
  600. else {
  601. if (fstat (fd, &st) == -1 ||
  602. (data =
  603. mmap (NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0))
  604. == MAP_FAILED) {
  605. msg_err ("cannot mmap file %s: %s", filename, strerror (errno));
  606. lua_pushnil (L);
  607. }
  608. else {
  609. if (lua_isstring (L, 2)) {
  610. const gchar *str = lua_tostring (L, 2);
  611. if (strcmp (str, "nist") == 0 || strcmp (str, "openssl") == 0) {
  612. alg = RSPAMD_CRYPTOBOX_MODE_NIST;
  613. }
  614. else if (strcmp (str, "curve25519") == 0 || strcmp (str, "default") == 0) {
  615. alg = RSPAMD_CRYPTOBOX_MODE_25519;
  616. }
  617. else {
  618. return luaL_error (L, "invalid keypair algorithm: %s", str);
  619. }
  620. }
  621. if (st.st_size > 0) {
  622. sig = rspamd_fstring_new_init (data, st.st_size);
  623. psig = lua_newuserdata (L, sizeof (rspamd_fstring_t *));
  624. rspamd_lua_setclass (L, "rspamd{cryptobox_signature}", -1);
  625. *psig = sig;
  626. }
  627. else {
  628. msg_err ("size of %s mismatches: %d while %d is expected",
  629. filename, (int)st.st_size,
  630. rspamd_cryptobox_signature_bytes (alg));
  631. lua_pushnil (L);
  632. }
  633. munmap (data, st.st_size);
  634. }
  635. close (fd);
  636. }
  637. }
  638. else {
  639. luaL_error (L, "bad input arguments");
  640. }
  641. return 1;
  642. }
  643. /***
  644. * @method rspamd_cryptobox_signature:save(file)
  645. * Stores signature in raw file
  646. * @param {string} file filename to use
  647. * @return {boolean} true if signature has been saved
  648. */
  649. static gint
  650. lua_cryptobox_signature_save (lua_State *L)
  651. {
  652. LUA_TRACE_POINT;
  653. rspamd_fstring_t *sig;
  654. gint fd, flags;
  655. const gchar *filename;
  656. gboolean forced = FALSE, res = TRUE;
  657. sig = lua_check_cryptobox_sign (L, 1);
  658. filename = luaL_checkstring (L, 2);
  659. if (!sig || !filename) {
  660. luaL_error (L, "bad input arguments");
  661. return 1;
  662. }
  663. if (lua_gettop (L) > 2) {
  664. forced = lua_toboolean (L, 3);
  665. }
  666. if (sig != NULL && filename != NULL) {
  667. flags = O_WRONLY | O_CREAT;
  668. if (forced) {
  669. flags |= O_TRUNC;
  670. }
  671. else {
  672. flags |= O_EXCL;
  673. }
  674. fd = open (filename, flags, 00644);
  675. if (fd == -1) {
  676. msg_err ("cannot create a signature file: %s, %s",
  677. filename,
  678. strerror (errno));
  679. lua_pushboolean (L, FALSE);
  680. }
  681. else {
  682. while (write (fd, sig->str, sig->len) == -1) {
  683. if (errno == EINTR) {
  684. continue;
  685. }
  686. msg_err ("cannot write to a signature file: %s, %s",
  687. filename,
  688. strerror (errno));
  689. res = FALSE;
  690. break;
  691. }
  692. lua_pushboolean (L, res);
  693. close (fd);
  694. }
  695. }
  696. else {
  697. return luaL_error (L, "invalid arguments");
  698. }
  699. return 1;
  700. }
  701. /***
  702. * @function rspamd_cryptobox_signature.create(data)
  703. * Creates signature object from raw data
  704. * @param {data} raw signature data
  705. * @return {cryptobox_signature} signature object
  706. */
  707. static gint
  708. lua_cryptobox_signature_create (lua_State *L)
  709. {
  710. LUA_TRACE_POINT;
  711. rspamd_fstring_t *sig, **psig;
  712. struct rspamd_lua_text *t;
  713. const gchar *data;
  714. gsize dlen;
  715. if (lua_isuserdata (L, 1)) {
  716. t = lua_check_text (L, 1);
  717. if (!t) {
  718. return luaL_error (L, "invalid arguments");
  719. }
  720. data = t->start;
  721. dlen = t->len;
  722. }
  723. else {
  724. data = luaL_checklstring (L, 1, &dlen);
  725. }
  726. if (data != NULL) {
  727. if (dlen == rspamd_cryptobox_signature_bytes (RSPAMD_CRYPTOBOX_MODE_25519)) {
  728. sig = rspamd_fstring_new_init (data, dlen);
  729. psig = lua_newuserdata (L, sizeof (rspamd_fstring_t *));
  730. rspamd_lua_setclass (L, "rspamd{cryptobox_signature}", -1);
  731. *psig = sig;
  732. }
  733. }
  734. else {
  735. return luaL_error (L, "bad input arguments");
  736. }
  737. return 1;
  738. }
  739. /***
  740. * @method cryptobox_signature:hex()
  741. * Return hex encoded signature string
  742. * @return {string} raw value of signature
  743. */
  744. static gint
  745. lua_cryptobox_signature_hex (lua_State *L)
  746. {
  747. LUA_TRACE_POINT;
  748. rspamd_fstring_t *sig = lua_check_cryptobox_sign (L, 1);
  749. gchar *encoded;
  750. if (sig) {
  751. encoded = rspamd_encode_hex (sig->str, sig->len);
  752. lua_pushstring (L, encoded);
  753. g_free (encoded);
  754. }
  755. else {
  756. return luaL_error (L, "invalid arguments");
  757. }
  758. return 1;
  759. }
  760. /***
  761. * @method cryptobox_signature:base32([b32type='default'])
  762. * Return base32 encoded signature string
  763. * @param {string} b32type base32 type (default, bleach, rfc)
  764. * @return {string} raw value of signature
  765. */
  766. static gint
  767. lua_cryptobox_signature_base32 (lua_State *L)
  768. {
  769. LUA_TRACE_POINT;
  770. rspamd_fstring_t *sig = lua_check_cryptobox_sign (L, 1);
  771. gchar *encoded;
  772. enum rspamd_base32_type btype = RSPAMD_BASE32_DEFAULT;
  773. if (lua_type (L, 2) == LUA_TSTRING) {
  774. btype = rspamd_base32_decode_type_from_str (lua_tostring (L, 2));
  775. if (btype == RSPAMD_BASE32_INVALID) {
  776. return luaL_error (L, "invalid b32 type: %s", lua_tostring (L, 2));
  777. }
  778. }
  779. if (sig) {
  780. encoded = rspamd_encode_base32 (sig->str, sig->len, btype);
  781. lua_pushstring (L, encoded);
  782. g_free (encoded);
  783. }
  784. else {
  785. return luaL_error (L, "invalid arguments");
  786. }
  787. return 1;
  788. }
  789. /***
  790. * @method cryptobox_signature:base64()
  791. * Return base64 encoded signature string
  792. * @return {string} raw value of signature
  793. */
  794. static gint
  795. lua_cryptobox_signature_base64 (lua_State *L)
  796. {
  797. LUA_TRACE_POINT;
  798. rspamd_fstring_t *sig = lua_check_cryptobox_sign (L, 1);
  799. gsize dlen;
  800. gchar *encoded;
  801. if (sig) {
  802. encoded = rspamd_encode_base64 (sig->str, sig->len, 0, &dlen);
  803. lua_pushlstring (L, encoded, dlen);
  804. g_free (encoded);
  805. }
  806. else {
  807. return luaL_error (L, "invalid arguments");
  808. }
  809. return 1;
  810. }
  811. /***
  812. * @method cryptobox_signature:bin()
  813. * Return raw signature string
  814. * @return {string} raw value of signature
  815. */
  816. static gint
  817. lua_cryptobox_signature_bin (lua_State *L)
  818. {
  819. LUA_TRACE_POINT;
  820. rspamd_fstring_t *sig = lua_check_cryptobox_sign (L, 1);
  821. if (sig) {
  822. lua_pushlstring (L, sig->str, sig->len);
  823. }
  824. else {
  825. return luaL_error (L, "invalid arguments");
  826. }
  827. return 1;
  828. }
  829. static gint
  830. lua_cryptobox_signature_gc (lua_State *L)
  831. {
  832. LUA_TRACE_POINT;
  833. rspamd_fstring_t *sig = lua_check_cryptobox_sign (L, 1);
  834. rspamd_fstring_free (sig);
  835. return 0;
  836. }
  837. static void
  838. rspamd_lua_hash_update (struct rspamd_lua_cryptobox_hash *h,
  839. const void *p, gsize len)
  840. {
  841. if (h) {
  842. switch (h->type) {
  843. case LUA_CRYPTOBOX_HASH_BLAKE2:
  844. rspamd_cryptobox_hash_update (h->content.h, p, len);
  845. break;
  846. case LUA_CRYPTOBOX_HASH_SSL:
  847. EVP_DigestUpdate (h->content.c, p, len);
  848. break;
  849. case LUA_CRYPTOBOX_HASH_HMAC:
  850. HMAC_Update (h->content.hmac_c, p, len);
  851. break;
  852. case LUA_CRYPTOBOX_HASH_XXHASH64:
  853. case LUA_CRYPTOBOX_HASH_XXHASH32:
  854. case LUA_CRYPTOBOX_HASH_MUM:
  855. case LUA_CRYPTOBOX_HASH_T1HA:
  856. rspamd_cryptobox_fast_hash_update (h->content.fh, p, len);
  857. break;
  858. default:
  859. g_assert_not_reached ();
  860. }
  861. }
  862. }
  863. static void
  864. lua_cryptobox_hash_dtor (struct rspamd_lua_cryptobox_hash *h)
  865. {
  866. if (h->type == LUA_CRYPTOBOX_HASH_SSL) {
  867. #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
  868. EVP_MD_CTX_cleanup (h->content.c);
  869. #else
  870. EVP_MD_CTX_reset (h->content.c);
  871. #endif
  872. EVP_MD_CTX_destroy (h->content.c);
  873. }
  874. else if (h->type == LUA_CRYPTOBOX_HASH_HMAC) {
  875. #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
  876. HMAC_CTX_cleanup (h->content.hmac_c);
  877. g_free (h->content.hmac_c);
  878. #else
  879. HMAC_CTX_free (h->content.hmac_c);
  880. #endif
  881. }
  882. else if (h->type == LUA_CRYPTOBOX_HASH_BLAKE2) {
  883. rspamd_explicit_memzero (h->content.h, sizeof (*h->content.h));
  884. free (h->content.h); /* Allocated by posix_memalign */
  885. }
  886. else {
  887. g_free (h->content.fh);
  888. }
  889. g_free (h);
  890. }
  891. static inline void
  892. rspamd_lua_hash_init_default (struct rspamd_lua_cryptobox_hash *h,
  893. const gchar *key, gsize keylen)
  894. {
  895. h->type = LUA_CRYPTOBOX_HASH_BLAKE2;
  896. if (posix_memalign ((void **)&h->content.h,
  897. _Alignof (rspamd_cryptobox_hash_state_t),
  898. sizeof (*h->content.h)) != 0) {
  899. g_assert_not_reached ();
  900. }
  901. rspamd_cryptobox_hash_init (h->content.h, key, keylen);
  902. h->out_len = rspamd_cryptobox_HASHBYTES;
  903. }
  904. static void
  905. rspamd_lua_ssl_hash_create (struct rspamd_lua_cryptobox_hash *h, const EVP_MD *htype,
  906. bool insecure)
  907. {
  908. h->type = LUA_CRYPTOBOX_HASH_SSL;
  909. h->content.c = EVP_MD_CTX_create ();
  910. h->out_len = EVP_MD_size (htype);
  911. if (insecure) {
  912. /* Should never ever be used for crypto/security purposes! */
  913. #ifdef EVP_MD_CTX_FLAG_NON_FIPS_ALLOW
  914. EVP_MD_CTX_set_flags(h->content.c, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
  915. #endif
  916. }
  917. EVP_DigestInit_ex (h->content.c, htype, NULL);
  918. }
  919. static void
  920. rspamd_lua_ssl_hmac_create (struct rspamd_lua_cryptobox_hash *h, const EVP_MD *htype,
  921. const gchar *key, gsize keylen,
  922. bool insecure)
  923. {
  924. h->type = LUA_CRYPTOBOX_HASH_HMAC;
  925. #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
  926. h->content.hmac_c = g_malloc0 (sizeof(*h->content.hmac_c));
  927. #else
  928. h->content.hmac_c = HMAC_CTX_new ();
  929. #endif
  930. h->out_len = EVP_MD_size (htype);
  931. #if OPENSSL_VERSION_NUMBER > 0x10100000L
  932. if (insecure) {
  933. /* Should never ever be used for crypto/security purposes! */
  934. #ifdef EVP_MD_CTX_FLAG_NON_FIPS_ALLOW
  935. HMAC_CTX_set_flags(h->content.hmac_c, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
  936. #endif
  937. }
  938. #endif
  939. HMAC_Init_ex (h->content.hmac_c, key, keylen, htype, NULL);
  940. }
  941. static struct rspamd_lua_cryptobox_hash *
  942. rspamd_lua_hash_create (const gchar *type, const gchar *key, gsize keylen)
  943. {
  944. struct rspamd_lua_cryptobox_hash *h;
  945. h = g_malloc0 (sizeof (*h));
  946. REF_INIT_RETAIN (h, lua_cryptobox_hash_dtor);
  947. if (type) {
  948. if (g_ascii_strcasecmp (type, "md5") == 0) {
  949. if (keylen > 0) {
  950. rspamd_lua_ssl_hmac_create(h, EVP_md5(), key, keylen, true);
  951. }
  952. else {
  953. rspamd_lua_ssl_hash_create(h, EVP_md5(), true);
  954. }
  955. }
  956. else if (g_ascii_strcasecmp (type, "sha1") == 0 ||
  957. g_ascii_strcasecmp (type, "sha") == 0) {
  958. if (keylen > 0) {
  959. rspamd_lua_ssl_hmac_create(h, EVP_sha1(), key, keylen, true);
  960. }
  961. else {
  962. rspamd_lua_ssl_hash_create(h, EVP_sha1(), true);
  963. }
  964. }
  965. else if (g_ascii_strcasecmp (type, "sha256") == 0) {
  966. if (keylen > 0) {
  967. rspamd_lua_ssl_hmac_create(h, EVP_sha256(), key, keylen, true);
  968. }
  969. else {
  970. rspamd_lua_ssl_hash_create(h, EVP_sha256(), true);
  971. }
  972. }
  973. else if (g_ascii_strcasecmp (type, "sha512") == 0) {
  974. if (keylen > 0) {
  975. rspamd_lua_ssl_hmac_create(h, EVP_sha512(), key, keylen, true);
  976. }
  977. else {
  978. rspamd_lua_ssl_hash_create(h, EVP_sha512(), true);
  979. }
  980. }
  981. else if (g_ascii_strcasecmp (type, "sha384") == 0) {
  982. if (keylen > 0) {
  983. rspamd_lua_ssl_hmac_create(h, EVP_sha384(), key, keylen, true);
  984. }
  985. else {
  986. rspamd_lua_ssl_hash_create(h, EVP_sha384(), true);
  987. }
  988. }
  989. else if (g_ascii_strcasecmp (type, "xxh64") == 0) {
  990. h->type = LUA_CRYPTOBOX_HASH_XXHASH64;
  991. h->content.fh = g_malloc0 (sizeof (*h->content.fh));
  992. rspamd_cryptobox_fast_hash_init_specific (h->content.fh,
  993. RSPAMD_CRYPTOBOX_XXHASH64, 0);
  994. h->out_len = sizeof (guint64);
  995. }
  996. else if (g_ascii_strcasecmp (type, "xxh32") == 0) {
  997. h->type = LUA_CRYPTOBOX_HASH_XXHASH32;
  998. h->content.fh = g_malloc0 (sizeof (*h->content.fh));
  999. rspamd_cryptobox_fast_hash_init_specific (h->content.fh,
  1000. RSPAMD_CRYPTOBOX_XXHASH32, 0);
  1001. h->out_len = sizeof (guint32);
  1002. }
  1003. else if (g_ascii_strcasecmp (type, "mum") == 0) {
  1004. h->type = LUA_CRYPTOBOX_HASH_MUM;
  1005. h->content.fh = g_malloc0 (sizeof (*h->content.fh));
  1006. rspamd_cryptobox_fast_hash_init_specific (h->content.fh,
  1007. RSPAMD_CRYPTOBOX_MUMHASH, 0);
  1008. h->out_len = sizeof (guint64);
  1009. }
  1010. else if (g_ascii_strcasecmp (type, "t1ha") == 0) {
  1011. h->type = LUA_CRYPTOBOX_HASH_T1HA;
  1012. h->content.fh = g_malloc0 (sizeof (*h->content.fh));
  1013. rspamd_cryptobox_fast_hash_init_specific (h->content.fh,
  1014. RSPAMD_CRYPTOBOX_T1HA, 0);
  1015. h->out_len = sizeof (guint64);
  1016. }
  1017. else if (g_ascii_strcasecmp (type, "blake2") == 0) {
  1018. rspamd_lua_hash_init_default (h, key, keylen);
  1019. }
  1020. else {
  1021. g_free (h);
  1022. return NULL;
  1023. }
  1024. }
  1025. else {
  1026. /* Default hash type */
  1027. rspamd_lua_hash_init_default (h, key, keylen);
  1028. }
  1029. return h;
  1030. }
  1031. /***
  1032. * @function rspamd_cryptobox_hash.create([string])
  1033. * Creates new hash context
  1034. * @param {string} data optional string to hash
  1035. * @return {cryptobox_hash} hash object
  1036. */
  1037. static gint
  1038. lua_cryptobox_hash_create (lua_State *L)
  1039. {
  1040. LUA_TRACE_POINT;
  1041. struct rspamd_lua_cryptobox_hash *h, **ph;
  1042. const gchar *s = NULL;
  1043. struct rspamd_lua_text *t;
  1044. gsize len = 0;
  1045. h = rspamd_lua_hash_create (NULL, NULL, 0);
  1046. if (lua_type (L, 1) == LUA_TSTRING) {
  1047. s = lua_tolstring (L, 1, &len);
  1048. }
  1049. else if (lua_type (L, 1) == LUA_TUSERDATA) {
  1050. t = lua_check_text (L, 1);
  1051. if (!t) {
  1052. return luaL_error (L, "invalid arguments");
  1053. }
  1054. s = t->start;
  1055. len = t->len;
  1056. }
  1057. if (s) {
  1058. rspamd_lua_hash_update (h, s, len);
  1059. }
  1060. ph = lua_newuserdata (L, sizeof (void *));
  1061. *ph = h;
  1062. rspamd_lua_setclass (L, "rspamd{cryptobox_hash}", -1);
  1063. return 1;
  1064. }
  1065. /***
  1066. * @function rspamd_cryptobox_hash.create_specific(type, [string])
  1067. * Creates new hash context
  1068. * @param {string} type type of hash (blake2, sha256, md5, sha512, mum, xxh64, xxh32, t1ha)
  1069. * @param {string} string initial data
  1070. * @return {cryptobox_hash} hash object
  1071. */
  1072. static gint
  1073. lua_cryptobox_hash_create_specific (lua_State *L)
  1074. {
  1075. LUA_TRACE_POINT;
  1076. struct rspamd_lua_cryptobox_hash *h, **ph;
  1077. const gchar *s = NULL, *type = luaL_checkstring (L, 1);
  1078. gsize len = 0;
  1079. struct rspamd_lua_text *t;
  1080. if (!type) {
  1081. return luaL_error (L, "invalid arguments");
  1082. }
  1083. h = rspamd_lua_hash_create (type, NULL, 0);
  1084. if (h == NULL) {
  1085. return luaL_error (L, "invalid hash type: %s", type);
  1086. }
  1087. if (lua_type (L, 2) == LUA_TSTRING) {
  1088. s = lua_tolstring (L, 2, &len);
  1089. }
  1090. else if (lua_type (L, 2) == LUA_TUSERDATA) {
  1091. t = lua_check_text (L, 2);
  1092. if (!t) {
  1093. return luaL_error (L, "invalid arguments");
  1094. }
  1095. s = t->start;
  1096. len = t->len;
  1097. }
  1098. if (s) {
  1099. rspamd_lua_hash_update (h, s, len);
  1100. }
  1101. ph = lua_newuserdata (L, sizeof (void *));
  1102. *ph = h;
  1103. rspamd_lua_setclass (L, "rspamd{cryptobox_hash}", -1);
  1104. return 1;
  1105. }
  1106. /***
  1107. * @function rspamd_cryptobox_hash.create_keyed(key, [string])
  1108. * Creates new hash context with specified key
  1109. * @param {string} key key
  1110. * @return {cryptobox_hash} hash object
  1111. */
  1112. static gint
  1113. lua_cryptobox_hash_create_keyed (lua_State *L)
  1114. {
  1115. LUA_TRACE_POINT;
  1116. struct rspamd_lua_cryptobox_hash *h, **ph;
  1117. const gchar *key, *s = NULL;
  1118. struct rspamd_lua_text *t;
  1119. gsize len = 0;
  1120. gsize keylen;
  1121. key = luaL_checklstring (L, 1, &keylen);
  1122. if (key != NULL) {
  1123. h = rspamd_lua_hash_create (NULL, key, keylen);
  1124. if (lua_type (L, 2) == LUA_TSTRING) {
  1125. s = lua_tolstring (L, 2, &len);
  1126. }
  1127. else if (lua_type (L, 2) == LUA_TUSERDATA) {
  1128. t = lua_check_text (L, 2);
  1129. if (!t) {
  1130. return luaL_error (L, "invalid arguments");
  1131. }
  1132. s = t->start;
  1133. len = t->len;
  1134. }
  1135. if (s) {
  1136. rspamd_lua_hash_update (h, s, len);
  1137. }
  1138. ph = lua_newuserdata (L, sizeof (void *));
  1139. *ph = h;
  1140. rspamd_lua_setclass (L, "rspamd{cryptobox_hash}", -1);
  1141. }
  1142. else {
  1143. return luaL_error (L, "invalid arguments");
  1144. }
  1145. return 1;
  1146. }
  1147. /***
  1148. * @function rspamd_cryptobox_hash.create_specific_keyed(key, type, [string])
  1149. * Creates new hash context with specified key
  1150. * @param {string} key key
  1151. * @return {cryptobox_hash} hash object
  1152. */
  1153. static gint
  1154. lua_cryptobox_hash_create_specific_keyed (lua_State *L)
  1155. {
  1156. LUA_TRACE_POINT;
  1157. struct rspamd_lua_cryptobox_hash *h, **ph;
  1158. const gchar *key, *s = NULL, *type = luaL_checkstring (L, 2);
  1159. struct rspamd_lua_text *t;
  1160. gsize len = 0;
  1161. gsize keylen;
  1162. key = luaL_checklstring (L, 1, &keylen);
  1163. if (key != NULL && type != NULL) {
  1164. h = rspamd_lua_hash_create (type, key, keylen);
  1165. if (lua_type (L, 3) == LUA_TSTRING) {
  1166. s = lua_tolstring (L, 3, &len);
  1167. }
  1168. else if (lua_type (L, 3) == LUA_TUSERDATA) {
  1169. t = lua_check_text (L, 3);
  1170. if (!t) {
  1171. return luaL_error (L, "invalid arguments");
  1172. }
  1173. s = t->start;
  1174. len = t->len;
  1175. }
  1176. if (s) {
  1177. rspamd_lua_hash_update (h, s, len);
  1178. }
  1179. ph = lua_newuserdata (L, sizeof (void *));
  1180. *ph = h;
  1181. rspamd_lua_setclass (L, "rspamd{cryptobox_hash}", -1);
  1182. }
  1183. else {
  1184. return luaL_error (L, "invalid arguments");
  1185. }
  1186. return 1;
  1187. }
  1188. /***
  1189. * @method cryptobox_hash:update(data)
  1190. * Updates hash with the specified data (hash should not be finalized using `hex` or `bin` methods)
  1191. * @param {string} data data to hash
  1192. */
  1193. static gint
  1194. lua_cryptobox_hash_update (lua_State *L)
  1195. {
  1196. LUA_TRACE_POINT;
  1197. struct rspamd_lua_cryptobox_hash *h = lua_check_cryptobox_hash (L, 1), **ph;
  1198. const gchar *data;
  1199. struct rspamd_lua_text *t;
  1200. gsize len;
  1201. if (lua_isuserdata (L, 2)) {
  1202. t = lua_check_text (L, 2);
  1203. if (!t) {
  1204. return luaL_error (L, "invalid arguments");
  1205. }
  1206. data = t->start;
  1207. len = t->len;
  1208. }
  1209. else {
  1210. data = luaL_checklstring (L, 2, &len);
  1211. }
  1212. if (lua_isnumber (L, 3)) {
  1213. gsize nlen = lua_tonumber (L, 3);
  1214. if (nlen > len) {
  1215. return luaL_error (L, "invalid length: %d while %d is available",
  1216. (int)nlen, (int)len);
  1217. }
  1218. len = nlen;
  1219. }
  1220. if (h && data) {
  1221. if (!h->is_finished) {
  1222. rspamd_lua_hash_update (h, data, len);
  1223. }
  1224. else {
  1225. return luaL_error (L, "hash is already finalized");
  1226. }
  1227. }
  1228. else {
  1229. return luaL_error (L, "invalid arguments");
  1230. }
  1231. ph = lua_newuserdata (L, sizeof (void *));
  1232. *ph = h;
  1233. REF_RETAIN (h);
  1234. rspamd_lua_setclass (L, "rspamd{cryptobox_hash}", -1);
  1235. return 1;
  1236. }
  1237. /***
  1238. * @method cryptobox_hash:reset()
  1239. * Resets hash to the initial state
  1240. */
  1241. static gint
  1242. lua_cryptobox_hash_reset (lua_State *L)
  1243. {
  1244. LUA_TRACE_POINT;
  1245. struct rspamd_lua_cryptobox_hash *h = lua_check_cryptobox_hash (L, 1), **ph;
  1246. if (h) {
  1247. switch (h->type) {
  1248. case LUA_CRYPTOBOX_HASH_BLAKE2:
  1249. memset (h->content.h, 0, sizeof (*h->content.h));
  1250. rspamd_cryptobox_hash_init (h->content.h, NULL, 0);
  1251. break;
  1252. case LUA_CRYPTOBOX_HASH_SSL:
  1253. EVP_DigestInit (h->content.c, EVP_MD_CTX_md (h->content.c));
  1254. break;
  1255. case LUA_CRYPTOBOX_HASH_HMAC:
  1256. #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
  1257. /* Old openssl is awesome... */
  1258. HMAC_Init_ex (h->content.hmac_c, NULL, 0, h->content.hmac_c->md, NULL);
  1259. #else
  1260. HMAC_CTX_reset (h->content.hmac_c);
  1261. #endif
  1262. break;
  1263. case LUA_CRYPTOBOX_HASH_XXHASH64:
  1264. rspamd_cryptobox_fast_hash_init_specific (h->content.fh,
  1265. RSPAMD_CRYPTOBOX_XXHASH64, 0);
  1266. break;
  1267. case LUA_CRYPTOBOX_HASH_XXHASH32:
  1268. rspamd_cryptobox_fast_hash_init_specific (h->content.fh,
  1269. RSPAMD_CRYPTOBOX_XXHASH32, 0);
  1270. break;
  1271. case LUA_CRYPTOBOX_HASH_MUM:
  1272. rspamd_cryptobox_fast_hash_init_specific (h->content.fh,
  1273. RSPAMD_CRYPTOBOX_MUMHASH, 0);
  1274. break;
  1275. case LUA_CRYPTOBOX_HASH_T1HA:
  1276. rspamd_cryptobox_fast_hash_init_specific (h->content.fh,
  1277. RSPAMD_CRYPTOBOX_T1HA, 0);
  1278. break;
  1279. default:
  1280. g_assert_not_reached ();
  1281. }
  1282. h->is_finished = FALSE;
  1283. }
  1284. else {
  1285. return luaL_error (L, "invalid arguments");
  1286. }
  1287. ph = lua_newuserdata (L, sizeof (void *));
  1288. *ph = h;
  1289. REF_RETAIN (h);
  1290. rspamd_lua_setclass (L, "rspamd{cryptobox_hash}", -1);
  1291. return 1;
  1292. }
  1293. static void
  1294. lua_cryptobox_hash_finish (struct rspamd_lua_cryptobox_hash *h)
  1295. {
  1296. guint64 ll;
  1297. guchar out[rspamd_cryptobox_HASHBYTES];
  1298. guint ssl_outlen = sizeof (out);
  1299. switch (h->type) {
  1300. case LUA_CRYPTOBOX_HASH_BLAKE2:
  1301. rspamd_cryptobox_hash_final (h->content.h, out);
  1302. memcpy (h->out, out, sizeof (out));
  1303. break;
  1304. case LUA_CRYPTOBOX_HASH_SSL:
  1305. EVP_DigestFinal_ex (h->content.c, out, &ssl_outlen);
  1306. h->out_len = ssl_outlen;
  1307. g_assert (ssl_outlen <= sizeof (h->out));
  1308. memcpy (h->out, out, ssl_outlen);
  1309. break;
  1310. case LUA_CRYPTOBOX_HASH_HMAC:
  1311. HMAC_Final (h->content.hmac_c, out, &ssl_outlen);
  1312. h->out_len = ssl_outlen;
  1313. g_assert (ssl_outlen <= sizeof (h->out));
  1314. memcpy (h->out, out, ssl_outlen);
  1315. break;
  1316. case LUA_CRYPTOBOX_HASH_XXHASH64:
  1317. case LUA_CRYPTOBOX_HASH_XXHASH32:
  1318. case LUA_CRYPTOBOX_HASH_MUM:
  1319. case LUA_CRYPTOBOX_HASH_T1HA:
  1320. ll = rspamd_cryptobox_fast_hash_final (h->content.fh);
  1321. memcpy (h->out, &ll, sizeof (ll));
  1322. break;
  1323. default:
  1324. g_assert_not_reached ();
  1325. }
  1326. h->is_finished = TRUE;
  1327. }
  1328. /***
  1329. * @method cryptobox_hash:hex()
  1330. * Finalizes hash and return it as hex string
  1331. * @return {string} hex value of hash
  1332. */
  1333. static gint
  1334. lua_cryptobox_hash_hex (lua_State *L)
  1335. {
  1336. LUA_TRACE_POINT;
  1337. struct rspamd_lua_cryptobox_hash *h = lua_check_cryptobox_hash (L, 1);
  1338. guchar out_hex[rspamd_cryptobox_HASHBYTES * 2 + 1], *r;
  1339. guint dlen;
  1340. if (h) {
  1341. if (!h->is_finished) {
  1342. lua_cryptobox_hash_finish (h);
  1343. }
  1344. memset (out_hex, 0, sizeof (out_hex));
  1345. r = h->out;
  1346. dlen = h->out_len;
  1347. if (lua_isnumber (L, 2)) {
  1348. guint lim = lua_tonumber (L, 2);
  1349. if (lim < dlen) {
  1350. r += dlen - lim;
  1351. dlen = lim;
  1352. }
  1353. }
  1354. rspamd_encode_hex_buf (r, dlen, out_hex, sizeof (out_hex));
  1355. lua_pushstring (L, out_hex);
  1356. }
  1357. else {
  1358. return luaL_error (L, "invalid arguments");
  1359. }
  1360. return 1;
  1361. }
  1362. /***
  1363. * @method cryptobox_hash:base32([b32type])
  1364. * Finalizes hash and return it as zbase32 (by default) string
  1365. * @param {string} b32type base32 type (default, bleach, rfc)
  1366. * @return {string} base32 value of hash
  1367. */
  1368. static gint
  1369. lua_cryptobox_hash_base32 (lua_State *L)
  1370. {
  1371. LUA_TRACE_POINT;
  1372. struct rspamd_lua_cryptobox_hash *h = lua_check_cryptobox_hash (L, 1);
  1373. guchar out_b32[rspamd_cryptobox_HASHBYTES * 2], *r;
  1374. guint dlen;
  1375. if (h) {
  1376. enum rspamd_base32_type btype = RSPAMD_BASE32_DEFAULT;
  1377. if (lua_type (L, 2) == LUA_TSTRING) {
  1378. btype = rspamd_base32_decode_type_from_str (lua_tostring (L, 2));
  1379. if (btype == RSPAMD_BASE32_INVALID) {
  1380. return luaL_error (L, "invalid b32 type: %s", lua_tostring (L, 2));
  1381. }
  1382. }
  1383. if (!h->is_finished) {
  1384. lua_cryptobox_hash_finish (h);
  1385. }
  1386. memset (out_b32, 0, sizeof (out_b32));
  1387. r = h->out;
  1388. dlen = h->out_len;
  1389. if (lua_isnumber (L, 2)) {
  1390. guint lim = lua_tonumber (L, 2);
  1391. if (lim < dlen) {
  1392. r += dlen - lim;
  1393. dlen = lim;
  1394. }
  1395. }
  1396. rspamd_encode_base32_buf (r, dlen, out_b32, sizeof (out_b32), btype);
  1397. lua_pushstring (L, out_b32);
  1398. }
  1399. else {
  1400. return luaL_error (L, "invalid arguments");
  1401. }
  1402. return 1;
  1403. }
  1404. /***
  1405. * @method cryptobox_hash:base64()
  1406. * Finalizes hash and return it as base64 string
  1407. * @return {string} base64 value of hash
  1408. */
  1409. static gint
  1410. lua_cryptobox_hash_base64 (lua_State *L)
  1411. {
  1412. LUA_TRACE_POINT;
  1413. struct rspamd_lua_cryptobox_hash *h = lua_check_cryptobox_hash (L, 1);
  1414. guchar *b64, *r;
  1415. gsize len;
  1416. guint dlen;
  1417. if (h) {
  1418. if (!h->is_finished) {
  1419. lua_cryptobox_hash_finish (h);
  1420. }
  1421. r = h->out;
  1422. dlen = h->out_len;
  1423. if (lua_isnumber (L, 2)) {
  1424. guint lim = lua_tonumber (L, 2);
  1425. if (lim < dlen) {
  1426. r += dlen - lim;
  1427. dlen = lim;
  1428. }
  1429. }
  1430. b64 = rspamd_encode_base64 (r, dlen, 0, &len);
  1431. lua_pushlstring (L, b64, len);
  1432. g_free (b64);
  1433. }
  1434. else {
  1435. return luaL_error (L, "invalid arguments");
  1436. }
  1437. return 1;
  1438. }
  1439. /***
  1440. * @method cryptobox_hash:bin()
  1441. * Finalizes hash and return it as raw string
  1442. * @return {string} raw value of hash
  1443. */
  1444. static gint
  1445. lua_cryptobox_hash_bin (lua_State *L)
  1446. {
  1447. LUA_TRACE_POINT;
  1448. struct rspamd_lua_cryptobox_hash *h = lua_check_cryptobox_hash (L, 1);
  1449. guchar *r;
  1450. guint dlen;
  1451. if (h) {
  1452. if (!h->is_finished) {
  1453. lua_cryptobox_hash_finish (h);
  1454. }
  1455. r = h->out;
  1456. dlen = h->out_len;
  1457. if (lua_isnumber (L, 2)) {
  1458. guint lim = lua_tonumber (L, 2);
  1459. if (lim < dlen) {
  1460. r += dlen - lim;
  1461. dlen = lim;
  1462. }
  1463. }
  1464. lua_pushlstring (L, r, dlen);
  1465. h->is_finished = TRUE;
  1466. }
  1467. else {
  1468. return luaL_error (L, "invalid arguments");
  1469. }
  1470. return 1;
  1471. }
  1472. static gint
  1473. lua_cryptobox_hash_gc (lua_State *L)
  1474. {
  1475. LUA_TRACE_POINT;
  1476. struct rspamd_lua_cryptobox_hash *h = lua_check_cryptobox_hash (L, 1);
  1477. REF_RELEASE (h);
  1478. return 0;
  1479. }
  1480. /***
  1481. * @function rspamd_cryptobox.verify_memory(pk, sig, data, [alg = 'curve25519'])
  1482. * Check memory using specified cryptobox key and signature
  1483. * @param {pubkey} pk public key to verify
  1484. * @param {sig} signature to check
  1485. * @param {string} data data to check signature against
  1486. * @return {boolean} `true` - if string matches cryptobox signature
  1487. */
  1488. static gint
  1489. lua_cryptobox_verify_memory (lua_State *L)
  1490. {
  1491. LUA_TRACE_POINT;
  1492. struct rspamd_cryptobox_pubkey *pk;
  1493. rspamd_fstring_t *signature;
  1494. struct rspamd_lua_text *t;
  1495. const gchar *data;
  1496. enum rspamd_cryptobox_mode alg = RSPAMD_CRYPTOBOX_MODE_25519;
  1497. gsize len;
  1498. gint ret;
  1499. pk = lua_check_cryptobox_pubkey (L, 1);
  1500. signature = lua_check_cryptobox_sign (L, 2);
  1501. if (lua_isuserdata (L, 3)) {
  1502. t = lua_check_text (L, 3);
  1503. if (!t) {
  1504. return luaL_error (L, "invalid arguments");
  1505. }
  1506. data = t->start;
  1507. len = t->len;
  1508. }
  1509. else {
  1510. data = luaL_checklstring (L, 3, &len);
  1511. }
  1512. if (lua_isstring (L, 4)) {
  1513. const gchar *str = lua_tostring (L, 4);
  1514. if (strcmp (str, "nist") == 0 || strcmp (str, "openssl") == 0) {
  1515. alg = RSPAMD_CRYPTOBOX_MODE_NIST;
  1516. }
  1517. else if (strcmp (str, "curve25519") == 0 || strcmp (str, "default") == 0) {
  1518. alg = RSPAMD_CRYPTOBOX_MODE_25519;
  1519. }
  1520. else {
  1521. return luaL_error (L, "invalid algorithm: %s", str);
  1522. }
  1523. }
  1524. if (pk != NULL && signature != NULL && data != NULL) {
  1525. ret = rspamd_cryptobox_verify (signature->str, signature->len, data, len,
  1526. rspamd_pubkey_get_pk (pk, NULL), alg);
  1527. if (ret) {
  1528. lua_pushboolean (L, 1);
  1529. }
  1530. else {
  1531. lua_pushboolean (L, 0);
  1532. }
  1533. }
  1534. else {
  1535. return luaL_error (L, "invalid arguments");
  1536. }
  1537. return 1;
  1538. }
  1539. /***
  1540. * @function rspamd_cryptobox.verify_file(pk, sig, file, [alg = 'curve25519'])
  1541. * Check file using specified cryptobox key and signature
  1542. * @param {pubkey} pk public key to verify
  1543. * @param {sig} signature to check
  1544. * @param {string} file to load data from
  1545. * @return {boolean} `true` - if string matches cryptobox signature
  1546. */
  1547. static gint
  1548. lua_cryptobox_verify_file (lua_State *L)
  1549. {
  1550. LUA_TRACE_POINT;
  1551. const gchar *fname;
  1552. struct rspamd_cryptobox_pubkey *pk;
  1553. rspamd_fstring_t *signature;
  1554. guchar *map = NULL;
  1555. enum rspamd_cryptobox_mode alg = RSPAMD_CRYPTOBOX_MODE_25519;
  1556. gsize len;
  1557. gint ret;
  1558. pk = lua_check_cryptobox_pubkey (L, 1);
  1559. signature = lua_check_cryptobox_sign (L, 2);
  1560. fname = luaL_checkstring (L, 3);
  1561. if (lua_isstring (L, 4)) {
  1562. const gchar *str = lua_tostring (L, 4);
  1563. if (strcmp (str, "nist") == 0 || strcmp (str, "openssl") == 0) {
  1564. alg = RSPAMD_CRYPTOBOX_MODE_NIST;
  1565. }
  1566. else if (strcmp (str, "curve25519") == 0 || strcmp (str, "default") == 0) {
  1567. alg = RSPAMD_CRYPTOBOX_MODE_25519;
  1568. }
  1569. else {
  1570. return luaL_error (L, "invalid algorithm: %s", str);
  1571. }
  1572. }
  1573. map = rspamd_file_xmap (fname, PROT_READ, &len, TRUE);
  1574. if (map != NULL && pk != NULL && signature != NULL) {
  1575. ret = rspamd_cryptobox_verify (signature->str, signature->len,
  1576. map, len,
  1577. rspamd_pubkey_get_pk (pk, NULL), alg);
  1578. if (ret) {
  1579. lua_pushboolean (L, 1);
  1580. }
  1581. else {
  1582. lua_pushboolean (L, 0);
  1583. }
  1584. }
  1585. else {
  1586. if (map != NULL) {
  1587. munmap (map, len);
  1588. }
  1589. return luaL_error (L, "invalid arguments");
  1590. }
  1591. if (map != NULL) {
  1592. munmap (map, len);
  1593. }
  1594. return 1;
  1595. }
  1596. /***
  1597. * @function rspamd_cryptobox.sign_memory(kp, data)
  1598. * Sign data using specified keypair
  1599. * @param {keypair} kp keypair to sign
  1600. * @param {string} data
  1601. * @return {cryptobox_signature} signature object
  1602. */
  1603. static gint
  1604. lua_cryptobox_sign_memory (lua_State *L)
  1605. {
  1606. LUA_TRACE_POINT;
  1607. struct rspamd_cryptobox_keypair *kp;
  1608. const gchar *data;
  1609. struct rspamd_lua_text *t;
  1610. gsize len = 0;
  1611. rspamd_fstring_t *sig, **psig;
  1612. kp = lua_check_cryptobox_keypair (L, 1);
  1613. if (lua_isuserdata (L, 2)) {
  1614. t = lua_check_text (L, 2);
  1615. if (!t) {
  1616. return luaL_error (L, "invalid arguments");
  1617. }
  1618. data = t->start;
  1619. len = t->len;
  1620. }
  1621. else {
  1622. data = luaL_checklstring (L, 2, &len);
  1623. }
  1624. if (!kp || !data || kp->type == RSPAMD_KEYPAIR_KEX) {
  1625. return luaL_error (L, "invalid arguments");
  1626. }
  1627. sig = rspamd_fstring_sized_new (rspamd_cryptobox_signature_bytes (
  1628. rspamd_keypair_alg (kp)));
  1629. unsigned long long siglen = sig->len;
  1630. rspamd_cryptobox_sign (sig->str, &siglen, data,
  1631. len, rspamd_keypair_component (kp, RSPAMD_KEYPAIR_COMPONENT_SK,
  1632. NULL), rspamd_keypair_alg (kp));
  1633. sig->len = siglen;
  1634. psig = lua_newuserdata (L, sizeof (void *));
  1635. *psig = sig;
  1636. rspamd_lua_setclass (L, "rspamd{cryptobox_signature}", -1);
  1637. return 1;
  1638. }
  1639. /***
  1640. * @function rspamd_cryptobox.sign_file(kp, file)
  1641. * Sign file using specified keypair
  1642. * @param {keypair} kp keypair to sign
  1643. * @param {string} filename
  1644. * @return {cryptobox_signature} signature object
  1645. */
  1646. static gint
  1647. lua_cryptobox_sign_file (lua_State *L)
  1648. {
  1649. LUA_TRACE_POINT;
  1650. struct rspamd_cryptobox_keypair *kp;
  1651. const gchar *filename;
  1652. gchar *data;
  1653. gsize len = 0;
  1654. rspamd_fstring_t *sig, **psig;
  1655. kp = lua_check_cryptobox_keypair (L, 1);
  1656. filename = luaL_checkstring (L, 2);
  1657. if (!kp || !filename) {
  1658. return luaL_error (L, "invalid arguments");
  1659. }
  1660. data = rspamd_file_xmap (filename, PROT_READ, &len, TRUE);
  1661. if (data == NULL) {
  1662. msg_err ("cannot mmap file %s: %s", filename, strerror (errno));
  1663. lua_pushnil (L);
  1664. }
  1665. else {
  1666. sig = rspamd_fstring_sized_new (rspamd_cryptobox_signature_bytes (
  1667. rspamd_keypair_alg (kp)));
  1668. unsigned long long siglen = sig->len;
  1669. rspamd_cryptobox_sign (sig->str, &siglen, data,
  1670. len, rspamd_keypair_component (kp, RSPAMD_KEYPAIR_COMPONENT_SK,
  1671. NULL), rspamd_keypair_alg (kp));
  1672. sig->len = siglen;
  1673. psig = lua_newuserdata (L, sizeof (void *));
  1674. *psig = sig;
  1675. rspamd_lua_setclass (L, "rspamd{cryptobox_signature}", -1);
  1676. munmap (data, len);
  1677. }
  1678. return 1;
  1679. }
  1680. /***
  1681. * @function rspamd_cryptobox.encrypt_memory(kp, data[, nist=false])
  1682. * Encrypt data using specified keypair/pubkey
  1683. * @param {keypair|string} kp keypair or pubkey in base32 to use
  1684. * @param {string|text} data
  1685. * @return {rspamd_text} encrypted text
  1686. */
  1687. static gint
  1688. lua_cryptobox_encrypt_memory (lua_State *L)
  1689. {
  1690. LUA_TRACE_POINT;
  1691. struct rspamd_cryptobox_keypair *kp = NULL;
  1692. struct rspamd_cryptobox_pubkey *pk = NULL;
  1693. const gchar *data;
  1694. guchar *out = NULL;
  1695. struct rspamd_lua_text *t, *res;
  1696. gsize len = 0, outlen = 0;
  1697. GError *err = NULL;
  1698. if (lua_type (L, 1) == LUA_TUSERDATA) {
  1699. if (rspamd_lua_check_udata_maybe (L, 1, "rspamd{cryptobox_keypair}")) {
  1700. kp = lua_check_cryptobox_keypair (L, 1);
  1701. }
  1702. else if (rspamd_lua_check_udata_maybe (L, 1, "rspamd{cryptobox_pubkey}")) {
  1703. pk = lua_check_cryptobox_pubkey (L, 1);
  1704. }
  1705. }
  1706. else if (lua_type (L, 1) == LUA_TSTRING) {
  1707. const gchar *b32;
  1708. gsize blen;
  1709. b32 = lua_tolstring (L, 1, &blen);
  1710. pk = rspamd_pubkey_from_base32 (b32, blen, RSPAMD_KEYPAIR_KEX,
  1711. lua_toboolean (L, 3) ?
  1712. RSPAMD_CRYPTOBOX_MODE_NIST : RSPAMD_CRYPTOBOX_MODE_25519);
  1713. }
  1714. if (lua_isuserdata (L, 2)) {
  1715. t = lua_check_text (L, 2);
  1716. if (!t) {
  1717. return luaL_error (L, "invalid arguments");
  1718. }
  1719. data = t->start;
  1720. len = t->len;
  1721. }
  1722. else {
  1723. data = luaL_checklstring (L, 2, &len);
  1724. }
  1725. if (!(kp || pk) || !data) {
  1726. return luaL_error (L, "invalid arguments");
  1727. }
  1728. if (kp) {
  1729. if (!rspamd_keypair_encrypt (kp, data, len, &out, &outlen, &err)) {
  1730. gint ret = luaL_error (L, "cannot encrypt data: %s", err->message);
  1731. g_error_free (err);
  1732. return ret;
  1733. }
  1734. }
  1735. else if (pk) {
  1736. if (!rspamd_pubkey_encrypt (pk, data, len, &out, &outlen, &err)) {
  1737. gint ret = luaL_error (L, "cannot encrypt data: %s", err->message);
  1738. g_error_free (err);
  1739. return ret;
  1740. }
  1741. }
  1742. res = lua_newuserdata (L, sizeof (*res));
  1743. res->flags = RSPAMD_TEXT_FLAG_OWN;
  1744. res->start = out;
  1745. res->len = outlen;
  1746. rspamd_lua_setclass (L, "rspamd{text}", -1);
  1747. return 1;
  1748. }
  1749. /***
  1750. * @function rspamd_cryptobox.encrypt_file(kp|pk_string, filename[, nist=false])
  1751. * Encrypt data using specified keypair/pubkey
  1752. * @param {keypair|string} kp keypair or pubkey in base32 to use
  1753. * @param {string} filename
  1754. * @return {rspamd_text} encrypted text
  1755. */
  1756. static gint
  1757. lua_cryptobox_encrypt_file (lua_State *L)
  1758. {
  1759. LUA_TRACE_POINT;
  1760. struct rspamd_cryptobox_keypair *kp = NULL;
  1761. struct rspamd_cryptobox_pubkey *pk = NULL;
  1762. const gchar *filename;
  1763. gchar *data;
  1764. guchar *out = NULL;
  1765. struct rspamd_lua_text *res;
  1766. gsize len = 0, outlen = 0;
  1767. GError *err = NULL;
  1768. if (lua_type (L, 1) == LUA_TUSERDATA) {
  1769. if (rspamd_lua_check_udata_maybe (L, 1, "rspamd{cryptobox_keypair}")) {
  1770. kp = lua_check_cryptobox_keypair (L, 1);
  1771. }
  1772. else if (rspamd_lua_check_udata_maybe (L, 1, "rspamd{cryptobox_pubkey}")) {
  1773. pk = lua_check_cryptobox_pubkey (L, 1);
  1774. }
  1775. }
  1776. else if (lua_type (L, 1) == LUA_TSTRING) {
  1777. const gchar *b32;
  1778. gsize blen;
  1779. b32 = lua_tolstring (L, 1, &blen);
  1780. pk = rspamd_pubkey_from_base32 (b32, blen, RSPAMD_KEYPAIR_KEX,
  1781. lua_toboolean (L, 3) ?
  1782. RSPAMD_CRYPTOBOX_MODE_NIST : RSPAMD_CRYPTOBOX_MODE_25519);
  1783. }
  1784. filename = luaL_checkstring (L, 2);
  1785. data = rspamd_file_xmap (filename, PROT_READ, &len, TRUE);
  1786. if (!(kp || pk) || !data) {
  1787. return luaL_error (L, "invalid arguments");
  1788. }
  1789. if (kp) {
  1790. if (!rspamd_keypair_encrypt (kp, data, len, &out, &outlen, &err)) {
  1791. gint ret = luaL_error (L, "cannot encrypt file %s: %s", filename,
  1792. err->message);
  1793. g_error_free (err);
  1794. munmap (data, len);
  1795. return ret;
  1796. }
  1797. }
  1798. else if (pk) {
  1799. if (!rspamd_pubkey_encrypt (pk, data, len, &out, &outlen, &err)) {
  1800. gint ret = luaL_error (L, "cannot encrypt file %s: %s", filename,
  1801. err->message);
  1802. g_error_free (err);
  1803. munmap (data, len);
  1804. return ret;
  1805. }
  1806. }
  1807. res = lua_newuserdata (L, sizeof (*res));
  1808. res->flags = RSPAMD_TEXT_FLAG_OWN;
  1809. res->start = out;
  1810. res->len = outlen;
  1811. rspamd_lua_setclass (L, "rspamd{text}", -1);
  1812. munmap (data, len);
  1813. return 1;
  1814. }
  1815. /***
  1816. * @function rspamd_cryptobox.decrypt_memory(kp, data[, nist = false])
  1817. * Encrypt data using specified keypair
  1818. * @param {keypair} kp keypair to use
  1819. * @param {string} data
  1820. * @return status,{rspamd_text}|error status is boolean variable followed by either unencrypted data or an error message
  1821. */
  1822. static gint
  1823. lua_cryptobox_decrypt_memory (lua_State *L)
  1824. {
  1825. LUA_TRACE_POINT;
  1826. struct rspamd_cryptobox_keypair *kp;
  1827. const gchar *data;
  1828. guchar *out;
  1829. struct rspamd_lua_text *t, *res;
  1830. gsize len = 0, outlen;
  1831. GError *err = NULL;
  1832. kp = lua_check_cryptobox_keypair (L, 1);
  1833. if (lua_isuserdata (L, 2)) {
  1834. t = lua_check_text (L, 2);
  1835. if (!t) {
  1836. return luaL_error (L, "invalid arguments");
  1837. }
  1838. data = t->start;
  1839. len = t->len;
  1840. }
  1841. else {
  1842. data = luaL_checklstring (L, 2, &len);
  1843. }
  1844. if (!kp || !data) {
  1845. return luaL_error (L, "invalid arguments");
  1846. }
  1847. if (!rspamd_keypair_decrypt (kp, data, len, &out, &outlen, &err)) {
  1848. lua_pushboolean (L, false);
  1849. lua_pushstring (L, err->message);
  1850. g_error_free (err);
  1851. }
  1852. else {
  1853. lua_pushboolean (L, true);
  1854. res = lua_newuserdata (L, sizeof (*res));
  1855. res->flags = RSPAMD_TEXT_FLAG_OWN;
  1856. res->start = out;
  1857. res->len = outlen;
  1858. rspamd_lua_setclass (L, "rspamd{text}", -1);
  1859. }
  1860. return 2;
  1861. }
  1862. /***
  1863. * @function rspamd_cryptobox.decrypt_file(kp, filename)
  1864. * Encrypt data using specified keypair
  1865. * @param {keypair} kp keypair to use
  1866. * @param {string} filename
  1867. * @return status,{rspamd_text}|error status is boolean variable followed by either unencrypted data or an error message
  1868. */
  1869. static gint
  1870. lua_cryptobox_decrypt_file (lua_State *L)
  1871. {
  1872. LUA_TRACE_POINT;
  1873. struct rspamd_cryptobox_keypair *kp;
  1874. const gchar *filename;
  1875. gchar *data;
  1876. guchar *out;
  1877. struct rspamd_lua_text *res;
  1878. gsize len = 0, outlen;
  1879. GError *err = NULL;
  1880. kp = lua_check_cryptobox_keypair (L, 1);
  1881. filename = luaL_checkstring (L, 2);
  1882. data = rspamd_file_xmap (filename, PROT_READ, &len, TRUE);
  1883. if (!kp || !data) {
  1884. return luaL_error (L, "invalid arguments");
  1885. }
  1886. if (!rspamd_keypair_decrypt (kp, data, len, &out, &outlen, &err)) {
  1887. lua_pushboolean (L, false);
  1888. lua_pushstring (L, err->message);
  1889. g_error_free (err);
  1890. }
  1891. else {
  1892. lua_pushboolean (L, true);
  1893. res = lua_newuserdata (L, sizeof (*res));
  1894. res->flags = RSPAMD_TEXT_FLAG_OWN;
  1895. res->start = out;
  1896. res->len = outlen;
  1897. rspamd_lua_setclass (L, "rspamd{text}", -1);
  1898. }
  1899. munmap (data, len);
  1900. return 2;
  1901. }
  1902. #define RSPAMD_CRYPTOBOX_AES_BLOCKSIZE 16
  1903. #define RSPAMD_CRYPTOBOX_AES_KEYSIZE 16
  1904. /***
  1905. * @function rspamd_cryptobox.encrypt_cookie(secret_key, secret_cookie)
  1906. * Specialised function that performs AES-CTR encryption of the provided cookie
  1907. * ```
  1908. * e := base64(nonce||aesencrypt(nonce, secret_cookie))
  1909. * nonce := uint32_le(unix_timestamp)||random_64bit
  1910. * aesencrypt := aes_ctr(nonce, secret_key) ^ pad(secret_cookie)
  1911. * pad := secret_cookie || 0^(32-len(secret_cookie))
  1912. * ```
  1913. * @param {string} secret_key secret key as a hex string (must be 16 bytes in raw or 32 in hex)
  1914. * @param {string} secret_cookie secret cookie as a string for up to 31 character
  1915. * @return {string} e function value for this sk and cookie
  1916. */
  1917. static gint
  1918. lua_cryptobox_encrypt_cookie (lua_State *L)
  1919. {
  1920. guchar aes_block[RSPAMD_CRYPTOBOX_AES_BLOCKSIZE], *blk;
  1921. guchar padded_cookie[RSPAMD_CRYPTOBOX_AES_BLOCKSIZE];
  1922. guchar nonce[RSPAMD_CRYPTOBOX_AES_BLOCKSIZE];
  1923. guchar aes_key[RSPAMD_CRYPTOBOX_AES_KEYSIZE];
  1924. guchar result[RSPAMD_CRYPTOBOX_AES_BLOCKSIZE * 2];
  1925. guint32 ts;
  1926. const gchar *sk, *cookie;
  1927. gsize sklen, cookie_len;
  1928. gint bklen;
  1929. sk = lua_tolstring (L, 1, &sklen);
  1930. cookie = lua_tolstring (L, 2, &cookie_len);
  1931. if (sk && cookie) {
  1932. if (sklen == 32) {
  1933. /* Hex */
  1934. rspamd_decode_hex_buf (sk, sklen, aes_key, sizeof (aes_key));
  1935. }
  1936. else if (sklen == RSPAMD_CRYPTOBOX_AES_KEYSIZE) {
  1937. /* Raw */
  1938. memcpy (aes_key, sk, sizeof (aes_key));
  1939. }
  1940. else {
  1941. return luaL_error (L, "invalid keysize %d", (gint)sklen);
  1942. }
  1943. if (cookie_len > sizeof (padded_cookie) - 1) {
  1944. return luaL_error (L, "cookie is too long %d", (gint)cookie_len);
  1945. }
  1946. /* Fill nonce */
  1947. ottery_rand_bytes (nonce, sizeof (guint64) + sizeof (guint32));
  1948. ts = (guint32)rspamd_get_calendar_ticks ();
  1949. ts = GUINT32_TO_LE (ts);
  1950. memcpy (nonce + sizeof (guint64) + sizeof (guint32), &ts, sizeof (ts));
  1951. /* Prepare padded cookie */
  1952. memset (padded_cookie, 0, sizeof (padded_cookie));
  1953. memcpy (padded_cookie, cookie, cookie_len);
  1954. /* Perform AES CTR via AES ECB on nonce */
  1955. EVP_CIPHER_CTX *ctx;
  1956. ctx = EVP_CIPHER_CTX_new ();
  1957. EVP_EncryptInit_ex (ctx, EVP_aes_128_ecb (), NULL, aes_key, NULL);
  1958. EVP_CIPHER_CTX_set_padding (ctx, 0);
  1959. bklen = sizeof (aes_block);
  1960. blk = aes_block;
  1961. g_assert (EVP_EncryptUpdate (ctx, blk, &bklen, nonce, sizeof (nonce)));
  1962. blk += bklen;
  1963. g_assert (EVP_EncryptFinal_ex(ctx, blk, &bklen));
  1964. EVP_CIPHER_CTX_free (ctx);
  1965. /* Encode result */
  1966. memcpy (result, nonce, sizeof (nonce));
  1967. for (guint i = 0; i < sizeof (aes_block); i ++) {
  1968. result[i + sizeof (nonce)] = padded_cookie[i] ^ aes_block[i];
  1969. }
  1970. gsize rlen;
  1971. gchar *res = rspamd_encode_base64 (result, sizeof (result),
  1972. 0, &rlen);
  1973. lua_pushlstring (L, res, rlen);
  1974. g_free (res);
  1975. rspamd_explicit_memzero (aes_key, sizeof (aes_key));
  1976. rspamd_explicit_memzero (aes_block, sizeof (aes_block));
  1977. }
  1978. else {
  1979. return luaL_error (L, "invalid arguments");
  1980. }
  1981. return 1;
  1982. }
  1983. /***
  1984. * @function rspamd_cryptobox.decrypt_cookie(secret_key, encrypted_cookie)
  1985. * Specialised function that performs AES-CTR decryption of the provided cookie in form
  1986. * ```
  1987. * e := base64(nonce||aesencrypt(nonce, secret_cookie))
  1988. * nonce := int32_le(unix_timestamp)||random_96bit
  1989. * aesencrypt := aes_ctr(nonce, secret_key) ^ pad(secret_cookie)
  1990. * pad := secret_cookie || 0^(32-len(secret_cookie))
  1991. * ```
  1992. * @param {string} secret_key secret key as a hex string (must be 16 bytes in raw or 32 in hex)
  1993. * @param {string} encrypted_cookie encrypted cookie as a base64 encoded string
  1994. * @return {string+number} decrypted value of the cookie and the cookie timestamp
  1995. */
  1996. static gint
  1997. lua_cryptobox_decrypt_cookie (lua_State *L)
  1998. {
  1999. guchar *blk;
  2000. guchar nonce[RSPAMD_CRYPTOBOX_AES_BLOCKSIZE];
  2001. guchar aes_key[RSPAMD_CRYPTOBOX_AES_KEYSIZE];
  2002. guchar *src;
  2003. guint32 ts;
  2004. const gchar *sk, *cookie;
  2005. gsize sklen, cookie_len;
  2006. gint bklen;
  2007. sk = lua_tolstring (L, 1, &sklen);
  2008. cookie = lua_tolstring (L, 2, &cookie_len);
  2009. if (sk && cookie) {
  2010. if (sklen == 32) {
  2011. /* Hex */
  2012. rspamd_decode_hex_buf (sk, sklen, aes_key, sizeof (aes_key));
  2013. }
  2014. else if (sklen == RSPAMD_CRYPTOBOX_AES_KEYSIZE) {
  2015. /* Raw */
  2016. memcpy (aes_key, sk, sizeof (aes_key));
  2017. }
  2018. else {
  2019. return luaL_error (L, "invalid keysize %d", (gint)sklen);
  2020. }
  2021. src = g_malloc (cookie_len);
  2022. rspamd_cryptobox_base64_decode (cookie, cookie_len, src, &cookie_len);
  2023. if (cookie_len != RSPAMD_CRYPTOBOX_AES_BLOCKSIZE * 2) {
  2024. g_free (src);
  2025. lua_pushnil (L);
  2026. return 1;
  2027. }
  2028. /* Perform AES CTR via AES ECB on nonce */
  2029. EVP_CIPHER_CTX *ctx;
  2030. ctx = EVP_CIPHER_CTX_new ();
  2031. /* As per CTR definition, we use encrypt for both encrypt and decrypt */
  2032. EVP_EncryptInit_ex (ctx, EVP_aes_128_ecb (), NULL, aes_key, NULL);
  2033. EVP_CIPHER_CTX_set_padding (ctx, 0);
  2034. /* Copy time */
  2035. memcpy (&ts, src + sizeof (guint64) + sizeof (guint32), sizeof (ts));
  2036. ts = GUINT32_FROM_LE (ts);
  2037. bklen = sizeof (nonce);
  2038. blk = nonce;
  2039. g_assert (EVP_EncryptUpdate (ctx, blk, &bklen, src,
  2040. RSPAMD_CRYPTOBOX_AES_BLOCKSIZE));
  2041. blk += bklen;
  2042. g_assert (EVP_EncryptFinal_ex (ctx, blk, &bklen));
  2043. EVP_CIPHER_CTX_free (ctx);
  2044. /* Decode result */
  2045. for (guint i = 0; i < RSPAMD_CRYPTOBOX_AES_BLOCKSIZE; i ++) {
  2046. src[i + sizeof (nonce)] ^= nonce[i];
  2047. }
  2048. if (src[RSPAMD_CRYPTOBOX_AES_BLOCKSIZE * 2 - 1] != '\0') {
  2049. /* Bad cookie */
  2050. lua_pushnil (L);
  2051. lua_pushnil (L);
  2052. }
  2053. else {
  2054. lua_pushstring (L, src + sizeof (nonce));
  2055. lua_pushnumber (L, ts);
  2056. }
  2057. rspamd_explicit_memzero (src, RSPAMD_CRYPTOBOX_AES_BLOCKSIZE * 2);
  2058. g_free (src);
  2059. rspamd_explicit_memzero (aes_key, sizeof (aes_key));
  2060. }
  2061. else {
  2062. return luaL_error (L, "invalid arguments");
  2063. }
  2064. return 2;
  2065. }
  2066. /***
  2067. * @function rspamd_cryptobox.pbkdf([password, [kdf_alg]])
  2068. * Function that encrypts password using PBKDF function.
  2069. * This function either reads password from STDIN or accepts prepared password as
  2070. * an argument
  2071. * @param {string} password optional password string
  2072. * @param {string} kdf_alg algorithm to use (catena or pbkdf2)
  2073. * @return {string} encrypted password or nil if error occurs
  2074. */
  2075. static gint
  2076. lua_cryptobox_pbkdf (lua_State *L)
  2077. {
  2078. const struct rspamd_controller_pbkdf *pbkdf = NULL;
  2079. const gchar *pbkdf_str = "catena";
  2080. gchar *password;
  2081. gsize pwlen;
  2082. if (lua_type (L, 2) == LUA_TSTRING) {
  2083. pbkdf_str = lua_tostring (L, 2);
  2084. }
  2085. for (guint i = 0; i < RSPAMD_PBKDF_ID_MAX - 1; i ++) {
  2086. pbkdf = &pbkdf_list[i];
  2087. if (g_ascii_strcasecmp (pbkdf_str, pbkdf->alias) == 0) {
  2088. break;
  2089. }
  2090. if (g_ascii_strcasecmp (pbkdf_str, pbkdf->name) == 0) {
  2091. break;
  2092. }
  2093. pbkdf = NULL;
  2094. }
  2095. if (pbkdf == NULL) {
  2096. return luaL_error (L, "invalid pbkdf algorithm: %s", pbkdf_str);
  2097. }
  2098. if (lua_type (L, 1) == LUA_TSTRING) {
  2099. password = g_strdup (lua_tolstring (L, 1, &pwlen));
  2100. }
  2101. else {
  2102. pwlen = 8192;
  2103. password = g_malloc0 (pwlen);
  2104. pwlen = rspamd_read_passphrase (password, pwlen, 0, NULL);
  2105. }
  2106. if (pwlen == 0) {
  2107. lua_pushnil (L);
  2108. return 1;
  2109. }
  2110. guchar *salt, *key;
  2111. gchar *encoded_salt, *encoded_key;
  2112. GString *result;
  2113. salt = g_alloca (pbkdf->salt_len);
  2114. key = g_alloca (pbkdf->key_len);
  2115. ottery_rand_bytes (salt, pbkdf->salt_len);
  2116. /* Derive key */
  2117. rspamd_cryptobox_pbkdf (password, pwlen,
  2118. salt, pbkdf->salt_len, key, pbkdf->key_len, pbkdf->complexity,
  2119. pbkdf->type);
  2120. encoded_salt = rspamd_encode_base32 (salt, pbkdf->salt_len, RSPAMD_BASE32_DEFAULT);
  2121. encoded_key = rspamd_encode_base32 (key, pbkdf->key_len, RSPAMD_BASE32_DEFAULT);
  2122. result = g_string_new ("");
  2123. rspamd_printf_gstring (result, "$%d$%s$%s", pbkdf->id, encoded_salt,
  2124. encoded_key);
  2125. g_free (encoded_salt);
  2126. g_free (encoded_key);
  2127. rspamd_explicit_memzero (password, pwlen);
  2128. g_free (password);
  2129. lua_pushlstring (L, result->str, result->len);
  2130. g_string_free (result, TRUE);
  2131. return 1;
  2132. }
  2133. /***
  2134. * @function rspamd_cryptobox.gen_dkim_keypair([alg, [nbits]])
  2135. * Generates DKIM keypair. Returns 2 base64 strings as rspamd_text: privkey and pubkey
  2136. * @param {string} alg optional algorithm (rsa default, can be ed25519)
  2137. * @param {number} nbits optional number of bits for rsa (default 1024)
  2138. * @return {rspamd_text,rspamd_text} private key and public key as base64 encoded strings
  2139. */
  2140. static gint
  2141. lua_cryptobox_gen_dkim_keypair (lua_State *L)
  2142. {
  2143. const gchar *alg_str = "rsa";
  2144. guint nbits = 1024;
  2145. struct rspamd_lua_text *priv_out, *pub_out;
  2146. if (lua_type (L, 1) == LUA_TSTRING) {
  2147. alg_str = lua_tostring (L, 1);
  2148. }
  2149. if (lua_type (L, 2) == LUA_TNUMBER) {
  2150. nbits = lua_tointeger (L, 2);
  2151. }
  2152. if (strcmp (alg_str, "rsa") == 0) {
  2153. BIGNUM *e;
  2154. RSA *r;
  2155. EVP_PKEY *pk;
  2156. e = BN_new ();
  2157. r = RSA_new ();
  2158. pk = EVP_PKEY_new ();
  2159. if (BN_set_word (e, RSA_F4) != 1) {
  2160. BN_free (e);
  2161. RSA_free (r);
  2162. EVP_PKEY_free (pk);
  2163. return luaL_error (L, "BN_set_word failed");
  2164. }
  2165. if (RSA_generate_key_ex (r, nbits, e, NULL) != 1) {
  2166. BN_free (e);
  2167. RSA_free (r);
  2168. EVP_PKEY_free (pk);
  2169. return luaL_error (L, "RSA_generate_key_ex failed");
  2170. }
  2171. if (EVP_PKEY_set1_RSA (pk, r) != 1) {
  2172. BN_free (e);
  2173. RSA_free (r);
  2174. EVP_PKEY_free (pk);
  2175. return luaL_error (L, "EVP_PKEY_set1_RSA failed");
  2176. }
  2177. BIO *mbio;
  2178. gint rc, len;
  2179. guchar *data;
  2180. gchar *b64_data;
  2181. gsize b64_len;
  2182. mbio = BIO_new (BIO_s_mem ());
  2183. /* Process private key */
  2184. rc = i2d_RSAPrivateKey_bio (mbio, r);
  2185. if (rc == 0) {
  2186. BIO_free (mbio);
  2187. BN_free (e);
  2188. RSA_free (r);
  2189. EVP_PKEY_free (pk);
  2190. return luaL_error (L, "i2d_RSAPrivateKey_bio failed");
  2191. }
  2192. len = BIO_get_mem_data (mbio, &data);
  2193. b64_data = rspamd_encode_base64 (data, len, -1, &b64_len);
  2194. priv_out = lua_newuserdata (L, sizeof (*priv_out));
  2195. rspamd_lua_setclass (L, "rspamd{text}", -1);
  2196. priv_out->start = b64_data;
  2197. priv_out->len = b64_len;
  2198. priv_out->flags = RSPAMD_TEXT_FLAG_OWN|RSPAMD_TEXT_FLAG_WIPE;
  2199. /* Process public key */
  2200. BIO_reset (mbio);
  2201. rc = i2d_RSA_PUBKEY_bio (mbio, r);
  2202. if (rc == 0) {
  2203. BIO_free (mbio);
  2204. BN_free (e);
  2205. RSA_free (r);
  2206. EVP_PKEY_free (pk);
  2207. return luaL_error (L, "i2d_RSA_PUBKEY_bio failed");
  2208. }
  2209. len = BIO_get_mem_data (mbio, &data);
  2210. b64_data = rspamd_encode_base64 (data, len, -1, &b64_len);
  2211. pub_out = lua_newuserdata (L, sizeof (*pub_out));
  2212. rspamd_lua_setclass (L, "rspamd{text}", -1);
  2213. pub_out->start = b64_data;
  2214. pub_out->len = b64_len;
  2215. pub_out->flags = RSPAMD_TEXT_FLAG_OWN;
  2216. BN_free (e);
  2217. RSA_free (r);
  2218. EVP_PKEY_free (pk);
  2219. BIO_free (mbio);
  2220. }
  2221. else if (strcmp (alg_str, "ed25519") == 0) {
  2222. rspamd_sig_pk_t pk;
  2223. rspamd_sig_sk_t sk;
  2224. gchar *b64_data;
  2225. gsize b64_len;
  2226. rspamd_cryptobox_keypair_sig (pk, sk, RSPAMD_CRYPTOBOX_MODE_25519);
  2227. /* Process private key */
  2228. b64_data = rspamd_encode_base64 (sk,
  2229. rspamd_cryptobox_sk_sig_bytes (RSPAMD_CRYPTOBOX_MODE_25519),
  2230. -1, &b64_len);
  2231. priv_out = lua_newuserdata (L, sizeof (*priv_out));
  2232. rspamd_lua_setclass (L, "rspamd{text}", -1);
  2233. priv_out->start = b64_data;
  2234. priv_out->len = b64_len;
  2235. priv_out->flags = RSPAMD_TEXT_FLAG_OWN|RSPAMD_TEXT_FLAG_WIPE;
  2236. /* Process public key */
  2237. b64_data = rspamd_encode_base64 (pk,
  2238. rspamd_cryptobox_pk_sig_bytes (RSPAMD_CRYPTOBOX_MODE_25519),
  2239. -1, &b64_len);
  2240. pub_out = lua_newuserdata (L, sizeof (*pub_out));
  2241. rspamd_lua_setclass (L, "rspamd{text}", -1);
  2242. pub_out->start = b64_data;
  2243. pub_out->len = b64_len;
  2244. pub_out->flags = RSPAMD_TEXT_FLAG_OWN;
  2245. rspamd_explicit_memzero (pk, sizeof (pk));
  2246. rspamd_explicit_memzero (sk, sizeof (sk));
  2247. }
  2248. else {
  2249. return luaL_error (L, "invalid algorithm %s", alg_str);
  2250. }
  2251. return 2;
  2252. }
  2253. /*
  2254. * Secretbox API
  2255. */
  2256. /* Ensure that KDF output is suitable for crypto_secretbox_KEYBYTES */
  2257. #ifdef crypto_generichash_BYTES_MIN
  2258. G_STATIC_ASSERT(crypto_secretbox_KEYBYTES >= crypto_generichash_BYTES_MIN);
  2259. #endif
  2260. /***
  2261. * @function rspamd_cryptobox_secretbox.create(secret_string, [params])
  2262. * Generates a secretbox state by expanding secret string
  2263. * @param {string/text} secret_string secret string (should have high enough entropy)
  2264. * @param {table} params optional parameters - NYI
  2265. * @return {rspamd_cryptobox_secretbox} opaque object with the key expanded
  2266. */
  2267. static gint
  2268. lua_cryptobox_secretbox_create (lua_State *L)
  2269. {
  2270. const gchar *in;
  2271. gsize inlen;
  2272. if (lua_isstring (L, 1)) {
  2273. in = lua_tolstring (L, 1, &inlen);
  2274. }
  2275. else if (lua_isuserdata (L, 1)) {
  2276. struct rspamd_lua_text *t = lua_check_text (L, 1);
  2277. if (!t) {
  2278. return luaL_error (L, "invalid arguments; userdata is not text");
  2279. }
  2280. in = t->start;
  2281. inlen = t->len;
  2282. }
  2283. else {
  2284. return luaL_error (L, "invalid arguments; userdata or string are expected");
  2285. }
  2286. if (in == NULL || inlen == 0) {
  2287. return luaL_error (L, "invalid arguments; non empty secret expected");
  2288. }
  2289. struct rspamd_lua_cryptobox_secretbox *sbox, **psbox;
  2290. sbox = g_malloc0 (sizeof (*sbox));
  2291. crypto_generichash (sbox->sk, sizeof (sbox->sk), in, inlen, NULL, 0);
  2292. psbox = lua_newuserdata (L, sizeof (*psbox));
  2293. *psbox = sbox;
  2294. rspamd_lua_setclass (L, "rspamd{cryptobox_secretbox}", -1);
  2295. return 1;
  2296. }
  2297. static gint
  2298. lua_cryptobox_secretbox_gc (lua_State *L)
  2299. {
  2300. struct rspamd_lua_cryptobox_secretbox *sbox =
  2301. lua_check_cryptobox_secretbox (L, 1);
  2302. if (sbox != NULL) {
  2303. sodium_memzero (sbox->sk, sizeof (sbox->sk));
  2304. g_free (sbox);
  2305. }
  2306. else {
  2307. return luaL_error (L, "invalid arguments");
  2308. }
  2309. return 0;
  2310. }
  2311. /***
  2312. * @method rspamd_cryptobox_secretbox:encrypt(input, [nonce])
  2313. * Encrypts data using secretbox. MAC is prepended to the message
  2314. * @param {string/text} input input to encrypt
  2315. * @param {string/text} nonce optional nonce (must be 1 - 192 bits length)
  2316. * @param {table} params optional parameters - NYI
  2317. * @return {rspamd_text},{rspamd_text} output with mac + nonce or just output if nonce is there
  2318. */
  2319. static gint
  2320. lua_cryptobox_secretbox_encrypt (lua_State *L)
  2321. {
  2322. const gchar *in, *nonce;
  2323. gsize inlen, nlen;
  2324. struct rspamd_lua_cryptobox_secretbox *sbox =
  2325. lua_check_cryptobox_secretbox (L, 1);
  2326. struct rspamd_lua_text *out;
  2327. if (sbox == NULL) {
  2328. return luaL_error (L, "invalid arguments");
  2329. }
  2330. if (lua_isstring (L, 2)) {
  2331. in = lua_tolstring (L, 2, &inlen);
  2332. }
  2333. else if (lua_isuserdata (L, 2)) {
  2334. struct rspamd_lua_text *t = lua_check_text (L, 2);
  2335. if (!t) {
  2336. return luaL_error (L, "invalid arguments; userdata is not text");
  2337. }
  2338. in = t->start;
  2339. inlen = t->len;
  2340. }
  2341. else {
  2342. return luaL_error (L, "invalid arguments; userdata or string are expected");
  2343. }
  2344. /* Nonce part */
  2345. if (!lua_isnoneornil (L, 3)) {
  2346. if (lua_isstring (L, 3)) {
  2347. nonce = lua_tolstring (L, 3, &nlen);
  2348. }
  2349. else if (lua_isuserdata (L, 3)) {
  2350. struct rspamd_lua_text *t = lua_check_text (L, 3);
  2351. if (!t) {
  2352. return luaL_error (L, "invalid arguments; userdata is not text");
  2353. }
  2354. nonce = t->start;
  2355. nlen = t->len;
  2356. }
  2357. else {
  2358. return luaL_error (L, "invalid arguments; userdata or string are expected");
  2359. }
  2360. if (nlen < 1 || nlen > crypto_secretbox_NONCEBYTES) {
  2361. return luaL_error (L, "bad nonce");
  2362. }
  2363. guchar real_nonce[crypto_secretbox_NONCEBYTES];
  2364. memset (real_nonce, 0, sizeof (real_nonce));
  2365. memcpy (real_nonce, nonce, nlen);
  2366. out = lua_new_text (L, NULL, inlen + crypto_secretbox_MACBYTES,
  2367. TRUE);
  2368. crypto_secretbox_easy ((guchar *)out->start, in, inlen,
  2369. nonce, sbox->sk);
  2370. return 1;
  2371. }
  2372. else {
  2373. /* Random nonce */
  2374. struct rspamd_lua_text *random_nonce;
  2375. out = lua_new_text (L, NULL, inlen + crypto_secretbox_MACBYTES,
  2376. TRUE);
  2377. random_nonce = lua_new_text (L, NULL, crypto_secretbox_NONCEBYTES, TRUE);
  2378. randombytes_buf ((guchar *)random_nonce->start, random_nonce->len);
  2379. crypto_secretbox_easy ((guchar *)out->start, in, inlen,
  2380. random_nonce->start, sbox->sk);
  2381. return 2; /* output + random nonce */
  2382. }
  2383. }
  2384. /***
  2385. * @method rspamd_cryptobox_secretbox:decrypt(input, nonce)
  2386. * Decrypts data using secretbox
  2387. * @param {string/text} nonce nonce used to encrypt
  2388. * @param {string/text} input input to decrypt
  2389. * @param {table} params optional parameters - NYI
  2390. * @return {boolean},{rspamd_text} decryption result + decrypted text
  2391. */
  2392. static gint
  2393. lua_cryptobox_secretbox_decrypt (lua_State *L)
  2394. {
  2395. const gchar *in, *nonce;
  2396. gsize inlen, nlen;
  2397. struct rspamd_lua_cryptobox_secretbox *sbox =
  2398. lua_check_cryptobox_secretbox (L, 1);
  2399. struct rspamd_lua_text *out;
  2400. if (sbox == NULL) {
  2401. return luaL_error (L, "invalid arguments");
  2402. }
  2403. /* Input argument */
  2404. if (lua_isstring (L, 2)) {
  2405. in = lua_tolstring (L, 2, &inlen);
  2406. }
  2407. else if (lua_isuserdata (L, 2)) {
  2408. struct rspamd_lua_text *t = lua_check_text (L, 2);
  2409. if (!t) {
  2410. return luaL_error (L, "invalid arguments; userdata is not text");
  2411. }
  2412. in = t->start;
  2413. inlen = t->len;
  2414. }
  2415. else {
  2416. return luaL_error (L, "invalid arguments; userdata or string are expected");
  2417. }
  2418. /* Nonce argument */
  2419. if (lua_isstring (L, 3)) {
  2420. nonce = lua_tolstring (L, 3, &nlen);
  2421. }
  2422. else if (lua_isuserdata (L, 3)) {
  2423. struct rspamd_lua_text *t = lua_check_text (L, 3);
  2424. if (!t) {
  2425. return luaL_error (L, "invalid arguments; userdata is not text");
  2426. }
  2427. nonce = t->start;
  2428. nlen = t->len;
  2429. }
  2430. else {
  2431. return luaL_error (L, "invalid arguments; userdata or string are expected");
  2432. }
  2433. if (nlen < 1 || nlen > crypto_secretbox_NONCEBYTES) {
  2434. lua_pushboolean (L, false);
  2435. lua_pushstring (L, "invalid nonce");
  2436. return 2;
  2437. }
  2438. if (inlen < crypto_secretbox_MACBYTES) {
  2439. lua_pushboolean (L, false);
  2440. lua_pushstring (L, "too short");
  2441. return 2;
  2442. }
  2443. guchar real_nonce[crypto_secretbox_NONCEBYTES];
  2444. memset (real_nonce, 0, sizeof (real_nonce));
  2445. memcpy (real_nonce, nonce, nlen);
  2446. out = lua_new_text (L, NULL, inlen - crypto_secretbox_MACBYTES,
  2447. TRUE);
  2448. gint text_pos = lua_gettop (L);
  2449. if (crypto_secretbox_open_easy ((guchar *)out->start, in, inlen,
  2450. nonce, sbox->sk) == 0) {
  2451. lua_pushboolean (L, true);
  2452. lua_pushvalue (L, text_pos); /* Prevent gc by copying in stack */
  2453. }
  2454. else {
  2455. lua_pushboolean (L, false);
  2456. lua_pushstring (L, "authentication error");
  2457. }
  2458. /* This causes gc method if decryption has failed */
  2459. lua_remove (L, text_pos);
  2460. return 2;
  2461. }
  2462. static gint
  2463. lua_load_pubkey (lua_State * L)
  2464. {
  2465. lua_newtable (L);
  2466. luaL_register (L, NULL, cryptoboxpubkeylib_f);
  2467. return 1;
  2468. }
  2469. static gint
  2470. lua_load_keypair (lua_State * L)
  2471. {
  2472. lua_newtable (L);
  2473. luaL_register (L, NULL, cryptoboxkeypairlib_f);
  2474. return 1;
  2475. }
  2476. static gint
  2477. lua_load_signature (lua_State * L)
  2478. {
  2479. lua_newtable (L);
  2480. luaL_register (L, NULL, cryptoboxsignlib_f);
  2481. return 1;
  2482. }
  2483. static gint
  2484. lua_load_hash (lua_State * L)
  2485. {
  2486. lua_newtable (L);
  2487. luaL_register (L, NULL, cryptoboxhashlib_f);
  2488. return 1;
  2489. }
  2490. static gint
  2491. lua_load_cryptobox_secretbox (lua_State * L)
  2492. {
  2493. lua_newtable (L);
  2494. luaL_register (L, NULL, cryptoboxsecretboxlib_f);
  2495. return 1;
  2496. }
  2497. static gint
  2498. lua_load_cryptobox (lua_State * L)
  2499. {
  2500. lua_newtable (L);
  2501. luaL_register (L, NULL, cryptoboxlib_f);
  2502. return 1;
  2503. }
  2504. void
  2505. luaopen_cryptobox (lua_State * L)
  2506. {
  2507. rspamd_lua_new_class (L, "rspamd{cryptobox_pubkey}", cryptoboxpubkeylib_m);
  2508. lua_pop (L, 1);
  2509. rspamd_lua_add_preload (L, "rspamd_cryptobox_pubkey", lua_load_pubkey);
  2510. rspamd_lua_new_class (L, "rspamd{cryptobox_keypair}", cryptoboxkeypairlib_m);
  2511. lua_pop (L, 1);
  2512. rspamd_lua_add_preload (L, "rspamd_cryptobox_keypair", lua_load_keypair);
  2513. rspamd_lua_new_class (L, "rspamd{cryptobox_signature}", cryptoboxsignlib_m);
  2514. lua_pop (L, 1);
  2515. rspamd_lua_add_preload (L, "rspamd_cryptobox_signature", lua_load_signature);
  2516. rspamd_lua_new_class (L, "rspamd{cryptobox_hash}", cryptoboxhashlib_m);
  2517. lua_pop (L, 1);
  2518. rspamd_lua_add_preload (L, "rspamd_cryptobox_hash", lua_load_hash);
  2519. rspamd_lua_new_class (L, "rspamd{cryptobox_secretbox}",
  2520. cryptoboxsecretboxlib_m);
  2521. lua_pop (L, 1);
  2522. rspamd_lua_add_preload (L, "rspamd_cryptobox_secretbox",
  2523. lua_load_cryptobox_secretbox);
  2524. rspamd_lua_add_preload (L, "rspamd_cryptobox", lua_load_cryptobox);
  2525. lua_settop (L, 0);
  2526. }