Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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