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

fuzzy_storage.c 88KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287
  1. /*
  2. * Copyright 2023 Vsevolod Stakhov
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. /*
  17. * Rspamd fuzzy storage server
  18. */
  19. #include "config.h"
  20. #include "libserver/fuzzy_wire.h"
  21. #include "util.h"
  22. #include "rspamd.h"
  23. #include "libserver/maps/map.h"
  24. #include "libserver/maps/map_helpers.h"
  25. #include "libserver/fuzzy_backend/fuzzy_backend.h"
  26. #include "ottery.h"
  27. #include "ref.h"
  28. #include "xxhash.h"
  29. #include "libserver/worker_util.h"
  30. #include "libserver/rspamd_control.h"
  31. #include "libcryptobox/cryptobox.h"
  32. #include "libcryptobox/keypairs_cache.h"
  33. #include "libcryptobox/keypair.h"
  34. #include "libutil/hash.h"
  35. #include "libserver/maps/map_private.h"
  36. #include "contrib/uthash/utlist.h"
  37. #include "lua/lua_common.h"
  38. #include "unix-std.h"
  39. #include <math.h>
  40. /* Resync value in seconds */
  41. #define DEFAULT_SYNC_TIMEOUT 60.0
  42. #define DEFAULT_KEYPAIR_CACHE_SIZE 512
  43. #define DEFAULT_MASTER_TIMEOUT 10.0
  44. #define DEFAULT_UPDATES_MAXFAIL 3
  45. #define DEFAULT_MAX_BUCKETS 2000
  46. #define DEFAULT_BUCKET_TTL 3600
  47. #define DEFAULT_BUCKET_MASK 24
  48. /* Update stats on keys each 1 hour */
  49. #define KEY_STAT_INTERVAL 3600.0
  50. static const gchar *local_db_name = "local";
  51. /* Init functions */
  52. gpointer init_fuzzy(struct rspamd_config *cfg);
  53. void start_fuzzy(struct rspamd_worker *worker);
  54. worker_t fuzzy_worker = {
  55. "fuzzy", /* Name */
  56. init_fuzzy, /* Init function */
  57. start_fuzzy, /* Start function */
  58. RSPAMD_WORKER_HAS_SOCKET | RSPAMD_WORKER_NO_STRICT_CONFIG,
  59. RSPAMD_WORKER_SOCKET_UDP, /* UDP socket */
  60. RSPAMD_WORKER_VER /* Version info */
  61. };
  62. struct fuzzy_global_stat {
  63. guint64 fuzzy_hashes;
  64. /**< number of fuzzy hashes stored */
  65. guint64 fuzzy_hashes_expired;
  66. /**< number of fuzzy hashes expired */
  67. guint64 fuzzy_hashes_checked[RSPAMD_FUZZY_EPOCH_MAX];
  68. /**< amount of check requests for each epoch */
  69. guint64 fuzzy_shingles_checked[RSPAMD_FUZZY_EPOCH_MAX];
  70. /**< amount of shingle check requests for each epoch */
  71. guint64 fuzzy_hashes_found[RSPAMD_FUZZY_EPOCH_MAX];
  72. /**< amount of invalid requests */
  73. guint64 invalid_requests;
  74. /**< amount of delayed hashes found */
  75. guint64 delayed_hashes;
  76. };
  77. struct fuzzy_key_stat {
  78. guint64 checked;
  79. guint64 matched;
  80. guint64 added;
  81. guint64 deleted;
  82. guint64 errors;
  83. /* Store averages for checked/matched per minute */
  84. struct rspamd_counter_data checked_ctr;
  85. struct rspamd_counter_data matched_ctr;
  86. gdouble last_checked_time;
  87. guint64 last_checked_count;
  88. guint64 last_matched_count;
  89. struct rspamd_cryptobox_keypair *keypair;
  90. rspamd_lru_hash_t *last_ips;
  91. ref_entry_t ref;
  92. };
  93. struct rspamd_leaky_bucket_elt {
  94. rspamd_inet_addr_t *addr;
  95. gdouble last;
  96. gdouble cur;
  97. };
  98. static const guint64 rspamd_fuzzy_storage_magic = 0x291a3253eb1b3ea5ULL;
  99. KHASH_SET_INIT_INT(fuzzy_key_ids_set);
  100. struct rspamd_fuzzy_storage_ctx {
  101. guint64 magic;
  102. /* Events base */
  103. struct ev_loop *event_loop;
  104. /* DNS resolver */
  105. struct rspamd_dns_resolver *resolver;
  106. /* Config */
  107. struct rspamd_config *cfg;
  108. /* END OF COMMON PART */
  109. struct fuzzy_global_stat stat;
  110. gdouble expire;
  111. gdouble sync_timeout;
  112. gdouble delay;
  113. struct rspamd_radix_map_helper *update_ips;
  114. struct rspamd_hash_map_helper *update_keys;
  115. struct rspamd_radix_map_helper *blocked_ips;
  116. struct rspamd_radix_map_helper *ratelimit_whitelist;
  117. struct rspamd_radix_map_helper *delay_whitelist;
  118. const ucl_object_t *update_map;
  119. const ucl_object_t *update_keys_map;
  120. const ucl_object_t *delay_whitelist_map;
  121. const ucl_object_t *blocked_map;
  122. const ucl_object_t *ratelimit_whitelist_map;
  123. guint keypair_cache_size;
  124. ev_timer stat_ev;
  125. ev_io peer_ev;
  126. /* Local keypair */
  127. struct rspamd_cryptobox_keypair *default_keypair; /* Bad clash, need for parse keypair */
  128. struct fuzzy_key *default_key;
  129. GHashTable *keys;
  130. gboolean encrypted_only;
  131. gboolean read_only;
  132. gboolean dedicated_update_worker;
  133. struct rspamd_keypair_cache *keypair_cache;
  134. struct rspamd_http_context *http_ctx;
  135. rspamd_lru_hash_t *errors_ips;
  136. rspamd_lru_hash_t *ratelimit_buckets;
  137. struct rspamd_fuzzy_backend *backend;
  138. GArray *updates_pending;
  139. guint updates_failed;
  140. guint updates_maxfail;
  141. /* Used to send data between workers */
  142. gint peer_fd;
  143. /* Ratelimits */
  144. guint leaky_bucket_ttl;
  145. guint leaky_bucket_mask;
  146. guint max_buckets;
  147. gboolean ratelimit_log_only;
  148. gdouble leaky_bucket_burst;
  149. gdouble leaky_bucket_rate;
  150. struct rspamd_worker *worker;
  151. const ucl_object_t *skip_map;
  152. struct rspamd_hash_map_helper *skip_hashes;
  153. gint lua_pre_handler_cbref;
  154. gint lua_post_handler_cbref;
  155. gint lua_blacklist_cbref;
  156. khash_t(fuzzy_key_ids_set) * default_forbidden_ids;
  157. /* Ids that should not override other ids */
  158. khash_t(fuzzy_key_ids_set) * weak_ids;
  159. };
  160. enum fuzzy_cmd_type {
  161. CMD_NORMAL,
  162. CMD_SHINGLE,
  163. CMD_ENCRYPTED_NORMAL,
  164. CMD_ENCRYPTED_SHINGLE
  165. };
  166. struct fuzzy_session {
  167. struct rspamd_worker *worker;
  168. rspamd_inet_addr_t *addr;
  169. struct rspamd_fuzzy_storage_ctx *ctx;
  170. struct rspamd_fuzzy_shingle_cmd cmd; /* Can handle both shingles and non-shingles */
  171. struct rspamd_fuzzy_encrypted_reply reply; /* Again: contains everything */
  172. struct fuzzy_key_stat *ip_stat;
  173. enum rspamd_fuzzy_epoch epoch;
  174. enum fuzzy_cmd_type cmd_type;
  175. gint fd;
  176. ev_tstamp timestamp;
  177. struct ev_io io;
  178. ref_entry_t ref;
  179. struct fuzzy_key *key;
  180. struct rspamd_fuzzy_cmd_extension *extensions;
  181. guchar nm[rspamd_cryptobox_MAX_NMBYTES];
  182. };
  183. struct fuzzy_peer_request {
  184. ev_io io_ev;
  185. struct fuzzy_peer_cmd cmd;
  186. };
  187. KHASH_INIT(fuzzy_key_flag_stat, int, struct fuzzy_key_stat, 1, kh_int_hash_func,
  188. kh_int_hash_equal);
  189. struct fuzzy_key {
  190. struct rspamd_cryptobox_keypair *key;
  191. struct rspamd_cryptobox_pubkey *pk;
  192. struct fuzzy_key_stat *stat;
  193. khash_t(fuzzy_key_flag_stat) * flags_stat;
  194. khash_t(fuzzy_key_ids_set) * forbidden_ids;
  195. };
  196. struct rspamd_updates_cbdata {
  197. GArray *updates_pending;
  198. struct rspamd_fuzzy_storage_ctx *ctx;
  199. gchar *source;
  200. gboolean final;
  201. };
  202. static void rspamd_fuzzy_write_reply(struct fuzzy_session *session);
  203. static gboolean rspamd_fuzzy_process_updates_queue(struct rspamd_fuzzy_storage_ctx *ctx,
  204. const gchar *source, gboolean final);
  205. static gboolean rspamd_fuzzy_check_client(struct rspamd_fuzzy_storage_ctx *ctx,
  206. rspamd_inet_addr_t *addr);
  207. static void rspamd_fuzzy_maybe_call_blacklisted(struct rspamd_fuzzy_storage_ctx *ctx,
  208. rspamd_inet_addr_t *addr,
  209. const gchar *reason);
  210. static gboolean
  211. rspamd_fuzzy_check_ratelimit(struct fuzzy_session *session)
  212. {
  213. rspamd_inet_addr_t *masked;
  214. struct rspamd_leaky_bucket_elt *elt;
  215. if (!session->addr) {
  216. return TRUE;
  217. }
  218. if (session->ctx->ratelimit_whitelist != NULL) {
  219. if (rspamd_match_radix_map_addr(session->ctx->ratelimit_whitelist,
  220. session->addr) != NULL) {
  221. return TRUE;
  222. }
  223. }
  224. /*
  225. if (rspamd_inet_address_is_local (session->addr, TRUE)) {
  226. return TRUE;
  227. }
  228. */
  229. masked = rspamd_inet_address_copy(session->addr, NULL);
  230. if (rspamd_inet_address_get_af(masked) == AF_INET) {
  231. rspamd_inet_address_apply_mask(masked,
  232. MIN(session->ctx->leaky_bucket_mask, 32));
  233. }
  234. else {
  235. /* Must be at least /64 */
  236. rspamd_inet_address_apply_mask(masked,
  237. MIN(MAX(session->ctx->leaky_bucket_mask * 4, 64), 128));
  238. }
  239. elt = rspamd_lru_hash_lookup(session->ctx->ratelimit_buckets, masked,
  240. (time_t) session->timestamp);
  241. if (elt) {
  242. gboolean ratelimited = FALSE, new_ratelimit = FALSE;
  243. if (isnan(elt->cur)) {
  244. /* There is an issue with the previous logic: the TTL is updated each time
  245. * we see that new bucket. Hence, we need to check the `last` and act accordingly
  246. */
  247. if (elt->last < session->timestamp && session->timestamp - elt->last >= session->ctx->leaky_bucket_ttl) {
  248. /*
  249. * We reset bucket to it's 90% capacity to allow some requests
  250. * This should cope with the issue when we block an IP network for some burst and never unblock it
  251. */
  252. elt->cur = session->ctx->leaky_bucket_burst * 0.9;
  253. elt->last = session->timestamp;
  254. }
  255. else {
  256. ratelimited = TRUE;
  257. }
  258. }
  259. else {
  260. /* Update bucket: leak some elements */
  261. if (elt->last < session->timestamp) {
  262. elt->cur -= session->ctx->leaky_bucket_rate * (session->timestamp - elt->last);
  263. elt->last = session->timestamp;
  264. if (elt->cur < 0) {
  265. elt->cur = 0;
  266. }
  267. }
  268. else {
  269. elt->last = session->timestamp;
  270. }
  271. /* Check the bucket */
  272. if (elt->cur >= session->ctx->leaky_bucket_burst) {
  273. msg_info("ratelimiting %s (%s), %.1f max elts",
  274. rspamd_inet_address_to_string(session->addr),
  275. rspamd_inet_address_to_string(masked),
  276. session->ctx->leaky_bucket_burst);
  277. elt->cur = NAN;
  278. new_ratelimit = TRUE;
  279. ratelimited = TRUE;
  280. }
  281. else {
  282. elt->cur++; /* Allow one more request */
  283. }
  284. }
  285. if (ratelimited) {
  286. rspamd_fuzzy_maybe_call_blacklisted(session->ctx, session->addr, "ratelimit");
  287. }
  288. if (new_ratelimit) {
  289. struct rspamd_srv_command srv_cmd;
  290. srv_cmd.type = RSPAMD_SRV_FUZZY_BLOCKED;
  291. srv_cmd.cmd.fuzzy_blocked.af = rspamd_inet_address_get_af(masked);
  292. if (srv_cmd.cmd.fuzzy_blocked.af == AF_INET || srv_cmd.cmd.fuzzy_blocked.af == AF_INET6) {
  293. socklen_t slen;
  294. struct sockaddr *sa = rspamd_inet_address_get_sa(masked, &slen);
  295. if (slen <= sizeof(srv_cmd.cmd.fuzzy_blocked.addr)) {
  296. memcpy(&srv_cmd.cmd.fuzzy_blocked.addr, sa, slen);
  297. msg_debug("propagating blocked address to other workers");
  298. rspamd_srv_send_command(session->worker, session->ctx->event_loop, &srv_cmd, -1, NULL, NULL);
  299. }
  300. else {
  301. msg_err("bad address length: %d, expected to be %d", (int) slen, (int) sizeof(srv_cmd.cmd.fuzzy_blocked.addr));
  302. }
  303. }
  304. }
  305. rspamd_inet_address_free(masked);
  306. return !ratelimited;
  307. }
  308. else {
  309. /* New bucket */
  310. elt = g_malloc(sizeof(*elt));
  311. elt->addr = masked; /* transfer ownership */
  312. elt->cur = 1;
  313. elt->last = session->timestamp;
  314. rspamd_lru_hash_insert(session->ctx->ratelimit_buckets,
  315. masked,
  316. elt,
  317. session->timestamp,
  318. session->ctx->leaky_bucket_ttl);
  319. }
  320. return TRUE;
  321. }
  322. static void
  323. rspamd_fuzzy_maybe_call_blacklisted(struct rspamd_fuzzy_storage_ctx *ctx,
  324. rspamd_inet_addr_t *addr,
  325. const gchar *reason)
  326. {
  327. if (ctx->lua_blacklist_cbref != -1) {
  328. lua_State *L = ctx->cfg->lua_state;
  329. gint err_idx, ret;
  330. lua_pushcfunction(L, &rspamd_lua_traceback);
  331. err_idx = lua_gettop(L);
  332. lua_rawgeti(L, LUA_REGISTRYINDEX, ctx->lua_blacklist_cbref);
  333. /* client IP */
  334. rspamd_lua_ip_push(L, addr);
  335. /* block reason */
  336. lua_pushstring(L, reason);
  337. if ((ret = lua_pcall(L, 2, 0, err_idx)) != 0) {
  338. msg_err("call to lua_blacklist_cbref "
  339. "script failed (%d): %s",
  340. ret, lua_tostring(L, -1));
  341. }
  342. lua_settop(L, 0);
  343. }
  344. }
  345. static gboolean
  346. rspamd_fuzzy_check_client(struct rspamd_fuzzy_storage_ctx *ctx,
  347. rspamd_inet_addr_t *addr)
  348. {
  349. if (ctx->blocked_ips != NULL) {
  350. if (rspamd_match_radix_map_addr(ctx->blocked_ips,
  351. addr) != NULL) {
  352. rspamd_fuzzy_maybe_call_blacklisted(ctx, addr, "blacklisted");
  353. return FALSE;
  354. }
  355. }
  356. return TRUE;
  357. }
  358. static gboolean
  359. rspamd_fuzzy_check_write(struct fuzzy_session *session)
  360. {
  361. if (session->ctx->read_only) {
  362. return FALSE;
  363. }
  364. if (session->ctx->update_ips != NULL && session->addr) {
  365. if (rspamd_inet_address_get_af(session->addr) == AF_UNIX) {
  366. return TRUE;
  367. }
  368. if (rspamd_match_radix_map_addr(session->ctx->update_ips,
  369. session->addr) == NULL) {
  370. return FALSE;
  371. }
  372. else {
  373. return TRUE;
  374. }
  375. }
  376. if (session->ctx->update_keys != NULL && session->key->stat && session->key->key) {
  377. static gchar base32_buf[rspamd_cryptobox_HASHBYTES * 2 + 1];
  378. guint raw_len;
  379. const guchar *pk_raw = rspamd_keypair_component(session->key->key,
  380. RSPAMD_KEYPAIR_COMPONENT_ID, &raw_len);
  381. gint encoded_len = rspamd_encode_base32_buf(pk_raw, raw_len,
  382. base32_buf, sizeof(base32_buf),
  383. RSPAMD_BASE32_DEFAULT);
  384. if (rspamd_match_hash_map(session->ctx->update_keys, base32_buf, encoded_len)) {
  385. return TRUE;
  386. }
  387. }
  388. return FALSE;
  389. }
  390. static void
  391. fuzzy_key_stat_dtor(gpointer p)
  392. {
  393. struct fuzzy_key_stat *st = p;
  394. if (st->last_ips) {
  395. rspamd_lru_hash_destroy(st->last_ips);
  396. }
  397. if (st->keypair) {
  398. rspamd_keypair_unref(st->keypair);
  399. }
  400. g_free(st);
  401. }
  402. static void
  403. fuzzy_key_stat_unref(gpointer p)
  404. {
  405. struct fuzzy_key_stat *st = p;
  406. REF_RELEASE(st);
  407. }
  408. static void
  409. fuzzy_key_dtor(gpointer p)
  410. {
  411. struct fuzzy_key *key = p;
  412. if (key) {
  413. if (key->stat) {
  414. REF_RELEASE(key->stat);
  415. }
  416. if (key->flags_stat) {
  417. kh_destroy(fuzzy_key_flag_stat, key->flags_stat);
  418. }
  419. if (key->forbidden_ids) {
  420. kh_destroy(fuzzy_key_ids_set, key->forbidden_ids);
  421. }
  422. g_free(key);
  423. }
  424. }
  425. static void
  426. fuzzy_count_callback(guint64 count, void *ud)
  427. {
  428. struct rspamd_fuzzy_storage_ctx *ctx = ud;
  429. ctx->stat.fuzzy_hashes = count;
  430. }
  431. static void
  432. fuzzy_rl_bucket_free(gpointer p)
  433. {
  434. struct rspamd_leaky_bucket_elt *elt = (struct rspamd_leaky_bucket_elt *) p;
  435. rspamd_inet_address_free(elt->addr);
  436. g_free(elt);
  437. }
  438. static void
  439. fuzzy_stat_count_callback(guint64 count, void *ud)
  440. {
  441. struct rspamd_fuzzy_storage_ctx *ctx = ud;
  442. ev_timer_again(ctx->event_loop, &ctx->stat_ev);
  443. ctx->stat.fuzzy_hashes = count;
  444. }
  445. static void
  446. rspamd_fuzzy_stat_callback(EV_P_ ev_timer *w, int revents)
  447. {
  448. struct rspamd_fuzzy_storage_ctx *ctx =
  449. (struct rspamd_fuzzy_storage_ctx *) w->data;
  450. rspamd_fuzzy_backend_count(ctx->backend, fuzzy_stat_count_callback, ctx);
  451. }
  452. static void
  453. fuzzy_update_version_callback(guint64 ver, void *ud)
  454. {
  455. }
  456. static void
  457. rspamd_fuzzy_updates_cb(gboolean success,
  458. guint nadded,
  459. guint ndeleted,
  460. guint nextended,
  461. guint nignored,
  462. void *ud)
  463. {
  464. struct rspamd_updates_cbdata *cbdata = ud;
  465. struct rspamd_fuzzy_storage_ctx *ctx;
  466. const gchar *source;
  467. ctx = cbdata->ctx;
  468. source = cbdata->source;
  469. if (success) {
  470. rspamd_fuzzy_backend_count(ctx->backend, fuzzy_count_callback, ctx);
  471. msg_info("successfully updated fuzzy storage %s: %d updates in queue; "
  472. "%d pending currently; "
  473. "%d added; %d deleted; %d extended; %d duplicates",
  474. ctx->worker->cf->bind_conf ? ctx->worker->cf->bind_conf->bind_line : "unknown",
  475. cbdata->updates_pending->len,
  476. ctx->updates_pending->len,
  477. nadded, ndeleted, nextended, nignored);
  478. rspamd_fuzzy_backend_version(ctx->backend, source,
  479. fuzzy_update_version_callback, NULL);
  480. ctx->updates_failed = 0;
  481. if (cbdata->final || ctx->worker->state != rspamd_worker_state_running) {
  482. /* Plan exit */
  483. ev_break(ctx->event_loop, EVBREAK_ALL);
  484. }
  485. }
  486. else {
  487. if (++ctx->updates_failed > ctx->updates_maxfail) {
  488. msg_err("cannot commit update transaction to fuzzy backend %s, discard "
  489. "%ud updates after %d retries",
  490. ctx->worker->cf->bind_conf ? ctx->worker->cf->bind_conf->bind_line : "unknown",
  491. cbdata->updates_pending->len,
  492. ctx->updates_maxfail);
  493. ctx->updates_failed = 0;
  494. if (cbdata->final || ctx->worker->state != rspamd_worker_state_running) {
  495. /* Plan exit */
  496. ev_break(ctx->event_loop, EVBREAK_ALL);
  497. }
  498. }
  499. else {
  500. if (ctx->updates_pending) {
  501. msg_err("cannot commit update transaction to fuzzy backend %s; "
  502. "%ud updates are still left; %ud currently pending;"
  503. " %d retries remaining",
  504. ctx->worker->cf->bind_conf ? ctx->worker->cf->bind_conf->bind_line : "unknown",
  505. cbdata->updates_pending->len,
  506. ctx->updates_pending->len,
  507. ctx->updates_maxfail - ctx->updates_failed);
  508. /* Move the remaining updates to ctx queue */
  509. g_array_append_vals(ctx->updates_pending,
  510. cbdata->updates_pending->data,
  511. cbdata->updates_pending->len);
  512. if (cbdata->final) {
  513. /* Try one more time */
  514. rspamd_fuzzy_process_updates_queue(cbdata->ctx, cbdata->source,
  515. cbdata->final);
  516. }
  517. }
  518. else {
  519. /* We have lost our ctx, so it is a race condition case */
  520. msg_err("cannot commit update transaction to fuzzy backend %s; "
  521. "%ud updates are still left; no more retries: a worker is terminated",
  522. ctx->worker->cf->bind_conf ? ctx->worker->cf->bind_conf->bind_line : "unknown",
  523. cbdata->updates_pending->len);
  524. }
  525. }
  526. }
  527. g_array_free(cbdata->updates_pending, TRUE);
  528. g_free(cbdata->source);
  529. g_free(cbdata);
  530. }
  531. static gboolean
  532. rspamd_fuzzy_process_updates_queue(struct rspamd_fuzzy_storage_ctx *ctx,
  533. const gchar *source, gboolean final)
  534. {
  535. struct rspamd_updates_cbdata *cbdata;
  536. if (ctx->updates_pending->len > 0) {
  537. cbdata = g_malloc(sizeof(*cbdata));
  538. cbdata->ctx = ctx;
  539. cbdata->final = final;
  540. cbdata->updates_pending = ctx->updates_pending;
  541. ctx->updates_pending = g_array_sized_new(FALSE, FALSE,
  542. sizeof(struct fuzzy_peer_cmd),
  543. MAX(cbdata->updates_pending->len, 1024));
  544. cbdata->source = g_strdup(source);
  545. rspamd_fuzzy_backend_process_updates(ctx->backend,
  546. cbdata->updates_pending,
  547. source, rspamd_fuzzy_updates_cb, cbdata);
  548. return TRUE;
  549. }
  550. else if (final) {
  551. /* No need to sync */
  552. ev_break(ctx->event_loop, EVBREAK_ALL);
  553. }
  554. return FALSE;
  555. }
  556. static void
  557. rspamd_fuzzy_reply_io(EV_P_ ev_io *w, int revents)
  558. {
  559. struct fuzzy_session *session = (struct fuzzy_session *) w->data;
  560. ev_io_stop(EV_A_ w);
  561. rspamd_fuzzy_write_reply(session);
  562. REF_RELEASE(session);
  563. }
  564. static void
  565. rspamd_fuzzy_write_reply(struct fuzzy_session *session)
  566. {
  567. gssize r;
  568. gsize len;
  569. gconstpointer data;
  570. if (session->cmd_type == CMD_ENCRYPTED_NORMAL ||
  571. session->cmd_type == CMD_ENCRYPTED_SHINGLE) {
  572. /* Encrypted reply */
  573. data = &session->reply;
  574. if (session->epoch > RSPAMD_FUZZY_EPOCH10) {
  575. len = sizeof(session->reply);
  576. }
  577. else {
  578. len = sizeof(session->reply.hdr) + sizeof(session->reply.rep.v1);
  579. }
  580. }
  581. else {
  582. data = &session->reply.rep;
  583. if (session->epoch > RSPAMD_FUZZY_EPOCH10) {
  584. len = sizeof(session->reply.rep);
  585. }
  586. else {
  587. len = sizeof(session->reply.rep.v1);
  588. }
  589. }
  590. r = rspamd_inet_address_sendto(session->fd, data, len, 0,
  591. session->addr);
  592. if (r == -1) {
  593. if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN) {
  594. /* Grab reference to avoid early destruction */
  595. REF_RETAIN(session);
  596. session->io.data = session;
  597. ev_io_init(&session->io,
  598. rspamd_fuzzy_reply_io, session->fd, EV_WRITE);
  599. ev_io_start(session->ctx->event_loop, &session->io);
  600. }
  601. else {
  602. msg_err("error while writing reply: %s", strerror(errno));
  603. }
  604. }
  605. }
  606. static void
  607. rspamd_fuzzy_update_key_stat(gboolean matched,
  608. struct fuzzy_key_stat *key_stat,
  609. guint cmd,
  610. struct rspamd_fuzzy_reply *res,
  611. ev_tstamp timestamp)
  612. {
  613. if (!matched && res->v1.value != 0) {
  614. key_stat->errors++;
  615. }
  616. else {
  617. if (cmd == FUZZY_CHECK) {
  618. key_stat->checked++;
  619. if (matched) {
  620. key_stat->matched++;
  621. }
  622. if (G_UNLIKELY(key_stat->last_checked_time == 0.0)) {
  623. key_stat->last_checked_time = timestamp;
  624. key_stat->last_checked_count = key_stat->checked;
  625. key_stat->last_matched_count = key_stat->matched;
  626. }
  627. else if (G_UNLIKELY(timestamp > key_stat->last_checked_time + KEY_STAT_INTERVAL)) {
  628. guint64 nchecked = key_stat->checked - key_stat->last_checked_count;
  629. guint64 nmatched = key_stat->matched - key_stat->last_matched_count;
  630. rspamd_set_counter_ema(&key_stat->checked_ctr, nchecked, 0.5f);
  631. rspamd_set_counter_ema(&key_stat->matched_ctr, nmatched, 0.5f);
  632. key_stat->last_checked_time = timestamp;
  633. key_stat->last_checked_count = key_stat->checked;
  634. key_stat->last_matched_count = key_stat->matched;
  635. }
  636. }
  637. else if (cmd == FUZZY_WRITE) {
  638. key_stat->added++;
  639. }
  640. else if (cmd == FUZZY_DEL) {
  641. key_stat->deleted++;
  642. }
  643. }
  644. }
  645. static void
  646. rspamd_fuzzy_update_stats(struct rspamd_fuzzy_storage_ctx *ctx,
  647. enum rspamd_fuzzy_epoch epoch,
  648. gboolean matched,
  649. gboolean is_shingle,
  650. gboolean is_delayed,
  651. struct fuzzy_key *key,
  652. struct fuzzy_key_stat *ip_stat,
  653. guint cmd,
  654. struct rspamd_fuzzy_reply *res,
  655. ev_tstamp timestamp)
  656. {
  657. ctx->stat.fuzzy_hashes_checked[epoch]++;
  658. if (matched) {
  659. ctx->stat.fuzzy_hashes_found[epoch]++;
  660. }
  661. if (is_shingle) {
  662. ctx->stat.fuzzy_shingles_checked[epoch]++;
  663. }
  664. if (is_delayed) {
  665. ctx->stat.delayed_hashes++;
  666. }
  667. if (key) {
  668. rspamd_fuzzy_update_key_stat(matched, key->stat, cmd, res, timestamp);
  669. if (matched || ((cmd == FUZZY_WRITE || cmd == FUZZY_DEL) && res->v1.value == 0)) {
  670. /* Update per flag stats */
  671. khiter_t k;
  672. struct fuzzy_key_stat *flag_stat;
  673. k = kh_get(fuzzy_key_flag_stat, key->flags_stat, res->v1.flag);
  674. if (k == kh_end(key->flags_stat)) {
  675. /* Insert new flag */
  676. int r;
  677. k = kh_put(fuzzy_key_flag_stat, key->flags_stat, res->v1.flag, &r);
  678. memset(&kh_value(key->flags_stat, k), 0, sizeof(struct fuzzy_key_stat));
  679. }
  680. flag_stat = &kh_value(key->flags_stat, k);
  681. rspamd_fuzzy_update_key_stat(matched, flag_stat, cmd, res, timestamp);
  682. }
  683. }
  684. if (ip_stat) {
  685. if (!matched && res->v1.value != 0) {
  686. ip_stat->errors++;
  687. }
  688. else {
  689. if (cmd == FUZZY_CHECK) {
  690. ip_stat->checked++;
  691. if (matched) {
  692. ip_stat->matched++;
  693. }
  694. }
  695. else if (cmd == FUZZY_WRITE) {
  696. ip_stat->added++;
  697. }
  698. else if (cmd == FUZZY_DEL) {
  699. ip_stat->deleted++;
  700. }
  701. }
  702. }
  703. }
  704. enum rspamd_fuzzy_reply_flags {
  705. RSPAMD_FUZZY_REPLY_ENCRYPTED = 0x1u << 0u,
  706. RSPAMD_FUZZY_REPLY_SHINGLE = 0x1u << 1u,
  707. RSPAMD_FUZZY_REPLY_DELAY = 0x1u << 2u,
  708. };
  709. static void
  710. rspamd_fuzzy_make_reply(struct rspamd_fuzzy_cmd *cmd,
  711. struct rspamd_fuzzy_reply *result,
  712. struct fuzzy_session *session,
  713. gint flags)
  714. {
  715. gsize len;
  716. if (cmd) {
  717. result->v1.tag = cmd->tag;
  718. memcpy(&session->reply.rep, result, sizeof(*result));
  719. if (flags & RSPAMD_FUZZY_REPLY_DELAY) {
  720. /* Hash is too fresh, need to delay it */
  721. session->reply.rep.ts = 0;
  722. session->reply.rep.v1.prob = 0.0f;
  723. session->reply.rep.v1.value = 0;
  724. }
  725. bool default_disabled = false;
  726. {
  727. khiter_t k;
  728. k = kh_get(fuzzy_key_ids_set, session->ctx->default_forbidden_ids, session->reply.rep.v1.flag);
  729. if (k != kh_end(session->ctx->default_forbidden_ids)) {
  730. /* Hash is from a forbidden flag by default */
  731. default_disabled = true;
  732. }
  733. }
  734. if (flags & RSPAMD_FUZZY_REPLY_ENCRYPTED) {
  735. if (session->reply.rep.v1.prob > 0 && session->key && session->key->forbidden_ids) {
  736. khiter_t k;
  737. k = kh_get(fuzzy_key_ids_set, session->key->forbidden_ids, session->reply.rep.v1.flag);
  738. if (k != kh_end(session->key->forbidden_ids)) {
  739. /* Hash is from a forbidden flag for this key */
  740. session->reply.rep.ts = 0;
  741. session->reply.rep.v1.prob = 0.0f;
  742. session->reply.rep.v1.value = 0;
  743. session->reply.rep.v1.flag = 0;
  744. }
  745. }
  746. else if (default_disabled) {
  747. /* Hash is from a forbidden flag by default */
  748. session->reply.rep.ts = 0;
  749. session->reply.rep.v1.prob = 0.0f;
  750. session->reply.rep.v1.value = 0;
  751. session->reply.rep.v1.flag = 0;
  752. }
  753. /* We need also to encrypt reply */
  754. ottery_rand_bytes(session->reply.hdr.nonce,
  755. sizeof(session->reply.hdr.nonce));
  756. /*
  757. * For old replies we need to encrypt just old part, otherwise
  758. * decryption would fail due to mac verification mistake
  759. */
  760. if (session->epoch > RSPAMD_FUZZY_EPOCH10) {
  761. len = sizeof(session->reply.rep);
  762. }
  763. else {
  764. len = sizeof(session->reply.rep.v1);
  765. }
  766. /* Update stats before encryption */
  767. if (cmd->cmd != FUZZY_STAT && cmd->cmd <= FUZZY_CLIENT_MAX) {
  768. rspamd_fuzzy_update_stats(session->ctx,
  769. session->epoch,
  770. session->reply.rep.v1.prob > 0.5f,
  771. flags & RSPAMD_FUZZY_REPLY_SHINGLE,
  772. flags & RSPAMD_FUZZY_REPLY_DELAY,
  773. session->key,
  774. session->ip_stat,
  775. cmd->cmd,
  776. &session->reply.rep,
  777. session->timestamp);
  778. }
  779. rspamd_cryptobox_encrypt_nm_inplace((guchar *) &session->reply.rep,
  780. len,
  781. session->reply.hdr.nonce,
  782. session->nm,
  783. session->reply.hdr.mac,
  784. RSPAMD_CRYPTOBOX_MODE_25519);
  785. }
  786. else if (default_disabled) {
  787. /* Hash is from a forbidden flag by default, and there is no encryption override */
  788. session->reply.rep.ts = 0;
  789. session->reply.rep.v1.prob = 0.0f;
  790. session->reply.rep.v1.value = 0;
  791. session->reply.rep.v1.flag = 0;
  792. }
  793. if (!(flags & RSPAMD_FUZZY_REPLY_ENCRYPTED)) {
  794. if (cmd->cmd != FUZZY_STAT && cmd->cmd <= FUZZY_CLIENT_MAX) {
  795. rspamd_fuzzy_update_stats(session->ctx,
  796. session->epoch,
  797. session->reply.rep.v1.prob > 0.5f,
  798. flags & RSPAMD_FUZZY_REPLY_SHINGLE,
  799. flags & RSPAMD_FUZZY_REPLY_DELAY,
  800. session->key,
  801. session->ip_stat,
  802. cmd->cmd,
  803. &session->reply.rep,
  804. session->timestamp);
  805. }
  806. }
  807. }
  808. rspamd_fuzzy_write_reply(session);
  809. }
  810. static gboolean
  811. fuzzy_peer_try_send(gint fd, struct fuzzy_peer_request *up_req)
  812. {
  813. gssize r;
  814. r = write(fd, &up_req->cmd, sizeof(up_req->cmd));
  815. if (r != sizeof(up_req->cmd)) {
  816. return FALSE;
  817. }
  818. return TRUE;
  819. }
  820. static void
  821. fuzzy_peer_send_io(EV_P_ ev_io *w, int revents)
  822. {
  823. struct fuzzy_peer_request *up_req = (struct fuzzy_peer_request *) w->data;
  824. if (!fuzzy_peer_try_send(w->fd, up_req)) {
  825. msg_err("cannot send update request to the peer: %s", strerror(errno));
  826. }
  827. ev_io_stop(EV_A_ w);
  828. g_free(up_req);
  829. }
  830. static void
  831. rspamd_fuzzy_extensions_tolua(lua_State *L,
  832. struct fuzzy_session *session)
  833. {
  834. struct rspamd_fuzzy_cmd_extension *ext;
  835. rspamd_inet_addr_t *addr;
  836. lua_createtable(L, 0, 0);
  837. LL_FOREACH(session->extensions, ext)
  838. {
  839. switch (ext->ext) {
  840. case RSPAMD_FUZZY_EXT_SOURCE_DOMAIN:
  841. lua_pushlstring(L, ext->payload, ext->length);
  842. lua_setfield(L, -2, "domain");
  843. break;
  844. case RSPAMD_FUZZY_EXT_SOURCE_IP4:
  845. addr = rspamd_inet_address_new(AF_INET, ext->payload);
  846. rspamd_lua_ip_push(L, addr);
  847. rspamd_inet_address_free(addr);
  848. lua_setfield(L, -2, "ip");
  849. break;
  850. case RSPAMD_FUZZY_EXT_SOURCE_IP6:
  851. addr = rspamd_inet_address_new(AF_INET6, ext->payload);
  852. rspamd_lua_ip_push(L, addr);
  853. rspamd_inet_address_free(addr);
  854. lua_setfield(L, -2, "ip");
  855. break;
  856. }
  857. }
  858. }
  859. static void
  860. rspamd_fuzzy_check_callback(struct rspamd_fuzzy_reply *result, void *ud)
  861. {
  862. struct fuzzy_session *session = ud;
  863. gboolean is_shingle = FALSE, __attribute__((unused)) encrypted = FALSE;
  864. struct rspamd_fuzzy_cmd *cmd = NULL;
  865. const struct rspamd_shingle *shingle = NULL;
  866. struct rspamd_shingle sgl_cpy;
  867. gint send_flags = 0;
  868. switch (session->cmd_type) {
  869. case CMD_ENCRYPTED_NORMAL:
  870. encrypted = TRUE;
  871. send_flags |= RSPAMD_FUZZY_REPLY_ENCRYPTED;
  872. /* Fallthrough */
  873. case CMD_NORMAL:
  874. cmd = &session->cmd.basic;
  875. break;
  876. case CMD_ENCRYPTED_SHINGLE:
  877. encrypted = TRUE;
  878. send_flags |= RSPAMD_FUZZY_REPLY_ENCRYPTED;
  879. /* Fallthrough */
  880. case CMD_SHINGLE:
  881. cmd = &session->cmd.basic;
  882. memcpy(&sgl_cpy, &session->cmd.sgl, sizeof(sgl_cpy));
  883. shingle = &sgl_cpy;
  884. is_shingle = TRUE;
  885. send_flags |= RSPAMD_FUZZY_REPLY_SHINGLE;
  886. break;
  887. }
  888. if (session->ctx->lua_post_handler_cbref != -1) {
  889. /* Start lua post handler */
  890. lua_State *L = session->ctx->cfg->lua_state;
  891. gint err_idx, ret;
  892. lua_pushcfunction(L, &rspamd_lua_traceback);
  893. err_idx = lua_gettop(L);
  894. /* Preallocate stack (small opt) */
  895. lua_checkstack(L, err_idx + 9);
  896. /* function */
  897. lua_rawgeti(L, LUA_REGISTRYINDEX, session->ctx->lua_post_handler_cbref);
  898. /* client IP */
  899. if (session->addr) {
  900. rspamd_lua_ip_push(L, session->addr);
  901. }
  902. else {
  903. lua_pushnil(L);
  904. }
  905. /* client command */
  906. lua_pushinteger(L, cmd->cmd);
  907. /* command value (push as rspamd_text) */
  908. (void) lua_new_text(L, result->digest, sizeof(result->digest), FALSE);
  909. /* is shingle */
  910. lua_pushboolean(L, is_shingle);
  911. /* result value */
  912. lua_pushinteger(L, result->v1.value);
  913. /* result probability */
  914. lua_pushnumber(L, result->v1.prob);
  915. /* result flag */
  916. lua_pushinteger(L, result->v1.flag);
  917. /* result timestamp */
  918. lua_pushinteger(L, result->ts);
  919. /* TODO: add additional data maybe (encryption, pubkey, etc) */
  920. rspamd_fuzzy_extensions_tolua(L, session);
  921. if ((ret = lua_pcall(L, 9, LUA_MULTRET, err_idx)) != 0) {
  922. msg_err("call to lua_post_handler lua "
  923. "script failed (%d): %s",
  924. ret, lua_tostring(L, -1));
  925. }
  926. else {
  927. /* Return values order:
  928. * the first reply will be on err_idx + 1
  929. * if it is true, then we need to read the former ones:
  930. * 2-nd will be reply code
  931. * 3-rd will be probability (or 0.0 if missing)
  932. * 4-th value is flag (or default flag if missing)
  933. */
  934. ret = lua_toboolean(L, err_idx + 1);
  935. if (ret) {
  936. /* Artificial reply */
  937. result->v1.value = lua_tointeger(L, err_idx + 2);
  938. if (lua_isnumber(L, err_idx + 3)) {
  939. result->v1.prob = lua_tonumber(L, err_idx + 3);
  940. }
  941. else {
  942. result->v1.prob = 0.0f;
  943. }
  944. if (lua_isnumber(L, err_idx + 4)) {
  945. result->v1.flag = lua_tointeger(L, err_idx + 4);
  946. }
  947. lua_settop(L, 0);
  948. rspamd_fuzzy_make_reply(cmd, result, session, send_flags);
  949. REF_RELEASE(session);
  950. return;
  951. }
  952. }
  953. lua_settop(L, 0);
  954. }
  955. if (!isnan(session->ctx->delay) &&
  956. rspamd_match_radix_map_addr(session->ctx->delay_whitelist,
  957. session->addr) == NULL) {
  958. gdouble hash_age = rspamd_get_calendar_ticks() - result->ts;
  959. gdouble jittered_age = rspamd_time_jitter(session->ctx->delay,
  960. session->ctx->delay / 2.0);
  961. if (hash_age < jittered_age) {
  962. send_flags |= RSPAMD_FUZZY_REPLY_DELAY;
  963. }
  964. }
  965. /* Refresh hash if found with strong confidence */
  966. if (result->v1.prob > 0.9 && !session->ctx->read_only) {
  967. struct fuzzy_peer_cmd up_cmd;
  968. struct fuzzy_peer_request *up_req;
  969. if (session->worker->index == 0) {
  970. /* Just add to the queue */
  971. memset(&up_cmd, 0, sizeof(up_cmd));
  972. up_cmd.is_shingle = is_shingle;
  973. memcpy(up_cmd.cmd.normal.digest, result->digest,
  974. sizeof(up_cmd.cmd.normal.digest));
  975. up_cmd.cmd.normal.flag = result->v1.flag;
  976. up_cmd.cmd.normal.cmd = FUZZY_REFRESH;
  977. up_cmd.cmd.normal.shingles_count = cmd->shingles_count;
  978. if (is_shingle && shingle) {
  979. memcpy(&up_cmd.cmd.shingle.sgl, shingle,
  980. sizeof(up_cmd.cmd.shingle.sgl));
  981. }
  982. g_array_append_val(session->ctx->updates_pending, up_cmd);
  983. }
  984. else {
  985. /* We need to send request to the peer */
  986. up_req = g_malloc0(sizeof(*up_req));
  987. up_req->cmd.is_shingle = is_shingle;
  988. memcpy(up_req->cmd.cmd.normal.digest, result->digest,
  989. sizeof(up_req->cmd.cmd.normal.digest));
  990. up_req->cmd.cmd.normal.flag = result->v1.flag;
  991. up_req->cmd.cmd.normal.cmd = FUZZY_REFRESH;
  992. up_req->cmd.cmd.normal.shingles_count = cmd->shingles_count;
  993. if (is_shingle && shingle) {
  994. memcpy(&up_req->cmd.cmd.shingle.sgl, shingle,
  995. sizeof(up_req->cmd.cmd.shingle.sgl));
  996. }
  997. if (!fuzzy_peer_try_send(session->ctx->peer_fd, up_req)) {
  998. up_req->io_ev.data = up_req;
  999. ev_io_init(&up_req->io_ev, fuzzy_peer_send_io,
  1000. session->ctx->peer_fd, EV_WRITE);
  1001. ev_io_start(session->ctx->event_loop, &up_req->io_ev);
  1002. }
  1003. else {
  1004. g_free(up_req);
  1005. }
  1006. }
  1007. }
  1008. rspamd_fuzzy_make_reply(cmd, result, session, send_flags);
  1009. REF_RELEASE(session);
  1010. }
  1011. static void
  1012. rspamd_fuzzy_process_command(struct fuzzy_session *session)
  1013. {
  1014. gboolean is_shingle = FALSE, __attribute__((unused)) encrypted = FALSE;
  1015. struct rspamd_fuzzy_cmd *cmd = NULL;
  1016. struct rspamd_fuzzy_reply result;
  1017. struct fuzzy_peer_cmd up_cmd;
  1018. struct fuzzy_peer_request *up_req;
  1019. struct fuzzy_key_stat *ip_stat = NULL;
  1020. gchar hexbuf[rspamd_cryptobox_HASHBYTES * 2 + 1];
  1021. rspamd_inet_addr_t *naddr;
  1022. gpointer ptr;
  1023. gsize up_len = 0;
  1024. gint send_flags = 0;
  1025. cmd = &session->cmd.basic;
  1026. switch (session->cmd_type) {
  1027. case CMD_NORMAL:
  1028. up_len = sizeof(session->cmd.basic);
  1029. break;
  1030. case CMD_SHINGLE:
  1031. up_len = sizeof(session->cmd);
  1032. is_shingle = TRUE;
  1033. send_flags |= RSPAMD_FUZZY_REPLY_SHINGLE;
  1034. break;
  1035. case CMD_ENCRYPTED_NORMAL:
  1036. up_len = sizeof(session->cmd.basic);
  1037. encrypted = TRUE;
  1038. send_flags |= RSPAMD_FUZZY_REPLY_ENCRYPTED;
  1039. break;
  1040. case CMD_ENCRYPTED_SHINGLE:
  1041. up_len = sizeof(session->cmd);
  1042. encrypted = TRUE;
  1043. is_shingle = TRUE;
  1044. send_flags |= RSPAMD_FUZZY_REPLY_SHINGLE | RSPAMD_FUZZY_REPLY_ENCRYPTED;
  1045. break;
  1046. default:
  1047. msg_err("invalid command type: %d", session->cmd_type);
  1048. return;
  1049. }
  1050. memset(&result, 0, sizeof(result));
  1051. memcpy(result.digest, cmd->digest, sizeof(result.digest));
  1052. result.v1.flag = cmd->flag;
  1053. result.v1.tag = cmd->tag;
  1054. if (session->ctx->lua_pre_handler_cbref != -1) {
  1055. /* Start lua pre handler */
  1056. lua_State *L = session->ctx->cfg->lua_state;
  1057. gint err_idx, ret;
  1058. lua_pushcfunction(L, &rspamd_lua_traceback);
  1059. err_idx = lua_gettop(L);
  1060. /* Preallocate stack (small opt) */
  1061. lua_checkstack(L, err_idx + 5);
  1062. /* function */
  1063. lua_rawgeti(L, LUA_REGISTRYINDEX, session->ctx->lua_pre_handler_cbref);
  1064. /* client IP */
  1065. rspamd_lua_ip_push(L, session->addr);
  1066. /* client command */
  1067. lua_pushinteger(L, cmd->cmd);
  1068. /* command value (push as rspamd_text) */
  1069. (void) lua_new_text(L, cmd->digest, sizeof(cmd->digest), FALSE);
  1070. /* is shingle */
  1071. lua_pushboolean(L, is_shingle);
  1072. /* TODO: add additional data maybe (encryption, pubkey, etc) */
  1073. rspamd_fuzzy_extensions_tolua(L, session);
  1074. if ((ret = lua_pcall(L, 5, LUA_MULTRET, err_idx)) != 0) {
  1075. msg_err("call to lua_pre_handler lua "
  1076. "script failed (%d): %s",
  1077. ret, lua_tostring(L, -1));
  1078. }
  1079. else {
  1080. /* Return values order:
  1081. * the first reply will be on err_idx + 1
  1082. * if it is true, then we need to read the former ones:
  1083. * 2-nd will be reply code
  1084. * 3-rd will be probability (or 0.0 if missing)
  1085. */
  1086. ret = lua_toboolean(L, err_idx + 1);
  1087. if (ret) {
  1088. /* Artificial reply */
  1089. result.v1.value = lua_tointeger(L, err_idx + 2);
  1090. if (lua_isnumber(L, err_idx + 3)) {
  1091. result.v1.prob = lua_tonumber(L, err_idx + 3);
  1092. }
  1093. else {
  1094. result.v1.prob = 0.0f;
  1095. }
  1096. lua_settop(L, 0);
  1097. rspamd_fuzzy_make_reply(cmd, &result, session, send_flags);
  1098. return;
  1099. }
  1100. }
  1101. lua_settop(L, 0);
  1102. }
  1103. if (G_UNLIKELY(cmd == NULL || up_len == 0)) {
  1104. result.v1.value = 500;
  1105. result.v1.prob = 0.0f;
  1106. rspamd_fuzzy_make_reply(cmd, &result, session, send_flags);
  1107. return;
  1108. }
  1109. if (session->ctx->encrypted_only && !encrypted) {
  1110. /* Do not accept unencrypted commands */
  1111. result.v1.value = 403;
  1112. result.v1.prob = 0.0f;
  1113. rspamd_fuzzy_make_reply(cmd, &result, session, send_flags);
  1114. return;
  1115. }
  1116. if (session->key && session->addr) {
  1117. ip_stat = rspamd_lru_hash_lookup(session->key->stat->last_ips,
  1118. session->addr, -1);
  1119. if (ip_stat == NULL) {
  1120. naddr = rspamd_inet_address_copy(session->addr, NULL);
  1121. ip_stat = g_malloc0(sizeof(*ip_stat));
  1122. REF_INIT_RETAIN(ip_stat, fuzzy_key_stat_dtor);
  1123. rspamd_lru_hash_insert(session->key->stat->last_ips,
  1124. naddr, ip_stat, -1, 0);
  1125. }
  1126. REF_RETAIN(ip_stat);
  1127. session->ip_stat = ip_stat;
  1128. }
  1129. if (cmd->cmd == FUZZY_CHECK) {
  1130. bool can_continue = true;
  1131. if (session->ctx->ratelimit_buckets) {
  1132. if (session->ctx->ratelimit_log_only) {
  1133. (void) rspamd_fuzzy_check_ratelimit(session); /* Check but ignore */
  1134. }
  1135. else {
  1136. can_continue = rspamd_fuzzy_check_ratelimit(session);
  1137. }
  1138. }
  1139. if (can_continue) {
  1140. REF_RETAIN(session);
  1141. rspamd_fuzzy_backend_check(session->ctx->backend, cmd,
  1142. rspamd_fuzzy_check_callback, session);
  1143. }
  1144. else {
  1145. result.v1.value = 403;
  1146. result.v1.prob = 0.0f;
  1147. result.v1.flag = 0;
  1148. rspamd_fuzzy_make_reply(cmd, &result, session, send_flags);
  1149. }
  1150. }
  1151. else if (cmd->cmd == FUZZY_STAT) {
  1152. /* Store approximation (if needed) */
  1153. result.v1.prob = session->ctx->stat.fuzzy_hashes;
  1154. /* Store high qword in value and low qword in flag */
  1155. result.v1.value = (gint32) ((guint64) session->ctx->stat.fuzzy_hashes >> 32);
  1156. result.v1.flag = (guint32) (session->ctx->stat.fuzzy_hashes & G_MAXUINT32);
  1157. rspamd_fuzzy_make_reply(cmd, &result, session, send_flags);
  1158. }
  1159. else if (cmd->cmd == FUZZY_PING) {
  1160. result.v1.prob = 1.0f;
  1161. result.v1.value = cmd->value;
  1162. rspamd_fuzzy_make_reply(cmd, &result, session, send_flags);
  1163. }
  1164. else {
  1165. if (rspamd_fuzzy_check_write(session)) {
  1166. /* Check whitelist */
  1167. if (session->ctx->skip_hashes && cmd->cmd == FUZZY_WRITE) {
  1168. rspamd_encode_hex_buf(cmd->digest, sizeof(cmd->digest),
  1169. hexbuf, sizeof(hexbuf) - 1);
  1170. hexbuf[sizeof(hexbuf) - 1] = '\0';
  1171. if (rspamd_match_hash_map(session->ctx->skip_hashes,
  1172. hexbuf, sizeof(hexbuf) - 1)) {
  1173. result.v1.value = 401;
  1174. result.v1.prob = 0.0f;
  1175. goto reply;
  1176. }
  1177. }
  1178. if (session->ctx->weak_ids && kh_get(fuzzy_key_ids_set, session->ctx->weak_ids, cmd->flag) != kh_end(session->ctx->weak_ids)) {
  1179. /* Flag command as weak */
  1180. cmd->version |= RSPAMD_FUZZY_FLAG_WEAK;
  1181. }
  1182. if (session->worker->index == 0 || session->ctx->peer_fd == -1) {
  1183. /* Just add to the queue */
  1184. up_cmd.is_shingle = is_shingle;
  1185. ptr = is_shingle ? (gpointer) &up_cmd.cmd.shingle : (gpointer) &up_cmd.cmd.normal;
  1186. memcpy(ptr, cmd, up_len);
  1187. g_array_append_val(session->ctx->updates_pending, up_cmd);
  1188. }
  1189. else {
  1190. /* We need to send request to the peer */
  1191. up_req = g_malloc0(sizeof(*up_req));
  1192. up_req->cmd.is_shingle = is_shingle;
  1193. ptr = is_shingle ? (gpointer) &up_req->cmd.cmd.shingle : (gpointer) &up_req->cmd.cmd.normal;
  1194. memcpy(ptr, cmd, up_len);
  1195. if (!fuzzy_peer_try_send(session->ctx->peer_fd, up_req)) {
  1196. up_req->io_ev.data = up_req;
  1197. ev_io_init(&up_req->io_ev, fuzzy_peer_send_io,
  1198. session->ctx->peer_fd, EV_WRITE);
  1199. ev_io_start(session->ctx->event_loop, &up_req->io_ev);
  1200. }
  1201. else {
  1202. g_free(up_req);
  1203. }
  1204. }
  1205. result.v1.value = 0;
  1206. result.v1.prob = 1.0f;
  1207. }
  1208. else {
  1209. result.v1.value = 403;
  1210. result.v1.prob = 0.0f;
  1211. }
  1212. reply:
  1213. rspamd_fuzzy_make_reply(cmd, &result, session, send_flags);
  1214. }
  1215. }
  1216. static enum rspamd_fuzzy_epoch
  1217. rspamd_fuzzy_command_valid(struct rspamd_fuzzy_cmd *cmd, gint r)
  1218. {
  1219. enum rspamd_fuzzy_epoch ret = RSPAMD_FUZZY_EPOCH_MAX;
  1220. switch (cmd->version & RSPAMD_FUZZY_VERSION_MASK) {
  1221. case 4:
  1222. if (cmd->shingles_count > 0) {
  1223. if (r >= sizeof(struct rspamd_fuzzy_shingle_cmd)) {
  1224. ret = RSPAMD_FUZZY_EPOCH11;
  1225. }
  1226. }
  1227. else {
  1228. if (r >= sizeof(*cmd)) {
  1229. ret = RSPAMD_FUZZY_EPOCH11;
  1230. }
  1231. }
  1232. break;
  1233. case 3:
  1234. if (cmd->shingles_count > 0) {
  1235. if (r == sizeof(struct rspamd_fuzzy_shingle_cmd)) {
  1236. ret = RSPAMD_FUZZY_EPOCH10;
  1237. }
  1238. }
  1239. else {
  1240. if (r == sizeof(*cmd)) {
  1241. ret = RSPAMD_FUZZY_EPOCH10;
  1242. }
  1243. }
  1244. break;
  1245. default:
  1246. break;
  1247. }
  1248. return ret;
  1249. }
  1250. static gboolean
  1251. rspamd_fuzzy_decrypt_command(struct fuzzy_session *s, guchar *buf, gsize buflen)
  1252. {
  1253. struct rspamd_fuzzy_encrypted_req_hdr hdr;
  1254. struct rspamd_cryptobox_pubkey *rk;
  1255. struct fuzzy_key *key;
  1256. if (s->ctx->default_key == NULL) {
  1257. msg_warn("received encrypted request when encryption is not enabled");
  1258. return FALSE;
  1259. }
  1260. if (buflen < sizeof(hdr)) {
  1261. msg_warn("XXX: should not be reached");
  1262. return FALSE;
  1263. }
  1264. memcpy(&hdr, buf, sizeof(hdr));
  1265. buf += sizeof(hdr);
  1266. buflen -= sizeof(hdr);
  1267. /* Try to find the desired key */
  1268. key = g_hash_table_lookup(s->ctx->keys, hdr.key_id);
  1269. if (key == NULL) {
  1270. /* Unknown key, assume default one */
  1271. key = s->ctx->default_key;
  1272. }
  1273. s->key = key;
  1274. /* Now process keypair */
  1275. rk = rspamd_pubkey_from_bin(hdr.pubkey, sizeof(hdr.pubkey),
  1276. RSPAMD_KEYPAIR_KEX, RSPAMD_CRYPTOBOX_MODE_25519);
  1277. if (rk == NULL) {
  1278. msg_err("bad key; ip=%s",
  1279. rspamd_inet_address_to_string(s->addr));
  1280. return FALSE;
  1281. }
  1282. rspamd_keypair_cache_process(s->ctx->keypair_cache, key->key, rk);
  1283. /* Now decrypt request */
  1284. if (!rspamd_cryptobox_decrypt_nm_inplace(buf, buflen, hdr.nonce,
  1285. rspamd_pubkey_get_nm(rk, key->key),
  1286. hdr.mac, RSPAMD_CRYPTOBOX_MODE_25519)) {
  1287. msg_err("decryption failed; ip=%s",
  1288. rspamd_inet_address_to_string(s->addr));
  1289. rspamd_pubkey_unref(rk);
  1290. return FALSE;
  1291. }
  1292. memcpy(s->nm, rspamd_pubkey_get_nm(rk, key->key), sizeof(s->nm));
  1293. rspamd_pubkey_unref(rk);
  1294. return TRUE;
  1295. }
  1296. static gboolean
  1297. rspamd_fuzzy_extensions_from_wire(struct fuzzy_session *s, guchar *buf, gsize buflen)
  1298. {
  1299. struct rspamd_fuzzy_cmd_extension *ext, *prev_ext;
  1300. guchar *storage, *p = buf, *end = buf + buflen;
  1301. gsize st_len = 0, n_ext = 0;
  1302. /* Read number of extensions to allocate array */
  1303. while (p < end) {
  1304. guchar cmd = *p++;
  1305. if (p < end) {
  1306. if (cmd == RSPAMD_FUZZY_EXT_SOURCE_DOMAIN) {
  1307. /* Next byte is buf length */
  1308. guchar dom_len = *p++;
  1309. if (dom_len <= (end - p)) {
  1310. st_len += dom_len;
  1311. n_ext++;
  1312. }
  1313. else {
  1314. /* Truncation */
  1315. return FALSE;
  1316. }
  1317. p += dom_len;
  1318. }
  1319. else if (cmd == RSPAMD_FUZZY_EXT_SOURCE_IP4) {
  1320. if (end - p >= sizeof(in_addr_t)) {
  1321. n_ext++;
  1322. st_len += sizeof(in_addr_t);
  1323. }
  1324. else {
  1325. /* Truncation */
  1326. return FALSE;
  1327. }
  1328. p += sizeof(in_addr_t);
  1329. }
  1330. else if (cmd == RSPAMD_FUZZY_EXT_SOURCE_IP6) {
  1331. if (end - p >= sizeof(struct in6_addr)) {
  1332. n_ext++;
  1333. st_len += sizeof(struct in6_addr);
  1334. }
  1335. else {
  1336. /* Truncation */
  1337. return FALSE;
  1338. }
  1339. p += sizeof(struct in6_addr);
  1340. }
  1341. else {
  1342. /* Invalid command */
  1343. return FALSE;
  1344. }
  1345. }
  1346. else {
  1347. /* Truncated extension */
  1348. return FALSE;
  1349. }
  1350. }
  1351. if (n_ext > 0) {
  1352. p = buf;
  1353. /*
  1354. * Memory layout: n_ext of struct rspamd_fuzzy_cmd_extension
  1355. * payload for each extension in a continuous data segment
  1356. */
  1357. storage = g_malloc(n_ext * sizeof(struct rspamd_fuzzy_cmd_extension) +
  1358. st_len);
  1359. guchar *data_buf = storage +
  1360. n_ext * sizeof(struct rspamd_fuzzy_cmd_extension);
  1361. ext = (struct rspamd_fuzzy_cmd_extension *) storage;
  1362. /* All validation has been done, so we can just go further */
  1363. while (p < end) {
  1364. prev_ext = ext;
  1365. guchar cmd = *p++;
  1366. if (cmd == RSPAMD_FUZZY_EXT_SOURCE_DOMAIN) {
  1367. /* Next byte is buf length */
  1368. guchar dom_len = *p++;
  1369. guchar *dest = data_buf;
  1370. ext->ext = RSPAMD_FUZZY_EXT_SOURCE_DOMAIN;
  1371. ext->next = ext + 1;
  1372. ext->length = dom_len;
  1373. ext->payload = dest;
  1374. memcpy(dest, p, dom_len);
  1375. p += dom_len;
  1376. data_buf += dom_len;
  1377. ext = ext->next;
  1378. }
  1379. else if (cmd == RSPAMD_FUZZY_EXT_SOURCE_IP4) {
  1380. guchar *dest = data_buf;
  1381. ext->ext = RSPAMD_FUZZY_EXT_SOURCE_IP4;
  1382. ext->next = ext + 1;
  1383. ext->length = sizeof(in_addr_t);
  1384. ext->payload = dest;
  1385. memcpy(dest, p, sizeof(in_addr_t));
  1386. p += sizeof(in_addr_t);
  1387. data_buf += sizeof(in_addr_t);
  1388. ext = ext->next;
  1389. }
  1390. else if (cmd == RSPAMD_FUZZY_EXT_SOURCE_IP6) {
  1391. guchar *dest = data_buf;
  1392. ext->ext = RSPAMD_FUZZY_EXT_SOURCE_IP6;
  1393. ext->next = ext + 1;
  1394. ext->length = sizeof(struct in6_addr);
  1395. ext->payload = dest;
  1396. memcpy(dest, p, sizeof(struct in6_addr));
  1397. p += sizeof(struct in6_addr);
  1398. data_buf += sizeof(struct in6_addr);
  1399. ext = ext->next;
  1400. }
  1401. else {
  1402. g_assert_not_reached();
  1403. }
  1404. }
  1405. /* Last next should be NULL */
  1406. prev_ext->next = NULL;
  1407. /* Rewind to the begin */
  1408. ext = (struct rspamd_fuzzy_cmd_extension *) storage;
  1409. s->extensions = ext;
  1410. }
  1411. return TRUE;
  1412. }
  1413. static gboolean
  1414. rspamd_fuzzy_cmd_from_wire(guchar *buf, guint buflen, struct fuzzy_session *s)
  1415. {
  1416. enum rspamd_fuzzy_epoch epoch;
  1417. gboolean encrypted = FALSE;
  1418. if (buflen < sizeof(struct rspamd_fuzzy_cmd)) {
  1419. msg_debug("truncated fuzzy command of size %d received", buflen);
  1420. return FALSE;
  1421. }
  1422. /* Now check encryption */
  1423. if (buflen >= sizeof(struct rspamd_fuzzy_encrypted_cmd)) {
  1424. if (memcmp(buf, fuzzy_encrypted_magic, sizeof(fuzzy_encrypted_magic)) == 0) {
  1425. /* Encrypted command */
  1426. encrypted = TRUE;
  1427. }
  1428. }
  1429. if (encrypted) {
  1430. /* Decrypt first */
  1431. if (!rspamd_fuzzy_decrypt_command(s, buf, buflen)) {
  1432. return FALSE;
  1433. }
  1434. else {
  1435. /*
  1436. * Advance buffer to skip encrypted header.
  1437. * Note that after rspamd_fuzzy_decrypt_command buf is unencrypted
  1438. */
  1439. buf += sizeof(struct rspamd_fuzzy_encrypted_req_hdr);
  1440. buflen -= sizeof(struct rspamd_fuzzy_encrypted_req_hdr);
  1441. }
  1442. }
  1443. /* Fill the normal command */
  1444. if (buflen < sizeof(s->cmd.basic)) {
  1445. msg_debug("truncated normal fuzzy command of size %d received", buflen);
  1446. return FALSE;
  1447. }
  1448. memcpy(&s->cmd.basic, buf, sizeof(s->cmd.basic));
  1449. epoch = rspamd_fuzzy_command_valid(&s->cmd.basic, buflen);
  1450. if (epoch == RSPAMD_FUZZY_EPOCH_MAX) {
  1451. msg_debug("invalid fuzzy command of size %d received", buflen);
  1452. return FALSE;
  1453. }
  1454. s->epoch = epoch;
  1455. /* Advance buf */
  1456. buf += sizeof(s->cmd.basic);
  1457. buflen -= sizeof(s->cmd.basic);
  1458. if (s->cmd.basic.shingles_count > 0) {
  1459. if (buflen >= sizeof(s->cmd.sgl)) {
  1460. /* Copy the shingles part */
  1461. memcpy(&s->cmd.sgl, buf, sizeof(s->cmd.sgl));
  1462. }
  1463. else {
  1464. /* Truncated stuff */
  1465. msg_debug("truncated fuzzy shingles command of size %d received", buflen);
  1466. return FALSE;
  1467. }
  1468. buf += sizeof(s->cmd.sgl);
  1469. buflen -= sizeof(s->cmd.sgl);
  1470. if (encrypted) {
  1471. s->cmd_type = CMD_ENCRYPTED_SHINGLE;
  1472. }
  1473. else {
  1474. s->cmd_type = CMD_SHINGLE;
  1475. }
  1476. }
  1477. else {
  1478. if (encrypted) {
  1479. s->cmd_type = CMD_ENCRYPTED_NORMAL;
  1480. }
  1481. else {
  1482. s->cmd_type = CMD_NORMAL;
  1483. }
  1484. }
  1485. if (buflen > 0) {
  1486. /* Process possible extensions */
  1487. if (!rspamd_fuzzy_extensions_from_wire(s, buf, buflen)) {
  1488. msg_debug("truncated fuzzy shingles command of size %d received", buflen);
  1489. return FALSE;
  1490. }
  1491. }
  1492. return TRUE;
  1493. }
  1494. static void
  1495. fuzzy_session_destroy(gpointer d)
  1496. {
  1497. struct fuzzy_session *session = d;
  1498. rspamd_inet_address_free(session->addr);
  1499. rspamd_explicit_memzero(session->nm, sizeof(session->nm));
  1500. session->worker->nconns--;
  1501. if (session->ip_stat) {
  1502. REF_RELEASE(session->ip_stat);
  1503. }
  1504. if (session->extensions) {
  1505. g_free(session->extensions);
  1506. }
  1507. g_free(session);
  1508. }
  1509. #define FUZZY_INPUT_BUFLEN 1024
  1510. #ifdef HAVE_RECVMMSG
  1511. #define MSGVEC_LEN 16
  1512. #else
  1513. #define MSGVEC_LEN 1
  1514. #endif
  1515. union sa_union {
  1516. struct sockaddr sa;
  1517. struct sockaddr_in s4;
  1518. struct sockaddr_in6 s6;
  1519. struct sockaddr_un su;
  1520. struct sockaddr_storage ss;
  1521. };
  1522. /*
  1523. * Accept new connection and construct task
  1524. */
  1525. static void
  1526. accept_fuzzy_socket(EV_P_ ev_io *w, int revents)
  1527. {
  1528. struct rspamd_worker *worker = (struct rspamd_worker *) w->data;
  1529. struct rspamd_fuzzy_storage_ctx *ctx;
  1530. struct fuzzy_session *session;
  1531. gssize r, msg_len;
  1532. guint64 *nerrors;
  1533. struct iovec iovs[MSGVEC_LEN];
  1534. guint8 bufs[MSGVEC_LEN][FUZZY_INPUT_BUFLEN];
  1535. union sa_union peer_sa[MSGVEC_LEN];
  1536. socklen_t salen = sizeof(peer_sa[0]);
  1537. #ifdef HAVE_RECVMMSG
  1538. #define MSG_FIELD(msg, field) msg.msg_hdr.field
  1539. struct mmsghdr msg[MSGVEC_LEN];
  1540. #else
  1541. #define MSG_FIELD(msg, field) msg.field
  1542. struct msghdr msg[MSGVEC_LEN];
  1543. #endif
  1544. memset(msg, 0, sizeof(*msg) * MSGVEC_LEN);
  1545. ctx = (struct rspamd_fuzzy_storage_ctx *) worker->ctx;
  1546. /* Prepare messages to receive */
  1547. for (int i = 0; i < MSGVEC_LEN; i++) {
  1548. /* Prepare msghdr structs */
  1549. iovs[i].iov_base = bufs[i];
  1550. iovs[i].iov_len = sizeof(bufs[i]);
  1551. MSG_FIELD(msg[i], msg_name) = (void *) &peer_sa[i];
  1552. MSG_FIELD(msg[i], msg_namelen) = salen;
  1553. MSG_FIELD(msg[i], msg_iov) = &iovs[i];
  1554. MSG_FIELD(msg[i], msg_iovlen) = 1;
  1555. }
  1556. /* Got some data */
  1557. if (revents == EV_READ) {
  1558. ev_now_update_if_cheap(ctx->event_loop);
  1559. for (;;) {
  1560. #ifdef HAVE_RECVMMSG
  1561. r = recvmmsg(w->fd, msg, MSGVEC_LEN, 0, NULL);
  1562. #else
  1563. r = recvmsg(w->fd, msg, 0);
  1564. #endif
  1565. if (r == -1) {
  1566. if (errno == EINTR) {
  1567. continue;
  1568. }
  1569. else if (errno == EAGAIN || errno == EWOULDBLOCK) {
  1570. return;
  1571. }
  1572. msg_err("got error while reading from socket: %d, %s",
  1573. errno,
  1574. strerror(errno));
  1575. return;
  1576. }
  1577. #ifndef HAVE_RECVMMSG
  1578. msg_len = r; /* Save real length in bytes here */
  1579. r = 1; /* Assume that we have received a single message */
  1580. #endif
  1581. for (int i = 0; i < r; i++) {
  1582. rspamd_inet_addr_t *client_addr;
  1583. if (MSG_FIELD(msg[i], msg_namelen) >= sizeof(struct sockaddr)) {
  1584. client_addr = rspamd_inet_address_from_sa(MSG_FIELD(msg[i], msg_name),
  1585. MSG_FIELD(msg[i], msg_namelen));
  1586. if (!rspamd_fuzzy_check_client(worker->ctx, client_addr)) {
  1587. /* Disallow forbidden clients silently */
  1588. rspamd_inet_address_free(client_addr);
  1589. continue;
  1590. }
  1591. }
  1592. else {
  1593. client_addr = NULL;
  1594. }
  1595. session = g_malloc0(sizeof(*session));
  1596. REF_INIT_RETAIN(session, fuzzy_session_destroy);
  1597. session->worker = worker;
  1598. session->fd = w->fd;
  1599. session->ctx = ctx;
  1600. session->timestamp = ev_now(ctx->event_loop);
  1601. session->addr = client_addr;
  1602. worker->nconns++;
  1603. /* Each message can have its length in case of recvmmsg */
  1604. #ifdef HAVE_RECVMMSG
  1605. msg_len = msg[i].msg_len;
  1606. #endif
  1607. if (rspamd_fuzzy_cmd_from_wire(iovs[i].iov_base,
  1608. msg_len, session)) {
  1609. /* Check shingles count sanity */
  1610. rspamd_fuzzy_process_command(session);
  1611. }
  1612. else {
  1613. /* Discard input */
  1614. session->ctx->stat.invalid_requests++;
  1615. msg_debug("invalid fuzzy command of size %z received", r);
  1616. if (session->addr) {
  1617. nerrors = rspamd_lru_hash_lookup(session->ctx->errors_ips,
  1618. session->addr, -1);
  1619. if (nerrors == NULL) {
  1620. nerrors = g_malloc(sizeof(*nerrors));
  1621. *nerrors = 1;
  1622. rspamd_lru_hash_insert(session->ctx->errors_ips,
  1623. rspamd_inet_address_copy(session->addr, NULL),
  1624. nerrors, -1, -1);
  1625. }
  1626. else {
  1627. *nerrors = *nerrors + 1;
  1628. }
  1629. }
  1630. }
  1631. REF_RELEASE(session);
  1632. }
  1633. #ifdef HAVE_RECVMMSG
  1634. /* Stop reading as we are using recvmmsg instead of recvmsg */
  1635. break;
  1636. #endif
  1637. }
  1638. }
  1639. }
  1640. static gboolean
  1641. rspamd_fuzzy_storage_periodic_callback(void *ud)
  1642. {
  1643. struct rspamd_fuzzy_storage_ctx *ctx = ud;
  1644. if (ctx->updates_pending->len > 0) {
  1645. rspamd_fuzzy_process_updates_queue(ctx, local_db_name, FALSE);
  1646. return TRUE;
  1647. }
  1648. return FALSE;
  1649. }
  1650. static gboolean
  1651. rspamd_fuzzy_storage_sync(struct rspamd_main *rspamd_main,
  1652. struct rspamd_worker *worker, gint fd,
  1653. gint attached_fd,
  1654. struct rspamd_control_command *cmd,
  1655. gpointer ud)
  1656. {
  1657. struct rspamd_fuzzy_storage_ctx *ctx = ud;
  1658. struct rspamd_control_reply rep;
  1659. rep.reply.fuzzy_sync.status = 0;
  1660. rep.type = RSPAMD_CONTROL_FUZZY_SYNC;
  1661. if (ctx->backend && worker->index == 0) {
  1662. rspamd_fuzzy_process_updates_queue(ctx, local_db_name, FALSE);
  1663. rspamd_fuzzy_backend_start_update(ctx->backend, ctx->sync_timeout,
  1664. rspamd_fuzzy_storage_periodic_callback, ctx);
  1665. }
  1666. if (write(fd, &rep, sizeof(rep)) != sizeof(rep)) {
  1667. msg_err("cannot write reply to the control socket: %s",
  1668. strerror(errno));
  1669. }
  1670. return TRUE;
  1671. }
  1672. static gboolean
  1673. rspamd_fuzzy_control_blocked(struct rspamd_main *rspamd_main,
  1674. struct rspamd_worker *worker, gint fd,
  1675. gint attached_fd,
  1676. struct rspamd_control_command *cmd,
  1677. gpointer ud)
  1678. {
  1679. struct rspamd_fuzzy_storage_ctx *ctx = (struct rspamd_fuzzy_storage_ctx *) ud;
  1680. struct rspamd_control_reply rep;
  1681. struct rspamd_leaky_bucket_elt *elt;
  1682. ev_tstamp now = ev_now(ctx->event_loop);
  1683. rspamd_inet_addr_t *addr = NULL;
  1684. rep.type = RSPAMD_CONTROL_FUZZY_BLOCKED;
  1685. rep.reply.fuzzy_blocked.status = 0;
  1686. if (cmd->cmd.fuzzy_blocked.af == AF_INET) {
  1687. addr = rspamd_inet_address_from_sa(&cmd->cmd.fuzzy_blocked.addr.sa,
  1688. sizeof(struct sockaddr_in));
  1689. }
  1690. else if (cmd->cmd.fuzzy_blocked.af == AF_INET6) {
  1691. addr = rspamd_inet_address_from_sa(&cmd->cmd.fuzzy_blocked.addr.sa,
  1692. sizeof(struct sockaddr_in6));
  1693. }
  1694. else {
  1695. msg_err("invalid address family: %d", cmd->cmd.fuzzy_blocked.af);
  1696. rep.reply.fuzzy_blocked.status = -1;
  1697. }
  1698. if (addr) {
  1699. elt = rspamd_lru_hash_lookup(ctx->ratelimit_buckets, addr,
  1700. (time_t) now);
  1701. if (elt) {
  1702. if (isnan(elt->cur)) {
  1703. /* Already ratelimited, ignore */
  1704. }
  1705. else {
  1706. elt->last = now;
  1707. elt->cur = NAN;
  1708. msg_info("propagating ratelimiting %s, %.1f max elts",
  1709. rspamd_inet_address_to_string(addr),
  1710. ctx->leaky_bucket_burst);
  1711. rspamd_fuzzy_maybe_call_blacklisted(ctx, addr, "ratelimit");
  1712. }
  1713. rspamd_inet_address_free(addr);
  1714. }
  1715. else {
  1716. /* New bucket */
  1717. elt = g_malloc(sizeof(*elt));
  1718. elt->addr = addr; /* transfer ownership */
  1719. elt->cur = NAN;
  1720. elt->last = now;
  1721. rspamd_lru_hash_insert(ctx->ratelimit_buckets,
  1722. addr,
  1723. elt,
  1724. (time_t) now,
  1725. ctx->leaky_bucket_ttl);
  1726. msg_info("propagating ratelimiting %s, %.1f max elts",
  1727. rspamd_inet_address_to_string(addr),
  1728. ctx->leaky_bucket_burst);
  1729. rspamd_fuzzy_maybe_call_blacklisted(ctx, addr, "ratelimit");
  1730. }
  1731. }
  1732. if (write(fd, &rep, sizeof(rep)) != sizeof(rep)) {
  1733. msg_err("cannot write reply to the control socket: %s",
  1734. strerror(errno));
  1735. }
  1736. return TRUE;
  1737. }
  1738. static gboolean
  1739. rspamd_fuzzy_storage_reload(struct rspamd_main *rspamd_main,
  1740. struct rspamd_worker *worker, gint fd,
  1741. gint attached_fd,
  1742. struct rspamd_control_command *cmd,
  1743. gpointer ud)
  1744. {
  1745. struct rspamd_fuzzy_storage_ctx *ctx = ud;
  1746. GError *err = NULL;
  1747. struct rspamd_control_reply rep;
  1748. msg_info("reloading fuzzy storage after receiving reload command");
  1749. if (ctx->backend) {
  1750. /* Close backend and reopen it one more time */
  1751. rspamd_fuzzy_backend_close(ctx->backend);
  1752. }
  1753. memset(&rep, 0, sizeof(rep));
  1754. rep.type = RSPAMD_CONTROL_RELOAD;
  1755. if ((ctx->backend = rspamd_fuzzy_backend_create(ctx->event_loop,
  1756. worker->cf->options, rspamd_main->cfg,
  1757. &err)) == NULL) {
  1758. msg_err("cannot open backend after reload: %e", err);
  1759. rep.reply.reload.status = err->code;
  1760. g_error_free(err);
  1761. }
  1762. else {
  1763. rep.reply.reload.status = 0;
  1764. }
  1765. if (ctx->backend && worker->index == 0) {
  1766. rspamd_fuzzy_backend_start_update(ctx->backend, ctx->sync_timeout,
  1767. rspamd_fuzzy_storage_periodic_callback, ctx);
  1768. }
  1769. if (write(fd, &rep, sizeof(rep)) != sizeof(rep)) {
  1770. msg_err("cannot write reply to the control socket: %s",
  1771. strerror(errno));
  1772. }
  1773. return TRUE;
  1774. }
  1775. static ucl_object_t *
  1776. rspamd_fuzzy_storage_stat_key(const struct fuzzy_key_stat *key_stat)
  1777. {
  1778. ucl_object_t *res;
  1779. res = ucl_object_typed_new(UCL_OBJECT);
  1780. ucl_object_insert_key(res, ucl_object_fromint(key_stat->checked),
  1781. "checked", 0, false);
  1782. ucl_object_insert_key(res, ucl_object_fromdouble(key_stat->checked_ctr.mean),
  1783. "checked_per_hour", 0, false);
  1784. ucl_object_insert_key(res, ucl_object_fromint(key_stat->matched),
  1785. "matched", 0, false);
  1786. ucl_object_insert_key(res, ucl_object_fromdouble(key_stat->matched_ctr.mean),
  1787. "matched_per_hour", 0, false);
  1788. ucl_object_insert_key(res, ucl_object_fromint(key_stat->added),
  1789. "added", 0, false);
  1790. ucl_object_insert_key(res, ucl_object_fromint(key_stat->deleted),
  1791. "deleted", 0, false);
  1792. ucl_object_insert_key(res, ucl_object_fromint(key_stat->errors),
  1793. "errors", 0, false);
  1794. return res;
  1795. }
  1796. static ucl_object_t *
  1797. rspamd_fuzzy_stat_to_ucl(struct rspamd_fuzzy_storage_ctx *ctx, gboolean ip_stat)
  1798. {
  1799. struct fuzzy_key_stat *key_stat;
  1800. GHashTableIter it;
  1801. struct fuzzy_key *fuzzy_key;
  1802. ucl_object_t *obj, *keys_obj, *elt, *ip_elt, *ip_cur;
  1803. gpointer k, v;
  1804. gint i;
  1805. gchar keyname[17];
  1806. obj = ucl_object_typed_new(UCL_OBJECT);
  1807. keys_obj = ucl_object_typed_new(UCL_OBJECT);
  1808. g_hash_table_iter_init(&it, ctx->keys);
  1809. while (g_hash_table_iter_next(&it, &k, &v)) {
  1810. fuzzy_key = v;
  1811. key_stat = fuzzy_key->stat;
  1812. if (key_stat) {
  1813. rspamd_snprintf(keyname, sizeof(keyname), "%8bs", k);
  1814. elt = rspamd_fuzzy_storage_stat_key(key_stat);
  1815. if (key_stat->last_ips && ip_stat) {
  1816. i = 0;
  1817. ip_elt = ucl_object_typed_new(UCL_OBJECT);
  1818. while ((i = rspamd_lru_hash_foreach(key_stat->last_ips,
  1819. i, &k, &v)) != -1) {
  1820. ip_cur = rspamd_fuzzy_storage_stat_key(v);
  1821. ucl_object_insert_key(ip_elt, ip_cur,
  1822. rspamd_inet_address_to_string(k), 0, true);
  1823. }
  1824. ucl_object_insert_key(elt, ip_elt, "ips", 0, false);
  1825. }
  1826. int flag;
  1827. struct fuzzy_key_stat *flag_stat;
  1828. ucl_object_t *flags_ucl = ucl_object_typed_new(UCL_OBJECT);
  1829. kh_foreach_key_value_ptr(fuzzy_key->flags_stat, flag, flag_stat, {
  1830. char intbuf[16];
  1831. rspamd_snprintf(intbuf, sizeof(intbuf), "%d", flag);
  1832. ucl_object_insert_key(flags_ucl, rspamd_fuzzy_storage_stat_key(flag_stat),
  1833. intbuf, 0, true);
  1834. });
  1835. ucl_object_insert_key(elt, flags_ucl, "flags", 0, false);
  1836. ucl_object_insert_key(elt,
  1837. rspamd_keypair_to_ucl(fuzzy_key->key, RSPAMD_KEYPAIR_DUMP_NO_SECRET | RSPAMD_KEYPAIR_DUMP_FLATTENED),
  1838. "keypair", 0, false);
  1839. ucl_object_insert_key(keys_obj, elt, keyname, 0, true);
  1840. }
  1841. }
  1842. ucl_object_insert_key(obj, keys_obj, "keys", 0, false);
  1843. /* Now generic stats */
  1844. ucl_object_insert_key(obj,
  1845. ucl_object_fromint(ctx->stat.fuzzy_hashes),
  1846. "fuzzy_stored",
  1847. 0,
  1848. false);
  1849. ucl_object_insert_key(obj,
  1850. ucl_object_fromint(ctx->stat.fuzzy_hashes_expired),
  1851. "fuzzy_expired",
  1852. 0,
  1853. false);
  1854. ucl_object_insert_key(obj,
  1855. ucl_object_fromint(ctx->stat.invalid_requests),
  1856. "invalid_requests",
  1857. 0,
  1858. false);
  1859. ucl_object_insert_key(obj,
  1860. ucl_object_fromint(ctx->stat.delayed_hashes),
  1861. "delayed_hashes",
  1862. 0,
  1863. false);
  1864. if (ctx->errors_ips && ip_stat) {
  1865. i = 0;
  1866. ip_elt = ucl_object_typed_new(UCL_OBJECT);
  1867. while ((i = rspamd_lru_hash_foreach(ctx->errors_ips, i, &k, &v)) != -1) {
  1868. ucl_object_insert_key(ip_elt,
  1869. ucl_object_fromint(*(guint64 *) v),
  1870. rspamd_inet_address_to_string(k), 0, true);
  1871. }
  1872. ucl_object_insert_key(obj,
  1873. ip_elt,
  1874. "errors_ips",
  1875. 0,
  1876. false);
  1877. }
  1878. /* Checked by epoch */
  1879. elt = ucl_object_typed_new(UCL_ARRAY);
  1880. for (i = RSPAMD_FUZZY_EPOCH10; i < RSPAMD_FUZZY_EPOCH_MAX; i++) {
  1881. ucl_array_append(elt,
  1882. ucl_object_fromint(ctx->stat.fuzzy_hashes_checked[i]));
  1883. }
  1884. ucl_object_insert_key(obj, elt, "fuzzy_checked", 0, false);
  1885. /* Shingles by epoch */
  1886. elt = ucl_object_typed_new(UCL_ARRAY);
  1887. for (i = RSPAMD_FUZZY_EPOCH10; i < RSPAMD_FUZZY_EPOCH_MAX; i++) {
  1888. ucl_array_append(elt,
  1889. ucl_object_fromint(ctx->stat.fuzzy_shingles_checked[i]));
  1890. }
  1891. ucl_object_insert_key(obj, elt, "fuzzy_shingles", 0, false);
  1892. /* Matched by epoch */
  1893. elt = ucl_object_typed_new(UCL_ARRAY);
  1894. for (i = RSPAMD_FUZZY_EPOCH10; i < RSPAMD_FUZZY_EPOCH_MAX; i++) {
  1895. ucl_array_append(elt,
  1896. ucl_object_fromint(ctx->stat.fuzzy_hashes_found[i]));
  1897. }
  1898. ucl_object_insert_key(obj, elt, "fuzzy_found", 0, false);
  1899. return obj;
  1900. }
  1901. static void
  1902. rspamd_fuzzy_maybe_load_ratelimits(struct rspamd_fuzzy_storage_ctx *ctx)
  1903. {
  1904. char path[PATH_MAX];
  1905. rspamd_snprintf(path, sizeof(path), "%s" G_DIR_SEPARATOR_S "fuzzy_ratelimits.ucl",
  1906. RSPAMD_DBDIR);
  1907. if (access(path, R_OK) != -1) {
  1908. struct ucl_parser *parser = ucl_parser_new(UCL_PARSER_NO_IMPLICIT_ARRAYS | UCL_PARSER_DISABLE_MACRO);
  1909. if (ucl_parser_add_file(parser, path)) {
  1910. ucl_object_t *obj = ucl_parser_get_object(parser);
  1911. int loaded = 0;
  1912. if (ucl_object_type(obj) == UCL_ARRAY) {
  1913. ucl_object_iter_t it = NULL;
  1914. const ucl_object_t *cur;
  1915. while ((cur = ucl_object_iterate(obj, &it, true)) != NULL) {
  1916. const ucl_object_t *ip, *value, *last;
  1917. const gchar *ip_str;
  1918. double limit_val, last_val;
  1919. ip = ucl_object_find_key(cur, "ip");
  1920. value = ucl_object_find_key(cur, "value");
  1921. last = ucl_object_find_key(cur, "last");
  1922. if (ip == NULL || value == NULL || last == NULL) {
  1923. msg_err("invalid ratelimit object");
  1924. continue;
  1925. }
  1926. ip_str = ucl_object_tostring(ip);
  1927. limit_val = ucl_object_todouble(value);
  1928. last_val = ucl_object_todouble(last);
  1929. if (ip_str == NULL || isnan(last_val)) {
  1930. msg_err("invalid ratelimit object");
  1931. continue;
  1932. }
  1933. rspamd_inet_addr_t *addr;
  1934. if (rspamd_parse_inet_address(&addr, ip_str, strlen(ip_str),
  1935. RSPAMD_INET_ADDRESS_PARSE_NO_UNIX | RSPAMD_INET_ADDRESS_PARSE_NO_PORT)) {
  1936. struct rspamd_leaky_bucket_elt *elt = g_malloc(sizeof(*elt));
  1937. elt->cur = limit_val;
  1938. elt->last = last_val;
  1939. elt->addr = addr;
  1940. rspamd_lru_hash_insert(ctx->ratelimit_buckets, addr, elt, elt->last, ctx->leaky_bucket_ttl);
  1941. loaded++;
  1942. }
  1943. else {
  1944. msg_err("invalid ratelimit ip: %s", ip_str);
  1945. continue;
  1946. }
  1947. }
  1948. msg_info("loaded %d ratelimit objects", loaded);
  1949. }
  1950. ucl_object_unref(obj);
  1951. }
  1952. ucl_parser_free(parser);
  1953. }
  1954. }
  1955. static void
  1956. rspamd_fuzzy_maybe_save_ratelimits(struct rspamd_fuzzy_storage_ctx *ctx)
  1957. {
  1958. char path[PATH_MAX];
  1959. rspamd_snprintf(path, sizeof(path), "%s" G_DIR_SEPARATOR_S "fuzzy_ratelimits.ucl.new",
  1960. RSPAMD_DBDIR);
  1961. FILE *f = fopen(path, "w");
  1962. if (f != NULL) {
  1963. ucl_object_t *top = ucl_object_typed_new(UCL_ARRAY);
  1964. int it = 0;
  1965. gpointer k, v;
  1966. ucl_object_reserve(top, rspamd_lru_hash_size(ctx->ratelimit_buckets));
  1967. while ((it = rspamd_lru_hash_foreach(ctx->ratelimit_buckets, it, &k, &v)) != -1) {
  1968. ucl_object_t *cur = ucl_object_typed_new(UCL_OBJECT);
  1969. struct rspamd_leaky_bucket_elt *elt = (struct rspamd_leaky_bucket_elt *) v;
  1970. ucl_object_insert_key(cur, ucl_object_fromdouble(elt->cur), "value", 0, false);
  1971. ucl_object_insert_key(cur, ucl_object_fromdouble(elt->last), "last", 0, false);
  1972. ucl_object_insert_key(cur, ucl_object_fromstring(rspamd_inet_address_to_string(elt->addr)), "ip", 0, false);
  1973. ucl_array_append(top, cur);
  1974. }
  1975. if (ucl_object_emit_full(top, UCL_EMIT_JSON_COMPACT, ucl_object_emit_file_funcs(f), NULL)) {
  1976. char npath[PATH_MAX];
  1977. fflush(f);
  1978. rspamd_snprintf(npath, sizeof(npath), "%s" G_DIR_SEPARATOR_S "fuzzy_ratelimits.ucl",
  1979. RSPAMD_DBDIR);
  1980. if (rename(path, npath) == -1) {
  1981. msg_warn("cannot rename %s to %s: %s", path, npath, strerror(errno));
  1982. }
  1983. else {
  1984. msg_info("saved %d ratelimits in %s", rspamd_lru_hash_size(ctx->ratelimit_buckets), npath);
  1985. }
  1986. }
  1987. else {
  1988. msg_warn("cannot serialize ratelimit buckets to %s: %s", path, strerror(errno));
  1989. }
  1990. fclose(f);
  1991. ucl_object_unref(top);
  1992. }
  1993. else {
  1994. msg_warn("cannot save ratelimit buckets to %s: %s", path, strerror(errno));
  1995. }
  1996. }
  1997. static int
  1998. lua_fuzzy_add_pre_handler(lua_State *L)
  1999. {
  2000. struct rspamd_worker *wrk, **pwrk = (struct rspamd_worker **)
  2001. rspamd_lua_check_udata(L, 1, "rspamd{worker}");
  2002. struct rspamd_fuzzy_storage_ctx *ctx;
  2003. if (!pwrk) {
  2004. return luaL_error(L, "invalid arguments, worker + function are expected");
  2005. }
  2006. wrk = *pwrk;
  2007. if (wrk && lua_isfunction(L, 2)) {
  2008. ctx = (struct rspamd_fuzzy_storage_ctx *) wrk->ctx;
  2009. if (ctx->lua_pre_handler_cbref != -1) {
  2010. /* Should not happen */
  2011. luaL_unref(L, LUA_REGISTRYINDEX, ctx->lua_pre_handler_cbref);
  2012. }
  2013. lua_pushvalue(L, 2);
  2014. ctx->lua_pre_handler_cbref = luaL_ref(L, LUA_REGISTRYINDEX);
  2015. }
  2016. else {
  2017. return luaL_error(L, "invalid arguments, worker + function are expected");
  2018. }
  2019. return 0;
  2020. }
  2021. static int
  2022. lua_fuzzy_add_post_handler(lua_State *L)
  2023. {
  2024. struct rspamd_worker *wrk, **pwrk = (struct rspamd_worker **)
  2025. rspamd_lua_check_udata(L, 1, "rspamd{worker}");
  2026. struct rspamd_fuzzy_storage_ctx *ctx;
  2027. if (!pwrk) {
  2028. return luaL_error(L, "invalid arguments, worker + function are expected");
  2029. }
  2030. wrk = *pwrk;
  2031. if (wrk && lua_isfunction(L, 2)) {
  2032. ctx = (struct rspamd_fuzzy_storage_ctx *) wrk->ctx;
  2033. if (ctx->lua_post_handler_cbref != -1) {
  2034. /* Should not happen */
  2035. luaL_unref(L, LUA_REGISTRYINDEX, ctx->lua_post_handler_cbref);
  2036. }
  2037. lua_pushvalue(L, 2);
  2038. ctx->lua_post_handler_cbref = luaL_ref(L, LUA_REGISTRYINDEX);
  2039. }
  2040. else {
  2041. return luaL_error(L, "invalid arguments, worker + function are expected");
  2042. }
  2043. return 0;
  2044. }
  2045. static int
  2046. lua_fuzzy_add_blacklist_handler(lua_State *L)
  2047. {
  2048. struct rspamd_worker *wrk, **pwrk = (struct rspamd_worker **)
  2049. rspamd_lua_check_udata(L, 1, "rspamd{worker}");
  2050. struct rspamd_fuzzy_storage_ctx *ctx;
  2051. if (!pwrk) {
  2052. return luaL_error(L, "invalid arguments, worker + function are expected");
  2053. }
  2054. wrk = *pwrk;
  2055. if (wrk && lua_isfunction(L, 2)) {
  2056. ctx = (struct rspamd_fuzzy_storage_ctx *) wrk->ctx;
  2057. if (ctx->lua_blacklist_cbref != -1) {
  2058. /* Should not happen */
  2059. luaL_unref(L, LUA_REGISTRYINDEX, ctx->lua_blacklist_cbref);
  2060. }
  2061. lua_pushvalue(L, 2);
  2062. ctx->lua_blacklist_cbref = luaL_ref(L, LUA_REGISTRYINDEX);
  2063. }
  2064. else {
  2065. return luaL_error(L, "invalid arguments, worker + function are expected");
  2066. }
  2067. return 0;
  2068. }
  2069. static gboolean
  2070. rspamd_fuzzy_storage_stat(struct rspamd_main *rspamd_main,
  2071. struct rspamd_worker *worker, gint fd,
  2072. gint attached_fd,
  2073. struct rspamd_control_command *cmd,
  2074. gpointer ud)
  2075. {
  2076. struct rspamd_fuzzy_storage_ctx *ctx = ud;
  2077. struct rspamd_control_reply rep;
  2078. ucl_object_t *obj;
  2079. struct ucl_emitter_functions *emit_subr;
  2080. guchar fdspace[CMSG_SPACE(sizeof(int))];
  2081. struct iovec iov;
  2082. struct msghdr msg;
  2083. struct cmsghdr *cmsg;
  2084. gint outfd = -1;
  2085. gchar tmppath[PATH_MAX];
  2086. memset(&rep, 0, sizeof(rep));
  2087. rep.type = RSPAMD_CONTROL_FUZZY_STAT;
  2088. rspamd_snprintf(tmppath, sizeof(tmppath), "%s%c%s-XXXXXXXXXX",
  2089. rspamd_main->cfg->temp_dir, G_DIR_SEPARATOR, "fuzzy-stat");
  2090. if ((outfd = mkstemp(tmppath)) == -1) {
  2091. rep.reply.fuzzy_stat.status = errno;
  2092. msg_info_main("cannot make temporary stat file for fuzzy stat: %s",
  2093. strerror(errno));
  2094. }
  2095. else {
  2096. rep.reply.fuzzy_stat.status = 0;
  2097. memcpy(rep.reply.fuzzy_stat.storage_id,
  2098. rspamd_fuzzy_backend_id(ctx->backend),
  2099. sizeof(rep.reply.fuzzy_stat.storage_id));
  2100. obj = rspamd_fuzzy_stat_to_ucl(ctx, TRUE);
  2101. emit_subr = ucl_object_emit_fd_funcs(outfd);
  2102. ucl_object_emit_full(obj, UCL_EMIT_JSON_COMPACT, emit_subr, NULL);
  2103. ucl_object_emit_funcs_free(emit_subr);
  2104. ucl_object_unref(obj);
  2105. /* Rewind output file */
  2106. close(outfd);
  2107. outfd = open(tmppath, O_RDONLY);
  2108. unlink(tmppath);
  2109. }
  2110. /* Now we can send outfd and status message */
  2111. memset(&msg, 0, sizeof(msg));
  2112. /* Attach fd to the message */
  2113. if (outfd != -1) {
  2114. memset(fdspace, 0, sizeof(fdspace));
  2115. msg.msg_control = fdspace;
  2116. msg.msg_controllen = sizeof(fdspace);
  2117. cmsg = CMSG_FIRSTHDR(&msg);
  2118. if (cmsg) {
  2119. cmsg->cmsg_level = SOL_SOCKET;
  2120. cmsg->cmsg_type = SCM_RIGHTS;
  2121. cmsg->cmsg_len = CMSG_LEN(sizeof(int));
  2122. memcpy(CMSG_DATA(cmsg), &outfd, sizeof(int));
  2123. }
  2124. }
  2125. iov.iov_base = &rep;
  2126. iov.iov_len = sizeof(rep);
  2127. msg.msg_iov = &iov;
  2128. msg.msg_iovlen = 1;
  2129. if (sendmsg(fd, &msg, 0) == -1) {
  2130. msg_err_main("cannot send fuzzy stat: %s", strerror(errno));
  2131. }
  2132. if (outfd != -1) {
  2133. close(outfd);
  2134. }
  2135. return TRUE;
  2136. }
  2137. static gboolean
  2138. fuzzy_parse_ids(rspamd_mempool_t *pool,
  2139. const ucl_object_t *obj,
  2140. gpointer ud,
  2141. struct rspamd_rcl_section *section,
  2142. GError **err)
  2143. {
  2144. struct rspamd_rcl_struct_parser *pd = (struct rspamd_rcl_struct_parser *) ud;
  2145. khash_t(fuzzy_key_ids_set) * target;
  2146. target = *(khash_t(fuzzy_key_ids_set) **) ((gchar *) pd->user_struct + pd->offset);
  2147. if (ucl_object_type(obj) == UCL_ARRAY) {
  2148. const ucl_object_t *cur;
  2149. ucl_object_iter_t it = NULL;
  2150. guint64 id;
  2151. while ((cur = ucl_object_iterate(obj, &it, true)) != NULL) {
  2152. if (ucl_object_toint_safe(cur, &id)) {
  2153. int r;
  2154. kh_put(fuzzy_key_ids_set, target, id, &r);
  2155. }
  2156. else {
  2157. return FALSE;
  2158. }
  2159. }
  2160. return TRUE;
  2161. }
  2162. else if (ucl_object_type(obj) == UCL_INT) {
  2163. int r;
  2164. kh_put(fuzzy_key_ids_set, target, ucl_object_toint(obj), &r);
  2165. return TRUE;
  2166. }
  2167. return FALSE;
  2168. }
  2169. static gboolean
  2170. fuzzy_parse_keypair(rspamd_mempool_t *pool,
  2171. const ucl_object_t *obj,
  2172. gpointer ud,
  2173. struct rspamd_rcl_section *section,
  2174. GError **err)
  2175. {
  2176. struct rspamd_rcl_struct_parser *pd = ud;
  2177. struct rspamd_fuzzy_storage_ctx *ctx;
  2178. struct rspamd_cryptobox_keypair *kp;
  2179. struct fuzzy_key_stat *keystat;
  2180. struct fuzzy_key *key;
  2181. const ucl_object_t *cur;
  2182. const guchar *pk;
  2183. ucl_object_iter_t it = NULL;
  2184. gboolean ret;
  2185. ctx = pd->user_struct;
  2186. pd->offset = G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, default_keypair);
  2187. /*
  2188. * Single key
  2189. */
  2190. if (ucl_object_type(obj) == UCL_STRING || ucl_object_type(obj) == UCL_OBJECT) {
  2191. ret = rspamd_rcl_parse_struct_keypair(pool, obj, pd, section, err);
  2192. if (!ret) {
  2193. return ret;
  2194. }
  2195. /* Insert key to the hash table */
  2196. kp = ctx->default_keypair;
  2197. if (kp == NULL) {
  2198. return FALSE;
  2199. }
  2200. if (rspamd_keypair_alg(kp) != RSPAMD_CRYPTOBOX_MODE_25519 ||
  2201. rspamd_keypair_type(kp) != RSPAMD_KEYPAIR_KEX) {
  2202. return FALSE;
  2203. }
  2204. key = g_malloc0(sizeof(*key));
  2205. key->key = kp;
  2206. keystat = g_malloc0(sizeof(*keystat));
  2207. REF_INIT_RETAIN(keystat, fuzzy_key_stat_dtor);
  2208. /* Hash of ip -> fuzzy_key_stat */
  2209. keystat->last_ips = rspamd_lru_hash_new_full(1024,
  2210. (GDestroyNotify) rspamd_inet_address_free,
  2211. fuzzy_key_stat_unref,
  2212. rspamd_inet_address_hash, rspamd_inet_address_equal);
  2213. key->stat = keystat;
  2214. key->flags_stat = kh_init(fuzzy_key_flag_stat);
  2215. /* Preallocate some space for flags */
  2216. kh_resize(fuzzy_key_flag_stat, key->flags_stat, 8);
  2217. pk = rspamd_keypair_component(kp, RSPAMD_KEYPAIR_COMPONENT_PK,
  2218. NULL);
  2219. keystat->keypair = rspamd_keypair_ref(kp);
  2220. /* We map entries by pubkey in binary form for faster lookup */
  2221. g_hash_table_insert(ctx->keys, (gpointer) pk, key);
  2222. ctx->default_key = key;
  2223. const ucl_object_t *extensions = rspamd_keypair_get_extensions(kp);
  2224. if (extensions) {
  2225. const ucl_object_t *forbidden_ids = ucl_object_lookup(extensions, "forbidden_ids");
  2226. if (forbidden_ids && ucl_object_type(forbidden_ids) == UCL_ARRAY) {
  2227. key->forbidden_ids = kh_init(fuzzy_key_ids_set);
  2228. while ((cur = ucl_object_iterate(forbidden_ids, &it, true)) != NULL) {
  2229. if (ucl_object_type(cur) == UCL_INT || ucl_object_type(cur) == UCL_FLOAT) {
  2230. int id = ucl_object_toint(cur);
  2231. int r;
  2232. kh_put(fuzzy_key_ids_set, key->forbidden_ids, id, &r);
  2233. }
  2234. }
  2235. }
  2236. }
  2237. msg_debug_pool_check("loaded keypair %*xs", 8, pk);
  2238. }
  2239. else if (ucl_object_type(obj) == UCL_ARRAY) {
  2240. while ((cur = ucl_object_iterate(obj, &it, true)) != NULL) {
  2241. if (!fuzzy_parse_keypair(pool, cur, pd, section, err)) {
  2242. msg_err_pool("cannot parse keypair");
  2243. }
  2244. }
  2245. }
  2246. return TRUE;
  2247. }
  2248. static guint
  2249. fuzzy_kp_hash(gconstpointer p)
  2250. {
  2251. return *(guint *) p;
  2252. }
  2253. static gboolean
  2254. fuzzy_kp_equal(gconstpointer a, gconstpointer b)
  2255. {
  2256. const guchar *pa = a, *pb = b;
  2257. return (memcmp(pa, pb, RSPAMD_FUZZY_KEYLEN) == 0);
  2258. }
  2259. gpointer
  2260. init_fuzzy(struct rspamd_config *cfg)
  2261. {
  2262. struct rspamd_fuzzy_storage_ctx *ctx;
  2263. GQuark type;
  2264. type = g_quark_try_string("fuzzy");
  2265. ctx = rspamd_mempool_alloc0(cfg->cfg_pool,
  2266. sizeof(struct rspamd_fuzzy_storage_ctx));
  2267. ctx->magic = rspamd_fuzzy_storage_magic;
  2268. ctx->sync_timeout = DEFAULT_SYNC_TIMEOUT;
  2269. ctx->keypair_cache_size = DEFAULT_KEYPAIR_CACHE_SIZE;
  2270. ctx->lua_pre_handler_cbref = -1;
  2271. ctx->lua_post_handler_cbref = -1;
  2272. ctx->lua_blacklist_cbref = -1;
  2273. ctx->keys = g_hash_table_new_full(fuzzy_kp_hash, fuzzy_kp_equal,
  2274. NULL, fuzzy_key_dtor);
  2275. rspamd_mempool_add_destructor(cfg->cfg_pool,
  2276. (rspamd_mempool_destruct_t) g_hash_table_unref, ctx->keys);
  2277. ctx->errors_ips = rspamd_lru_hash_new_full(1024,
  2278. (GDestroyNotify) rspamd_inet_address_free, g_free,
  2279. rspamd_inet_address_hash, rspamd_inet_address_equal);
  2280. rspamd_mempool_add_destructor(cfg->cfg_pool,
  2281. (rspamd_mempool_destruct_t) rspamd_lru_hash_destroy, ctx->errors_ips);
  2282. ctx->cfg = cfg;
  2283. ctx->updates_maxfail = DEFAULT_UPDATES_MAXFAIL;
  2284. ctx->leaky_bucket_mask = DEFAULT_BUCKET_MASK;
  2285. ctx->leaky_bucket_ttl = DEFAULT_BUCKET_TTL;
  2286. ctx->max_buckets = DEFAULT_MAX_BUCKETS;
  2287. ctx->leaky_bucket_burst = NAN;
  2288. ctx->leaky_bucket_rate = NAN;
  2289. ctx->delay = NAN;
  2290. ctx->default_forbidden_ids = kh_init(fuzzy_key_ids_set);
  2291. ctx->weak_ids = kh_init(fuzzy_key_ids_set);
  2292. rspamd_rcl_register_worker_option(cfg,
  2293. type,
  2294. "sync",
  2295. rspamd_rcl_parse_struct_time,
  2296. ctx,
  2297. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx,
  2298. sync_timeout),
  2299. RSPAMD_CL_FLAG_TIME_FLOAT,
  2300. "Time to perform database sync, default: " G_STRINGIFY(DEFAULT_SYNC_TIMEOUT) " seconds");
  2301. rspamd_rcl_register_worker_option(cfg,
  2302. type,
  2303. "expire",
  2304. rspamd_rcl_parse_struct_time,
  2305. ctx,
  2306. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx,
  2307. expire),
  2308. RSPAMD_CL_FLAG_TIME_FLOAT,
  2309. "Default expire time for hashes, default: " G_STRINGIFY(DEFAULT_EXPIRE) " seconds");
  2310. rspamd_rcl_register_worker_option(cfg,
  2311. type,
  2312. "delay",
  2313. rspamd_rcl_parse_struct_time,
  2314. ctx,
  2315. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx,
  2316. delay),
  2317. RSPAMD_CL_FLAG_TIME_FLOAT,
  2318. "Default delay time for hashes, default: not enabled");
  2319. rspamd_rcl_register_worker_option(cfg,
  2320. type,
  2321. "allow_update",
  2322. rspamd_rcl_parse_struct_ucl,
  2323. ctx,
  2324. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, update_map),
  2325. 0,
  2326. "Allow modifications from the following IP addresses");
  2327. rspamd_rcl_register_worker_option(cfg,
  2328. type,
  2329. "allow_update_keys",
  2330. rspamd_rcl_parse_struct_ucl,
  2331. ctx,
  2332. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, update_keys_map),
  2333. 0,
  2334. "Allow modifications for those using specific public keys");
  2335. rspamd_rcl_register_worker_option(cfg,
  2336. type,
  2337. "delay_whitelist",
  2338. rspamd_rcl_parse_struct_ucl,
  2339. ctx,
  2340. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, delay_whitelist_map),
  2341. 0,
  2342. "Disable delay check for the following IP addresses");
  2343. rspamd_rcl_register_worker_option(cfg,
  2344. type,
  2345. "keypair",
  2346. fuzzy_parse_keypair,
  2347. ctx,
  2348. 0,
  2349. RSPAMD_CL_FLAG_MULTIPLE,
  2350. "Encryption keypair (can be repeated for different keys)");
  2351. rspamd_rcl_register_worker_option(cfg,
  2352. type,
  2353. "forbidden_ids",
  2354. fuzzy_parse_ids,
  2355. ctx,
  2356. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, default_forbidden_ids),
  2357. 0,
  2358. "Deny specific flags by default");
  2359. rspamd_rcl_register_worker_option(cfg,
  2360. type,
  2361. "weak_ids",
  2362. fuzzy_parse_ids,
  2363. ctx,
  2364. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, weak_ids),
  2365. 0,
  2366. "Treat these flags as weak (i.e. they do not overwrite strong flags)");
  2367. rspamd_rcl_register_worker_option(cfg,
  2368. type,
  2369. "keypair_cache_size",
  2370. rspamd_rcl_parse_struct_integer,
  2371. ctx,
  2372. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx,
  2373. keypair_cache_size),
  2374. RSPAMD_CL_FLAG_UINT,
  2375. "Size of keypairs cache, default: " G_STRINGIFY(DEFAULT_KEYPAIR_CACHE_SIZE));
  2376. rspamd_rcl_register_worker_option(cfg,
  2377. type,
  2378. "encrypted_only",
  2379. rspamd_rcl_parse_struct_boolean,
  2380. ctx,
  2381. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, encrypted_only),
  2382. 0,
  2383. "Allow encrypted requests only (and forbid all unknown keys or plaintext requests)");
  2384. rspamd_rcl_register_worker_option(cfg,
  2385. type,
  2386. "dedicated_update_worker",
  2387. rspamd_rcl_parse_struct_boolean,
  2388. ctx,
  2389. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, dedicated_update_worker),
  2390. 0,
  2391. "Use worker 0 for updates only");
  2392. rspamd_rcl_register_worker_option(cfg,
  2393. type,
  2394. "read_only",
  2395. rspamd_rcl_parse_struct_boolean,
  2396. ctx,
  2397. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, read_only),
  2398. 0,
  2399. "Work in read only mode");
  2400. rspamd_rcl_register_worker_option(cfg,
  2401. type,
  2402. "blocked",
  2403. rspamd_rcl_parse_struct_ucl,
  2404. ctx,
  2405. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, blocked_map),
  2406. 0,
  2407. "Block requests from specific networks");
  2408. rspamd_rcl_register_worker_option(cfg,
  2409. type,
  2410. "updates_maxfail",
  2411. rspamd_rcl_parse_struct_integer,
  2412. ctx,
  2413. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, updates_maxfail),
  2414. RSPAMD_CL_FLAG_UINT,
  2415. "Maximum number of updates to be failed before discarding");
  2416. rspamd_rcl_register_worker_option(cfg,
  2417. type,
  2418. "skip_hashes",
  2419. rspamd_rcl_parse_struct_ucl,
  2420. ctx,
  2421. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, skip_map),
  2422. 0,
  2423. "Skip specific hashes from the map");
  2424. /* Ratelimits */
  2425. rspamd_rcl_register_worker_option(cfg,
  2426. type,
  2427. "ratelimit_whitelist",
  2428. rspamd_rcl_parse_struct_ucl,
  2429. ctx,
  2430. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, ratelimit_whitelist_map),
  2431. 0,
  2432. "Skip specific addresses from rate limiting");
  2433. rspamd_rcl_register_worker_option(cfg,
  2434. type,
  2435. "ratelimit_max_buckets",
  2436. rspamd_rcl_parse_struct_integer,
  2437. ctx,
  2438. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, max_buckets),
  2439. RSPAMD_CL_FLAG_UINT,
  2440. "Maximum number of leaky buckets (default: " G_STRINGIFY(DEFAULT_MAX_BUCKETS) ")");
  2441. rspamd_rcl_register_worker_option(cfg,
  2442. type,
  2443. "ratelimit_network_mask",
  2444. rspamd_rcl_parse_struct_integer,
  2445. ctx,
  2446. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, leaky_bucket_mask),
  2447. RSPAMD_CL_FLAG_UINT,
  2448. "Network mask to apply for IPv4 rate addresses (default: " G_STRINGIFY(DEFAULT_BUCKET_MASK) ")");
  2449. rspamd_rcl_register_worker_option(cfg,
  2450. type,
  2451. "ratelimit_bucket_ttl",
  2452. rspamd_rcl_parse_struct_time,
  2453. ctx,
  2454. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, leaky_bucket_ttl),
  2455. RSPAMD_CL_FLAG_TIME_INTEGER,
  2456. "Time to live for ratelimit element (default: " G_STRINGIFY(DEFAULT_BUCKET_TTL) ")");
  2457. rspamd_rcl_register_worker_option(cfg,
  2458. type,
  2459. "ratelimit_rate",
  2460. rspamd_rcl_parse_struct_double,
  2461. ctx,
  2462. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, leaky_bucket_rate),
  2463. 0,
  2464. "Leak rate in requests per second");
  2465. rspamd_rcl_register_worker_option(cfg,
  2466. type,
  2467. "ratelimit_burst",
  2468. rspamd_rcl_parse_struct_double,
  2469. ctx,
  2470. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, leaky_bucket_burst),
  2471. 0,
  2472. "Peak value for ratelimit bucket");
  2473. rspamd_rcl_register_worker_option(cfg,
  2474. type,
  2475. "ratelimit_log_only",
  2476. rspamd_rcl_parse_struct_boolean,
  2477. ctx,
  2478. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, ratelimit_log_only),
  2479. 0,
  2480. "Don't really ban on ratelimit reaching, just log");
  2481. return ctx;
  2482. }
  2483. static void
  2484. rspamd_fuzzy_peer_io(EV_P_ ev_io *w, int revents)
  2485. {
  2486. struct fuzzy_peer_cmd cmd;
  2487. struct rspamd_fuzzy_storage_ctx *ctx =
  2488. (struct rspamd_fuzzy_storage_ctx *) w->data;
  2489. gssize r;
  2490. for (;;) {
  2491. r = read(w->fd, &cmd, sizeof(cmd));
  2492. if (r != sizeof(cmd)) {
  2493. if (errno == EINTR) {
  2494. continue;
  2495. }
  2496. if (errno != EAGAIN) {
  2497. msg_err("cannot read command from peers: %s", strerror(errno));
  2498. }
  2499. break;
  2500. }
  2501. else {
  2502. g_array_append_val(ctx->updates_pending, cmd);
  2503. }
  2504. }
  2505. }
  2506. static void
  2507. fuzzy_peer_rep(struct rspamd_worker *worker,
  2508. struct rspamd_srv_reply *rep, gint rep_fd,
  2509. gpointer ud)
  2510. {
  2511. struct rspamd_fuzzy_storage_ctx *ctx = ud;
  2512. GList *cur;
  2513. struct rspamd_worker_listen_socket *ls;
  2514. struct rspamd_worker_accept_event *ac_ev;
  2515. ctx->peer_fd = rep_fd;
  2516. if (rep_fd == -1) {
  2517. msg_err("cannot receive peer fd from the main process");
  2518. exit(EXIT_FAILURE);
  2519. }
  2520. else {
  2521. rspamd_socket_nonblocking(rep_fd);
  2522. }
  2523. msg_info("got peer fd reply from the main process");
  2524. /* Start listening */
  2525. cur = worker->cf->listen_socks;
  2526. while (cur) {
  2527. ls = cur->data;
  2528. if (ls->fd != -1) {
  2529. msg_info("start listening on %s",
  2530. rspamd_inet_address_to_string_pretty(ls->addr));
  2531. if (ls->type == RSPAMD_WORKER_SOCKET_UDP) {
  2532. ac_ev = g_malloc0(sizeof(*ac_ev));
  2533. ac_ev->accept_ev.data = worker;
  2534. ac_ev->event_loop = ctx->event_loop;
  2535. ev_io_init(&ac_ev->accept_ev, accept_fuzzy_socket, ls->fd,
  2536. EV_READ);
  2537. ev_io_start(ctx->event_loop, &ac_ev->accept_ev);
  2538. DL_APPEND(worker->accept_events, ac_ev);
  2539. }
  2540. else {
  2541. /* We allow TCP listeners only for a update worker */
  2542. g_assert_not_reached();
  2543. }
  2544. }
  2545. cur = g_list_next(cur);
  2546. }
  2547. if (ctx->peer_fd != -1) {
  2548. if (worker->index == 0) {
  2549. /* Listen for peer requests */
  2550. shutdown(ctx->peer_fd, SHUT_WR);
  2551. ctx->peer_ev.data = ctx;
  2552. ev_io_init(&ctx->peer_ev, rspamd_fuzzy_peer_io, ctx->peer_fd, EV_READ);
  2553. ev_io_start(ctx->event_loop, &ctx->peer_ev);
  2554. }
  2555. else {
  2556. shutdown(ctx->peer_fd, SHUT_RD);
  2557. }
  2558. }
  2559. }
  2560. /*
  2561. * Start worker process
  2562. */
  2563. __attribute__((noreturn)) void
  2564. start_fuzzy(struct rspamd_worker *worker)
  2565. {
  2566. struct rspamd_fuzzy_storage_ctx *ctx = worker->ctx;
  2567. GError *err = NULL;
  2568. struct rspamd_srv_command srv_cmd;
  2569. struct rspamd_config *cfg = worker->srv->cfg;
  2570. g_assert(rspamd_worker_check_context(worker->ctx, rspamd_fuzzy_storage_magic));
  2571. ctx->event_loop = rspamd_prepare_worker(worker,
  2572. "fuzzy",
  2573. NULL);
  2574. ctx->peer_fd = -1;
  2575. ctx->worker = worker;
  2576. ctx->cfg = worker->srv->cfg;
  2577. ctx->resolver = rspamd_dns_resolver_init(worker->srv->logger,
  2578. ctx->event_loop,
  2579. worker->srv->cfg);
  2580. rspamd_upstreams_library_config(worker->srv->cfg, ctx->cfg->ups_ctx,
  2581. ctx->event_loop, ctx->resolver->r);
  2582. /* Since this worker uses maps it needs a valid HTTP context */
  2583. ctx->http_ctx = rspamd_http_context_create(ctx->cfg, ctx->event_loop,
  2584. ctx->cfg->ups_ctx);
  2585. if (ctx->keypair_cache_size > 0) {
  2586. /* Create keypairs cache */
  2587. ctx->keypair_cache = rspamd_keypair_cache_new(ctx->keypair_cache_size);
  2588. }
  2589. if ((ctx->backend = rspamd_fuzzy_backend_create(ctx->event_loop,
  2590. worker->cf->options, cfg, &err)) == NULL) {
  2591. msg_err("cannot open backend: %e", err);
  2592. if (err) {
  2593. g_error_free(err);
  2594. }
  2595. exit(EXIT_SUCCESS);
  2596. }
  2597. rspamd_fuzzy_backend_count(ctx->backend, fuzzy_count_callback, ctx);
  2598. if (worker->index == 0) {
  2599. ctx->updates_pending = g_array_sized_new(FALSE, FALSE,
  2600. sizeof(struct fuzzy_peer_cmd), 1024);
  2601. rspamd_fuzzy_backend_start_update(ctx->backend, ctx->sync_timeout,
  2602. rspamd_fuzzy_storage_periodic_callback, ctx);
  2603. if (ctx->dedicated_update_worker && worker->cf->count > 1) {
  2604. msg_info_config("stop serving clients request in dedicated update mode");
  2605. rspamd_worker_stop_accept(worker);
  2606. GList *cur = worker->cf->listen_socks;
  2607. while (cur) {
  2608. struct rspamd_worker_listen_socket *ls =
  2609. (struct rspamd_worker_listen_socket *) cur->data;
  2610. if (ls->fd != -1) {
  2611. close(ls->fd);
  2612. }
  2613. cur = g_list_next(cur);
  2614. }
  2615. }
  2616. }
  2617. ctx->stat_ev.data = ctx;
  2618. ev_timer_init(&ctx->stat_ev, rspamd_fuzzy_stat_callback, ctx->sync_timeout,
  2619. ctx->sync_timeout);
  2620. ev_timer_start(ctx->event_loop, &ctx->stat_ev);
  2621. /* Register custom reload and stat commands for the control socket */
  2622. rspamd_control_worker_add_cmd_handler(worker, RSPAMD_CONTROL_RELOAD,
  2623. rspamd_fuzzy_storage_reload, ctx);
  2624. rspamd_control_worker_add_cmd_handler(worker, RSPAMD_CONTROL_FUZZY_STAT,
  2625. rspamd_fuzzy_storage_stat, ctx);
  2626. rspamd_control_worker_add_cmd_handler(worker, RSPAMD_CONTROL_FUZZY_SYNC,
  2627. rspamd_fuzzy_storage_sync, ctx);
  2628. rspamd_control_worker_add_cmd_handler(worker, RSPAMD_CONTROL_FUZZY_BLOCKED,
  2629. rspamd_fuzzy_control_blocked, ctx);
  2630. if (ctx->update_map != NULL) {
  2631. rspamd_config_radix_from_ucl(worker->srv->cfg, ctx->update_map,
  2632. "Allow fuzzy updates from specified addresses",
  2633. &ctx->update_ips, NULL, worker, "fuzzy update");
  2634. }
  2635. if (ctx->update_keys_map != NULL) {
  2636. struct rspamd_map *m;
  2637. if ((m = rspamd_map_add_from_ucl(worker->srv->cfg, ctx->update_keys_map,
  2638. "Allow fuzzy updates from specified public keys",
  2639. rspamd_kv_list_read,
  2640. rspamd_kv_list_fin,
  2641. rspamd_kv_list_dtor,
  2642. (void **) &ctx->update_keys, worker, RSPAMD_MAP_DEFAULT)) == NULL) {
  2643. msg_warn_config("cannot load allow keys map from %s",
  2644. ucl_object_tostring(ctx->update_keys_map));
  2645. }
  2646. else {
  2647. m->active_http = TRUE;
  2648. }
  2649. }
  2650. if (ctx->skip_map != NULL) {
  2651. struct rspamd_map *m;
  2652. if ((m = rspamd_map_add_from_ucl(cfg, ctx->skip_map,
  2653. "Skip hashes",
  2654. rspamd_kv_list_read,
  2655. rspamd_kv_list_fin,
  2656. rspamd_kv_list_dtor,
  2657. (void **) &ctx->skip_hashes,
  2658. worker, RSPAMD_MAP_DEFAULT)) == NULL) {
  2659. msg_warn_config("cannot load hashes list from %s",
  2660. ucl_object_tostring(ctx->skip_map));
  2661. }
  2662. else {
  2663. m->active_http = TRUE;
  2664. }
  2665. }
  2666. if (ctx->blocked_map != NULL) {
  2667. rspamd_config_radix_from_ucl(worker->srv->cfg, ctx->blocked_map,
  2668. "Block fuzzy requests from the specific IPs",
  2669. &ctx->blocked_ips,
  2670. NULL,
  2671. worker, "fuzzy blocked");
  2672. }
  2673. /* Create radix trees */
  2674. if (ctx->ratelimit_whitelist_map != NULL) {
  2675. rspamd_config_radix_from_ucl(worker->srv->cfg, ctx->ratelimit_whitelist_map,
  2676. "Skip ratelimits from specific ip addresses/networks",
  2677. &ctx->ratelimit_whitelist,
  2678. NULL,
  2679. worker, "fuzzy ratelimit whitelist");
  2680. }
  2681. if (!isnan(ctx->delay) && ctx->delay_whitelist_map != NULL) {
  2682. rspamd_config_radix_from_ucl(worker->srv->cfg, ctx->delay_whitelist_map,
  2683. "Skip delay from the following ips",
  2684. &ctx->delay_whitelist, NULL, worker,
  2685. "fuzzy delayed whitelist");
  2686. }
  2687. /* Ratelimits */
  2688. if (!isnan(ctx->leaky_bucket_rate) && !isnan(ctx->leaky_bucket_burst)) {
  2689. ctx->ratelimit_buckets = rspamd_lru_hash_new_full(ctx->max_buckets,
  2690. NULL, fuzzy_rl_bucket_free,
  2691. rspamd_inet_address_hash, rspamd_inet_address_equal);
  2692. rspamd_fuzzy_maybe_load_ratelimits(ctx);
  2693. }
  2694. /* Maps events */
  2695. ctx->resolver = rspamd_dns_resolver_init(worker->srv->logger,
  2696. ctx->event_loop,
  2697. worker->srv->cfg);
  2698. rspamd_map_watch(worker->srv->cfg, ctx->event_loop,
  2699. ctx->resolver, worker, RSPAMD_MAP_WATCH_WORKER);
  2700. /* Get peer pipe */
  2701. memset(&srv_cmd, 0, sizeof(srv_cmd));
  2702. srv_cmd.type = RSPAMD_SRV_SOCKETPAIR;
  2703. srv_cmd.cmd.spair.af = SOCK_DGRAM;
  2704. srv_cmd.cmd.spair.pair_num = worker->index;
  2705. memset(srv_cmd.cmd.spair.pair_id, 0, sizeof(srv_cmd.cmd.spair.pair_id));
  2706. /* 6 bytes of id (including \0) and bind_conf id */
  2707. G_STATIC_ASSERT(sizeof(srv_cmd.cmd.spair.pair_id) >=
  2708. sizeof("fuzzy") + sizeof(guint64));
  2709. memcpy(srv_cmd.cmd.spair.pair_id, "fuzzy", sizeof("fuzzy"));
  2710. /* Distinguish workers from each others... */
  2711. if (worker->cf->bind_conf && worker->cf->bind_conf->bind_line) {
  2712. guint64 bind_hash = rspamd_cryptobox_fast_hash(worker->cf->bind_conf->bind_line,
  2713. strlen(worker->cf->bind_conf->bind_line), 0xdeadbabe);
  2714. /* 8 more bytes */
  2715. memcpy(srv_cmd.cmd.spair.pair_id + sizeof("fuzzy"), &bind_hash,
  2716. sizeof(bind_hash));
  2717. }
  2718. rspamd_srv_send_command(worker, ctx->event_loop, &srv_cmd, -1,
  2719. fuzzy_peer_rep, ctx);
  2720. /*
  2721. * Extra fields available for this particular worker
  2722. */
  2723. luaL_Reg fuzzy_lua_reg = {
  2724. .name = "add_fuzzy_pre_handler",
  2725. .func = lua_fuzzy_add_pre_handler,
  2726. };
  2727. rspamd_lua_add_metamethod(ctx->cfg->lua_state, "rspamd{worker}", &fuzzy_lua_reg);
  2728. fuzzy_lua_reg = (luaL_Reg){
  2729. .name = "add_fuzzy_post_handler",
  2730. .func = lua_fuzzy_add_post_handler,
  2731. };
  2732. rspamd_lua_add_metamethod(ctx->cfg->lua_state, "rspamd{worker}", &fuzzy_lua_reg);
  2733. fuzzy_lua_reg = (luaL_Reg){
  2734. .name = "add_fuzzy_blacklist_handler",
  2735. .func = lua_fuzzy_add_blacklist_handler,
  2736. };
  2737. rspamd_lua_add_metamethod(ctx->cfg->lua_state, "rspamd{worker}", &fuzzy_lua_reg);
  2738. rspamd_lua_run_postloads(ctx->cfg->lua_state, ctx->cfg, ctx->event_loop,
  2739. worker);
  2740. ev_loop(ctx->event_loop, 0);
  2741. rspamd_worker_block_signals();
  2742. if (ctx->peer_fd != -1) {
  2743. if (worker->index == 0) {
  2744. ev_io_stop(ctx->event_loop, &ctx->peer_ev);
  2745. }
  2746. close(ctx->peer_fd);
  2747. }
  2748. if (worker->index == 0 && ctx->updates_pending->len > 0) {
  2749. msg_info_config("start another event loop to sync fuzzy storage");
  2750. if (rspamd_fuzzy_process_updates_queue(ctx, local_db_name, TRUE)) {
  2751. ev_loop(ctx->event_loop, 0);
  2752. msg_info_config("sync cycle is done");
  2753. }
  2754. else {
  2755. msg_info_config("no need to sync");
  2756. }
  2757. }
  2758. rspamd_fuzzy_backend_close(ctx->backend);
  2759. if (worker->index == 0) {
  2760. g_array_free(ctx->updates_pending, TRUE);
  2761. ctx->updates_pending = NULL;
  2762. }
  2763. if (ctx->keypair_cache) {
  2764. rspamd_keypair_cache_destroy(ctx->keypair_cache);
  2765. }
  2766. if (ctx->ratelimit_buckets) {
  2767. /* Try the best to save ratelimits from the proper worker */
  2768. if ((!ctx->dedicated_update_worker && worker->index == 0) ||
  2769. (ctx->dedicated_update_worker && worker->index == 1)) {
  2770. rspamd_fuzzy_maybe_save_ratelimits(ctx);
  2771. }
  2772. rspamd_lru_hash_destroy(ctx->ratelimit_buckets);
  2773. }
  2774. if (ctx->lua_pre_handler_cbref != -1) {
  2775. luaL_unref(ctx->cfg->lua_state, LUA_REGISTRYINDEX, ctx->lua_pre_handler_cbref);
  2776. }
  2777. if (ctx->lua_post_handler_cbref != -1) {
  2778. luaL_unref(ctx->cfg->lua_state, LUA_REGISTRYINDEX, ctx->lua_post_handler_cbref);
  2779. }
  2780. if (ctx->lua_blacklist_cbref != -1) {
  2781. luaL_unref(ctx->cfg->lua_state, LUA_REGISTRYINDEX, ctx->lua_blacklist_cbref);
  2782. }
  2783. if (ctx->default_forbidden_ids) {
  2784. kh_destroy(fuzzy_key_ids_set, ctx->default_forbidden_ids);
  2785. }
  2786. if (ctx->weak_ids) {
  2787. kh_destroy(fuzzy_key_ids_set, ctx->weak_ids);
  2788. }
  2789. REF_RELEASE(ctx->cfg);
  2790. rspamd_log_close(worker->srv->logger);
  2791. rspamd_unset_crash_handler(worker->srv);
  2792. exit(EXIT_SUCCESS);
  2793. }