You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

dkim.c 82KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588
  1. /*
  2. * Copyright 2024 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. #include "config.h"
  17. #include "rspamd.h"
  18. #include "message.h"
  19. #include "dkim.h"
  20. #include "dns.h"
  21. #include "utlist.h"
  22. #include "unix-std.h"
  23. #include "mempool_vars_internal.h"
  24. #include <openssl/evp.h>
  25. #include <openssl/rsa.h>
  26. #include <openssl/engine.h>
  27. /* special DNS tokens */
  28. #define DKIM_DNSKEYNAME "_domainkey"
  29. /* ed25519 key lengths */
  30. #define ED25519_B64_BYTES 45
  31. #define ED25519_BYTES 32
  32. /* Canonization methods */
  33. #define DKIM_CANON_UNKNOWN (-1) /* unknown method */
  34. #define DKIM_CANON_SIMPLE 0 /* as specified in DKIM spec */
  35. #define DKIM_CANON_RELAXED 1 /* as specified in DKIM spec */
  36. #define DKIM_CANON_DEFAULT DKIM_CANON_SIMPLE
  37. #define RSPAMD_SHORT_BH_LEN 8
  38. /* Params */
  39. enum rspamd_dkim_param_type {
  40. DKIM_PARAM_UNKNOWN = -1,
  41. DKIM_PARAM_SIGNATURE = 0,
  42. DKIM_PARAM_SIGNALG,
  43. DKIM_PARAM_DOMAIN,
  44. DKIM_PARAM_CANONALG,
  45. DKIM_PARAM_QUERYMETHOD,
  46. DKIM_PARAM_SELECTOR,
  47. DKIM_PARAM_HDRLIST,
  48. DKIM_PARAM_VERSION,
  49. DKIM_PARAM_IDENTITY,
  50. DKIM_PARAM_TIMESTAMP,
  51. DKIM_PARAM_EXPIRATION,
  52. DKIM_PARAM_COPIEDHDRS,
  53. DKIM_PARAM_BODYHASH,
  54. DKIM_PARAM_BODYLENGTH,
  55. DKIM_PARAM_IDX,
  56. DKIM_PARAM_CV,
  57. DKIM_PARAM_IGNORE
  58. };
  59. #define RSPAMD_DKIM_MAX_ARC_IDX 10
  60. #define msg_err_dkim(...) rspamd_default_log_function(G_LOG_LEVEL_CRITICAL, \
  61. "dkim", ctx->pool->tag.uid, \
  62. RSPAMD_LOG_FUNC, \
  63. __VA_ARGS__)
  64. #define msg_warn_dkim(...) rspamd_default_log_function(G_LOG_LEVEL_WARNING, \
  65. "dkim", ctx->pool->tag.uid, \
  66. RSPAMD_LOG_FUNC, \
  67. __VA_ARGS__)
  68. #define msg_info_dkim(...) rspamd_default_log_function(G_LOG_LEVEL_INFO, \
  69. "dkim", ctx->pool->tag.uid, \
  70. RSPAMD_LOG_FUNC, \
  71. __VA_ARGS__)
  72. #define msg_debug_dkim(...) rspamd_conditional_debug_fast(NULL, NULL, \
  73. rspamd_dkim_log_id, "dkim", ctx->pool->tag.uid, \
  74. RSPAMD_LOG_FUNC, \
  75. __VA_ARGS__)
  76. #define msg_debug_dkim_taskless(...) rspamd_conditional_debug_fast(NULL, NULL, \
  77. rspamd_dkim_log_id, "dkim", "", \
  78. RSPAMD_LOG_FUNC, \
  79. __VA_ARGS__)
  80. INIT_LOG_MODULE(dkim)
  81. #define RSPAMD_DKIM_FLAG_OVERSIGN (1u << 0u)
  82. #define RSPAMD_DKIM_FLAG_OVERSIGN_EXISTING (1u << 1u)
  83. union rspamd_dkim_header_stat {
  84. struct _st {
  85. uint16_t count;
  86. uint16_t flags;
  87. } s;
  88. uint32_t n;
  89. };
  90. struct rspamd_dkim_common_ctx {
  91. rspamd_mempool_t *pool;
  92. uint64_t sig_hash;
  93. gsize len;
  94. GPtrArray *hlist;
  95. GHashTable *htable; /* header -> count mapping */
  96. EVP_MD_CTX *headers_hash;
  97. EVP_MD_CTX *body_hash;
  98. enum rspamd_dkim_type type;
  99. unsigned int idx;
  100. int header_canon_type;
  101. int body_canon_type;
  102. unsigned int body_canonicalised;
  103. unsigned int headers_canonicalised;
  104. gboolean is_sign;
  105. };
  106. enum rspamd_arc_seal_cv {
  107. RSPAMD_ARC_UNKNOWN = 0,
  108. RSPAMD_ARC_NONE,
  109. RSPAMD_ARC_INVALID,
  110. RSPAMD_ARC_FAIL,
  111. RSPAMD_ARC_PASS
  112. };
  113. struct rspamd_dkim_context_s {
  114. struct rspamd_dkim_common_ctx common;
  115. rspamd_mempool_t *pool;
  116. struct rspamd_dns_resolver *resolver;
  117. gsize blen;
  118. gsize bhlen;
  119. int sig_alg;
  120. unsigned int ver;
  121. time_t timestamp;
  122. time_t expiration;
  123. char *domain;
  124. char *selector;
  125. int8_t *b;
  126. char *short_b;
  127. int8_t *bh;
  128. char *dns_key;
  129. enum rspamd_arc_seal_cv cv;
  130. const char *dkim_header;
  131. };
  132. #define RSPAMD_DKIM_KEY_ID_LEN 16
  133. struct rspamd_dkim_key_s {
  134. uint8_t *keydata;
  135. uint8_t *raw_key;
  136. gsize keylen;
  137. gsize decoded_len;
  138. char key_id[RSPAMD_DKIM_KEY_ID_LEN];
  139. union {
  140. RSA *key_rsa;
  141. EC_KEY *key_ecdsa;
  142. unsigned char *key_eddsa;
  143. } key;
  144. BIO *key_bio;
  145. EVP_PKEY *key_evp;
  146. time_t mtime;
  147. unsigned int ttl;
  148. enum rspamd_dkim_key_type type;
  149. ref_entry_t ref;
  150. };
  151. struct rspamd_dkim_sign_context_s {
  152. struct rspamd_dkim_common_ctx common;
  153. rspamd_dkim_sign_key_t *key;
  154. };
  155. struct rspamd_dkim_header {
  156. const char *name;
  157. int count;
  158. };
  159. /* Parser of dkim params */
  160. typedef gboolean (*dkim_parse_param_f)(rspamd_dkim_context_t *ctx,
  161. const char *param, gsize len, GError **err);
  162. static gboolean rspamd_dkim_parse_signature(rspamd_dkim_context_t *ctx,
  163. const char *param,
  164. gsize len,
  165. GError **err);
  166. static gboolean rspamd_dkim_parse_signalg(rspamd_dkim_context_t *ctx,
  167. const char *param,
  168. gsize len,
  169. GError **err);
  170. static gboolean rspamd_dkim_parse_domain(rspamd_dkim_context_t *ctx,
  171. const char *param,
  172. gsize len,
  173. GError **err);
  174. static gboolean rspamd_dkim_parse_canonalg(rspamd_dkim_context_t *ctx,
  175. const char *param,
  176. gsize len,
  177. GError **err);
  178. static gboolean rspamd_dkim_parse_ignore(rspamd_dkim_context_t *ctx,
  179. const char *param,
  180. gsize len,
  181. GError **err);
  182. static gboolean rspamd_dkim_parse_selector(rspamd_dkim_context_t *ctx,
  183. const char *param,
  184. gsize len,
  185. GError **err);
  186. static gboolean rspamd_dkim_parse_hdrlist(rspamd_dkim_context_t *ctx,
  187. const char *param,
  188. gsize len,
  189. GError **err);
  190. static gboolean rspamd_dkim_parse_version(rspamd_dkim_context_t *ctx,
  191. const char *param,
  192. gsize len,
  193. GError **err);
  194. static gboolean rspamd_dkim_parse_timestamp(rspamd_dkim_context_t *ctx,
  195. const char *param,
  196. gsize len,
  197. GError **err);
  198. static gboolean rspamd_dkim_parse_expiration(rspamd_dkim_context_t *ctx,
  199. const char *param,
  200. gsize len,
  201. GError **err);
  202. static gboolean rspamd_dkim_parse_bodyhash(rspamd_dkim_context_t *ctx,
  203. const char *param,
  204. gsize len,
  205. GError **err);
  206. static gboolean rspamd_dkim_parse_bodylength(rspamd_dkim_context_t *ctx,
  207. const char *param,
  208. gsize len,
  209. GError **err);
  210. static gboolean rspamd_dkim_parse_idx(rspamd_dkim_context_t *ctx,
  211. const char *param,
  212. gsize len,
  213. GError **err);
  214. static gboolean rspamd_dkim_parse_cv(rspamd_dkim_context_t *ctx,
  215. const char *param,
  216. gsize len,
  217. GError **err);
  218. static const dkim_parse_param_f parser_funcs[] = {
  219. [DKIM_PARAM_SIGNATURE] = rspamd_dkim_parse_signature,
  220. [DKIM_PARAM_SIGNALG] = rspamd_dkim_parse_signalg,
  221. [DKIM_PARAM_DOMAIN] = rspamd_dkim_parse_domain,
  222. [DKIM_PARAM_CANONALG] = rspamd_dkim_parse_canonalg,
  223. [DKIM_PARAM_QUERYMETHOD] = rspamd_dkim_parse_ignore,
  224. [DKIM_PARAM_SELECTOR] = rspamd_dkim_parse_selector,
  225. [DKIM_PARAM_HDRLIST] = rspamd_dkim_parse_hdrlist,
  226. [DKIM_PARAM_VERSION] = rspamd_dkim_parse_version,
  227. [DKIM_PARAM_IDENTITY] = rspamd_dkim_parse_ignore,
  228. [DKIM_PARAM_TIMESTAMP] = rspamd_dkim_parse_timestamp,
  229. [DKIM_PARAM_EXPIRATION] = rspamd_dkim_parse_expiration,
  230. [DKIM_PARAM_COPIEDHDRS] = rspamd_dkim_parse_ignore,
  231. [DKIM_PARAM_BODYHASH] = rspamd_dkim_parse_bodyhash,
  232. [DKIM_PARAM_BODYLENGTH] = rspamd_dkim_parse_bodylength,
  233. [DKIM_PARAM_IDX] = rspamd_dkim_parse_idx,
  234. [DKIM_PARAM_CV] = rspamd_dkim_parse_cv,
  235. [DKIM_PARAM_IGNORE] = rspamd_dkim_parse_ignore,
  236. };
  237. #define DKIM_ERROR dkim_error_quark()
  238. GQuark
  239. dkim_error_quark(void)
  240. {
  241. return g_quark_from_static_string("dkim-error-quark");
  242. }
  243. /* Parsers implementation */
  244. static gboolean
  245. rspamd_dkim_parse_signature(rspamd_dkim_context_t *ctx,
  246. const char *param,
  247. gsize len,
  248. GError **err)
  249. {
  250. ctx->b = rspamd_mempool_alloc0(ctx->pool, len);
  251. ctx->short_b = rspamd_mempool_alloc0(ctx->pool, RSPAMD_SHORT_BH_LEN + 1);
  252. rspamd_strlcpy(ctx->short_b, param, MIN(len, RSPAMD_SHORT_BH_LEN + 1));
  253. (void) rspamd_cryptobox_base64_decode(param, len, ctx->b, &ctx->blen);
  254. return TRUE;
  255. }
  256. static gboolean
  257. rspamd_dkim_parse_signalg(rspamd_dkim_context_t *ctx,
  258. const char *param,
  259. gsize len,
  260. GError **err)
  261. {
  262. /* XXX: ugly size comparison, improve this code style some day */
  263. if (len == 8) {
  264. if (memcmp(param, "rsa-sha1", len) == 0) {
  265. ctx->sig_alg = DKIM_SIGN_RSASHA1;
  266. return TRUE;
  267. }
  268. }
  269. else if (len == 10) {
  270. if (memcmp(param, "rsa-sha256", len) == 0) {
  271. ctx->sig_alg = DKIM_SIGN_RSASHA256;
  272. return TRUE;
  273. }
  274. else if (memcmp(param, "rsa-sha512", len) == 0) {
  275. ctx->sig_alg = DKIM_SIGN_RSASHA512;
  276. return TRUE;
  277. }
  278. }
  279. else if (len == 15) {
  280. if (memcmp(param, "ecdsa256-sha256", len) == 0) {
  281. ctx->sig_alg = DKIM_SIGN_ECDSASHA256;
  282. return TRUE;
  283. }
  284. else if (memcmp(param, "ecdsa256-sha512", len) == 0) {
  285. ctx->sig_alg = DKIM_SIGN_ECDSASHA512;
  286. return TRUE;
  287. }
  288. }
  289. else if (len == 14) {
  290. if (memcmp(param, "ed25519-sha256", len) == 0) {
  291. ctx->sig_alg = DKIM_SIGN_EDDSASHA256;
  292. return TRUE;
  293. }
  294. }
  295. g_set_error(err,
  296. DKIM_ERROR,
  297. DKIM_SIGERROR_INVALID_A,
  298. "invalid dkim sign algorithm");
  299. return FALSE;
  300. }
  301. static gboolean
  302. rspamd_dkim_parse_domain(rspamd_dkim_context_t *ctx,
  303. const char *param,
  304. gsize len,
  305. GError **err)
  306. {
  307. if (!rspamd_str_has_8bit(param, len)) {
  308. ctx->domain = rspamd_mempool_alloc(ctx->pool, len + 1);
  309. rspamd_strlcpy(ctx->domain, param, len + 1);
  310. }
  311. else {
  312. ctx->domain = rspamd_dns_resolver_idna_convert_utf8(ctx->resolver,
  313. ctx->pool, param, len, NULL);
  314. if (!ctx->domain) {
  315. g_set_error(err,
  316. DKIM_ERROR,
  317. DKIM_SIGERROR_INVALID_H,
  318. "invalid dkim domain tag %.*s: idna failed",
  319. (int) len, param);
  320. return FALSE;
  321. }
  322. }
  323. return TRUE;
  324. }
  325. static gboolean
  326. rspamd_dkim_parse_canonalg(rspamd_dkim_context_t *ctx,
  327. const char *param,
  328. gsize len,
  329. GError **err)
  330. {
  331. const char *p, *slash = NULL, *end = param + len;
  332. gsize sl = 0;
  333. p = param;
  334. while (p != end) {
  335. if (*p == '/') {
  336. slash = p;
  337. break;
  338. }
  339. p++;
  340. sl++;
  341. }
  342. if (slash == NULL) {
  343. /* Only check header */
  344. if (len == 6 && memcmp(param, "simple", len) == 0) {
  345. ctx->common.header_canon_type = DKIM_CANON_SIMPLE;
  346. return TRUE;
  347. }
  348. else if (len == 7 && memcmp(param, "relaxed", len) == 0) {
  349. ctx->common.header_canon_type = DKIM_CANON_RELAXED;
  350. return TRUE;
  351. }
  352. }
  353. else {
  354. /* First check header */
  355. if (sl == 6 && memcmp(param, "simple", sl) == 0) {
  356. ctx->common.header_canon_type = DKIM_CANON_SIMPLE;
  357. }
  358. else if (sl == 7 && memcmp(param, "relaxed", sl) == 0) {
  359. ctx->common.header_canon_type = DKIM_CANON_RELAXED;
  360. }
  361. else {
  362. goto err;
  363. }
  364. /* Check body */
  365. len -= sl + 1;
  366. slash++;
  367. if (len == 6 && memcmp(slash, "simple", len) == 0) {
  368. ctx->common.body_canon_type = DKIM_CANON_SIMPLE;
  369. return TRUE;
  370. }
  371. else if (len == 7 && memcmp(slash, "relaxed", len) == 0) {
  372. ctx->common.body_canon_type = DKIM_CANON_RELAXED;
  373. return TRUE;
  374. }
  375. }
  376. err:
  377. g_set_error(err,
  378. DKIM_ERROR,
  379. DKIM_SIGERROR_INVALID_A,
  380. "invalid dkim canonization algorithm");
  381. return FALSE;
  382. }
  383. static gboolean
  384. rspamd_dkim_parse_ignore(rspamd_dkim_context_t *ctx,
  385. const char *param,
  386. gsize len,
  387. GError **err)
  388. {
  389. /* Just ignore unused params */
  390. return TRUE;
  391. }
  392. static gboolean
  393. rspamd_dkim_parse_selector(rspamd_dkim_context_t *ctx,
  394. const char *param,
  395. gsize len,
  396. GError **err)
  397. {
  398. if (!rspamd_str_has_8bit(param, len)) {
  399. ctx->selector = rspamd_mempool_alloc(ctx->pool, len + 1);
  400. rspamd_strlcpy(ctx->selector, param, len + 1);
  401. }
  402. else {
  403. ctx->selector = rspamd_dns_resolver_idna_convert_utf8(ctx->resolver,
  404. ctx->pool, param, len, NULL);
  405. if (!ctx->selector) {
  406. g_set_error(err,
  407. DKIM_ERROR,
  408. DKIM_SIGERROR_INVALID_H,
  409. "invalid dkim selector tag %.*s: idna failed",
  410. (int) len, param);
  411. return FALSE;
  412. }
  413. }
  414. return TRUE;
  415. }
  416. static void
  417. rspamd_dkim_hlist_free(void *ud)
  418. {
  419. GPtrArray *a = ud;
  420. g_ptr_array_free(a, TRUE);
  421. }
  422. static gboolean
  423. rspamd_dkim_parse_hdrlist_common(struct rspamd_dkim_common_ctx *ctx,
  424. const char *param,
  425. gsize len,
  426. gboolean sign,
  427. GError **err)
  428. {
  429. const char *c, *p, *end = param + len;
  430. char *h;
  431. gboolean from_found = FALSE, oversign, existing;
  432. unsigned int count = 0;
  433. struct rspamd_dkim_header *new;
  434. gpointer found;
  435. union rspamd_dkim_header_stat u;
  436. p = param;
  437. while (p <= end) {
  438. if ((p == end || *p == ':')) {
  439. count++;
  440. }
  441. p++;
  442. }
  443. if (count > 0) {
  444. ctx->hlist = g_ptr_array_sized_new(count);
  445. }
  446. else {
  447. return FALSE;
  448. }
  449. c = param;
  450. p = param;
  451. ctx->htable = g_hash_table_new(rspamd_strcase_hash, rspamd_strcase_equal);
  452. while (p <= end) {
  453. if ((p == end || *p == ':') && p - c > 0) {
  454. oversign = FALSE;
  455. existing = FALSE;
  456. h = rspamd_mempool_alloc(ctx->pool, p - c + 1);
  457. rspamd_strlcpy(h, c, p - c + 1);
  458. g_strstrip(h);
  459. if (sign) {
  460. if (rspamd_lc_cmp(h, "(o)", 3) == 0) {
  461. oversign = TRUE;
  462. h += 3;
  463. msg_debug_dkim("oversign header: %s", h);
  464. }
  465. else if (rspamd_lc_cmp(h, "(x)", 3) == 0) {
  466. oversign = TRUE;
  467. existing = TRUE;
  468. h += 3;
  469. msg_debug_dkim("oversign existing header: %s", h);
  470. }
  471. }
  472. /* Check mandatory from */
  473. if (!from_found && g_ascii_strcasecmp(h, "from") == 0) {
  474. from_found = TRUE;
  475. }
  476. new = rspamd_mempool_alloc(ctx->pool,
  477. sizeof(struct rspamd_dkim_header));
  478. new->name = h;
  479. new->count = 0;
  480. u.n = 0;
  481. g_ptr_array_add(ctx->hlist, new);
  482. found = g_hash_table_lookup(ctx->htable, h);
  483. if (oversign) {
  484. if (found) {
  485. msg_err_dkim("specified oversigned header more than once: %s",
  486. h);
  487. }
  488. u.s.flags |= RSPAMD_DKIM_FLAG_OVERSIGN;
  489. if (existing) {
  490. u.s.flags |= RSPAMD_DKIM_FLAG_OVERSIGN_EXISTING;
  491. }
  492. u.s.count = 0;
  493. }
  494. else {
  495. if (found != NULL) {
  496. u.n = GPOINTER_TO_UINT(found);
  497. new->count = u.s.count;
  498. u.s.count++;
  499. }
  500. else {
  501. /* Insert new header order to the list */
  502. u.s.count = new->count + 1;
  503. }
  504. }
  505. g_hash_table_insert(ctx->htable, h, GUINT_TO_POINTER(u.n));
  506. c = p + 1;
  507. p++;
  508. }
  509. else {
  510. p++;
  511. }
  512. }
  513. if (!ctx->hlist) {
  514. g_set_error(err,
  515. DKIM_ERROR,
  516. DKIM_SIGERROR_INVALID_H,
  517. "invalid dkim header list");
  518. return FALSE;
  519. }
  520. else {
  521. if (!from_found) {
  522. g_ptr_array_free(ctx->hlist, TRUE);
  523. g_set_error(err,
  524. DKIM_ERROR,
  525. DKIM_SIGERROR_INVALID_H,
  526. "invalid dkim header list, from header is missing");
  527. return FALSE;
  528. }
  529. rspamd_mempool_add_destructor(ctx->pool,
  530. (rspamd_mempool_destruct_t) rspamd_dkim_hlist_free,
  531. ctx->hlist);
  532. rspamd_mempool_add_destructor(ctx->pool,
  533. (rspamd_mempool_destruct_t) g_hash_table_unref,
  534. ctx->htable);
  535. }
  536. return TRUE;
  537. }
  538. static gboolean
  539. rspamd_dkim_parse_hdrlist(rspamd_dkim_context_t *ctx,
  540. const char *param,
  541. gsize len,
  542. GError **err)
  543. {
  544. return rspamd_dkim_parse_hdrlist_common(&ctx->common, param, len, FALSE, err);
  545. }
  546. static gboolean
  547. rspamd_dkim_parse_version(rspamd_dkim_context_t *ctx,
  548. const char *param,
  549. gsize len,
  550. GError **err)
  551. {
  552. if (len != 1 || *param != '1') {
  553. g_set_error(err,
  554. DKIM_ERROR,
  555. DKIM_SIGERROR_VERSION,
  556. "invalid dkim version");
  557. return FALSE;
  558. }
  559. ctx->ver = 1;
  560. return TRUE;
  561. }
  562. static gboolean
  563. rspamd_dkim_parse_timestamp(rspamd_dkim_context_t *ctx,
  564. const char *param,
  565. gsize len,
  566. GError **err)
  567. {
  568. gulong val;
  569. if (!rspamd_strtoul(param, len, &val)) {
  570. g_set_error(err,
  571. DKIM_ERROR,
  572. DKIM_SIGERROR_UNKNOWN,
  573. "invalid dkim timestamp");
  574. return FALSE;
  575. }
  576. ctx->timestamp = val;
  577. return TRUE;
  578. }
  579. static gboolean
  580. rspamd_dkim_parse_expiration(rspamd_dkim_context_t *ctx,
  581. const char *param,
  582. gsize len,
  583. GError **err)
  584. {
  585. gulong val;
  586. if (!rspamd_strtoul(param, len, &val)) {
  587. g_set_error(err,
  588. DKIM_ERROR,
  589. DKIM_SIGERROR_UNKNOWN,
  590. "invalid dkim expiration");
  591. return FALSE;
  592. }
  593. ctx->expiration = val;
  594. return TRUE;
  595. }
  596. static gboolean
  597. rspamd_dkim_parse_bodyhash(rspamd_dkim_context_t *ctx,
  598. const char *param,
  599. gsize len,
  600. GError **err)
  601. {
  602. ctx->bh = rspamd_mempool_alloc0(ctx->pool, len);
  603. (void) rspamd_cryptobox_base64_decode(param, len, ctx->bh, &ctx->bhlen);
  604. return TRUE;
  605. }
  606. static gboolean
  607. rspamd_dkim_parse_bodylength(rspamd_dkim_context_t *ctx,
  608. const char *param,
  609. gsize len,
  610. GError **err)
  611. {
  612. gulong val;
  613. if (!rspamd_strtoul(param, len, &val)) {
  614. g_set_error(err,
  615. DKIM_ERROR,
  616. DKIM_SIGERROR_INVALID_L,
  617. "invalid dkim body length");
  618. return FALSE;
  619. }
  620. ctx->common.len = val;
  621. return TRUE;
  622. }
  623. static gboolean
  624. rspamd_dkim_parse_idx(rspamd_dkim_context_t *ctx,
  625. const char *param,
  626. gsize len,
  627. GError **err)
  628. {
  629. gulong val;
  630. if (!rspamd_strtoul(param, len, &val)) {
  631. g_set_error(err,
  632. DKIM_ERROR,
  633. DKIM_SIGERROR_INVALID_L,
  634. "invalid ARC idx");
  635. return FALSE;
  636. }
  637. ctx->common.idx = val;
  638. return TRUE;
  639. }
  640. static gboolean
  641. rspamd_dkim_parse_cv(rspamd_dkim_context_t *ctx,
  642. const char *param,
  643. gsize len,
  644. GError **err)
  645. {
  646. /* Only check header */
  647. if (len == 4 && memcmp(param, "fail", len) == 0) {
  648. ctx->cv = RSPAMD_ARC_FAIL;
  649. return TRUE;
  650. }
  651. else if (len == 4 && memcmp(param, "pass", len) == 0) {
  652. ctx->cv = RSPAMD_ARC_PASS;
  653. return TRUE;
  654. }
  655. else if (len == 4 && memcmp(param, "none", len) == 0) {
  656. ctx->cv = RSPAMD_ARC_NONE;
  657. return TRUE;
  658. }
  659. else if (len == 7 && memcmp(param, "invalid", len) == 0) {
  660. ctx->cv = RSPAMD_ARC_INVALID;
  661. return TRUE;
  662. }
  663. g_set_error(err,
  664. DKIM_ERROR,
  665. DKIM_SIGERROR_UNKNOWN,
  666. "invalid arc seal verification result");
  667. return FALSE;
  668. }
  669. static void
  670. rspamd_dkim_add_arc_seal_headers(rspamd_mempool_t *pool,
  671. struct rspamd_dkim_common_ctx *ctx)
  672. {
  673. struct rspamd_dkim_header *hdr;
  674. int count = ctx->idx, i;
  675. ctx->hlist = g_ptr_array_sized_new(count * 3 - 1);
  676. for (i = 0; i < count; i++) {
  677. /* Authentication results */
  678. hdr = rspamd_mempool_alloc(pool, sizeof(*hdr));
  679. hdr->name = RSPAMD_DKIM_ARC_AUTHHEADER;
  680. hdr->count = -(i + 1);
  681. g_ptr_array_add(ctx->hlist, hdr);
  682. /* Arc signature */
  683. hdr = rspamd_mempool_alloc(pool, sizeof(*hdr));
  684. hdr->name = RSPAMD_DKIM_ARC_SIGNHEADER;
  685. hdr->count = -(i + 1);
  686. g_ptr_array_add(ctx->hlist, hdr);
  687. /* Arc seal (except last one) */
  688. if (i != count - 1) {
  689. hdr = rspamd_mempool_alloc(pool, sizeof(*hdr));
  690. hdr->name = RSPAMD_DKIM_ARC_SEALHEADER;
  691. hdr->count = -(i + 1);
  692. g_ptr_array_add(ctx->hlist, hdr);
  693. }
  694. }
  695. rspamd_mempool_add_destructor(ctx->pool,
  696. (rspamd_mempool_destruct_t) rspamd_dkim_hlist_free,
  697. ctx->hlist);
  698. }
  699. /**
  700. * Create new dkim context from signature
  701. * @param sig message's signature
  702. * @param pool pool to allocate memory from
  703. * @param err pointer to error object
  704. * @return new context or NULL
  705. */
  706. rspamd_dkim_context_t *
  707. rspamd_create_dkim_context(const char *sig,
  708. rspamd_mempool_t *pool,
  709. struct rspamd_dns_resolver *resolver,
  710. unsigned int time_jitter,
  711. enum rspamd_dkim_type type,
  712. GError **err)
  713. {
  714. const char *p, *c, *tag = NULL, *end;
  715. int taglen;
  716. int param = DKIM_PARAM_UNKNOWN;
  717. const EVP_MD *md_alg;
  718. time_t now;
  719. rspamd_dkim_context_t *ctx;
  720. enum {
  721. DKIM_STATE_TAG = 0,
  722. DKIM_STATE_AFTER_TAG,
  723. DKIM_STATE_VALUE,
  724. DKIM_STATE_SKIP_SPACES = 99,
  725. DKIM_STATE_ERROR = 100
  726. } state,
  727. next_state;
  728. if (sig == NULL) {
  729. g_set_error(err,
  730. DKIM_ERROR,
  731. DKIM_SIGERROR_EMPTY_B,
  732. "empty signature");
  733. return NULL;
  734. }
  735. ctx = rspamd_mempool_alloc0(pool, sizeof(rspamd_dkim_context_t));
  736. ctx->pool = pool;
  737. ctx->resolver = resolver;
  738. if (type == RSPAMD_DKIM_ARC_SEAL) {
  739. ctx->common.header_canon_type = DKIM_CANON_RELAXED;
  740. ctx->common.body_canon_type = DKIM_CANON_RELAXED;
  741. }
  742. else {
  743. ctx->common.header_canon_type = DKIM_CANON_DEFAULT;
  744. ctx->common.body_canon_type = DKIM_CANON_DEFAULT;
  745. }
  746. ctx->sig_alg = DKIM_SIGN_UNKNOWN;
  747. ctx->common.pool = pool;
  748. ctx->common.type = type;
  749. /* A simple state machine of parsing tags */
  750. state = DKIM_STATE_SKIP_SPACES;
  751. next_state = DKIM_STATE_TAG;
  752. taglen = 0;
  753. p = sig;
  754. c = sig;
  755. end = p + strlen(p);
  756. ctx->common.sig_hash = rspamd_cryptobox_fast_hash(sig, end - sig,
  757. rspamd_hash_seed());
  758. msg_debug_dkim("create dkim context sig = %L", ctx->common.sig_hash);
  759. while (p <= end) {
  760. switch (state) {
  761. case DKIM_STATE_TAG:
  762. if (g_ascii_isspace(*p)) {
  763. taglen = (int) (p - c);
  764. while (*p && g_ascii_isspace(*p)) {
  765. /* Skip spaces before '=' sign */
  766. p++;
  767. }
  768. if (*p != '=') {
  769. g_set_error(err,
  770. DKIM_ERROR,
  771. DKIM_SIGERROR_UNKNOWN,
  772. "invalid dkim param");
  773. state = DKIM_STATE_ERROR;
  774. }
  775. else {
  776. state = DKIM_STATE_SKIP_SPACES;
  777. next_state = DKIM_STATE_AFTER_TAG;
  778. param = DKIM_PARAM_UNKNOWN;
  779. p++;
  780. tag = c;
  781. }
  782. }
  783. else if (*p == '=') {
  784. state = DKIM_STATE_SKIP_SPACES;
  785. next_state = DKIM_STATE_AFTER_TAG;
  786. param = DKIM_PARAM_UNKNOWN;
  787. p++;
  788. tag = c;
  789. }
  790. else {
  791. taglen++;
  792. if (taglen > G_MAXINT8) {
  793. g_set_error(err,
  794. DKIM_ERROR,
  795. DKIM_SIGERROR_UNKNOWN,
  796. "too long dkim tag");
  797. state = DKIM_STATE_ERROR;
  798. }
  799. else {
  800. p++;
  801. }
  802. }
  803. break;
  804. case DKIM_STATE_AFTER_TAG:
  805. /* We got tag at tag and len at taglen */
  806. switch (taglen) {
  807. case 0:
  808. g_set_error(err,
  809. DKIM_ERROR,
  810. DKIM_SIGERROR_UNKNOWN,
  811. "zero length dkim param");
  812. state = DKIM_STATE_ERROR;
  813. break;
  814. case 1:
  815. /* 1 character tags */
  816. switch (*tag) {
  817. case 'v':
  818. if (type == RSPAMD_DKIM_NORMAL) {
  819. param = DKIM_PARAM_VERSION;
  820. }
  821. else {
  822. g_set_error(err,
  823. DKIM_ERROR,
  824. DKIM_SIGERROR_UNKNOWN,
  825. "invalid ARC v param");
  826. state = DKIM_STATE_ERROR;
  827. break;
  828. }
  829. break;
  830. case 'a':
  831. param = DKIM_PARAM_SIGNALG;
  832. break;
  833. case 'b':
  834. param = DKIM_PARAM_SIGNATURE;
  835. break;
  836. case 'c':
  837. param = DKIM_PARAM_CANONALG;
  838. break;
  839. case 'd':
  840. param = DKIM_PARAM_DOMAIN;
  841. break;
  842. case 'h':
  843. if (type == RSPAMD_DKIM_ARC_SEAL) {
  844. g_set_error(err,
  845. DKIM_ERROR,
  846. DKIM_SIGERROR_UNKNOWN,
  847. "ARC seal must NOT have h= tag");
  848. state = DKIM_STATE_ERROR;
  849. break;
  850. }
  851. else {
  852. param = DKIM_PARAM_HDRLIST;
  853. }
  854. break;
  855. case 'i':
  856. if (type == RSPAMD_DKIM_NORMAL) {
  857. param = DKIM_PARAM_IDENTITY;
  858. }
  859. else {
  860. param = DKIM_PARAM_IDX;
  861. }
  862. break;
  863. case 'l':
  864. param = DKIM_PARAM_BODYLENGTH;
  865. break;
  866. case 'q':
  867. param = DKIM_PARAM_QUERYMETHOD;
  868. break;
  869. case 's':
  870. param = DKIM_PARAM_SELECTOR;
  871. break;
  872. case 't':
  873. param = DKIM_PARAM_TIMESTAMP;
  874. break;
  875. case 'x':
  876. param = DKIM_PARAM_EXPIRATION;
  877. break;
  878. case 'z':
  879. param = DKIM_PARAM_COPIEDHDRS;
  880. break;
  881. case 'r':
  882. param = DKIM_PARAM_IGNORE;
  883. break;
  884. default:
  885. param = DKIM_PARAM_UNKNOWN;
  886. msg_debug_dkim("unknown DKIM param %c, ignoring it", *tag);
  887. break;
  888. }
  889. break;
  890. case 2:
  891. /* Two characters tags, e.g. `bh` */
  892. if (tag[0] == 'b' && tag[1] == 'h') {
  893. if (type == RSPAMD_DKIM_ARC_SEAL) {
  894. g_set_error(err,
  895. DKIM_ERROR,
  896. DKIM_SIGERROR_UNKNOWN,
  897. "ARC seal must NOT have bh= tag");
  898. state = DKIM_STATE_ERROR;
  899. }
  900. else {
  901. param = DKIM_PARAM_BODYHASH;
  902. }
  903. }
  904. else if (tag[0] == 'c' && tag[1] == 'v') {
  905. if (type != RSPAMD_DKIM_ARC_SEAL) {
  906. g_set_error(err,
  907. DKIM_ERROR,
  908. DKIM_SIGERROR_UNKNOWN,
  909. "cv tag is valid for ARC-Seal only");
  910. state = DKIM_STATE_ERROR;
  911. }
  912. else {
  913. param = DKIM_PARAM_CV;
  914. }
  915. }
  916. else {
  917. param = DKIM_PARAM_UNKNOWN;
  918. msg_debug_dkim("unknown DKIM param %*s, ignoring it", taglen, tag);
  919. }
  920. break;
  921. default:
  922. /* Long and unknown (yet) DKIM tag */
  923. param = DKIM_PARAM_UNKNOWN;
  924. msg_debug_dkim("unknown DKIM param %*s, ignoring it", taglen, tag);
  925. break;
  926. }
  927. if (state != DKIM_STATE_ERROR) {
  928. /* Skip spaces */
  929. state = DKIM_STATE_SKIP_SPACES;
  930. next_state = DKIM_STATE_VALUE;
  931. }
  932. break;
  933. case DKIM_STATE_VALUE:
  934. if (*p == ';') {
  935. if (p - c == 0 || c > p) {
  936. state = DKIM_STATE_ERROR;
  937. }
  938. else {
  939. /* Cut trailing spaces for value */
  940. int tlen = p - c;
  941. const char *tmp = p - 1;
  942. while (tlen > 0) {
  943. if (!g_ascii_isspace(*tmp)) {
  944. break;
  945. }
  946. tlen--;
  947. tmp--;
  948. }
  949. if (param != DKIM_PARAM_UNKNOWN) {
  950. if (!parser_funcs[param](ctx, c, tlen, err)) {
  951. state = DKIM_STATE_ERROR;
  952. }
  953. else {
  954. state = DKIM_STATE_SKIP_SPACES;
  955. next_state = DKIM_STATE_TAG;
  956. p++;
  957. taglen = 0;
  958. }
  959. }
  960. else {
  961. /* Unknown param has been ignored */
  962. msg_debug_dkim("ignored unknown tag parameter value: %*s = %*s",
  963. taglen, tag, tlen, c);
  964. state = DKIM_STATE_SKIP_SPACES;
  965. next_state = DKIM_STATE_TAG;
  966. p++;
  967. taglen = 0;
  968. }
  969. }
  970. }
  971. else if (p == end) {
  972. /* Last parameter with no `;` character */
  973. int tlen = p - c;
  974. const char *tmp = p - 1;
  975. while (tlen > 0) {
  976. if (!g_ascii_isspace(*tmp)) {
  977. break;
  978. }
  979. tlen--;
  980. tmp--;
  981. }
  982. if (param != DKIM_PARAM_UNKNOWN) {
  983. if (!parser_funcs[param](ctx, c, tlen, err)) {
  984. state = DKIM_STATE_ERROR;
  985. }
  986. }
  987. else {
  988. msg_debug_dkim("ignored unknown tag parameter value: %*s: %*s",
  989. taglen, tag, tlen, c);
  990. }
  991. if (state == DKIM_STATE_ERROR) {
  992. /*
  993. * We need to return from here as state machine won't
  994. * do any more steps after p == end
  995. */
  996. if (err) {
  997. msg_info_dkim("dkim parse failed: %e", *err);
  998. }
  999. return NULL;
  1000. }
  1001. /* Finish processing */
  1002. p++;
  1003. }
  1004. else {
  1005. p++;
  1006. }
  1007. break;
  1008. case DKIM_STATE_SKIP_SPACES:
  1009. if (g_ascii_isspace(*p)) {
  1010. p++;
  1011. }
  1012. else {
  1013. c = p;
  1014. state = next_state;
  1015. }
  1016. break;
  1017. case DKIM_STATE_ERROR:
  1018. if (err && *err) {
  1019. msg_info_dkim("dkim parse failed: %s", (*err)->message);
  1020. return NULL;
  1021. }
  1022. else {
  1023. msg_info_dkim("dkim parse failed: unknown error when parsing %c tag",
  1024. tag ? *tag : '?');
  1025. return NULL;
  1026. }
  1027. break;
  1028. }
  1029. }
  1030. if (type == RSPAMD_DKIM_ARC_SEAL) {
  1031. rspamd_dkim_add_arc_seal_headers(pool, &ctx->common);
  1032. }
  1033. /* Now check validity of signature */
  1034. if (ctx->b == NULL) {
  1035. g_set_error(err,
  1036. DKIM_ERROR,
  1037. DKIM_SIGERROR_EMPTY_B,
  1038. "b parameter missing");
  1039. return NULL;
  1040. }
  1041. if (ctx->common.type != RSPAMD_DKIM_ARC_SEAL && ctx->bh == NULL) {
  1042. g_set_error(err,
  1043. DKIM_ERROR,
  1044. DKIM_SIGERROR_EMPTY_BH,
  1045. "bh parameter missing");
  1046. return NULL;
  1047. }
  1048. if (ctx->domain == NULL) {
  1049. g_set_error(err,
  1050. DKIM_ERROR,
  1051. DKIM_SIGERROR_EMPTY_D,
  1052. "domain parameter missing");
  1053. return NULL;
  1054. }
  1055. if (ctx->selector == NULL) {
  1056. g_set_error(err,
  1057. DKIM_ERROR,
  1058. DKIM_SIGERROR_EMPTY_S,
  1059. "selector parameter missing");
  1060. return NULL;
  1061. }
  1062. if (ctx->common.type == RSPAMD_DKIM_NORMAL && ctx->ver == 0) {
  1063. g_set_error(err,
  1064. DKIM_ERROR,
  1065. DKIM_SIGERROR_EMPTY_V,
  1066. "v parameter missing");
  1067. return NULL;
  1068. }
  1069. if (ctx->common.hlist == NULL) {
  1070. g_set_error(err,
  1071. DKIM_ERROR,
  1072. DKIM_SIGERROR_EMPTY_H,
  1073. "h parameter missing");
  1074. return NULL;
  1075. }
  1076. if (ctx->sig_alg == DKIM_SIGN_UNKNOWN) {
  1077. g_set_error(err,
  1078. DKIM_ERROR,
  1079. DKIM_SIGERROR_EMPTY_S,
  1080. "s parameter missing");
  1081. return NULL;
  1082. }
  1083. if (type != RSPAMD_DKIM_ARC_SEAL) {
  1084. if (ctx->sig_alg == DKIM_SIGN_RSASHA1) {
  1085. /* Check bh length */
  1086. if (ctx->bhlen != (unsigned int) EVP_MD_size(EVP_sha1())) {
  1087. g_set_error(err,
  1088. DKIM_ERROR,
  1089. DKIM_SIGERROR_BADSIG,
  1090. "signature has incorrect length: %zu",
  1091. ctx->bhlen);
  1092. return NULL;
  1093. }
  1094. }
  1095. else if (ctx->sig_alg == DKIM_SIGN_RSASHA256 ||
  1096. ctx->sig_alg == DKIM_SIGN_ECDSASHA256) {
  1097. if (ctx->bhlen !=
  1098. (unsigned int) EVP_MD_size(EVP_sha256())) {
  1099. g_set_error(err,
  1100. DKIM_ERROR,
  1101. DKIM_SIGERROR_BADSIG,
  1102. "signature has incorrect length: %zu",
  1103. ctx->bhlen);
  1104. return NULL;
  1105. }
  1106. }
  1107. else if (ctx->sig_alg == DKIM_SIGN_RSASHA512 ||
  1108. ctx->sig_alg == DKIM_SIGN_ECDSASHA512) {
  1109. if (ctx->bhlen !=
  1110. (unsigned int) EVP_MD_size(EVP_sha512())) {
  1111. g_set_error(err,
  1112. DKIM_ERROR,
  1113. DKIM_SIGERROR_BADSIG,
  1114. "signature has incorrect length: %zu",
  1115. ctx->bhlen);
  1116. return NULL;
  1117. }
  1118. }
  1119. }
  1120. /* Check expiration */
  1121. now = time(NULL);
  1122. if (ctx->timestamp && now < ctx->timestamp && ctx->timestamp - now > (int) time_jitter) {
  1123. g_set_error(err,
  1124. DKIM_ERROR,
  1125. DKIM_SIGERROR_FUTURE,
  1126. "signature was made in future, ignoring");
  1127. return NULL;
  1128. }
  1129. if (ctx->expiration && ctx->expiration < now) {
  1130. g_set_error(err,
  1131. DKIM_ERROR,
  1132. DKIM_SIGERROR_EXPIRED,
  1133. "signature has expired");
  1134. return NULL;
  1135. }
  1136. if (ctx->common.type != RSPAMD_DKIM_NORMAL && (ctx->common.idx == 0 ||
  1137. ctx->common.idx > RSPAMD_DKIM_MAX_ARC_IDX)) {
  1138. g_set_error(err,
  1139. DKIM_ERROR,
  1140. DKIM_SIGERROR_UNKNOWN,
  1141. "i parameter missing or invalid for ARC");
  1142. return NULL;
  1143. }
  1144. if (ctx->common.type == RSPAMD_DKIM_ARC_SEAL) {
  1145. if (ctx->cv == RSPAMD_ARC_UNKNOWN) {
  1146. g_set_error(err,
  1147. DKIM_ERROR,
  1148. DKIM_SIGERROR_UNKNOWN,
  1149. "cv parameter missing or invalid for ARC");
  1150. return NULL;
  1151. }
  1152. }
  1153. /* Now create dns key to request further */
  1154. gsize dnslen = strlen(ctx->domain) + strlen(ctx->selector) +
  1155. sizeof(DKIM_DNSKEYNAME) + 2;
  1156. ctx->dns_key = rspamd_mempool_alloc(ctx->pool, dnslen);
  1157. rspamd_snprintf(ctx->dns_key,
  1158. dnslen,
  1159. "%s.%s.%s",
  1160. ctx->selector,
  1161. DKIM_DNSKEYNAME,
  1162. ctx->domain);
  1163. /* Create checksums for further operations */
  1164. if (ctx->sig_alg == DKIM_SIGN_RSASHA1) {
  1165. md_alg = EVP_sha1();
  1166. }
  1167. else if (ctx->sig_alg == DKIM_SIGN_RSASHA256 ||
  1168. ctx->sig_alg == DKIM_SIGN_ECDSASHA256 ||
  1169. ctx->sig_alg == DKIM_SIGN_EDDSASHA256) {
  1170. md_alg = EVP_sha256();
  1171. }
  1172. else if (ctx->sig_alg == DKIM_SIGN_RSASHA512 ||
  1173. ctx->sig_alg == DKIM_SIGN_ECDSASHA512) {
  1174. md_alg = EVP_sha512();
  1175. }
  1176. else {
  1177. g_set_error(err,
  1178. DKIM_ERROR,
  1179. DKIM_SIGERROR_BADSIG,
  1180. "signature has unsupported signature algorithm");
  1181. return NULL;
  1182. }
  1183. #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
  1184. ctx->common.body_hash = EVP_MD_CTX_create();
  1185. EVP_DigestInit_ex(ctx->common.body_hash, md_alg, NULL);
  1186. ctx->common.headers_hash = EVP_MD_CTX_create();
  1187. EVP_DigestInit_ex(ctx->common.headers_hash, md_alg, NULL);
  1188. rspamd_mempool_add_destructor(pool,
  1189. (rspamd_mempool_destruct_t) EVP_MD_CTX_destroy, ctx->common.body_hash);
  1190. rspamd_mempool_add_destructor(pool,
  1191. (rspamd_mempool_destruct_t) EVP_MD_CTX_destroy, ctx->common.headers_hash);
  1192. #else
  1193. ctx->common.body_hash = EVP_MD_CTX_new();
  1194. EVP_DigestInit_ex(ctx->common.body_hash, md_alg, NULL);
  1195. ctx->common.headers_hash = EVP_MD_CTX_new();
  1196. EVP_DigestInit_ex(ctx->common.headers_hash, md_alg, NULL);
  1197. rspamd_mempool_add_destructor(pool,
  1198. (rspamd_mempool_destruct_t) EVP_MD_CTX_free, ctx->common.body_hash);
  1199. rspamd_mempool_add_destructor(pool,
  1200. (rspamd_mempool_destruct_t) EVP_MD_CTX_free, ctx->common.headers_hash);
  1201. #endif
  1202. ctx->dkim_header = sig;
  1203. return ctx;
  1204. }
  1205. struct rspamd_dkim_key_cbdata {
  1206. rspamd_dkim_context_t *ctx;
  1207. dkim_key_handler_f handler;
  1208. gpointer ud;
  1209. };
  1210. rspamd_dkim_key_t *
  1211. rspamd_dkim_make_key(const char *keydata,
  1212. unsigned int keylen, enum rspamd_dkim_key_type type, GError **err)
  1213. {
  1214. rspamd_dkim_key_t *key = NULL;
  1215. if (keylen < 3) {
  1216. g_set_error(err,
  1217. DKIM_ERROR,
  1218. DKIM_SIGERROR_KEYFAIL,
  1219. "DKIM key is too short to be valid");
  1220. return NULL;
  1221. }
  1222. key = g_malloc0(sizeof(rspamd_dkim_key_t));
  1223. REF_INIT_RETAIN(key, rspamd_dkim_key_free);
  1224. key->keydata = g_malloc0(keylen + 1);
  1225. key->raw_key = g_malloc(keylen);
  1226. key->decoded_len = keylen;
  1227. key->type = type;
  1228. /* Copy key skipping all spaces and newlines */
  1229. const char *h = keydata;
  1230. uint8_t *t = key->raw_key;
  1231. while (h - keydata < keylen) {
  1232. if (!g_ascii_isspace(*h)) {
  1233. *t++ = *h++;
  1234. }
  1235. else {
  1236. h++;
  1237. }
  1238. }
  1239. key->keylen = t - key->raw_key;
  1240. if (!rspamd_cryptobox_base64_decode(key->raw_key, key->keylen, key->keydata,
  1241. &key->decoded_len)) {
  1242. REF_RELEASE(key);
  1243. g_set_error(err,
  1244. DKIM_ERROR,
  1245. DKIM_SIGERROR_KEYFAIL,
  1246. "DKIM key is not a valid base64 string");
  1247. return NULL;
  1248. }
  1249. /* Calculate ID -> md5 */
  1250. EVP_MD_CTX *mdctx = EVP_MD_CTX_create();
  1251. #ifdef EVP_MD_CTX_FLAG_NON_FIPS_ALLOW
  1252. EVP_MD_CTX_set_flags(mdctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
  1253. #endif
  1254. if (EVP_DigestInit_ex(mdctx, EVP_md5(), NULL) == 1) {
  1255. unsigned int dlen = sizeof(key->key_id);
  1256. EVP_DigestUpdate(mdctx, key->keydata, key->decoded_len);
  1257. EVP_DigestFinal_ex(mdctx, key->key_id, &dlen);
  1258. }
  1259. EVP_MD_CTX_destroy(mdctx);
  1260. if (key->type == RSPAMD_DKIM_KEY_EDDSA) {
  1261. key->key.key_eddsa = key->keydata;
  1262. if (key->decoded_len != rspamd_cryptobox_pk_sig_bytes(
  1263. RSPAMD_CRYPTOBOX_MODE_25519)) {
  1264. g_set_error(err,
  1265. DKIM_ERROR,
  1266. DKIM_SIGERROR_KEYFAIL,
  1267. "DKIM key is has invalid length %d for eddsa; expected %d",
  1268. (int) key->decoded_len,
  1269. rspamd_cryptobox_pk_sig_bytes(RSPAMD_CRYPTOBOX_MODE_25519));
  1270. REF_RELEASE(key);
  1271. return NULL;
  1272. }
  1273. }
  1274. else {
  1275. key->key_bio = BIO_new_mem_buf(key->keydata, key->decoded_len);
  1276. if (key->key_bio == NULL) {
  1277. g_set_error(err,
  1278. DKIM_ERROR,
  1279. DKIM_SIGERROR_KEYFAIL,
  1280. "cannot make ssl bio from key");
  1281. REF_RELEASE(key);
  1282. return NULL;
  1283. }
  1284. key->key_evp = d2i_PUBKEY_bio(key->key_bio, NULL);
  1285. if (key->key_evp == NULL) {
  1286. g_set_error(err,
  1287. DKIM_ERROR,
  1288. DKIM_SIGERROR_KEYFAIL,
  1289. "cannot extract pubkey from bio");
  1290. REF_RELEASE(key);
  1291. return NULL;
  1292. }
  1293. if (type == RSPAMD_DKIM_KEY_RSA) {
  1294. key->key.key_rsa = EVP_PKEY_get1_RSA(key->key_evp);
  1295. if (key->key.key_rsa == NULL) {
  1296. g_set_error(err,
  1297. DKIM_ERROR,
  1298. DKIM_SIGERROR_KEYFAIL,
  1299. "cannot extract rsa key from evp key");
  1300. REF_RELEASE(key);
  1301. return NULL;
  1302. }
  1303. }
  1304. else {
  1305. key->key.key_ecdsa = EVP_PKEY_get1_EC_KEY(key->key_evp);
  1306. if (key->key.key_ecdsa == NULL) {
  1307. g_set_error(err,
  1308. DKIM_ERROR,
  1309. DKIM_SIGERROR_KEYFAIL,
  1310. "cannot extract ecdsa key from evp key");
  1311. REF_RELEASE(key);
  1312. return NULL;
  1313. }
  1314. }
  1315. }
  1316. return key;
  1317. }
  1318. const unsigned char *
  1319. rspamd_dkim_key_id(rspamd_dkim_key_t *key)
  1320. {
  1321. if (key) {
  1322. return key->key_id;
  1323. }
  1324. return NULL;
  1325. }
  1326. /**
  1327. * Free DKIM key
  1328. * @param key
  1329. */
  1330. void rspamd_dkim_key_free(rspamd_dkim_key_t *key)
  1331. {
  1332. if (key->key_evp) {
  1333. EVP_PKEY_free(key->key_evp);
  1334. }
  1335. if (key->type == RSPAMD_DKIM_KEY_RSA) {
  1336. if (key->key.key_rsa) {
  1337. RSA_free(key->key.key_rsa);
  1338. }
  1339. }
  1340. else if (key->type == RSPAMD_DKIM_KEY_ECDSA) {
  1341. if (key->key.key_ecdsa) {
  1342. EC_KEY_free(key->key.key_ecdsa);
  1343. }
  1344. }
  1345. /* Nothing in case of eddsa key */
  1346. if (key->key_bio) {
  1347. BIO_free(key->key_bio);
  1348. }
  1349. g_free(key->raw_key);
  1350. g_free(key->keydata);
  1351. g_free(key);
  1352. }
  1353. void rspamd_dkim_sign_key_free(rspamd_dkim_sign_key_t *key)
  1354. {
  1355. if (key->key_evp) {
  1356. EVP_PKEY_free(key->key_evp);
  1357. }
  1358. if (key->type == RSPAMD_DKIM_KEY_RSA) {
  1359. if (key->key.key_rsa) {
  1360. RSA_free(key->key.key_rsa);
  1361. }
  1362. }
  1363. if (key->key_bio) {
  1364. BIO_free(key->key_bio);
  1365. }
  1366. if (key->type == RSPAMD_DKIM_KEY_EDDSA) {
  1367. rspamd_explicit_memzero(key->key.key_eddsa, key->keylen);
  1368. g_free(key->keydata);
  1369. }
  1370. g_free(key);
  1371. }
  1372. rspamd_dkim_key_t *
  1373. rspamd_dkim_parse_key(const char *txt, gsize *keylen, GError **err)
  1374. {
  1375. const char *c, *p, *end, *key = NULL, *alg = "rsa";
  1376. enum {
  1377. read_tag = 0,
  1378. read_tag_before_eqsign,
  1379. read_eqsign,
  1380. read_p_tag,
  1381. read_k_tag,
  1382. ignore_value,
  1383. skip_spaces,
  1384. } state = read_tag,
  1385. next_state;
  1386. char tag = '\0';
  1387. gsize klen = 0, alglen = 0;
  1388. c = txt;
  1389. p = txt;
  1390. end = txt + strlen(txt);
  1391. while (p < end) {
  1392. switch (state) {
  1393. case read_tag:
  1394. if (*p == '=') {
  1395. state = read_eqsign;
  1396. }
  1397. else if (g_ascii_isspace(*p)) {
  1398. state = skip_spaces;
  1399. if (tag != '\0') {
  1400. /* We had tag letter */
  1401. next_state = read_tag_before_eqsign;
  1402. }
  1403. else {
  1404. /* We had no tag letter, so we ignore empty tag */
  1405. next_state = read_tag;
  1406. }
  1407. }
  1408. else {
  1409. tag = *p;
  1410. }
  1411. p++;
  1412. break;
  1413. case read_tag_before_eqsign:
  1414. /* Input: spaces before eqsign
  1415. * Output: either read a next tag (previous had no value), or read value
  1416. * p is moved forward
  1417. */
  1418. if (*p == '=') {
  1419. state = read_eqsign;
  1420. }
  1421. else {
  1422. tag = *p;
  1423. state = read_tag;
  1424. }
  1425. p++;
  1426. break;
  1427. case read_eqsign:
  1428. /* Always switch to skip spaces state and do not advance p */
  1429. state = skip_spaces;
  1430. if (tag == 'p') {
  1431. next_state = read_p_tag;
  1432. }
  1433. else if (tag == 'k') {
  1434. next_state = read_k_tag;
  1435. }
  1436. else {
  1437. /* Unknown tag, ignore */
  1438. next_state = ignore_value;
  1439. tag = '\0';
  1440. }
  1441. break;
  1442. case read_p_tag:
  1443. if (*p == ';') {
  1444. klen = p - c;
  1445. key = c;
  1446. state = read_tag;
  1447. tag = '\0';
  1448. p++;
  1449. }
  1450. else {
  1451. p++;
  1452. }
  1453. break;
  1454. case read_k_tag:
  1455. if (*p == ';') {
  1456. alglen = p - c;
  1457. alg = c;
  1458. state = read_tag;
  1459. tag = '\0';
  1460. p++;
  1461. }
  1462. else if (g_ascii_isspace(*p)) {
  1463. alglen = p - c;
  1464. alg = c;
  1465. state = skip_spaces;
  1466. next_state = read_tag;
  1467. tag = '\0';
  1468. }
  1469. else {
  1470. p++;
  1471. }
  1472. break;
  1473. case ignore_value:
  1474. if (*p == ';') {
  1475. state = read_tag;
  1476. tag = '\0';
  1477. p++;
  1478. }
  1479. else if (g_ascii_isspace(*p)) {
  1480. state = skip_spaces;
  1481. next_state = read_tag;
  1482. tag = '\0';
  1483. }
  1484. else {
  1485. p++;
  1486. }
  1487. break;
  1488. case skip_spaces:
  1489. /* Skip spaces and switch to the next state if needed */
  1490. if (g_ascii_isspace(*p)) {
  1491. p++;
  1492. }
  1493. else {
  1494. c = p;
  1495. state = next_state;
  1496. }
  1497. break;
  1498. default:
  1499. break;
  1500. }
  1501. }
  1502. /* Leftover */
  1503. switch (state) {
  1504. case read_p_tag:
  1505. klen = p - c;
  1506. key = c;
  1507. break;
  1508. case read_k_tag:
  1509. alglen = p - c;
  1510. alg = c;
  1511. break;
  1512. default:
  1513. break;
  1514. }
  1515. if (klen == 0 || key == NULL) {
  1516. g_set_error(err,
  1517. DKIM_ERROR,
  1518. DKIM_SIGERROR_KEYFAIL,
  1519. "key is missing");
  1520. return NULL;
  1521. }
  1522. if (alglen == 0 || alg == NULL) {
  1523. alg = "rsa"; /* Implicit */
  1524. alglen = 3;
  1525. }
  1526. if (keylen) {
  1527. *keylen = klen;
  1528. }
  1529. if (alglen == 8 && rspamd_lc_cmp(alg, "ecdsa256", alglen) == 0) {
  1530. return rspamd_dkim_make_key(key, klen,
  1531. RSPAMD_DKIM_KEY_ECDSA, err);
  1532. }
  1533. else if (alglen == 7 && rspamd_lc_cmp(alg, "ed25519", alglen) == 0) {
  1534. return rspamd_dkim_make_key(key, klen,
  1535. RSPAMD_DKIM_KEY_EDDSA, err);
  1536. }
  1537. else {
  1538. /* We assume RSA default in all cases */
  1539. return rspamd_dkim_make_key(key, klen,
  1540. RSPAMD_DKIM_KEY_RSA, err);
  1541. }
  1542. g_assert_not_reached();
  1543. return NULL;
  1544. }
  1545. /* Get TXT request data and parse it */
  1546. static void
  1547. rspamd_dkim_dns_cb(struct rdns_reply *reply, gpointer arg)
  1548. {
  1549. struct rspamd_dkim_key_cbdata *cbdata = arg;
  1550. rspamd_dkim_key_t *key = NULL;
  1551. GError *err = NULL;
  1552. struct rdns_reply_entry *elt;
  1553. gsize keylen = 0;
  1554. if (reply->code != RDNS_RC_NOERROR) {
  1555. int err_code = DKIM_SIGERROR_NOKEY;
  1556. if (reply->code == RDNS_RC_NOREC) {
  1557. err_code = DKIM_SIGERROR_NOREC;
  1558. }
  1559. else if (reply->code == RDNS_RC_NXDOMAIN) {
  1560. err_code = DKIM_SIGERROR_NOREC;
  1561. }
  1562. g_set_error(&err,
  1563. DKIM_ERROR,
  1564. err_code,
  1565. "dns request to %s failed: %s",
  1566. cbdata->ctx->dns_key,
  1567. rdns_strerror(reply->code));
  1568. cbdata->handler(NULL, 0, cbdata->ctx, cbdata->ud, err);
  1569. }
  1570. else {
  1571. LL_FOREACH(reply->entries, elt)
  1572. {
  1573. if (elt->type == RDNS_REQUEST_TXT) {
  1574. if (err != NULL) {
  1575. /* Free error as it is insignificant */
  1576. g_error_free(err);
  1577. err = NULL;
  1578. }
  1579. key = rspamd_dkim_parse_key(elt->content.txt.data,
  1580. &keylen,
  1581. &err);
  1582. if (key) {
  1583. key->ttl = elt->ttl;
  1584. break;
  1585. }
  1586. }
  1587. }
  1588. cbdata->handler(key, keylen, cbdata->ctx, cbdata->ud, err);
  1589. }
  1590. }
  1591. /**
  1592. * Make DNS request for specified context and obtain and parse key
  1593. * @param ctx dkim context from signature
  1594. * @param resolver dns resolver object
  1595. * @param s async session to make request
  1596. * @return
  1597. */
  1598. gboolean
  1599. rspamd_get_dkim_key(rspamd_dkim_context_t *ctx,
  1600. struct rspamd_task *task,
  1601. dkim_key_handler_f handler,
  1602. gpointer ud)
  1603. {
  1604. struct rspamd_dkim_key_cbdata *cbdata;
  1605. g_return_val_if_fail(ctx != NULL, FALSE);
  1606. g_return_val_if_fail(ctx->dns_key != NULL, FALSE);
  1607. cbdata =
  1608. rspamd_mempool_alloc(ctx->pool,
  1609. sizeof(struct rspamd_dkim_key_cbdata));
  1610. cbdata->ctx = ctx;
  1611. cbdata->handler = handler;
  1612. cbdata->ud = ud;
  1613. return rspamd_dns_resolver_request_task_forced(task,
  1614. rspamd_dkim_dns_cb,
  1615. cbdata,
  1616. RDNS_REQUEST_TXT,
  1617. ctx->dns_key);
  1618. }
  1619. static gboolean
  1620. rspamd_dkim_relaxed_body_step(struct rspamd_dkim_common_ctx *ctx, EVP_MD_CTX *ck,
  1621. const char **start, unsigned int size,
  1622. gssize *remain)
  1623. {
  1624. const char *h;
  1625. char *t;
  1626. unsigned int len, inlen;
  1627. gssize octets_remain;
  1628. gboolean got_sp, ret = TRUE;
  1629. char buf[1024];
  1630. len = size;
  1631. inlen = sizeof(buf) - 1;
  1632. h = *start;
  1633. t = buf;
  1634. got_sp = FALSE;
  1635. octets_remain = *remain;
  1636. while (len > 0 && inlen > 0 && (octets_remain > 0)) {
  1637. if (*h == '\r' || *h == '\n') {
  1638. if (got_sp) {
  1639. /* Ignore spaces at the end of line */
  1640. t--;
  1641. }
  1642. *t++ = '\r';
  1643. *t++ = '\n';
  1644. if (len > 1 && (*h == '\r' && h[1] == '\n')) {
  1645. h += 2;
  1646. len -= 2;
  1647. octets_remain -= 2;
  1648. }
  1649. else {
  1650. h++;
  1651. len--;
  1652. if (octets_remain >= 2) {
  1653. octets_remain -= 2; /* Input has just \n or \r so we actually add more octets */
  1654. }
  1655. else {
  1656. octets_remain--;
  1657. break;
  1658. }
  1659. }
  1660. break;
  1661. }
  1662. else if (g_ascii_isspace(*h)) {
  1663. if (got_sp) {
  1664. /* Ignore multiply spaces */
  1665. h++;
  1666. len--;
  1667. continue;
  1668. }
  1669. else {
  1670. *t++ = ' ';
  1671. h++;
  1672. inlen--;
  1673. len--;
  1674. octets_remain--;
  1675. got_sp = TRUE;
  1676. continue;
  1677. }
  1678. }
  1679. else {
  1680. got_sp = FALSE;
  1681. }
  1682. *t++ = *h++;
  1683. inlen--;
  1684. len--;
  1685. octets_remain--;
  1686. }
  1687. if (octets_remain < 0) {
  1688. /* Absurdic l tag value, but we still need to rewind the t pointer back */
  1689. while (t > buf && octets_remain < 0) {
  1690. t--;
  1691. octets_remain++;
  1692. }
  1693. ret = FALSE;
  1694. }
  1695. *start = h;
  1696. if (t - buf > 0) {
  1697. gsize cklen = t - buf;
  1698. EVP_DigestUpdate(ck, buf, cklen);
  1699. ctx->body_canonicalised += cklen;
  1700. msg_debug_dkim("relaxed update signature with body buffer "
  1701. "(%z size, %z -> %z remain)",
  1702. cklen, *remain, octets_remain);
  1703. *remain = octets_remain;
  1704. }
  1705. return ret && ((len > 0) && (octets_remain > 0));
  1706. }
  1707. static gboolean
  1708. rspamd_dkim_simple_body_step(struct rspamd_dkim_common_ctx *ctx,
  1709. EVP_MD_CTX *ck, const char **start, unsigned int size,
  1710. gssize *remain)
  1711. {
  1712. const char *h;
  1713. char *t;
  1714. unsigned int len, inlen;
  1715. gssize octets_remain;
  1716. char buf[1024];
  1717. len = size;
  1718. inlen = sizeof(buf) - 1;
  1719. h = *start;
  1720. t = &buf[0];
  1721. octets_remain = *remain;
  1722. while (len > 0 && inlen > 0 && (octets_remain != 0)) {
  1723. if (*h == '\r' || *h == '\n') {
  1724. *t++ = '\r';
  1725. *t++ = '\n';
  1726. if (len > 1 && (*h == '\r' && h[1] == '\n')) {
  1727. h += 2;
  1728. len -= 2;
  1729. if (octets_remain >= 2) {
  1730. octets_remain -= 2; /* Input has just \n or \r so we actually add more octets */
  1731. }
  1732. else {
  1733. octets_remain--;
  1734. }
  1735. }
  1736. else {
  1737. h++;
  1738. len--;
  1739. if (octets_remain >= 2) {
  1740. octets_remain -= 2; /* Input has just \n or \r so we actually add more octets */
  1741. }
  1742. else {
  1743. octets_remain--;
  1744. }
  1745. }
  1746. break;
  1747. }
  1748. *t++ = *h++;
  1749. octets_remain--;
  1750. inlen--;
  1751. len--;
  1752. }
  1753. *start = h;
  1754. if (t - buf > 0) {
  1755. gsize cklen = t - buf;
  1756. EVP_DigestUpdate(ck, buf, cklen);
  1757. ctx->body_canonicalised += cklen;
  1758. msg_debug_dkim("simple update signature with body buffer "
  1759. "(%z size, %z -> %z remain)",
  1760. cklen, *remain, octets_remain);
  1761. *remain = octets_remain;
  1762. }
  1763. return ((len != 0) && (octets_remain != 0));
  1764. }
  1765. static const char *
  1766. rspamd_dkim_skip_empty_lines(const char *start, const char *end,
  1767. unsigned int type, gboolean sign, gboolean *need_crlf)
  1768. {
  1769. const char *p = end - 1, *t;
  1770. enum {
  1771. init = 0,
  1772. init_2,
  1773. got_cr,
  1774. got_lf,
  1775. got_crlf,
  1776. test_spaces,
  1777. } state = init;
  1778. unsigned int skip = 0;
  1779. while (p >= start) {
  1780. switch (state) {
  1781. case init:
  1782. if (*p == '\r') {
  1783. state = got_cr;
  1784. }
  1785. else if (*p == '\n') {
  1786. state = got_lf;
  1787. }
  1788. else if (type == DKIM_CANON_RELAXED && *p == ' ') {
  1789. skip = 0;
  1790. state = test_spaces;
  1791. }
  1792. else {
  1793. if (sign || type != DKIM_CANON_RELAXED) {
  1794. *need_crlf = TRUE;
  1795. }
  1796. goto end;
  1797. }
  1798. break;
  1799. case init_2:
  1800. if (*p == '\r') {
  1801. state = got_cr;
  1802. }
  1803. else if (*p == '\n') {
  1804. state = got_lf;
  1805. }
  1806. else if (type == DKIM_CANON_RELAXED && (*p == ' ' || *p == '\t')) {
  1807. skip = 0;
  1808. state = test_spaces;
  1809. }
  1810. else {
  1811. goto end;
  1812. }
  1813. break;
  1814. case got_cr:
  1815. if (p >= start + 1) {
  1816. if (*(p - 1) == '\r') {
  1817. p--;
  1818. state = got_cr;
  1819. }
  1820. else if (*(p - 1) == '\n') {
  1821. if ((*p - 2) == '\r') {
  1822. /* \r\n\r -> we know about one line */
  1823. p -= 1;
  1824. state = got_crlf;
  1825. }
  1826. else {
  1827. /* \n\r -> we know about one line */
  1828. p -= 1;
  1829. state = got_lf;
  1830. }
  1831. }
  1832. else if (type == DKIM_CANON_RELAXED && (*(p - 1) == ' ' ||
  1833. *(p - 1) == '\t')) {
  1834. skip = 1;
  1835. state = test_spaces;
  1836. }
  1837. else {
  1838. goto end;
  1839. }
  1840. }
  1841. else {
  1842. if (g_ascii_isspace(*(p - 1))) {
  1843. if (type == DKIM_CANON_RELAXED) {
  1844. p -= 1;
  1845. }
  1846. }
  1847. goto end;
  1848. }
  1849. break;
  1850. case got_lf:
  1851. if (p >= start + 1) {
  1852. if (*(p - 1) == '\r') {
  1853. state = got_crlf;
  1854. }
  1855. else if (*(p - 1) == '\n') {
  1856. /* We know about one line */
  1857. p--;
  1858. state = got_lf;
  1859. }
  1860. else if (type == DKIM_CANON_RELAXED && (*(p - 1) == ' ' ||
  1861. *(p - 1) == '\t')) {
  1862. skip = 1;
  1863. state = test_spaces;
  1864. }
  1865. else {
  1866. goto end;
  1867. }
  1868. }
  1869. else {
  1870. if (g_ascii_isspace(*(p - 1))) {
  1871. if (type == DKIM_CANON_RELAXED) {
  1872. p -= 1;
  1873. }
  1874. }
  1875. goto end;
  1876. }
  1877. break;
  1878. case got_crlf:
  1879. if (p >= start + 2) {
  1880. if (*(p - 2) == '\r') {
  1881. p -= 2;
  1882. state = got_cr;
  1883. }
  1884. else if (*(p - 2) == '\n') {
  1885. p -= 2;
  1886. state = got_lf;
  1887. }
  1888. else if (type == DKIM_CANON_RELAXED && (*(p - 2) == ' ' ||
  1889. *(p - 2) == '\t')) {
  1890. skip = 2;
  1891. state = test_spaces;
  1892. }
  1893. else {
  1894. goto end;
  1895. }
  1896. }
  1897. else {
  1898. if (g_ascii_isspace(*(p - 2))) {
  1899. if (type == DKIM_CANON_RELAXED) {
  1900. p -= 2;
  1901. }
  1902. }
  1903. goto end;
  1904. }
  1905. break;
  1906. case test_spaces:
  1907. t = p - skip;
  1908. while (t >= start + 2 && (*t == ' ' || *t == '\t')) {
  1909. t--;
  1910. }
  1911. if (*t == '\r') {
  1912. p = t;
  1913. state = got_cr;
  1914. }
  1915. else if (*t == '\n') {
  1916. p = t;
  1917. state = got_lf;
  1918. }
  1919. else {
  1920. goto end;
  1921. }
  1922. break;
  1923. }
  1924. }
  1925. end:
  1926. return p;
  1927. }
  1928. static gboolean
  1929. rspamd_dkim_canonize_body(struct rspamd_dkim_common_ctx *ctx,
  1930. const char *start,
  1931. const char *end,
  1932. gboolean sign)
  1933. {
  1934. const char *p;
  1935. gssize remain = ctx->len ? ctx->len : G_MAXSSIZE;
  1936. unsigned int total_len = end - start;
  1937. gboolean need_crlf = FALSE;
  1938. if (start == NULL) {
  1939. /* Empty body */
  1940. if (ctx->body_canon_type == DKIM_CANON_SIMPLE) {
  1941. EVP_DigestUpdate(ctx->body_hash, CRLF, sizeof(CRLF) - 1);
  1942. ctx->body_canonicalised += sizeof(CRLF) - 1;
  1943. }
  1944. else {
  1945. EVP_DigestUpdate(ctx->body_hash, "", 0);
  1946. }
  1947. }
  1948. else {
  1949. /* Strip extra ending CRLF */
  1950. p = rspamd_dkim_skip_empty_lines(start, end, ctx->body_canon_type,
  1951. sign, &need_crlf);
  1952. end = p + 1;
  1953. if (end == start) {
  1954. /* Empty body */
  1955. if (ctx->body_canon_type == DKIM_CANON_SIMPLE) {
  1956. EVP_DigestUpdate(ctx->body_hash, CRLF, sizeof(CRLF) - 1);
  1957. ctx->body_canonicalised += sizeof(CRLF) - 1;
  1958. }
  1959. else {
  1960. EVP_DigestUpdate(ctx->body_hash, "", 0);
  1961. }
  1962. }
  1963. else {
  1964. if (ctx->body_canon_type == DKIM_CANON_SIMPLE) {
  1965. /* Simple canonization */
  1966. while (rspamd_dkim_simple_body_step(ctx, ctx->body_hash,
  1967. &start, end - start, &remain))
  1968. ;
  1969. /*
  1970. * If we have l= tag then we cannot add crlf...
  1971. */
  1972. if (need_crlf) {
  1973. /* l is evil... */
  1974. if (ctx->len == 0) {
  1975. remain = 2;
  1976. }
  1977. else {
  1978. if (ctx->len <= total_len) {
  1979. /* We don't have enough l to add \r\n */
  1980. remain = 0;
  1981. }
  1982. else {
  1983. if (ctx->len - total_len >= 2) {
  1984. remain = 2;
  1985. }
  1986. else {
  1987. remain = ctx->len - total_len;
  1988. }
  1989. }
  1990. }
  1991. start = "\r\n";
  1992. end = start + 2;
  1993. rspamd_dkim_simple_body_step(ctx, ctx->body_hash,
  1994. &start, end - start, &remain);
  1995. }
  1996. }
  1997. else {
  1998. while (rspamd_dkim_relaxed_body_step(ctx, ctx->body_hash,
  1999. &start, end - start, &remain))
  2000. ;
  2001. if (need_crlf) {
  2002. start = "\r\n";
  2003. end = start + 2;
  2004. remain = 2;
  2005. rspamd_dkim_relaxed_body_step(ctx, ctx->body_hash,
  2006. &start, end - start, &remain);
  2007. }
  2008. }
  2009. }
  2010. return TRUE;
  2011. }
  2012. /* TODO: Implement relaxed algorithm */
  2013. return FALSE;
  2014. }
  2015. /* Update hash converting all CR and LF to CRLF */
  2016. static void
  2017. rspamd_dkim_hash_update(EVP_MD_CTX *ck, const char *begin, gsize len)
  2018. {
  2019. const char *p, *c, *end;
  2020. end = begin + len;
  2021. p = begin;
  2022. c = p;
  2023. while (p < end) {
  2024. if (*p == '\r') {
  2025. EVP_DigestUpdate(ck, c, p - c);
  2026. EVP_DigestUpdate(ck, CRLF, sizeof(CRLF) - 1);
  2027. p++;
  2028. if (p < end && *p == '\n') {
  2029. p++;
  2030. }
  2031. c = p;
  2032. }
  2033. else if (*p == '\n') {
  2034. EVP_DigestUpdate(ck, c, p - c);
  2035. EVP_DigestUpdate(ck, CRLF, sizeof(CRLF) - 1);
  2036. p++;
  2037. c = p;
  2038. }
  2039. else {
  2040. p++;
  2041. }
  2042. }
  2043. if (p > c) {
  2044. EVP_DigestUpdate(ck, c, p - c);
  2045. }
  2046. }
  2047. /* Update hash by signature value (ignoring b= tag) */
  2048. static void
  2049. rspamd_dkim_signature_update(struct rspamd_dkim_common_ctx *ctx,
  2050. const char *begin,
  2051. unsigned int len)
  2052. {
  2053. const char *p, *c, *end;
  2054. gboolean tag, skip;
  2055. end = begin + len;
  2056. p = begin;
  2057. c = begin;
  2058. tag = TRUE;
  2059. skip = FALSE;
  2060. while (p < end) {
  2061. if (tag && p[0] == 'b' && p[1] == '=') {
  2062. /* Add to signature */
  2063. msg_debug_dkim("initial update hash with signature part: %*s",
  2064. (int) (p - c + 2),
  2065. c);
  2066. ctx->headers_canonicalised += p - c + 2;
  2067. rspamd_dkim_hash_update(ctx->headers_hash, c, p - c + 2);
  2068. skip = TRUE;
  2069. }
  2070. else if (skip && (*p == ';' || p == end - 1)) {
  2071. skip = FALSE;
  2072. c = p;
  2073. }
  2074. else if (!tag && *p == ';') {
  2075. tag = TRUE;
  2076. }
  2077. else if (tag && *p == '=') {
  2078. tag = FALSE;
  2079. }
  2080. p++;
  2081. }
  2082. p--;
  2083. /* Skip \r\n at the end */
  2084. while ((*p == '\r' || *p == '\n') && p >= c) {
  2085. p--;
  2086. }
  2087. if (p - c + 1 > 0) {
  2088. msg_debug_dkim("final update hash with signature part: %*s",
  2089. (int) (p - c + 1), c);
  2090. ctx->headers_canonicalised += p - c + 1;
  2091. rspamd_dkim_hash_update(ctx->headers_hash, c, p - c + 1);
  2092. }
  2093. }
  2094. goffset
  2095. rspamd_dkim_canonize_header_relaxed_str(const char *hname,
  2096. const char *hvalue,
  2097. char *out,
  2098. gsize outlen)
  2099. {
  2100. char *t;
  2101. const unsigned char *h;
  2102. gboolean got_sp;
  2103. /* Name part */
  2104. t = out;
  2105. h = hname;
  2106. while (*h && t - out < outlen) {
  2107. *t++ = lc_map[*h++];
  2108. }
  2109. if (t - out >= outlen) {
  2110. return -1;
  2111. }
  2112. *t++ = ':';
  2113. /* Value part */
  2114. h = hvalue;
  2115. /* Skip spaces at the beginning */
  2116. while (g_ascii_isspace(*h)) {
  2117. h++;
  2118. }
  2119. got_sp = FALSE;
  2120. while (*h && (t - out < outlen)) {
  2121. if (g_ascii_isspace(*h)) {
  2122. if (got_sp) {
  2123. h++;
  2124. continue;
  2125. }
  2126. else {
  2127. got_sp = TRUE;
  2128. *t++ = ' ';
  2129. h++;
  2130. continue;
  2131. }
  2132. }
  2133. else {
  2134. got_sp = FALSE;
  2135. }
  2136. *t++ = *h++;
  2137. }
  2138. if (g_ascii_isspace(*(t - 1))) {
  2139. t--;
  2140. }
  2141. if (t - out >= outlen - 2) {
  2142. return -1;
  2143. }
  2144. *t++ = '\r';
  2145. *t++ = '\n';
  2146. *t = '\0';
  2147. return t - out;
  2148. }
  2149. static gboolean
  2150. rspamd_dkim_canonize_header_relaxed(struct rspamd_dkim_common_ctx *ctx,
  2151. const char *header,
  2152. const char *header_name,
  2153. gboolean is_sign,
  2154. unsigned int count,
  2155. bool is_seal)
  2156. {
  2157. static char st_buf[8192];
  2158. char *buf;
  2159. unsigned int inlen;
  2160. goffset r;
  2161. gboolean allocated = FALSE;
  2162. inlen = strlen(header) + strlen(header_name) + sizeof(":" CRLF);
  2163. if (inlen > sizeof(st_buf)) {
  2164. buf = g_malloc(inlen);
  2165. allocated = TRUE;
  2166. }
  2167. else {
  2168. /* Faster */
  2169. buf = st_buf;
  2170. }
  2171. r = rspamd_dkim_canonize_header_relaxed_str(header_name, header, buf, inlen);
  2172. g_assert(r != -1);
  2173. if (!is_sign) {
  2174. msg_debug_dkim("update %s with header (idx=%d): %s",
  2175. is_seal ? "seal" : "signature", count, buf);
  2176. EVP_DigestUpdate(ctx->headers_hash, buf, r);
  2177. }
  2178. else {
  2179. rspamd_dkim_signature_update(ctx, buf, r);
  2180. }
  2181. if (allocated) {
  2182. g_free(buf);
  2183. }
  2184. return TRUE;
  2185. }
  2186. static gboolean
  2187. rspamd_dkim_canonize_header(struct rspamd_dkim_common_ctx *ctx,
  2188. struct rspamd_task *task,
  2189. const char *header_name,
  2190. int count,
  2191. const char *dkim_header,
  2192. const char *dkim_domain)
  2193. {
  2194. struct rspamd_mime_header *rh, *cur, *sel = NULL;
  2195. int hdr_cnt = 0;
  2196. bool use_idx = false, is_sign = ctx->is_sign;
  2197. /*
  2198. * TODO:
  2199. * Temporary hack to prevent linked list being misused until refactored
  2200. */
  2201. const unsigned int max_list_iters = 1000;
  2202. if (count < 0) {
  2203. use_idx = true;
  2204. count = -(count); /* use i= in header content as it is arc stuff */
  2205. }
  2206. if (dkim_header == NULL) {
  2207. rh = rspamd_message_get_header_array(task, header_name,
  2208. is_sign);
  2209. if (rh) {
  2210. /* Check uniqueness of the header but we count from the bottom to top */
  2211. if (!use_idx) {
  2212. for (cur = rh->prev;; cur = cur->prev) {
  2213. if (hdr_cnt == count) {
  2214. sel = cur;
  2215. }
  2216. hdr_cnt++;
  2217. if (cur == rh || hdr_cnt >= max_list_iters) {
  2218. /* Cycle */
  2219. break;
  2220. }
  2221. }
  2222. if ((rh->flags & RSPAMD_HEADER_UNIQUE) && hdr_cnt > 1) {
  2223. uint64_t random_cookie = ottery_rand_uint64();
  2224. msg_warn_dkim("header %s is intended to be unique by"
  2225. " email standards, but we have %d headers of this"
  2226. " type, artificially break DKIM check",
  2227. header_name,
  2228. hdr_cnt);
  2229. rspamd_dkim_hash_update(ctx->headers_hash,
  2230. (const char *) &random_cookie,
  2231. sizeof(random_cookie));
  2232. ctx->headers_canonicalised += sizeof(random_cookie);
  2233. return FALSE;
  2234. }
  2235. if (hdr_cnt <= count) {
  2236. /*
  2237. * If DKIM has less headers requested than there are in a
  2238. * message, then it's fine, it allows adding extra headers
  2239. */
  2240. return TRUE;
  2241. }
  2242. }
  2243. else {
  2244. /*
  2245. * This branch is used for ARC headers, and it orders them based on
  2246. * i=<number> string and not their real order in the list of headers
  2247. */
  2248. char idx_buf[16];
  2249. int id_len, i;
  2250. id_len = rspamd_snprintf(idx_buf, sizeof(idx_buf), "i=%d;",
  2251. count);
  2252. for (cur = rh->prev, i = 0; i < max_list_iters; cur = cur->prev, i++) {
  2253. if (cur->decoded &&
  2254. rspamd_substring_search(cur->decoded, strlen(cur->decoded),
  2255. idx_buf, id_len) != -1) {
  2256. sel = cur;
  2257. break;
  2258. }
  2259. if (cur == rh) {
  2260. /* Cycle */
  2261. break;
  2262. }
  2263. }
  2264. if (sel == NULL) {
  2265. return FALSE;
  2266. }
  2267. }
  2268. /* Selected header must be non-null if previous condition is false */
  2269. g_assert(sel != NULL);
  2270. if (ctx->header_canon_type == DKIM_CANON_SIMPLE) {
  2271. rspamd_dkim_hash_update(ctx->headers_hash, sel->raw_value,
  2272. sel->raw_len);
  2273. ctx->headers_canonicalised += sel->raw_len;
  2274. msg_debug_dkim("update %s with header (idx=%d): %*s",
  2275. (use_idx ? "seal" : "signature"),
  2276. count, (int) sel->raw_len, sel->raw_value);
  2277. }
  2278. else {
  2279. if (is_sign && (sel->flags & RSPAMD_HEADER_FROM)) {
  2280. /* Special handling of the From handling when rewrite is done */
  2281. gboolean has_rewrite = FALSE;
  2282. unsigned int i;
  2283. struct rspamd_email_address *addr;
  2284. PTR_ARRAY_FOREACH(MESSAGE_FIELD(task, from_mime), i, addr)
  2285. {
  2286. if ((addr->flags & RSPAMD_EMAIL_ADDR_ORIGINAL) && !(addr->flags & RSPAMD_EMAIL_ADDR_ALIASED)) {
  2287. has_rewrite = TRUE;
  2288. }
  2289. }
  2290. if (has_rewrite) {
  2291. PTR_ARRAY_FOREACH(MESSAGE_FIELD(task, from_mime), i, addr)
  2292. {
  2293. if (!(addr->flags & RSPAMD_EMAIL_ADDR_ORIGINAL)) {
  2294. if (!rspamd_dkim_canonize_header_relaxed(ctx, addr->raw,
  2295. header_name, FALSE, i, use_idx)) {
  2296. return FALSE;
  2297. }
  2298. return TRUE;
  2299. }
  2300. }
  2301. }
  2302. }
  2303. if (!rspamd_dkim_canonize_header_relaxed(ctx, sel->value,
  2304. header_name, FALSE, count, use_idx)) {
  2305. return FALSE;
  2306. }
  2307. }
  2308. }
  2309. }
  2310. else {
  2311. /* For signature check just use the saved dkim header */
  2312. if (ctx->header_canon_type == DKIM_CANON_SIMPLE) {
  2313. /* We need to find our own signature and use it */
  2314. rh = rspamd_message_get_header_array(task, header_name, is_sign);
  2315. if (rh) {
  2316. /* We need to find our own signature */
  2317. if (!dkim_domain) {
  2318. msg_err_dkim("cannot verify dkim as we have no dkim domain!");
  2319. return FALSE;
  2320. }
  2321. gboolean found = FALSE;
  2322. DL_FOREACH(rh, cur)
  2323. {
  2324. uint64_t th = rspamd_cryptobox_fast_hash(cur->decoded,
  2325. strlen(cur->decoded), rspamd_hash_seed());
  2326. if (th == ctx->sig_hash) {
  2327. rspamd_dkim_signature_update(ctx, cur->raw_value,
  2328. cur->raw_len);
  2329. found = TRUE;
  2330. break;
  2331. }
  2332. }
  2333. if (!found) {
  2334. msg_err_dkim("BUGON: cannot verify dkim as we have lost our signature"
  2335. " during simple canonicalisation, expected hash=%L",
  2336. ctx->sig_hash);
  2337. return FALSE;
  2338. }
  2339. }
  2340. else {
  2341. return FALSE;
  2342. }
  2343. }
  2344. else {
  2345. if (!rspamd_dkim_canonize_header_relaxed(ctx,
  2346. dkim_header,
  2347. header_name,
  2348. TRUE, 0, use_idx)) {
  2349. return FALSE;
  2350. }
  2351. }
  2352. }
  2353. return TRUE;
  2354. }
  2355. struct rspamd_dkim_cached_hash {
  2356. unsigned char *digest_normal;
  2357. unsigned char *digest_cr;
  2358. unsigned char *digest_crlf;
  2359. char *type;
  2360. };
  2361. static struct rspamd_dkim_cached_hash *
  2362. rspamd_dkim_check_bh_cached(struct rspamd_dkim_common_ctx *ctx,
  2363. struct rspamd_task *task, gsize bhlen, gboolean is_sign)
  2364. {
  2365. char typebuf[64];
  2366. struct rspamd_dkim_cached_hash *res;
  2367. rspamd_snprintf(typebuf, sizeof(typebuf),
  2368. RSPAMD_MEMPOOL_DKIM_BH_CACHE "%z_%s_%d_%z",
  2369. bhlen,
  2370. ctx->body_canon_type == DKIM_CANON_RELAXED ? "1" : "0",
  2371. !!is_sign,
  2372. ctx->len);
  2373. res = rspamd_mempool_get_variable(task->task_pool,
  2374. typebuf);
  2375. if (!res) {
  2376. res = rspamd_mempool_alloc0(task->task_pool, sizeof(*res));
  2377. res->type = rspamd_mempool_strdup(task->task_pool, typebuf);
  2378. rspamd_mempool_set_variable(task->task_pool,
  2379. res->type, res, NULL);
  2380. }
  2381. return res;
  2382. }
  2383. static const char *
  2384. rspamd_dkim_type_to_string(enum rspamd_dkim_type t)
  2385. {
  2386. switch (t) {
  2387. case RSPAMD_DKIM_NORMAL:
  2388. return "dkim";
  2389. case RSPAMD_DKIM_ARC_SIG:
  2390. return "arc_sig";
  2391. case RSPAMD_DKIM_ARC_SEAL:
  2392. default:
  2393. return "arc_seal";
  2394. }
  2395. }
  2396. /**
  2397. * Check task for dkim context using dkim key
  2398. * @param ctx dkim verify context
  2399. * @param key dkim key (from cache or from dns request)
  2400. * @param task task to check
  2401. * @return
  2402. */
  2403. struct rspamd_dkim_check_result *
  2404. rspamd_dkim_check(rspamd_dkim_context_t *ctx,
  2405. rspamd_dkim_key_t *key,
  2406. struct rspamd_task *task)
  2407. {
  2408. const char *body_end, *body_start;
  2409. unsigned char raw_digest[EVP_MAX_MD_SIZE];
  2410. struct rspamd_dkim_cached_hash *cached_bh = NULL;
  2411. EVP_MD_CTX *cpy_ctx = NULL;
  2412. gsize dlen = 0;
  2413. struct rspamd_dkim_check_result *res;
  2414. unsigned int i;
  2415. struct rspamd_dkim_header *dh;
  2416. int nid;
  2417. g_return_val_if_fail(ctx != NULL, NULL);
  2418. g_return_val_if_fail(key != NULL, NULL);
  2419. g_return_val_if_fail(task->msg.len > 0, NULL);
  2420. /* First of all find place of body */
  2421. body_end = task->msg.begin + task->msg.len;
  2422. body_start = MESSAGE_FIELD(task, raw_headers_content).body_start;
  2423. res = rspamd_mempool_alloc0(task->task_pool, sizeof(*res));
  2424. res->ctx = ctx;
  2425. res->selector = ctx->selector;
  2426. res->domain = ctx->domain;
  2427. res->fail_reason = NULL;
  2428. res->short_b = ctx->short_b;
  2429. res->rcode = DKIM_CONTINUE;
  2430. if (!body_start) {
  2431. res->rcode = DKIM_ERROR;
  2432. return res;
  2433. }
  2434. if (ctx->common.type != RSPAMD_DKIM_ARC_SEAL) {
  2435. dlen = EVP_MD_CTX_size(ctx->common.body_hash);
  2436. cached_bh = rspamd_dkim_check_bh_cached(&ctx->common, task,
  2437. dlen, FALSE);
  2438. if (!cached_bh->digest_normal) {
  2439. /* Start canonization of body part */
  2440. if (!rspamd_dkim_canonize_body(&ctx->common, body_start, body_end,
  2441. FALSE)) {
  2442. res->rcode = DKIM_RECORD_ERROR;
  2443. return res;
  2444. }
  2445. }
  2446. }
  2447. /* Now canonize headers */
  2448. for (i = 0; i < ctx->common.hlist->len; i++) {
  2449. dh = g_ptr_array_index(ctx->common.hlist, i);
  2450. rspamd_dkim_canonize_header(&ctx->common, task, dh->name, dh->count,
  2451. NULL, NULL);
  2452. }
  2453. /* Canonize dkim signature */
  2454. switch (ctx->common.type) {
  2455. case RSPAMD_DKIM_NORMAL:
  2456. rspamd_dkim_canonize_header(&ctx->common, task, RSPAMD_DKIM_SIGNHEADER, 0,
  2457. ctx->dkim_header, ctx->domain);
  2458. break;
  2459. case RSPAMD_DKIM_ARC_SIG:
  2460. rspamd_dkim_canonize_header(&ctx->common, task, RSPAMD_DKIM_ARC_SIGNHEADER, 0,
  2461. ctx->dkim_header, ctx->domain);
  2462. break;
  2463. case RSPAMD_DKIM_ARC_SEAL:
  2464. rspamd_dkim_canonize_header(&ctx->common, task, RSPAMD_DKIM_ARC_SEALHEADER, 0,
  2465. ctx->dkim_header, ctx->domain);
  2466. break;
  2467. }
  2468. /* Use cached BH for all but arc seal, if it is not NULL we are not in arc seal mode */
  2469. if (cached_bh != NULL) {
  2470. if (!cached_bh->digest_normal) {
  2471. /* Copy md_ctx to deal with broken CRLF at the end */
  2472. cpy_ctx = EVP_MD_CTX_create();
  2473. EVP_MD_CTX_copy(cpy_ctx, ctx->common.body_hash);
  2474. EVP_DigestFinal_ex(cpy_ctx, raw_digest, NULL);
  2475. cached_bh->digest_normal = rspamd_mempool_alloc(task->task_pool,
  2476. sizeof(raw_digest));
  2477. memcpy(cached_bh->digest_normal, raw_digest, sizeof(raw_digest));
  2478. }
  2479. /* Check bh field */
  2480. if (memcmp(ctx->bh, cached_bh->digest_normal, ctx->bhlen) != 0) {
  2481. msg_debug_dkim(
  2482. "bh value mismatch: %*xs versus %*xs, try add LF; try adding CRLF",
  2483. (int) dlen, ctx->bh,
  2484. (int) dlen, raw_digest);
  2485. if (cpy_ctx) {
  2486. /* Try add CRLF */
  2487. #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
  2488. EVP_MD_CTX_cleanup(cpy_ctx);
  2489. #else
  2490. EVP_MD_CTX_reset(cpy_ctx);
  2491. #endif
  2492. EVP_MD_CTX_copy(cpy_ctx, ctx->common.body_hash);
  2493. EVP_DigestUpdate(cpy_ctx, "\r\n", 2);
  2494. EVP_DigestFinal_ex(cpy_ctx, raw_digest, NULL);
  2495. cached_bh->digest_crlf = rspamd_mempool_alloc(task->task_pool,
  2496. sizeof(raw_digest));
  2497. memcpy(cached_bh->digest_crlf, raw_digest, sizeof(raw_digest));
  2498. if (memcmp(ctx->bh, raw_digest, ctx->bhlen) != 0) {
  2499. msg_debug_dkim(
  2500. "bh value mismatch after added CRLF: %*xs versus %*xs, try add LF",
  2501. (int) dlen, ctx->bh,
  2502. (int) dlen, raw_digest);
  2503. /* Try add LF */
  2504. #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
  2505. EVP_MD_CTX_cleanup(cpy_ctx);
  2506. #else
  2507. EVP_MD_CTX_reset(cpy_ctx);
  2508. #endif
  2509. EVP_MD_CTX_copy(cpy_ctx, ctx->common.body_hash);
  2510. EVP_DigestUpdate(cpy_ctx, "\n", 1);
  2511. EVP_DigestFinal_ex(cpy_ctx, raw_digest, NULL);
  2512. cached_bh->digest_cr = rspamd_mempool_alloc(task->task_pool,
  2513. sizeof(raw_digest));
  2514. memcpy(cached_bh->digest_cr, raw_digest, sizeof(raw_digest));
  2515. if (memcmp(ctx->bh, raw_digest, ctx->bhlen) != 0) {
  2516. msg_debug_dkim("bh value mismatch after added LF: %*xs versus %*xs",
  2517. (int) dlen, ctx->bh,
  2518. (int) dlen, raw_digest);
  2519. res->fail_reason = "body hash did not verify";
  2520. res->rcode = DKIM_REJECT;
  2521. }
  2522. }
  2523. }
  2524. else if (cached_bh->digest_crlf) {
  2525. if (memcmp(ctx->bh, cached_bh->digest_crlf, ctx->bhlen) != 0) {
  2526. msg_debug_dkim("bh value mismatch after added CRLF: %*xs versus %*xs",
  2527. (int) dlen, ctx->bh,
  2528. (int) dlen, cached_bh->digest_crlf);
  2529. if (cached_bh->digest_cr) {
  2530. if (memcmp(ctx->bh, cached_bh->digest_cr, ctx->bhlen) != 0) {
  2531. msg_debug_dkim(
  2532. "bh value mismatch after added LF: %*xs versus %*xs",
  2533. (int) dlen, ctx->bh,
  2534. (int) dlen, cached_bh->digest_cr);
  2535. res->fail_reason = "body hash did not verify";
  2536. res->rcode = DKIM_REJECT;
  2537. }
  2538. }
  2539. else {
  2540. res->fail_reason = "body hash did not verify";
  2541. res->rcode = DKIM_REJECT;
  2542. }
  2543. }
  2544. }
  2545. else {
  2546. msg_debug_dkim(
  2547. "bh value mismatch: %*xs versus %*xs",
  2548. (int) dlen, ctx->bh,
  2549. (int) dlen, cached_bh->digest_normal);
  2550. res->fail_reason = "body hash did not verify";
  2551. res->rcode = DKIM_REJECT;
  2552. }
  2553. }
  2554. if (cpy_ctx) {
  2555. #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
  2556. EVP_MD_CTX_cleanup(cpy_ctx);
  2557. #else
  2558. EVP_MD_CTX_reset(cpy_ctx);
  2559. #endif
  2560. EVP_MD_CTX_destroy(cpy_ctx);
  2561. }
  2562. if (res->rcode == DKIM_REJECT) {
  2563. msg_info_dkim(
  2564. "%s: bh value mismatch: got %*Bs, expected %*Bs; "
  2565. "body length %d->%d; d=%s; s=%s",
  2566. rspamd_dkim_type_to_string(ctx->common.type),
  2567. (int) dlen, cached_bh->digest_normal,
  2568. (int) dlen, ctx->bh,
  2569. (int) (body_end - body_start), ctx->common.body_canonicalised,
  2570. ctx->domain, ctx->selector);
  2571. return res;
  2572. }
  2573. }
  2574. dlen = EVP_MD_CTX_size(ctx->common.headers_hash);
  2575. EVP_DigestFinal_ex(ctx->common.headers_hash, raw_digest, NULL);
  2576. /* Check headers signature */
  2577. if (ctx->sig_alg == DKIM_SIGN_RSASHA1) {
  2578. nid = NID_sha1;
  2579. }
  2580. else if (ctx->sig_alg == DKIM_SIGN_RSASHA256 ||
  2581. ctx->sig_alg == DKIM_SIGN_ECDSASHA256 ||
  2582. ctx->sig_alg == DKIM_SIGN_EDDSASHA256) {
  2583. nid = NID_sha256;
  2584. }
  2585. else if (ctx->sig_alg == DKIM_SIGN_RSASHA512 ||
  2586. ctx->sig_alg == DKIM_SIGN_ECDSASHA512) {
  2587. nid = NID_sha512;
  2588. }
  2589. else {
  2590. /* Not reached */
  2591. nid = NID_sha1;
  2592. }
  2593. switch (key->type) {
  2594. case RSPAMD_DKIM_KEY_RSA:
  2595. if (RSA_verify(nid, raw_digest, dlen, ctx->b, ctx->blen,
  2596. key->key.key_rsa) != 1) {
  2597. msg_debug_dkim("headers rsa verify failed");
  2598. ERR_clear_error();
  2599. res->rcode = DKIM_REJECT;
  2600. res->fail_reason = "headers rsa verify failed";
  2601. msg_info_dkim(
  2602. "%s: headers RSA verification failure; "
  2603. "body length %d->%d; headers length %d; d=%s; s=%s; key_md5=%*xs; orig header: %s",
  2604. rspamd_dkim_type_to_string(ctx->common.type),
  2605. (int) (body_end - body_start), ctx->common.body_canonicalised,
  2606. ctx->common.headers_canonicalised,
  2607. ctx->domain, ctx->selector,
  2608. RSPAMD_DKIM_KEY_ID_LEN, rspamd_dkim_key_id(key),
  2609. ctx->dkim_header);
  2610. }
  2611. break;
  2612. case RSPAMD_DKIM_KEY_ECDSA:
  2613. if (ECDSA_verify(nid, raw_digest, dlen, ctx->b, ctx->blen,
  2614. key->key.key_ecdsa) != 1) {
  2615. msg_info_dkim(
  2616. "%s: headers ECDSA verification failure; "
  2617. "body length %d->%d; headers length %d; d=%s; s=%s; key_md5=%*xs; orig header: %s",
  2618. rspamd_dkim_type_to_string(ctx->common.type),
  2619. (int) (body_end - body_start), ctx->common.body_canonicalised,
  2620. ctx->common.headers_canonicalised,
  2621. ctx->domain, ctx->selector,
  2622. RSPAMD_DKIM_KEY_ID_LEN, rspamd_dkim_key_id(key),
  2623. ctx->dkim_header);
  2624. msg_debug_dkim("headers ecdsa verify failed");
  2625. ERR_clear_error();
  2626. res->rcode = DKIM_REJECT;
  2627. res->fail_reason = "headers ecdsa verify failed";
  2628. }
  2629. break;
  2630. case RSPAMD_DKIM_KEY_EDDSA:
  2631. if (!rspamd_cryptobox_verify(ctx->b, ctx->blen, raw_digest, dlen,
  2632. key->key.key_eddsa, RSPAMD_CRYPTOBOX_MODE_25519)) {
  2633. msg_info_dkim(
  2634. "%s: headers EDDSA verification failure; "
  2635. "body length %d->%d; headers length %d; d=%s; s=%s; key_md5=%*xs; orig header: %s",
  2636. rspamd_dkim_type_to_string(ctx->common.type),
  2637. (int) (body_end - body_start), ctx->common.body_canonicalised,
  2638. ctx->common.headers_canonicalised,
  2639. ctx->domain, ctx->selector,
  2640. RSPAMD_DKIM_KEY_ID_LEN, rspamd_dkim_key_id(key),
  2641. ctx->dkim_header);
  2642. msg_debug_dkim("headers eddsa verify failed");
  2643. res->rcode = DKIM_REJECT;
  2644. res->fail_reason = "headers eddsa verify failed";
  2645. }
  2646. break;
  2647. }
  2648. if (ctx->common.type == RSPAMD_DKIM_ARC_SEAL && res->rcode == DKIM_CONTINUE) {
  2649. switch (ctx->cv) {
  2650. case RSPAMD_ARC_INVALID:
  2651. msg_info_dkim("arc seal is invalid i=%d", ctx->common.idx);
  2652. res->rcode = DKIM_PERM_ERROR;
  2653. res->fail_reason = "arc seal is invalid";
  2654. break;
  2655. case RSPAMD_ARC_FAIL:
  2656. msg_info_dkim("arc seal failed i=%d", ctx->common.idx);
  2657. res->rcode = DKIM_REJECT;
  2658. res->fail_reason = "arc seal failed";
  2659. break;
  2660. default:
  2661. break;
  2662. }
  2663. }
  2664. return res;
  2665. }
  2666. struct rspamd_dkim_check_result *
  2667. rspamd_dkim_create_result(rspamd_dkim_context_t *ctx,
  2668. enum rspamd_dkim_check_rcode rcode,
  2669. struct rspamd_task *task)
  2670. {
  2671. struct rspamd_dkim_check_result *res;
  2672. res = rspamd_mempool_alloc0(task->task_pool, sizeof(*res));
  2673. res->ctx = ctx;
  2674. res->selector = ctx->selector;
  2675. res->domain = ctx->domain;
  2676. res->fail_reason = NULL;
  2677. res->short_b = ctx->short_b;
  2678. res->rcode = rcode;
  2679. return res;
  2680. }
  2681. rspamd_dkim_key_t *
  2682. rspamd_dkim_key_ref(rspamd_dkim_key_t *k)
  2683. {
  2684. REF_RETAIN(k);
  2685. return k;
  2686. }
  2687. void rspamd_dkim_key_unref(rspamd_dkim_key_t *k)
  2688. {
  2689. REF_RELEASE(k);
  2690. }
  2691. rspamd_dkim_sign_key_t *
  2692. rspamd_dkim_sign_key_ref(rspamd_dkim_sign_key_t *k)
  2693. {
  2694. REF_RETAIN(k);
  2695. return k;
  2696. }
  2697. void rspamd_dkim_sign_key_unref(rspamd_dkim_sign_key_t *k)
  2698. {
  2699. REF_RELEASE(k);
  2700. }
  2701. const char *
  2702. rspamd_dkim_get_domain(rspamd_dkim_context_t *ctx)
  2703. {
  2704. if (ctx) {
  2705. return ctx->domain;
  2706. }
  2707. return NULL;
  2708. }
  2709. const char *
  2710. rspamd_dkim_get_selector(rspamd_dkim_context_t *ctx)
  2711. {
  2712. if (ctx) {
  2713. return ctx->selector;
  2714. }
  2715. return NULL;
  2716. }
  2717. unsigned int rspamd_dkim_key_get_ttl(rspamd_dkim_key_t *k)
  2718. {
  2719. if (k) {
  2720. return k->ttl;
  2721. }
  2722. return 0;
  2723. }
  2724. const char *
  2725. rspamd_dkim_get_dns_key(rspamd_dkim_context_t *ctx)
  2726. {
  2727. if (ctx) {
  2728. return ctx->dns_key;
  2729. }
  2730. return NULL;
  2731. }
  2732. #define PEM_SIG "-----BEGIN"
  2733. rspamd_dkim_sign_key_t *
  2734. rspamd_dkim_sign_key_load(const char *key, gsize len,
  2735. enum rspamd_dkim_key_format type,
  2736. GError **err)
  2737. {
  2738. unsigned char *map = NULL, *tmp = NULL;
  2739. gsize maplen;
  2740. rspamd_dkim_sign_key_t *nkey;
  2741. time_t mtime = time(NULL);
  2742. if (type < 0 || type > RSPAMD_DKIM_KEY_UNKNOWN || len == 0 || key == NULL) {
  2743. g_set_error(err, dkim_error_quark(), DKIM_SIGERROR_KEYFAIL,
  2744. "invalid key type to load: %d", type);
  2745. return NULL;
  2746. }
  2747. nkey = g_malloc0(sizeof(*nkey));
  2748. nkey->mtime = mtime;
  2749. msg_debug_dkim_taskless("got public key with length %z and type %d",
  2750. len, type);
  2751. /* Load key file if needed */
  2752. if (type == RSPAMD_DKIM_KEY_FILE) {
  2753. struct stat st;
  2754. if (stat(key, &st) != 0) {
  2755. g_set_error(err, dkim_error_quark(), DKIM_SIGERROR_KEYFAIL,
  2756. "cannot stat key file: '%s' %s", key, strerror(errno));
  2757. g_free(nkey);
  2758. return NULL;
  2759. }
  2760. nkey->mtime = st.st_mtime;
  2761. map = rspamd_file_xmap(key, PROT_READ, &maplen, TRUE);
  2762. if (map == NULL) {
  2763. g_set_error(err, dkim_error_quark(), DKIM_SIGERROR_KEYFAIL,
  2764. "cannot map key file: '%s' %s", key, strerror(errno));
  2765. g_free(nkey);
  2766. return NULL;
  2767. }
  2768. key = map;
  2769. len = maplen;
  2770. if (maplen > sizeof(PEM_SIG) &&
  2771. strncmp(map, PEM_SIG, sizeof(PEM_SIG) - 1) == 0) {
  2772. type = RSPAMD_DKIM_KEY_PEM;
  2773. }
  2774. else if (rspamd_cryptobox_base64_is_valid(map, maplen)) {
  2775. type = RSPAMD_DKIM_KEY_BASE64;
  2776. }
  2777. else {
  2778. type = RSPAMD_DKIM_KEY_RAW;
  2779. }
  2780. }
  2781. if (type == RSPAMD_DKIM_KEY_UNKNOWN) {
  2782. if (len > sizeof(PEM_SIG) &&
  2783. memcmp(key, PEM_SIG, sizeof(PEM_SIG) - 1) == 0) {
  2784. type = RSPAMD_DKIM_KEY_PEM;
  2785. }
  2786. else {
  2787. type = RSPAMD_DKIM_KEY_RAW;
  2788. }
  2789. }
  2790. if (type == RSPAMD_DKIM_KEY_BASE64) {
  2791. type = RSPAMD_DKIM_KEY_RAW;
  2792. tmp = g_malloc(len);
  2793. rspamd_cryptobox_base64_decode(key, len, tmp, &len);
  2794. key = tmp;
  2795. }
  2796. if (type == RSPAMD_DKIM_KEY_RAW && (len == 32 ||
  2797. len == rspamd_cryptobox_sk_sig_bytes(RSPAMD_CRYPTOBOX_MODE_25519))) {
  2798. if (len == 32) {
  2799. /* Seeded key, need scalarmult */
  2800. unsigned char pk[32];
  2801. nkey->type = RSPAMD_DKIM_KEY_EDDSA;
  2802. nkey->key.key_eddsa = g_malloc(
  2803. rspamd_cryptobox_sk_sig_bytes(RSPAMD_CRYPTOBOX_MODE_25519));
  2804. crypto_sign_ed25519_seed_keypair(pk, nkey->key.key_eddsa, key);
  2805. nkey->keylen = rspamd_cryptobox_sk_sig_bytes(RSPAMD_CRYPTOBOX_MODE_25519);
  2806. }
  2807. else {
  2808. /* Full ed25519 key */
  2809. unsigned klen = rspamd_cryptobox_sk_sig_bytes(RSPAMD_CRYPTOBOX_MODE_25519);
  2810. nkey->type = RSPAMD_DKIM_KEY_EDDSA;
  2811. nkey->key.key_eddsa = g_malloc(klen);
  2812. memcpy(nkey->key.key_eddsa, key, klen);
  2813. nkey->keylen = klen;
  2814. }
  2815. }
  2816. else {
  2817. nkey->key_bio = BIO_new_mem_buf(key, len);
  2818. if (type == RSPAMD_DKIM_KEY_RAW) {
  2819. if (d2i_PrivateKey_bio(nkey->key_bio, &nkey->key_evp) == NULL) {
  2820. g_set_error(err, dkim_error_quark(), DKIM_SIGERROR_KEYFAIL,
  2821. "cannot parse raw private key: %s",
  2822. ERR_error_string(ERR_get_error(), NULL));
  2823. rspamd_dkim_sign_key_free(nkey);
  2824. nkey = NULL;
  2825. goto end;
  2826. }
  2827. }
  2828. else {
  2829. if (!PEM_read_bio_PrivateKey(nkey->key_bio, &nkey->key_evp, NULL, NULL)) {
  2830. g_set_error(err, dkim_error_quark(), DKIM_SIGERROR_KEYFAIL,
  2831. "cannot parse pem private key: %s",
  2832. ERR_error_string(ERR_get_error(), NULL));
  2833. rspamd_dkim_sign_key_free(nkey);
  2834. nkey = NULL;
  2835. goto end;
  2836. }
  2837. }
  2838. nkey->key.key_rsa = EVP_PKEY_get1_RSA(nkey->key_evp);
  2839. if (nkey->key.key_rsa == NULL) {
  2840. g_set_error(err,
  2841. DKIM_ERROR,
  2842. DKIM_SIGERROR_KEYFAIL,
  2843. "cannot extract rsa key from evp key");
  2844. rspamd_dkim_sign_key_free(nkey);
  2845. nkey = NULL;
  2846. goto end;
  2847. }
  2848. nkey->type = RSPAMD_DKIM_KEY_RSA;
  2849. }
  2850. REF_INIT_RETAIN(nkey, rspamd_dkim_sign_key_free);
  2851. end:
  2852. if (map != NULL) {
  2853. munmap(map, maplen);
  2854. }
  2855. if (tmp != NULL) {
  2856. rspamd_explicit_memzero(tmp, len);
  2857. g_free(tmp);
  2858. }
  2859. return nkey;
  2860. }
  2861. #undef PEM_SIG
  2862. gboolean
  2863. rspamd_dkim_sign_key_maybe_invalidate(rspamd_dkim_sign_key_t *key, time_t mtime)
  2864. {
  2865. if (mtime > key->mtime) {
  2866. return TRUE;
  2867. }
  2868. return FALSE;
  2869. }
  2870. rspamd_dkim_sign_context_t *
  2871. rspamd_create_dkim_sign_context(struct rspamd_task *task,
  2872. rspamd_dkim_sign_key_t *priv_key,
  2873. int headers_canon,
  2874. int body_canon,
  2875. const char *headers,
  2876. enum rspamd_dkim_type type,
  2877. GError **err)
  2878. {
  2879. rspamd_dkim_sign_context_t *nctx;
  2880. if (headers_canon != DKIM_CANON_SIMPLE && headers_canon != DKIM_CANON_RELAXED) {
  2881. g_set_error(err,
  2882. DKIM_ERROR,
  2883. DKIM_SIGERROR_INVALID_HC,
  2884. "bad headers canonicalisation");
  2885. return NULL;
  2886. }
  2887. if (body_canon != DKIM_CANON_SIMPLE && body_canon != DKIM_CANON_RELAXED) {
  2888. g_set_error(err,
  2889. DKIM_ERROR,
  2890. DKIM_SIGERROR_INVALID_BC,
  2891. "bad body canonicalisation");
  2892. return NULL;
  2893. }
  2894. if (!priv_key || (!priv_key->key.key_rsa && !priv_key->key.key_eddsa)) {
  2895. g_set_error(err,
  2896. DKIM_ERROR,
  2897. DKIM_SIGERROR_KEYFAIL,
  2898. "bad key to sign");
  2899. return NULL;
  2900. }
  2901. nctx = rspamd_mempool_alloc0(task->task_pool, sizeof(*nctx));
  2902. nctx->common.pool = task->task_pool;
  2903. nctx->common.header_canon_type = headers_canon;
  2904. nctx->common.body_canon_type = body_canon;
  2905. nctx->common.type = type;
  2906. nctx->common.is_sign = TRUE;
  2907. if (type != RSPAMD_DKIM_ARC_SEAL) {
  2908. if (!rspamd_dkim_parse_hdrlist_common(&nctx->common, headers,
  2909. strlen(headers), TRUE,
  2910. err)) {
  2911. return NULL;
  2912. }
  2913. }
  2914. else {
  2915. rspamd_dkim_add_arc_seal_headers(task->task_pool, &nctx->common);
  2916. }
  2917. nctx->key = rspamd_dkim_sign_key_ref(priv_key);
  2918. rspamd_mempool_add_destructor(task->task_pool,
  2919. (rspamd_mempool_destruct_t) rspamd_dkim_sign_key_unref, priv_key);
  2920. #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
  2921. nctx->common.body_hash = EVP_MD_CTX_create();
  2922. EVP_DigestInit_ex(nctx->common.body_hash, EVP_sha256(), NULL);
  2923. nctx->common.headers_hash = EVP_MD_CTX_create();
  2924. EVP_DigestInit_ex(nctx->common.headers_hash, EVP_sha256(), NULL);
  2925. rspamd_mempool_add_destructor(task->task_pool,
  2926. (rspamd_mempool_destruct_t) EVP_MD_CTX_destroy, nctx->common.body_hash);
  2927. rspamd_mempool_add_destructor(task->task_pool,
  2928. (rspamd_mempool_destruct_t) EVP_MD_CTX_destroy, nctx->common.headers_hash);
  2929. #else
  2930. nctx->common.body_hash = EVP_MD_CTX_new();
  2931. EVP_DigestInit_ex(nctx->common.body_hash, EVP_sha256(), NULL);
  2932. nctx->common.headers_hash = EVP_MD_CTX_new();
  2933. EVP_DigestInit_ex(nctx->common.headers_hash, EVP_sha256(), NULL);
  2934. rspamd_mempool_add_destructor(task->task_pool,
  2935. (rspamd_mempool_destruct_t) EVP_MD_CTX_free, nctx->common.body_hash);
  2936. rspamd_mempool_add_destructor(task->task_pool,
  2937. (rspamd_mempool_destruct_t) EVP_MD_CTX_free, nctx->common.headers_hash);
  2938. #endif
  2939. return nctx;
  2940. }
  2941. GString *
  2942. rspamd_dkim_sign(struct rspamd_task *task, const char *selector,
  2943. const char *domain, time_t expire, gsize len, unsigned int idx,
  2944. const char *arc_cv, rspamd_dkim_sign_context_t *ctx)
  2945. {
  2946. GString *hdr;
  2947. struct rspamd_dkim_header *dh;
  2948. const char *body_end, *body_start, *hname;
  2949. unsigned char raw_digest[EVP_MAX_MD_SIZE];
  2950. struct rspamd_dkim_cached_hash *cached_bh = NULL;
  2951. gsize dlen = 0;
  2952. unsigned int i, j;
  2953. char *b64_data;
  2954. unsigned char *sig_buf;
  2955. unsigned int sig_len;
  2956. unsigned int headers_len = 0, cur_len = 0;
  2957. union rspamd_dkim_header_stat hstat;
  2958. g_assert(ctx != NULL);
  2959. /* First of all find place of body */
  2960. body_end = task->msg.begin + task->msg.len;
  2961. body_start = MESSAGE_FIELD(task, raw_headers_content).body_start;
  2962. if (len > 0) {
  2963. ctx->common.len = len;
  2964. }
  2965. if (!body_start) {
  2966. return NULL;
  2967. }
  2968. /* Start canonization of body part */
  2969. if (ctx->common.type != RSPAMD_DKIM_ARC_SEAL) {
  2970. dlen = EVP_MD_CTX_size(ctx->common.body_hash);
  2971. cached_bh = rspamd_dkim_check_bh_cached(&ctx->common, task,
  2972. dlen, TRUE);
  2973. if (!cached_bh->digest_normal) {
  2974. /* Start canonization of body part */
  2975. if (!rspamd_dkim_canonize_body(&ctx->common, body_start, body_end,
  2976. TRUE)) {
  2977. return NULL;
  2978. }
  2979. }
  2980. }
  2981. hdr = g_string_sized_new(255);
  2982. if (ctx->common.type == RSPAMD_DKIM_NORMAL) {
  2983. rspamd_printf_gstring(hdr, "v=1; a=%s; c=%s/%s; d=%s; s=%s; ",
  2984. ctx->key->type == RSPAMD_DKIM_KEY_RSA ? "rsa-sha256" : "ed25519-sha256",
  2985. ctx->common.header_canon_type == DKIM_CANON_RELAXED ? "relaxed" : "simple",
  2986. ctx->common.body_canon_type == DKIM_CANON_RELAXED ? "relaxed" : "simple",
  2987. domain, selector);
  2988. }
  2989. else if (ctx->common.type == RSPAMD_DKIM_ARC_SIG) {
  2990. rspamd_printf_gstring(hdr, "i=%d; a=%s; c=%s/%s; d=%s; s=%s; ",
  2991. idx,
  2992. ctx->key->type == RSPAMD_DKIM_KEY_RSA ? "rsa-sha256" : "ed25519-sha256",
  2993. ctx->common.header_canon_type == DKIM_CANON_RELAXED ? "relaxed" : "simple",
  2994. ctx->common.body_canon_type == DKIM_CANON_RELAXED ? "relaxed" : "simple",
  2995. domain, selector);
  2996. }
  2997. else {
  2998. g_assert(arc_cv != NULL);
  2999. rspamd_printf_gstring(hdr, "i=%d; a=%s; d=%s; s=%s; cv=%s; ",
  3000. idx,
  3001. ctx->key->type == RSPAMD_DKIM_KEY_RSA ? "rsa-sha256" : "ed25519-sha256",
  3002. domain,
  3003. selector,
  3004. arc_cv);
  3005. }
  3006. if (expire > 0) {
  3007. rspamd_printf_gstring(hdr, "x=%t; ", expire);
  3008. }
  3009. if (ctx->common.type != RSPAMD_DKIM_ARC_SEAL) {
  3010. if (len > 0) {
  3011. rspamd_printf_gstring(hdr, "l=%z; ", len);
  3012. }
  3013. }
  3014. rspamd_printf_gstring(hdr, "t=%t; h=", time(NULL));
  3015. /* Now canonize headers */
  3016. for (i = 0; i < ctx->common.hlist->len; i++) {
  3017. struct rspamd_mime_header *rh, *cur;
  3018. dh = g_ptr_array_index(ctx->common.hlist, i);
  3019. /* We allow oversigning if dh->count > number of headers with this name */
  3020. hstat.n = GPOINTER_TO_UINT(g_hash_table_lookup(ctx->common.htable, dh->name));
  3021. if (hstat.s.flags & RSPAMD_DKIM_FLAG_OVERSIGN) {
  3022. /* Do oversigning */
  3023. unsigned int count = 0;
  3024. rh = rspamd_message_get_header_array(task, dh->name, FALSE);
  3025. if (rh) {
  3026. DL_FOREACH(rh, cur)
  3027. {
  3028. /* Sign all existing headers */
  3029. rspamd_dkim_canonize_header(&ctx->common, task, dh->name,
  3030. count,
  3031. NULL, NULL);
  3032. count++;
  3033. }
  3034. }
  3035. /* Now add one more entry to oversign */
  3036. if (count > 0 || !(hstat.s.flags & RSPAMD_DKIM_FLAG_OVERSIGN_EXISTING)) {
  3037. cur_len = (strlen(dh->name) + 1) * (count + 1);
  3038. headers_len += cur_len;
  3039. if (headers_len > 70 && i > 0 && i < ctx->common.hlist->len - 1) {
  3040. rspamd_printf_gstring(hdr, " ");
  3041. headers_len = cur_len;
  3042. }
  3043. for (j = 0; j < count + 1; j++) {
  3044. rspamd_printf_gstring(hdr, "%s:", dh->name);
  3045. }
  3046. }
  3047. }
  3048. else {
  3049. rh = rspamd_message_get_header_array(task, dh->name, FALSE);
  3050. if (rh) {
  3051. if (hstat.s.count > 0) {
  3052. cur_len = (strlen(dh->name) + 1) * (hstat.s.count);
  3053. headers_len += cur_len;
  3054. if (headers_len > 70 && i > 0 && i < ctx->common.hlist->len - 1) {
  3055. rspamd_printf_gstring(hdr, " ");
  3056. headers_len = cur_len;
  3057. }
  3058. for (j = 0; j < hstat.s.count; j++) {
  3059. rspamd_printf_gstring(hdr, "%s:", dh->name);
  3060. }
  3061. }
  3062. rspamd_dkim_canonize_header(&ctx->common, task,
  3063. dh->name, dh->count,
  3064. NULL, NULL);
  3065. }
  3066. }
  3067. g_hash_table_remove(ctx->common.htable, dh->name);
  3068. }
  3069. /* Replace the last ':' with ';' */
  3070. hdr->str[hdr->len - 1] = ';';
  3071. if (ctx->common.type != RSPAMD_DKIM_ARC_SEAL) {
  3072. if (!cached_bh->digest_normal) {
  3073. EVP_DigestFinal_ex(ctx->common.body_hash, raw_digest, NULL);
  3074. cached_bh->digest_normal = rspamd_mempool_alloc(task->task_pool,
  3075. sizeof(raw_digest));
  3076. memcpy(cached_bh->digest_normal, raw_digest, sizeof(raw_digest));
  3077. }
  3078. b64_data = rspamd_encode_base64(cached_bh->digest_normal, dlen, 0, NULL);
  3079. rspamd_printf_gstring(hdr, " bh=%s; b=", b64_data);
  3080. g_free(b64_data);
  3081. }
  3082. else {
  3083. rspamd_printf_gstring(hdr, " b=");
  3084. }
  3085. switch (ctx->common.type) {
  3086. case RSPAMD_DKIM_NORMAL:
  3087. default:
  3088. hname = RSPAMD_DKIM_SIGNHEADER;
  3089. break;
  3090. case RSPAMD_DKIM_ARC_SIG:
  3091. hname = RSPAMD_DKIM_ARC_SIGNHEADER;
  3092. break;
  3093. case RSPAMD_DKIM_ARC_SEAL:
  3094. hname = RSPAMD_DKIM_ARC_SEALHEADER;
  3095. break;
  3096. }
  3097. if (ctx->common.header_canon_type == DKIM_CANON_RELAXED) {
  3098. if (!rspamd_dkim_canonize_header_relaxed(&ctx->common,
  3099. hdr->str,
  3100. hname,
  3101. TRUE,
  3102. 0,
  3103. ctx->common.type == RSPAMD_DKIM_ARC_SEAL)) {
  3104. g_string_free(hdr, TRUE);
  3105. return NULL;
  3106. }
  3107. }
  3108. else {
  3109. /* Will likely have issues with folding */
  3110. rspamd_dkim_hash_update(ctx->common.headers_hash, hdr->str,
  3111. hdr->len);
  3112. ctx->common.headers_canonicalised += hdr->len;
  3113. msg_debug_task("update signature with header: %*s",
  3114. (int) hdr->len, hdr->str);
  3115. }
  3116. dlen = EVP_MD_CTX_size(ctx->common.headers_hash);
  3117. EVP_DigestFinal_ex(ctx->common.headers_hash, raw_digest, NULL);
  3118. if (ctx->key->type == RSPAMD_DKIM_KEY_RSA) {
  3119. sig_len = RSA_size(ctx->key->key.key_rsa);
  3120. sig_buf = g_alloca(sig_len);
  3121. if (RSA_sign(NID_sha256, raw_digest, dlen, sig_buf, &sig_len,
  3122. ctx->key->key.key_rsa) != 1) {
  3123. g_string_free(hdr, TRUE);
  3124. msg_err_task("rsa sign error: %s",
  3125. ERR_error_string(ERR_get_error(), NULL));
  3126. return NULL;
  3127. }
  3128. }
  3129. else if (ctx->key->type == RSPAMD_DKIM_KEY_EDDSA) {
  3130. sig_len = rspamd_cryptobox_signature_bytes(RSPAMD_CRYPTOBOX_MODE_25519);
  3131. sig_buf = g_alloca(sig_len);
  3132. rspamd_cryptobox_sign(sig_buf, NULL, raw_digest, dlen,
  3133. ctx->key->key.key_eddsa, RSPAMD_CRYPTOBOX_MODE_25519);
  3134. }
  3135. else {
  3136. g_string_free(hdr, TRUE);
  3137. msg_err_task("unsupported key type for signing");
  3138. return NULL;
  3139. }
  3140. if (task->protocol_flags & RSPAMD_TASK_PROTOCOL_FLAG_MILTER) {
  3141. b64_data = rspamd_encode_base64_fold(sig_buf, sig_len, 70, NULL,
  3142. RSPAMD_TASK_NEWLINES_LF);
  3143. }
  3144. else {
  3145. b64_data = rspamd_encode_base64_fold(sig_buf, sig_len, 70, NULL,
  3146. MESSAGE_FIELD(task, nlines_type));
  3147. }
  3148. rspamd_printf_gstring(hdr, "%s", b64_data);
  3149. g_free(b64_data);
  3150. return hdr;
  3151. }
  3152. gboolean
  3153. rspamd_dkim_match_keys(rspamd_dkim_key_t *pk,
  3154. rspamd_dkim_sign_key_t *sk,
  3155. GError **err)
  3156. {
  3157. if (pk == NULL || sk == NULL) {
  3158. g_set_error(err, dkim_error_quark(), DKIM_SIGERROR_KEYFAIL,
  3159. "missing public or private key");
  3160. return FALSE;
  3161. }
  3162. if (pk->type != sk->type) {
  3163. g_set_error(err, dkim_error_quark(), DKIM_SIGERROR_KEYFAIL,
  3164. "public and private key types do not match");
  3165. return FALSE;
  3166. }
  3167. if (pk->type == RSPAMD_DKIM_KEY_EDDSA) {
  3168. if (memcmp(sk->key.key_eddsa + 32, pk->key.key_eddsa, 32) != 0) {
  3169. g_set_error(err, dkim_error_quark(), DKIM_SIGERROR_KEYHASHMISMATCH,
  3170. "pubkey does not match private key");
  3171. return FALSE;
  3172. }
  3173. }
  3174. else if (EVP_PKEY_cmp(pk->key_evp, sk->key_evp) != 1) {
  3175. g_set_error(err, dkim_error_quark(), DKIM_SIGERROR_KEYHASHMISMATCH,
  3176. "pubkey does not match private key");
  3177. return FALSE;
  3178. }
  3179. return TRUE;
  3180. }