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 81KB

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