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

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