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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285
  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. result.v1.prob = 1.0f;
  1153. result.v1.value = 0;
  1154. result.v1.flag = session->ctx->stat.fuzzy_hashes;
  1155. rspamd_fuzzy_make_reply(cmd, &result, session, send_flags);
  1156. }
  1157. else if (cmd->cmd == FUZZY_PING) {
  1158. result.v1.prob = 1.0f;
  1159. result.v1.value = cmd->value;
  1160. rspamd_fuzzy_make_reply(cmd, &result, session, send_flags);
  1161. }
  1162. else {
  1163. if (rspamd_fuzzy_check_write(session)) {
  1164. /* Check whitelist */
  1165. if (session->ctx->skip_hashes && cmd->cmd == FUZZY_WRITE) {
  1166. rspamd_encode_hex_buf(cmd->digest, sizeof(cmd->digest),
  1167. hexbuf, sizeof(hexbuf) - 1);
  1168. hexbuf[sizeof(hexbuf) - 1] = '\0';
  1169. if (rspamd_match_hash_map(session->ctx->skip_hashes,
  1170. hexbuf, sizeof(hexbuf) - 1)) {
  1171. result.v1.value = 401;
  1172. result.v1.prob = 0.0f;
  1173. goto reply;
  1174. }
  1175. }
  1176. if (session->ctx->weak_ids && kh_get(fuzzy_key_ids_set, session->ctx->weak_ids, cmd->flag) != kh_end(session->ctx->weak_ids)) {
  1177. /* Flag command as weak */
  1178. cmd->version |= RSPAMD_FUZZY_FLAG_WEAK;
  1179. }
  1180. if (session->worker->index == 0 || session->ctx->peer_fd == -1) {
  1181. /* Just add to the queue */
  1182. up_cmd.is_shingle = is_shingle;
  1183. ptr = is_shingle ? (gpointer) &up_cmd.cmd.shingle : (gpointer) &up_cmd.cmd.normal;
  1184. memcpy(ptr, cmd, up_len);
  1185. g_array_append_val(session->ctx->updates_pending, up_cmd);
  1186. }
  1187. else {
  1188. /* We need to send request to the peer */
  1189. up_req = g_malloc0(sizeof(*up_req));
  1190. up_req->cmd.is_shingle = is_shingle;
  1191. ptr = is_shingle ? (gpointer) &up_req->cmd.cmd.shingle : (gpointer) &up_req->cmd.cmd.normal;
  1192. memcpy(ptr, cmd, up_len);
  1193. if (!fuzzy_peer_try_send(session->ctx->peer_fd, up_req)) {
  1194. up_req->io_ev.data = up_req;
  1195. ev_io_init(&up_req->io_ev, fuzzy_peer_send_io,
  1196. session->ctx->peer_fd, EV_WRITE);
  1197. ev_io_start(session->ctx->event_loop, &up_req->io_ev);
  1198. }
  1199. else {
  1200. g_free(up_req);
  1201. }
  1202. }
  1203. result.v1.value = 0;
  1204. result.v1.prob = 1.0f;
  1205. }
  1206. else {
  1207. result.v1.value = 403;
  1208. result.v1.prob = 0.0f;
  1209. }
  1210. reply:
  1211. rspamd_fuzzy_make_reply(cmd, &result, session, send_flags);
  1212. }
  1213. }
  1214. static enum rspamd_fuzzy_epoch
  1215. rspamd_fuzzy_command_valid(struct rspamd_fuzzy_cmd *cmd, gint r)
  1216. {
  1217. enum rspamd_fuzzy_epoch ret = RSPAMD_FUZZY_EPOCH_MAX;
  1218. switch (cmd->version & RSPAMD_FUZZY_VERSION_MASK) {
  1219. case 4:
  1220. if (cmd->shingles_count > 0) {
  1221. if (r >= sizeof(struct rspamd_fuzzy_shingle_cmd)) {
  1222. ret = RSPAMD_FUZZY_EPOCH11;
  1223. }
  1224. }
  1225. else {
  1226. if (r >= sizeof(*cmd)) {
  1227. ret = RSPAMD_FUZZY_EPOCH11;
  1228. }
  1229. }
  1230. break;
  1231. case 3:
  1232. if (cmd->shingles_count > 0) {
  1233. if (r == sizeof(struct rspamd_fuzzy_shingle_cmd)) {
  1234. ret = RSPAMD_FUZZY_EPOCH10;
  1235. }
  1236. }
  1237. else {
  1238. if (r == sizeof(*cmd)) {
  1239. ret = RSPAMD_FUZZY_EPOCH10;
  1240. }
  1241. }
  1242. break;
  1243. default:
  1244. break;
  1245. }
  1246. return ret;
  1247. }
  1248. static gboolean
  1249. rspamd_fuzzy_decrypt_command(struct fuzzy_session *s, guchar *buf, gsize buflen)
  1250. {
  1251. struct rspamd_fuzzy_encrypted_req_hdr hdr;
  1252. struct rspamd_cryptobox_pubkey *rk;
  1253. struct fuzzy_key *key;
  1254. if (s->ctx->default_key == NULL) {
  1255. msg_warn("received encrypted request when encryption is not enabled");
  1256. return FALSE;
  1257. }
  1258. if (buflen < sizeof(hdr)) {
  1259. msg_warn("XXX: should not be reached");
  1260. return FALSE;
  1261. }
  1262. memcpy(&hdr, buf, sizeof(hdr));
  1263. buf += sizeof(hdr);
  1264. buflen -= sizeof(hdr);
  1265. /* Try to find the desired key */
  1266. key = g_hash_table_lookup(s->ctx->keys, hdr.key_id);
  1267. if (key == NULL) {
  1268. /* Unknown key, assume default one */
  1269. key = s->ctx->default_key;
  1270. }
  1271. s->key = key;
  1272. /* Now process keypair */
  1273. rk = rspamd_pubkey_from_bin(hdr.pubkey, sizeof(hdr.pubkey),
  1274. RSPAMD_KEYPAIR_KEX, RSPAMD_CRYPTOBOX_MODE_25519);
  1275. if (rk == NULL) {
  1276. msg_err("bad key; ip=%s",
  1277. rspamd_inet_address_to_string(s->addr));
  1278. return FALSE;
  1279. }
  1280. rspamd_keypair_cache_process(s->ctx->keypair_cache, key->key, rk);
  1281. /* Now decrypt request */
  1282. if (!rspamd_cryptobox_decrypt_nm_inplace(buf, buflen, hdr.nonce,
  1283. rspamd_pubkey_get_nm(rk, key->key),
  1284. hdr.mac, RSPAMD_CRYPTOBOX_MODE_25519)) {
  1285. msg_err("decryption failed; ip=%s",
  1286. rspamd_inet_address_to_string(s->addr));
  1287. rspamd_pubkey_unref(rk);
  1288. return FALSE;
  1289. }
  1290. memcpy(s->nm, rspamd_pubkey_get_nm(rk, key->key), sizeof(s->nm));
  1291. rspamd_pubkey_unref(rk);
  1292. return TRUE;
  1293. }
  1294. static gboolean
  1295. rspamd_fuzzy_extensions_from_wire(struct fuzzy_session *s, guchar *buf, gsize buflen)
  1296. {
  1297. struct rspamd_fuzzy_cmd_extension *ext, *prev_ext;
  1298. guchar *storage, *p = buf, *end = buf + buflen;
  1299. gsize st_len = 0, n_ext = 0;
  1300. /* Read number of extensions to allocate array */
  1301. while (p < end) {
  1302. guchar cmd = *p++;
  1303. if (p < end) {
  1304. if (cmd == RSPAMD_FUZZY_EXT_SOURCE_DOMAIN) {
  1305. /* Next byte is buf length */
  1306. guchar dom_len = *p++;
  1307. if (dom_len <= (end - p)) {
  1308. st_len += dom_len;
  1309. n_ext++;
  1310. }
  1311. else {
  1312. /* Truncation */
  1313. return FALSE;
  1314. }
  1315. p += dom_len;
  1316. }
  1317. else if (cmd == RSPAMD_FUZZY_EXT_SOURCE_IP4) {
  1318. if (end - p >= sizeof(in_addr_t)) {
  1319. n_ext++;
  1320. st_len += sizeof(in_addr_t);
  1321. }
  1322. else {
  1323. /* Truncation */
  1324. return FALSE;
  1325. }
  1326. p += sizeof(in_addr_t);
  1327. }
  1328. else if (cmd == RSPAMD_FUZZY_EXT_SOURCE_IP6) {
  1329. if (end - p >= sizeof(struct in6_addr)) {
  1330. n_ext++;
  1331. st_len += sizeof(struct in6_addr);
  1332. }
  1333. else {
  1334. /* Truncation */
  1335. return FALSE;
  1336. }
  1337. p += sizeof(struct in6_addr);
  1338. }
  1339. else {
  1340. /* Invalid command */
  1341. return FALSE;
  1342. }
  1343. }
  1344. else {
  1345. /* Truncated extension */
  1346. return FALSE;
  1347. }
  1348. }
  1349. if (n_ext > 0) {
  1350. p = buf;
  1351. /*
  1352. * Memory layout: n_ext of struct rspamd_fuzzy_cmd_extension
  1353. * payload for each extension in a continuous data segment
  1354. */
  1355. storage = g_malloc(n_ext * sizeof(struct rspamd_fuzzy_cmd_extension) +
  1356. st_len);
  1357. guchar *data_buf = storage +
  1358. n_ext * sizeof(struct rspamd_fuzzy_cmd_extension);
  1359. ext = (struct rspamd_fuzzy_cmd_extension *) storage;
  1360. /* All validation has been done, so we can just go further */
  1361. while (p < end) {
  1362. prev_ext = ext;
  1363. guchar cmd = *p++;
  1364. if (cmd == RSPAMD_FUZZY_EXT_SOURCE_DOMAIN) {
  1365. /* Next byte is buf length */
  1366. guchar dom_len = *p++;
  1367. guchar *dest = data_buf;
  1368. ext->ext = RSPAMD_FUZZY_EXT_SOURCE_DOMAIN;
  1369. ext->next = ext + 1;
  1370. ext->length = dom_len;
  1371. ext->payload = dest;
  1372. memcpy(dest, p, dom_len);
  1373. p += dom_len;
  1374. data_buf += dom_len;
  1375. ext = ext->next;
  1376. }
  1377. else if (cmd == RSPAMD_FUZZY_EXT_SOURCE_IP4) {
  1378. guchar *dest = data_buf;
  1379. ext->ext = RSPAMD_FUZZY_EXT_SOURCE_IP4;
  1380. ext->next = ext + 1;
  1381. ext->length = sizeof(in_addr_t);
  1382. ext->payload = dest;
  1383. memcpy(dest, p, sizeof(in_addr_t));
  1384. p += sizeof(in_addr_t);
  1385. data_buf += sizeof(in_addr_t);
  1386. ext = ext->next;
  1387. }
  1388. else if (cmd == RSPAMD_FUZZY_EXT_SOURCE_IP6) {
  1389. guchar *dest = data_buf;
  1390. ext->ext = RSPAMD_FUZZY_EXT_SOURCE_IP6;
  1391. ext->next = ext + 1;
  1392. ext->length = sizeof(struct in6_addr);
  1393. ext->payload = dest;
  1394. memcpy(dest, p, sizeof(struct in6_addr));
  1395. p += sizeof(struct in6_addr);
  1396. data_buf += sizeof(struct in6_addr);
  1397. ext = ext->next;
  1398. }
  1399. else {
  1400. g_assert_not_reached();
  1401. }
  1402. }
  1403. /* Last next should be NULL */
  1404. prev_ext->next = NULL;
  1405. /* Rewind to the begin */
  1406. ext = (struct rspamd_fuzzy_cmd_extension *) storage;
  1407. s->extensions = ext;
  1408. }
  1409. return TRUE;
  1410. }
  1411. static gboolean
  1412. rspamd_fuzzy_cmd_from_wire(guchar *buf, guint buflen, struct fuzzy_session *s)
  1413. {
  1414. enum rspamd_fuzzy_epoch epoch;
  1415. gboolean encrypted = FALSE;
  1416. if (buflen < sizeof(struct rspamd_fuzzy_cmd)) {
  1417. msg_debug("truncated fuzzy command of size %d received", buflen);
  1418. return FALSE;
  1419. }
  1420. /* Now check encryption */
  1421. if (buflen >= sizeof(struct rspamd_fuzzy_encrypted_cmd)) {
  1422. if (memcmp(buf, fuzzy_encrypted_magic, sizeof(fuzzy_encrypted_magic)) == 0) {
  1423. /* Encrypted command */
  1424. encrypted = TRUE;
  1425. }
  1426. }
  1427. if (encrypted) {
  1428. /* Decrypt first */
  1429. if (!rspamd_fuzzy_decrypt_command(s, buf, buflen)) {
  1430. return FALSE;
  1431. }
  1432. else {
  1433. /*
  1434. * Advance buffer to skip encrypted header.
  1435. * Note that after rspamd_fuzzy_decrypt_command buf is unencrypted
  1436. */
  1437. buf += sizeof(struct rspamd_fuzzy_encrypted_req_hdr);
  1438. buflen -= sizeof(struct rspamd_fuzzy_encrypted_req_hdr);
  1439. }
  1440. }
  1441. /* Fill the normal command */
  1442. if (buflen < sizeof(s->cmd.basic)) {
  1443. msg_debug("truncated normal fuzzy command of size %d received", buflen);
  1444. return FALSE;
  1445. }
  1446. memcpy(&s->cmd.basic, buf, sizeof(s->cmd.basic));
  1447. epoch = rspamd_fuzzy_command_valid(&s->cmd.basic, buflen);
  1448. if (epoch == RSPAMD_FUZZY_EPOCH_MAX) {
  1449. msg_debug("invalid fuzzy command of size %d received", buflen);
  1450. return FALSE;
  1451. }
  1452. s->epoch = epoch;
  1453. /* Advance buf */
  1454. buf += sizeof(s->cmd.basic);
  1455. buflen -= sizeof(s->cmd.basic);
  1456. if (s->cmd.basic.shingles_count > 0) {
  1457. if (buflen >= sizeof(s->cmd.sgl)) {
  1458. /* Copy the shingles part */
  1459. memcpy(&s->cmd.sgl, buf, sizeof(s->cmd.sgl));
  1460. }
  1461. else {
  1462. /* Truncated stuff */
  1463. msg_debug("truncated fuzzy shingles command of size %d received", buflen);
  1464. return FALSE;
  1465. }
  1466. buf += sizeof(s->cmd.sgl);
  1467. buflen -= sizeof(s->cmd.sgl);
  1468. if (encrypted) {
  1469. s->cmd_type = CMD_ENCRYPTED_SHINGLE;
  1470. }
  1471. else {
  1472. s->cmd_type = CMD_SHINGLE;
  1473. }
  1474. }
  1475. else {
  1476. if (encrypted) {
  1477. s->cmd_type = CMD_ENCRYPTED_NORMAL;
  1478. }
  1479. else {
  1480. s->cmd_type = CMD_NORMAL;
  1481. }
  1482. }
  1483. if (buflen > 0) {
  1484. /* Process possible extensions */
  1485. if (!rspamd_fuzzy_extensions_from_wire(s, buf, buflen)) {
  1486. msg_debug("truncated fuzzy shingles command of size %d received", buflen);
  1487. return FALSE;
  1488. }
  1489. }
  1490. return TRUE;
  1491. }
  1492. static void
  1493. fuzzy_session_destroy(gpointer d)
  1494. {
  1495. struct fuzzy_session *session = d;
  1496. rspamd_inet_address_free(session->addr);
  1497. rspamd_explicit_memzero(session->nm, sizeof(session->nm));
  1498. session->worker->nconns--;
  1499. if (session->ip_stat) {
  1500. REF_RELEASE(session->ip_stat);
  1501. }
  1502. if (session->extensions) {
  1503. g_free(session->extensions);
  1504. }
  1505. g_free(session);
  1506. }
  1507. #define FUZZY_INPUT_BUFLEN 1024
  1508. #ifdef HAVE_RECVMMSG
  1509. #define MSGVEC_LEN 16
  1510. #else
  1511. #define MSGVEC_LEN 1
  1512. #endif
  1513. union sa_union {
  1514. struct sockaddr sa;
  1515. struct sockaddr_in s4;
  1516. struct sockaddr_in6 s6;
  1517. struct sockaddr_un su;
  1518. struct sockaddr_storage ss;
  1519. };
  1520. /*
  1521. * Accept new connection and construct task
  1522. */
  1523. static void
  1524. accept_fuzzy_socket(EV_P_ ev_io *w, int revents)
  1525. {
  1526. struct rspamd_worker *worker = (struct rspamd_worker *) w->data;
  1527. struct rspamd_fuzzy_storage_ctx *ctx;
  1528. struct fuzzy_session *session;
  1529. gssize r, msg_len;
  1530. guint64 *nerrors;
  1531. struct iovec iovs[MSGVEC_LEN];
  1532. guint8 bufs[MSGVEC_LEN][FUZZY_INPUT_BUFLEN];
  1533. union sa_union peer_sa[MSGVEC_LEN];
  1534. socklen_t salen = sizeof(peer_sa[0]);
  1535. #ifdef HAVE_RECVMMSG
  1536. #define MSG_FIELD(msg, field) msg.msg_hdr.field
  1537. struct mmsghdr msg[MSGVEC_LEN];
  1538. #else
  1539. #define MSG_FIELD(msg, field) msg.field
  1540. struct msghdr msg[MSGVEC_LEN];
  1541. #endif
  1542. memset(msg, 0, sizeof(*msg) * MSGVEC_LEN);
  1543. ctx = (struct rspamd_fuzzy_storage_ctx *) worker->ctx;
  1544. /* Prepare messages to receive */
  1545. for (int i = 0; i < MSGVEC_LEN; i++) {
  1546. /* Prepare msghdr structs */
  1547. iovs[i].iov_base = bufs[i];
  1548. iovs[i].iov_len = sizeof(bufs[i]);
  1549. MSG_FIELD(msg[i], msg_name) = (void *) &peer_sa[i];
  1550. MSG_FIELD(msg[i], msg_namelen) = salen;
  1551. MSG_FIELD(msg[i], msg_iov) = &iovs[i];
  1552. MSG_FIELD(msg[i], msg_iovlen) = 1;
  1553. }
  1554. /* Got some data */
  1555. if (revents == EV_READ) {
  1556. ev_now_update_if_cheap(ctx->event_loop);
  1557. for (;;) {
  1558. #ifdef HAVE_RECVMMSG
  1559. r = recvmmsg(w->fd, msg, MSGVEC_LEN, 0, NULL);
  1560. #else
  1561. r = recvmsg(w->fd, msg, 0);
  1562. #endif
  1563. if (r == -1) {
  1564. if (errno == EINTR) {
  1565. continue;
  1566. }
  1567. else if (errno == EAGAIN || errno == EWOULDBLOCK) {
  1568. return;
  1569. }
  1570. msg_err("got error while reading from socket: %d, %s",
  1571. errno,
  1572. strerror(errno));
  1573. return;
  1574. }
  1575. #ifndef HAVE_RECVMMSG
  1576. msg_len = r; /* Save real length in bytes here */
  1577. r = 1; /* Assume that we have received a single message */
  1578. #endif
  1579. for (int i = 0; i < r; i++) {
  1580. rspamd_inet_addr_t *client_addr;
  1581. if (MSG_FIELD(msg[i], msg_namelen) >= sizeof(struct sockaddr)) {
  1582. client_addr = rspamd_inet_address_from_sa(MSG_FIELD(msg[i], msg_name),
  1583. MSG_FIELD(msg[i], msg_namelen));
  1584. if (!rspamd_fuzzy_check_client(worker->ctx, client_addr)) {
  1585. /* Disallow forbidden clients silently */
  1586. rspamd_inet_address_free(client_addr);
  1587. continue;
  1588. }
  1589. }
  1590. else {
  1591. client_addr = NULL;
  1592. }
  1593. session = g_malloc0(sizeof(*session));
  1594. REF_INIT_RETAIN(session, fuzzy_session_destroy);
  1595. session->worker = worker;
  1596. session->fd = w->fd;
  1597. session->ctx = ctx;
  1598. session->timestamp = ev_now(ctx->event_loop);
  1599. session->addr = client_addr;
  1600. worker->nconns++;
  1601. /* Each message can have its length in case of recvmmsg */
  1602. #ifdef HAVE_RECVMMSG
  1603. msg_len = msg[i].msg_len;
  1604. #endif
  1605. if (rspamd_fuzzy_cmd_from_wire(iovs[i].iov_base,
  1606. msg_len, session)) {
  1607. /* Check shingles count sanity */
  1608. rspamd_fuzzy_process_command(session);
  1609. }
  1610. else {
  1611. /* Discard input */
  1612. session->ctx->stat.invalid_requests++;
  1613. msg_debug("invalid fuzzy command of size %z received", r);
  1614. if (session->addr) {
  1615. nerrors = rspamd_lru_hash_lookup(session->ctx->errors_ips,
  1616. session->addr, -1);
  1617. if (nerrors == NULL) {
  1618. nerrors = g_malloc(sizeof(*nerrors));
  1619. *nerrors = 1;
  1620. rspamd_lru_hash_insert(session->ctx->errors_ips,
  1621. rspamd_inet_address_copy(session->addr, NULL),
  1622. nerrors, -1, -1);
  1623. }
  1624. else {
  1625. *nerrors = *nerrors + 1;
  1626. }
  1627. }
  1628. }
  1629. REF_RELEASE(session);
  1630. }
  1631. #ifdef HAVE_RECVMMSG
  1632. /* Stop reading as we are using recvmmsg instead of recvmsg */
  1633. break;
  1634. #endif
  1635. }
  1636. }
  1637. }
  1638. static gboolean
  1639. rspamd_fuzzy_storage_periodic_callback(void *ud)
  1640. {
  1641. struct rspamd_fuzzy_storage_ctx *ctx = ud;
  1642. if (ctx->updates_pending->len > 0) {
  1643. rspamd_fuzzy_process_updates_queue(ctx, local_db_name, FALSE);
  1644. return TRUE;
  1645. }
  1646. return FALSE;
  1647. }
  1648. static gboolean
  1649. rspamd_fuzzy_storage_sync(struct rspamd_main *rspamd_main,
  1650. struct rspamd_worker *worker, gint fd,
  1651. gint attached_fd,
  1652. struct rspamd_control_command *cmd,
  1653. gpointer ud)
  1654. {
  1655. struct rspamd_fuzzy_storage_ctx *ctx = ud;
  1656. struct rspamd_control_reply rep;
  1657. rep.reply.fuzzy_sync.status = 0;
  1658. rep.type = RSPAMD_CONTROL_FUZZY_SYNC;
  1659. if (ctx->backend && worker->index == 0) {
  1660. rspamd_fuzzy_process_updates_queue(ctx, local_db_name, FALSE);
  1661. rspamd_fuzzy_backend_start_update(ctx->backend, ctx->sync_timeout,
  1662. rspamd_fuzzy_storage_periodic_callback, ctx);
  1663. }
  1664. if (write(fd, &rep, sizeof(rep)) != sizeof(rep)) {
  1665. msg_err("cannot write reply to the control socket: %s",
  1666. strerror(errno));
  1667. }
  1668. return TRUE;
  1669. }
  1670. static gboolean
  1671. rspamd_fuzzy_control_blocked(struct rspamd_main *rspamd_main,
  1672. struct rspamd_worker *worker, gint fd,
  1673. gint attached_fd,
  1674. struct rspamd_control_command *cmd,
  1675. gpointer ud)
  1676. {
  1677. struct rspamd_fuzzy_storage_ctx *ctx = (struct rspamd_fuzzy_storage_ctx *) ud;
  1678. struct rspamd_control_reply rep;
  1679. struct rspamd_leaky_bucket_elt *elt;
  1680. ev_tstamp now = ev_now(ctx->event_loop);
  1681. rspamd_inet_addr_t *addr = NULL;
  1682. rep.type = RSPAMD_CONTROL_FUZZY_BLOCKED;
  1683. rep.reply.fuzzy_blocked.status = 0;
  1684. if (cmd->cmd.fuzzy_blocked.af == AF_INET) {
  1685. addr = rspamd_inet_address_from_sa(&cmd->cmd.fuzzy_blocked.addr.sa,
  1686. sizeof(struct sockaddr_in));
  1687. }
  1688. else if (cmd->cmd.fuzzy_blocked.af == AF_INET6) {
  1689. addr = rspamd_inet_address_from_sa(&cmd->cmd.fuzzy_blocked.addr.sa,
  1690. sizeof(struct sockaddr_in6));
  1691. }
  1692. else {
  1693. msg_err("invalid address family: %d", cmd->cmd.fuzzy_blocked.af);
  1694. rep.reply.fuzzy_blocked.status = -1;
  1695. }
  1696. if (addr) {
  1697. elt = rspamd_lru_hash_lookup(ctx->ratelimit_buckets, addr,
  1698. (time_t) now);
  1699. if (elt) {
  1700. if (isnan(elt->cur)) {
  1701. /* Already ratelimited, ignore */
  1702. }
  1703. else {
  1704. elt->last = now;
  1705. elt->cur = NAN;
  1706. msg_info("propagating ratelimiting %s, %.1f max elts",
  1707. rspamd_inet_address_to_string(addr),
  1708. ctx->leaky_bucket_burst);
  1709. rspamd_fuzzy_maybe_call_blacklisted(ctx, addr, "ratelimit");
  1710. }
  1711. rspamd_inet_address_free(addr);
  1712. }
  1713. else {
  1714. /* New bucket */
  1715. elt = g_malloc(sizeof(*elt));
  1716. elt->addr = addr; /* transfer ownership */
  1717. elt->cur = NAN;
  1718. elt->last = now;
  1719. rspamd_lru_hash_insert(ctx->ratelimit_buckets,
  1720. addr,
  1721. elt,
  1722. (time_t) now,
  1723. ctx->leaky_bucket_ttl);
  1724. msg_info("propagating ratelimiting %s, %.1f max elts",
  1725. rspamd_inet_address_to_string(addr),
  1726. ctx->leaky_bucket_burst);
  1727. rspamd_fuzzy_maybe_call_blacklisted(ctx, addr, "ratelimit");
  1728. }
  1729. }
  1730. if (write(fd, &rep, sizeof(rep)) != sizeof(rep)) {
  1731. msg_err("cannot write reply to the control socket: %s",
  1732. strerror(errno));
  1733. }
  1734. return TRUE;
  1735. }
  1736. static gboolean
  1737. rspamd_fuzzy_storage_reload(struct rspamd_main *rspamd_main,
  1738. struct rspamd_worker *worker, gint fd,
  1739. gint attached_fd,
  1740. struct rspamd_control_command *cmd,
  1741. gpointer ud)
  1742. {
  1743. struct rspamd_fuzzy_storage_ctx *ctx = ud;
  1744. GError *err = NULL;
  1745. struct rspamd_control_reply rep;
  1746. msg_info("reloading fuzzy storage after receiving reload command");
  1747. if (ctx->backend) {
  1748. /* Close backend and reopen it one more time */
  1749. rspamd_fuzzy_backend_close(ctx->backend);
  1750. }
  1751. memset(&rep, 0, sizeof(rep));
  1752. rep.type = RSPAMD_CONTROL_RELOAD;
  1753. if ((ctx->backend = rspamd_fuzzy_backend_create(ctx->event_loop,
  1754. worker->cf->options, rspamd_main->cfg,
  1755. &err)) == NULL) {
  1756. msg_err("cannot open backend after reload: %e", err);
  1757. rep.reply.reload.status = err->code;
  1758. g_error_free(err);
  1759. }
  1760. else {
  1761. rep.reply.reload.status = 0;
  1762. }
  1763. if (ctx->backend && worker->index == 0) {
  1764. rspamd_fuzzy_backend_start_update(ctx->backend, ctx->sync_timeout,
  1765. rspamd_fuzzy_storage_periodic_callback, ctx);
  1766. }
  1767. if (write(fd, &rep, sizeof(rep)) != sizeof(rep)) {
  1768. msg_err("cannot write reply to the control socket: %s",
  1769. strerror(errno));
  1770. }
  1771. return TRUE;
  1772. }
  1773. static ucl_object_t *
  1774. rspamd_fuzzy_storage_stat_key(const struct fuzzy_key_stat *key_stat)
  1775. {
  1776. ucl_object_t *res;
  1777. res = ucl_object_typed_new(UCL_OBJECT);
  1778. ucl_object_insert_key(res, ucl_object_fromint(key_stat->checked),
  1779. "checked", 0, false);
  1780. ucl_object_insert_key(res, ucl_object_fromdouble(key_stat->checked_ctr.mean),
  1781. "checked_per_hour", 0, false);
  1782. ucl_object_insert_key(res, ucl_object_fromint(key_stat->matched),
  1783. "matched", 0, false);
  1784. ucl_object_insert_key(res, ucl_object_fromdouble(key_stat->matched_ctr.mean),
  1785. "matched_per_hour", 0, false);
  1786. ucl_object_insert_key(res, ucl_object_fromint(key_stat->added),
  1787. "added", 0, false);
  1788. ucl_object_insert_key(res, ucl_object_fromint(key_stat->deleted),
  1789. "deleted", 0, false);
  1790. ucl_object_insert_key(res, ucl_object_fromint(key_stat->errors),
  1791. "errors", 0, false);
  1792. return res;
  1793. }
  1794. static ucl_object_t *
  1795. rspamd_fuzzy_stat_to_ucl(struct rspamd_fuzzy_storage_ctx *ctx, gboolean ip_stat)
  1796. {
  1797. struct fuzzy_key_stat *key_stat;
  1798. GHashTableIter it;
  1799. struct fuzzy_key *fuzzy_key;
  1800. ucl_object_t *obj, *keys_obj, *elt, *ip_elt, *ip_cur;
  1801. gpointer k, v;
  1802. gint i;
  1803. gchar keyname[17];
  1804. obj = ucl_object_typed_new(UCL_OBJECT);
  1805. keys_obj = ucl_object_typed_new(UCL_OBJECT);
  1806. g_hash_table_iter_init(&it, ctx->keys);
  1807. while (g_hash_table_iter_next(&it, &k, &v)) {
  1808. fuzzy_key = v;
  1809. key_stat = fuzzy_key->stat;
  1810. if (key_stat) {
  1811. rspamd_snprintf(keyname, sizeof(keyname), "%8bs", k);
  1812. elt = rspamd_fuzzy_storage_stat_key(key_stat);
  1813. if (key_stat->last_ips && ip_stat) {
  1814. i = 0;
  1815. ip_elt = ucl_object_typed_new(UCL_OBJECT);
  1816. while ((i = rspamd_lru_hash_foreach(key_stat->last_ips,
  1817. i, &k, &v)) != -1) {
  1818. ip_cur = rspamd_fuzzy_storage_stat_key(v);
  1819. ucl_object_insert_key(ip_elt, ip_cur,
  1820. rspamd_inet_address_to_string(k), 0, true);
  1821. }
  1822. ucl_object_insert_key(elt, ip_elt, "ips", 0, false);
  1823. }
  1824. int flag;
  1825. struct fuzzy_key_stat *flag_stat;
  1826. ucl_object_t *flags_ucl = ucl_object_typed_new(UCL_OBJECT);
  1827. kh_foreach_key_value_ptr(fuzzy_key->flags_stat, flag, flag_stat, {
  1828. char intbuf[16];
  1829. rspamd_snprintf(intbuf, sizeof(intbuf), "%d", flag);
  1830. ucl_object_insert_key(flags_ucl, rspamd_fuzzy_storage_stat_key(flag_stat),
  1831. intbuf, 0, true);
  1832. });
  1833. ucl_object_insert_key(elt, flags_ucl, "flags", 0, false);
  1834. ucl_object_insert_key(elt,
  1835. rspamd_keypair_to_ucl(fuzzy_key->key, RSPAMD_KEYPAIR_DUMP_NO_SECRET | RSPAMD_KEYPAIR_DUMP_FLATTENED),
  1836. "keypair", 0, false);
  1837. ucl_object_insert_key(keys_obj, elt, keyname, 0, true);
  1838. }
  1839. }
  1840. ucl_object_insert_key(obj, keys_obj, "keys", 0, false);
  1841. /* Now generic stats */
  1842. ucl_object_insert_key(obj,
  1843. ucl_object_fromint(ctx->stat.fuzzy_hashes),
  1844. "fuzzy_stored",
  1845. 0,
  1846. false);
  1847. ucl_object_insert_key(obj,
  1848. ucl_object_fromint(ctx->stat.fuzzy_hashes_expired),
  1849. "fuzzy_expired",
  1850. 0,
  1851. false);
  1852. ucl_object_insert_key(obj,
  1853. ucl_object_fromint(ctx->stat.invalid_requests),
  1854. "invalid_requests",
  1855. 0,
  1856. false);
  1857. ucl_object_insert_key(obj,
  1858. ucl_object_fromint(ctx->stat.delayed_hashes),
  1859. "delayed_hashes",
  1860. 0,
  1861. false);
  1862. if (ctx->errors_ips && ip_stat) {
  1863. i = 0;
  1864. ip_elt = ucl_object_typed_new(UCL_OBJECT);
  1865. while ((i = rspamd_lru_hash_foreach(ctx->errors_ips, i, &k, &v)) != -1) {
  1866. ucl_object_insert_key(ip_elt,
  1867. ucl_object_fromint(*(guint64 *) v),
  1868. rspamd_inet_address_to_string(k), 0, true);
  1869. }
  1870. ucl_object_insert_key(obj,
  1871. ip_elt,
  1872. "errors_ips",
  1873. 0,
  1874. false);
  1875. }
  1876. /* Checked by epoch */
  1877. elt = ucl_object_typed_new(UCL_ARRAY);
  1878. for (i = RSPAMD_FUZZY_EPOCH10; i < RSPAMD_FUZZY_EPOCH_MAX; i++) {
  1879. ucl_array_append(elt,
  1880. ucl_object_fromint(ctx->stat.fuzzy_hashes_checked[i]));
  1881. }
  1882. ucl_object_insert_key(obj, elt, "fuzzy_checked", 0, false);
  1883. /* Shingles by epoch */
  1884. elt = ucl_object_typed_new(UCL_ARRAY);
  1885. for (i = RSPAMD_FUZZY_EPOCH10; i < RSPAMD_FUZZY_EPOCH_MAX; i++) {
  1886. ucl_array_append(elt,
  1887. ucl_object_fromint(ctx->stat.fuzzy_shingles_checked[i]));
  1888. }
  1889. ucl_object_insert_key(obj, elt, "fuzzy_shingles", 0, false);
  1890. /* Matched by epoch */
  1891. elt = ucl_object_typed_new(UCL_ARRAY);
  1892. for (i = RSPAMD_FUZZY_EPOCH10; i < RSPAMD_FUZZY_EPOCH_MAX; i++) {
  1893. ucl_array_append(elt,
  1894. ucl_object_fromint(ctx->stat.fuzzy_hashes_found[i]));
  1895. }
  1896. ucl_object_insert_key(obj, elt, "fuzzy_found", 0, false);
  1897. return obj;
  1898. }
  1899. static void
  1900. rspamd_fuzzy_maybe_load_ratelimits(struct rspamd_fuzzy_storage_ctx *ctx)
  1901. {
  1902. char path[PATH_MAX];
  1903. rspamd_snprintf(path, sizeof(path), "%s" G_DIR_SEPARATOR_S "fuzzy_ratelimits.ucl",
  1904. RSPAMD_DBDIR);
  1905. if (access(path, R_OK) != -1) {
  1906. struct ucl_parser *parser = ucl_parser_new(UCL_PARSER_NO_IMPLICIT_ARRAYS | UCL_PARSER_DISABLE_MACRO);
  1907. if (ucl_parser_add_file(parser, path)) {
  1908. ucl_object_t *obj = ucl_parser_get_object(parser);
  1909. int loaded = 0;
  1910. if (ucl_object_type(obj) == UCL_ARRAY) {
  1911. ucl_object_iter_t it = NULL;
  1912. const ucl_object_t *cur;
  1913. while ((cur = ucl_object_iterate(obj, &it, true)) != NULL) {
  1914. const ucl_object_t *ip, *value, *last;
  1915. const gchar *ip_str;
  1916. double limit_val, last_val;
  1917. ip = ucl_object_find_key(cur, "ip");
  1918. value = ucl_object_find_key(cur, "value");
  1919. last = ucl_object_find_key(cur, "last");
  1920. if (ip == NULL || value == NULL || last == NULL) {
  1921. msg_err("invalid ratelimit object");
  1922. continue;
  1923. }
  1924. ip_str = ucl_object_tostring(ip);
  1925. limit_val = ucl_object_todouble(value);
  1926. last_val = ucl_object_todouble(last);
  1927. if (ip_str == NULL || isnan(last_val)) {
  1928. msg_err("invalid ratelimit object");
  1929. continue;
  1930. }
  1931. rspamd_inet_addr_t *addr;
  1932. if (rspamd_parse_inet_address(&addr, ip_str, strlen(ip_str),
  1933. RSPAMD_INET_ADDRESS_PARSE_NO_UNIX | RSPAMD_INET_ADDRESS_PARSE_NO_PORT)) {
  1934. struct rspamd_leaky_bucket_elt *elt = g_malloc(sizeof(*elt));
  1935. elt->cur = limit_val;
  1936. elt->last = last_val;
  1937. elt->addr = addr;
  1938. rspamd_lru_hash_insert(ctx->ratelimit_buckets, addr, elt, elt->last, ctx->leaky_bucket_ttl);
  1939. loaded++;
  1940. }
  1941. else {
  1942. msg_err("invalid ratelimit ip: %s", ip_str);
  1943. continue;
  1944. }
  1945. }
  1946. msg_info("loaded %d ratelimit objects", loaded);
  1947. }
  1948. ucl_object_unref(obj);
  1949. }
  1950. ucl_parser_free(parser);
  1951. }
  1952. }
  1953. static void
  1954. rspamd_fuzzy_maybe_save_ratelimits(struct rspamd_fuzzy_storage_ctx *ctx)
  1955. {
  1956. char path[PATH_MAX];
  1957. rspamd_snprintf(path, sizeof(path), "%s" G_DIR_SEPARATOR_S "fuzzy_ratelimits.ucl.new",
  1958. RSPAMD_DBDIR);
  1959. FILE *f = fopen(path, "w");
  1960. if (f != NULL) {
  1961. ucl_object_t *top = ucl_object_typed_new(UCL_ARRAY);
  1962. int it = 0;
  1963. gpointer k, v;
  1964. ucl_object_reserve(top, rspamd_lru_hash_size(ctx->ratelimit_buckets));
  1965. while ((it = rspamd_lru_hash_foreach(ctx->ratelimit_buckets, it, &k, &v)) != -1) {
  1966. ucl_object_t *cur = ucl_object_typed_new(UCL_OBJECT);
  1967. struct rspamd_leaky_bucket_elt *elt = (struct rspamd_leaky_bucket_elt *) v;
  1968. ucl_object_insert_key(cur, ucl_object_fromdouble(elt->cur), "value", 0, false);
  1969. ucl_object_insert_key(cur, ucl_object_fromdouble(elt->last), "last", 0, false);
  1970. ucl_object_insert_key(cur, ucl_object_fromstring(rspamd_inet_address_to_string(elt->addr)), "ip", 0, false);
  1971. ucl_array_append(top, cur);
  1972. }
  1973. if (ucl_object_emit_full(top, UCL_EMIT_JSON_COMPACT, ucl_object_emit_file_funcs(f), NULL)) {
  1974. char npath[PATH_MAX];
  1975. fflush(f);
  1976. rspamd_snprintf(npath, sizeof(npath), "%s" G_DIR_SEPARATOR_S "fuzzy_ratelimits.ucl",
  1977. RSPAMD_DBDIR);
  1978. if (rename(path, npath) == -1) {
  1979. msg_warn("cannot rename %s to %s: %s", path, npath, strerror(errno));
  1980. }
  1981. else {
  1982. msg_info("saved %d ratelimits in %s", rspamd_lru_hash_size(ctx->ratelimit_buckets), npath);
  1983. }
  1984. }
  1985. else {
  1986. msg_warn("cannot serialize ratelimit buckets to %s: %s", path, strerror(errno));
  1987. }
  1988. fclose(f);
  1989. ucl_object_unref(top);
  1990. }
  1991. else {
  1992. msg_warn("cannot save ratelimit buckets to %s: %s", path, strerror(errno));
  1993. }
  1994. }
  1995. static int
  1996. lua_fuzzy_add_pre_handler(lua_State *L)
  1997. {
  1998. struct rspamd_worker *wrk, **pwrk = (struct rspamd_worker **)
  1999. rspamd_lua_check_udata(L, 1, "rspamd{worker}");
  2000. struct rspamd_fuzzy_storage_ctx *ctx;
  2001. if (!pwrk) {
  2002. return luaL_error(L, "invalid arguments, worker + function are expected");
  2003. }
  2004. wrk = *pwrk;
  2005. if (wrk && lua_isfunction(L, 2)) {
  2006. ctx = (struct rspamd_fuzzy_storage_ctx *) wrk->ctx;
  2007. if (ctx->lua_pre_handler_cbref != -1) {
  2008. /* Should not happen */
  2009. luaL_unref(L, LUA_REGISTRYINDEX, ctx->lua_pre_handler_cbref);
  2010. }
  2011. lua_pushvalue(L, 2);
  2012. ctx->lua_pre_handler_cbref = luaL_ref(L, LUA_REGISTRYINDEX);
  2013. }
  2014. else {
  2015. return luaL_error(L, "invalid arguments, worker + function are expected");
  2016. }
  2017. return 0;
  2018. }
  2019. static int
  2020. lua_fuzzy_add_post_handler(lua_State *L)
  2021. {
  2022. struct rspamd_worker *wrk, **pwrk = (struct rspamd_worker **)
  2023. rspamd_lua_check_udata(L, 1, "rspamd{worker}");
  2024. struct rspamd_fuzzy_storage_ctx *ctx;
  2025. if (!pwrk) {
  2026. return luaL_error(L, "invalid arguments, worker + function are expected");
  2027. }
  2028. wrk = *pwrk;
  2029. if (wrk && lua_isfunction(L, 2)) {
  2030. ctx = (struct rspamd_fuzzy_storage_ctx *) wrk->ctx;
  2031. if (ctx->lua_post_handler_cbref != -1) {
  2032. /* Should not happen */
  2033. luaL_unref(L, LUA_REGISTRYINDEX, ctx->lua_post_handler_cbref);
  2034. }
  2035. lua_pushvalue(L, 2);
  2036. ctx->lua_post_handler_cbref = luaL_ref(L, LUA_REGISTRYINDEX);
  2037. }
  2038. else {
  2039. return luaL_error(L, "invalid arguments, worker + function are expected");
  2040. }
  2041. return 0;
  2042. }
  2043. static int
  2044. lua_fuzzy_add_blacklist_handler(lua_State *L)
  2045. {
  2046. struct rspamd_worker *wrk, **pwrk = (struct rspamd_worker **)
  2047. rspamd_lua_check_udata(L, 1, "rspamd{worker}");
  2048. struct rspamd_fuzzy_storage_ctx *ctx;
  2049. if (!pwrk) {
  2050. return luaL_error(L, "invalid arguments, worker + function are expected");
  2051. }
  2052. wrk = *pwrk;
  2053. if (wrk && lua_isfunction(L, 2)) {
  2054. ctx = (struct rspamd_fuzzy_storage_ctx *) wrk->ctx;
  2055. if (ctx->lua_blacklist_cbref != -1) {
  2056. /* Should not happen */
  2057. luaL_unref(L, LUA_REGISTRYINDEX, ctx->lua_blacklist_cbref);
  2058. }
  2059. lua_pushvalue(L, 2);
  2060. ctx->lua_blacklist_cbref = luaL_ref(L, LUA_REGISTRYINDEX);
  2061. }
  2062. else {
  2063. return luaL_error(L, "invalid arguments, worker + function are expected");
  2064. }
  2065. return 0;
  2066. }
  2067. static gboolean
  2068. rspamd_fuzzy_storage_stat(struct rspamd_main *rspamd_main,
  2069. struct rspamd_worker *worker, gint fd,
  2070. gint attached_fd,
  2071. struct rspamd_control_command *cmd,
  2072. gpointer ud)
  2073. {
  2074. struct rspamd_fuzzy_storage_ctx *ctx = ud;
  2075. struct rspamd_control_reply rep;
  2076. ucl_object_t *obj;
  2077. struct ucl_emitter_functions *emit_subr;
  2078. guchar fdspace[CMSG_SPACE(sizeof(int))];
  2079. struct iovec iov;
  2080. struct msghdr msg;
  2081. struct cmsghdr *cmsg;
  2082. gint outfd = -1;
  2083. gchar tmppath[PATH_MAX];
  2084. memset(&rep, 0, sizeof(rep));
  2085. rep.type = RSPAMD_CONTROL_FUZZY_STAT;
  2086. rspamd_snprintf(tmppath, sizeof(tmppath), "%s%c%s-XXXXXXXXXX",
  2087. rspamd_main->cfg->temp_dir, G_DIR_SEPARATOR, "fuzzy-stat");
  2088. if ((outfd = mkstemp(tmppath)) == -1) {
  2089. rep.reply.fuzzy_stat.status = errno;
  2090. msg_info_main("cannot make temporary stat file for fuzzy stat: %s",
  2091. strerror(errno));
  2092. }
  2093. else {
  2094. rep.reply.fuzzy_stat.status = 0;
  2095. memcpy(rep.reply.fuzzy_stat.storage_id,
  2096. rspamd_fuzzy_backend_id(ctx->backend),
  2097. sizeof(rep.reply.fuzzy_stat.storage_id));
  2098. obj = rspamd_fuzzy_stat_to_ucl(ctx, TRUE);
  2099. emit_subr = ucl_object_emit_fd_funcs(outfd);
  2100. ucl_object_emit_full(obj, UCL_EMIT_JSON_COMPACT, emit_subr, NULL);
  2101. ucl_object_emit_funcs_free(emit_subr);
  2102. ucl_object_unref(obj);
  2103. /* Rewind output file */
  2104. close(outfd);
  2105. outfd = open(tmppath, O_RDONLY);
  2106. unlink(tmppath);
  2107. }
  2108. /* Now we can send outfd and status message */
  2109. memset(&msg, 0, sizeof(msg));
  2110. /* Attach fd to the message */
  2111. if (outfd != -1) {
  2112. memset(fdspace, 0, sizeof(fdspace));
  2113. msg.msg_control = fdspace;
  2114. msg.msg_controllen = sizeof(fdspace);
  2115. cmsg = CMSG_FIRSTHDR(&msg);
  2116. if (cmsg) {
  2117. cmsg->cmsg_level = SOL_SOCKET;
  2118. cmsg->cmsg_type = SCM_RIGHTS;
  2119. cmsg->cmsg_len = CMSG_LEN(sizeof(int));
  2120. memcpy(CMSG_DATA(cmsg), &outfd, sizeof(int));
  2121. }
  2122. }
  2123. iov.iov_base = &rep;
  2124. iov.iov_len = sizeof(rep);
  2125. msg.msg_iov = &iov;
  2126. msg.msg_iovlen = 1;
  2127. if (sendmsg(fd, &msg, 0) == -1) {
  2128. msg_err_main("cannot send fuzzy stat: %s", strerror(errno));
  2129. }
  2130. if (outfd != -1) {
  2131. close(outfd);
  2132. }
  2133. return TRUE;
  2134. }
  2135. static gboolean
  2136. fuzzy_parse_ids(rspamd_mempool_t *pool,
  2137. const ucl_object_t *obj,
  2138. gpointer ud,
  2139. struct rspamd_rcl_section *section,
  2140. GError **err)
  2141. {
  2142. struct rspamd_rcl_struct_parser *pd = (struct rspamd_rcl_struct_parser *) ud;
  2143. khash_t(fuzzy_key_ids_set) * target;
  2144. target = *(khash_t(fuzzy_key_ids_set) **) ((gchar *) pd->user_struct + pd->offset);
  2145. if (ucl_object_type(obj) == UCL_ARRAY) {
  2146. const ucl_object_t *cur;
  2147. ucl_object_iter_t it = NULL;
  2148. guint64 id;
  2149. while ((cur = ucl_object_iterate(obj, &it, true)) != NULL) {
  2150. if (ucl_object_toint_safe(cur, &id)) {
  2151. int r;
  2152. kh_put(fuzzy_key_ids_set, target, id, &r);
  2153. }
  2154. else {
  2155. return FALSE;
  2156. }
  2157. }
  2158. return TRUE;
  2159. }
  2160. else if (ucl_object_type(obj) == UCL_INT) {
  2161. int r;
  2162. kh_put(fuzzy_key_ids_set, target, ucl_object_toint(obj), &r);
  2163. return TRUE;
  2164. }
  2165. return FALSE;
  2166. }
  2167. static gboolean
  2168. fuzzy_parse_keypair(rspamd_mempool_t *pool,
  2169. const ucl_object_t *obj,
  2170. gpointer ud,
  2171. struct rspamd_rcl_section *section,
  2172. GError **err)
  2173. {
  2174. struct rspamd_rcl_struct_parser *pd = ud;
  2175. struct rspamd_fuzzy_storage_ctx *ctx;
  2176. struct rspamd_cryptobox_keypair *kp;
  2177. struct fuzzy_key_stat *keystat;
  2178. struct fuzzy_key *key;
  2179. const ucl_object_t *cur;
  2180. const guchar *pk;
  2181. ucl_object_iter_t it = NULL;
  2182. gboolean ret;
  2183. ctx = pd->user_struct;
  2184. pd->offset = G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, default_keypair);
  2185. /*
  2186. * Single key
  2187. */
  2188. if (ucl_object_type(obj) == UCL_STRING || ucl_object_type(obj) == UCL_OBJECT) {
  2189. ret = rspamd_rcl_parse_struct_keypair(pool, obj, pd, section, err);
  2190. if (!ret) {
  2191. return ret;
  2192. }
  2193. /* Insert key to the hash table */
  2194. kp = ctx->default_keypair;
  2195. if (kp == NULL) {
  2196. return FALSE;
  2197. }
  2198. if (rspamd_keypair_alg(kp) != RSPAMD_CRYPTOBOX_MODE_25519 ||
  2199. rspamd_keypair_type(kp) != RSPAMD_KEYPAIR_KEX) {
  2200. return FALSE;
  2201. }
  2202. key = g_malloc0(sizeof(*key));
  2203. key->key = kp;
  2204. keystat = g_malloc0(sizeof(*keystat));
  2205. REF_INIT_RETAIN(keystat, fuzzy_key_stat_dtor);
  2206. /* Hash of ip -> fuzzy_key_stat */
  2207. keystat->last_ips = rspamd_lru_hash_new_full(1024,
  2208. (GDestroyNotify) rspamd_inet_address_free,
  2209. fuzzy_key_stat_unref,
  2210. rspamd_inet_address_hash, rspamd_inet_address_equal);
  2211. key->stat = keystat;
  2212. key->flags_stat = kh_init(fuzzy_key_flag_stat);
  2213. /* Preallocate some space for flags */
  2214. kh_resize(fuzzy_key_flag_stat, key->flags_stat, 8);
  2215. pk = rspamd_keypair_component(kp, RSPAMD_KEYPAIR_COMPONENT_PK,
  2216. NULL);
  2217. keystat->keypair = rspamd_keypair_ref(kp);
  2218. /* We map entries by pubkey in binary form for faster lookup */
  2219. g_hash_table_insert(ctx->keys, (gpointer) pk, key);
  2220. ctx->default_key = key;
  2221. const ucl_object_t *extensions = rspamd_keypair_get_extensions(kp);
  2222. if (extensions) {
  2223. const ucl_object_t *forbidden_ids = ucl_object_lookup(extensions, "forbidden_ids");
  2224. if (forbidden_ids && ucl_object_type(forbidden_ids) == UCL_ARRAY) {
  2225. key->forbidden_ids = kh_init(fuzzy_key_ids_set);
  2226. while ((cur = ucl_object_iterate(forbidden_ids, &it, true)) != NULL) {
  2227. if (ucl_object_type(cur) == UCL_INT || ucl_object_type(cur) == UCL_FLOAT) {
  2228. int id = ucl_object_toint(cur);
  2229. int r;
  2230. kh_put(fuzzy_key_ids_set, key->forbidden_ids, id, &r);
  2231. }
  2232. }
  2233. }
  2234. }
  2235. msg_debug_pool_check("loaded keypair %*xs", 8, pk);
  2236. }
  2237. else if (ucl_object_type(obj) == UCL_ARRAY) {
  2238. while ((cur = ucl_object_iterate(obj, &it, true)) != NULL) {
  2239. if (!fuzzy_parse_keypair(pool, cur, pd, section, err)) {
  2240. msg_err_pool("cannot parse keypair");
  2241. }
  2242. }
  2243. }
  2244. return TRUE;
  2245. }
  2246. static guint
  2247. fuzzy_kp_hash(gconstpointer p)
  2248. {
  2249. return *(guint *) p;
  2250. }
  2251. static gboolean
  2252. fuzzy_kp_equal(gconstpointer a, gconstpointer b)
  2253. {
  2254. const guchar *pa = a, *pb = b;
  2255. return (memcmp(pa, pb, RSPAMD_FUZZY_KEYLEN) == 0);
  2256. }
  2257. gpointer
  2258. init_fuzzy(struct rspamd_config *cfg)
  2259. {
  2260. struct rspamd_fuzzy_storage_ctx *ctx;
  2261. GQuark type;
  2262. type = g_quark_try_string("fuzzy");
  2263. ctx = rspamd_mempool_alloc0(cfg->cfg_pool,
  2264. sizeof(struct rspamd_fuzzy_storage_ctx));
  2265. ctx->magic = rspamd_fuzzy_storage_magic;
  2266. ctx->sync_timeout = DEFAULT_SYNC_TIMEOUT;
  2267. ctx->keypair_cache_size = DEFAULT_KEYPAIR_CACHE_SIZE;
  2268. ctx->lua_pre_handler_cbref = -1;
  2269. ctx->lua_post_handler_cbref = -1;
  2270. ctx->lua_blacklist_cbref = -1;
  2271. ctx->keys = g_hash_table_new_full(fuzzy_kp_hash, fuzzy_kp_equal,
  2272. NULL, fuzzy_key_dtor);
  2273. rspamd_mempool_add_destructor(cfg->cfg_pool,
  2274. (rspamd_mempool_destruct_t) g_hash_table_unref, ctx->keys);
  2275. ctx->errors_ips = rspamd_lru_hash_new_full(1024,
  2276. (GDestroyNotify) rspamd_inet_address_free, g_free,
  2277. rspamd_inet_address_hash, rspamd_inet_address_equal);
  2278. rspamd_mempool_add_destructor(cfg->cfg_pool,
  2279. (rspamd_mempool_destruct_t) rspamd_lru_hash_destroy, ctx->errors_ips);
  2280. ctx->cfg = cfg;
  2281. ctx->updates_maxfail = DEFAULT_UPDATES_MAXFAIL;
  2282. ctx->leaky_bucket_mask = DEFAULT_BUCKET_MASK;
  2283. ctx->leaky_bucket_ttl = DEFAULT_BUCKET_TTL;
  2284. ctx->max_buckets = DEFAULT_MAX_BUCKETS;
  2285. ctx->leaky_bucket_burst = NAN;
  2286. ctx->leaky_bucket_rate = NAN;
  2287. ctx->delay = NAN;
  2288. ctx->default_forbidden_ids = kh_init(fuzzy_key_ids_set);
  2289. ctx->weak_ids = kh_init(fuzzy_key_ids_set);
  2290. rspamd_rcl_register_worker_option(cfg,
  2291. type,
  2292. "sync",
  2293. rspamd_rcl_parse_struct_time,
  2294. ctx,
  2295. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx,
  2296. sync_timeout),
  2297. RSPAMD_CL_FLAG_TIME_FLOAT,
  2298. "Time to perform database sync, default: " G_STRINGIFY(DEFAULT_SYNC_TIMEOUT) " seconds");
  2299. rspamd_rcl_register_worker_option(cfg,
  2300. type,
  2301. "expire",
  2302. rspamd_rcl_parse_struct_time,
  2303. ctx,
  2304. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx,
  2305. expire),
  2306. RSPAMD_CL_FLAG_TIME_FLOAT,
  2307. "Default expire time for hashes, default: " G_STRINGIFY(DEFAULT_EXPIRE) " seconds");
  2308. rspamd_rcl_register_worker_option(cfg,
  2309. type,
  2310. "delay",
  2311. rspamd_rcl_parse_struct_time,
  2312. ctx,
  2313. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx,
  2314. delay),
  2315. RSPAMD_CL_FLAG_TIME_FLOAT,
  2316. "Default delay time for hashes, default: not enabled");
  2317. rspamd_rcl_register_worker_option(cfg,
  2318. type,
  2319. "allow_update",
  2320. rspamd_rcl_parse_struct_ucl,
  2321. ctx,
  2322. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, update_map),
  2323. 0,
  2324. "Allow modifications from the following IP addresses");
  2325. rspamd_rcl_register_worker_option(cfg,
  2326. type,
  2327. "allow_update_keys",
  2328. rspamd_rcl_parse_struct_ucl,
  2329. ctx,
  2330. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, update_keys_map),
  2331. 0,
  2332. "Allow modifications for those using specific public keys");
  2333. rspamd_rcl_register_worker_option(cfg,
  2334. type,
  2335. "delay_whitelist",
  2336. rspamd_rcl_parse_struct_ucl,
  2337. ctx,
  2338. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, delay_whitelist_map),
  2339. 0,
  2340. "Disable delay check for the following IP addresses");
  2341. rspamd_rcl_register_worker_option(cfg,
  2342. type,
  2343. "keypair",
  2344. fuzzy_parse_keypair,
  2345. ctx,
  2346. 0,
  2347. RSPAMD_CL_FLAG_MULTIPLE,
  2348. "Encryption keypair (can be repeated for different keys)");
  2349. rspamd_rcl_register_worker_option(cfg,
  2350. type,
  2351. "forbidden_ids",
  2352. fuzzy_parse_ids,
  2353. ctx,
  2354. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, default_forbidden_ids),
  2355. 0,
  2356. "Deny specific flags by default");
  2357. rspamd_rcl_register_worker_option(cfg,
  2358. type,
  2359. "weak_ids",
  2360. fuzzy_parse_ids,
  2361. ctx,
  2362. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, weak_ids),
  2363. 0,
  2364. "Treat these flags as weak (i.e. they do not overwrite strong flags)");
  2365. rspamd_rcl_register_worker_option(cfg,
  2366. type,
  2367. "keypair_cache_size",
  2368. rspamd_rcl_parse_struct_integer,
  2369. ctx,
  2370. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx,
  2371. keypair_cache_size),
  2372. RSPAMD_CL_FLAG_UINT,
  2373. "Size of keypairs cache, default: " G_STRINGIFY(DEFAULT_KEYPAIR_CACHE_SIZE));
  2374. rspamd_rcl_register_worker_option(cfg,
  2375. type,
  2376. "encrypted_only",
  2377. rspamd_rcl_parse_struct_boolean,
  2378. ctx,
  2379. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, encrypted_only),
  2380. 0,
  2381. "Allow encrypted requests only (and forbid all unknown keys or plaintext requests)");
  2382. rspamd_rcl_register_worker_option(cfg,
  2383. type,
  2384. "dedicated_update_worker",
  2385. rspamd_rcl_parse_struct_boolean,
  2386. ctx,
  2387. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, dedicated_update_worker),
  2388. 0,
  2389. "Use worker 0 for updates only");
  2390. rspamd_rcl_register_worker_option(cfg,
  2391. type,
  2392. "read_only",
  2393. rspamd_rcl_parse_struct_boolean,
  2394. ctx,
  2395. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, read_only),
  2396. 0,
  2397. "Work in read only mode");
  2398. rspamd_rcl_register_worker_option(cfg,
  2399. type,
  2400. "blocked",
  2401. rspamd_rcl_parse_struct_ucl,
  2402. ctx,
  2403. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, blocked_map),
  2404. 0,
  2405. "Block requests from specific networks");
  2406. rspamd_rcl_register_worker_option(cfg,
  2407. type,
  2408. "updates_maxfail",
  2409. rspamd_rcl_parse_struct_integer,
  2410. ctx,
  2411. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, updates_maxfail),
  2412. RSPAMD_CL_FLAG_UINT,
  2413. "Maximum number of updates to be failed before discarding");
  2414. rspamd_rcl_register_worker_option(cfg,
  2415. type,
  2416. "skip_hashes",
  2417. rspamd_rcl_parse_struct_ucl,
  2418. ctx,
  2419. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, skip_map),
  2420. 0,
  2421. "Skip specific hashes from the map");
  2422. /* Ratelimits */
  2423. rspamd_rcl_register_worker_option(cfg,
  2424. type,
  2425. "ratelimit_whitelist",
  2426. rspamd_rcl_parse_struct_ucl,
  2427. ctx,
  2428. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, ratelimit_whitelist_map),
  2429. 0,
  2430. "Skip specific addresses from rate limiting");
  2431. rspamd_rcl_register_worker_option(cfg,
  2432. type,
  2433. "ratelimit_max_buckets",
  2434. rspamd_rcl_parse_struct_integer,
  2435. ctx,
  2436. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, max_buckets),
  2437. RSPAMD_CL_FLAG_UINT,
  2438. "Maximum number of leaky buckets (default: " G_STRINGIFY(DEFAULT_MAX_BUCKETS) ")");
  2439. rspamd_rcl_register_worker_option(cfg,
  2440. type,
  2441. "ratelimit_network_mask",
  2442. rspamd_rcl_parse_struct_integer,
  2443. ctx,
  2444. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, leaky_bucket_mask),
  2445. RSPAMD_CL_FLAG_UINT,
  2446. "Network mask to apply for IPv4 rate addresses (default: " G_STRINGIFY(DEFAULT_BUCKET_MASK) ")");
  2447. rspamd_rcl_register_worker_option(cfg,
  2448. type,
  2449. "ratelimit_bucket_ttl",
  2450. rspamd_rcl_parse_struct_time,
  2451. ctx,
  2452. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, leaky_bucket_ttl),
  2453. RSPAMD_CL_FLAG_TIME_INTEGER,
  2454. "Time to live for ratelimit element (default: " G_STRINGIFY(DEFAULT_BUCKET_TTL) ")");
  2455. rspamd_rcl_register_worker_option(cfg,
  2456. type,
  2457. "ratelimit_rate",
  2458. rspamd_rcl_parse_struct_double,
  2459. ctx,
  2460. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, leaky_bucket_rate),
  2461. 0,
  2462. "Leak rate in requests per second");
  2463. rspamd_rcl_register_worker_option(cfg,
  2464. type,
  2465. "ratelimit_burst",
  2466. rspamd_rcl_parse_struct_double,
  2467. ctx,
  2468. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, leaky_bucket_burst),
  2469. 0,
  2470. "Peak value for ratelimit bucket");
  2471. rspamd_rcl_register_worker_option(cfg,
  2472. type,
  2473. "ratelimit_log_only",
  2474. rspamd_rcl_parse_struct_boolean,
  2475. ctx,
  2476. G_STRUCT_OFFSET(struct rspamd_fuzzy_storage_ctx, ratelimit_log_only),
  2477. 0,
  2478. "Don't really ban on ratelimit reaching, just log");
  2479. return ctx;
  2480. }
  2481. static void
  2482. rspamd_fuzzy_peer_io(EV_P_ ev_io *w, int revents)
  2483. {
  2484. struct fuzzy_peer_cmd cmd;
  2485. struct rspamd_fuzzy_storage_ctx *ctx =
  2486. (struct rspamd_fuzzy_storage_ctx *) w->data;
  2487. gssize r;
  2488. for (;;) {
  2489. r = read(w->fd, &cmd, sizeof(cmd));
  2490. if (r != sizeof(cmd)) {
  2491. if (errno == EINTR) {
  2492. continue;
  2493. }
  2494. if (errno != EAGAIN) {
  2495. msg_err("cannot read command from peers: %s", strerror(errno));
  2496. }
  2497. break;
  2498. }
  2499. else {
  2500. g_array_append_val(ctx->updates_pending, cmd);
  2501. }
  2502. }
  2503. }
  2504. static void
  2505. fuzzy_peer_rep(struct rspamd_worker *worker,
  2506. struct rspamd_srv_reply *rep, gint rep_fd,
  2507. gpointer ud)
  2508. {
  2509. struct rspamd_fuzzy_storage_ctx *ctx = ud;
  2510. GList *cur;
  2511. struct rspamd_worker_listen_socket *ls;
  2512. struct rspamd_worker_accept_event *ac_ev;
  2513. ctx->peer_fd = rep_fd;
  2514. if (rep_fd == -1) {
  2515. msg_err("cannot receive peer fd from the main process");
  2516. exit(EXIT_FAILURE);
  2517. }
  2518. else {
  2519. rspamd_socket_nonblocking(rep_fd);
  2520. }
  2521. msg_info("got peer fd reply from the main process");
  2522. /* Start listening */
  2523. cur = worker->cf->listen_socks;
  2524. while (cur) {
  2525. ls = cur->data;
  2526. if (ls->fd != -1) {
  2527. msg_info("start listening on %s",
  2528. rspamd_inet_address_to_string_pretty(ls->addr));
  2529. if (ls->type == RSPAMD_WORKER_SOCKET_UDP) {
  2530. ac_ev = g_malloc0(sizeof(*ac_ev));
  2531. ac_ev->accept_ev.data = worker;
  2532. ac_ev->event_loop = ctx->event_loop;
  2533. ev_io_init(&ac_ev->accept_ev, accept_fuzzy_socket, ls->fd,
  2534. EV_READ);
  2535. ev_io_start(ctx->event_loop, &ac_ev->accept_ev);
  2536. DL_APPEND(worker->accept_events, ac_ev);
  2537. }
  2538. else {
  2539. /* We allow TCP listeners only for a update worker */
  2540. g_assert_not_reached();
  2541. }
  2542. }
  2543. cur = g_list_next(cur);
  2544. }
  2545. if (ctx->peer_fd != -1) {
  2546. if (worker->index == 0) {
  2547. /* Listen for peer requests */
  2548. shutdown(ctx->peer_fd, SHUT_WR);
  2549. ctx->peer_ev.data = ctx;
  2550. ev_io_init(&ctx->peer_ev, rspamd_fuzzy_peer_io, ctx->peer_fd, EV_READ);
  2551. ev_io_start(ctx->event_loop, &ctx->peer_ev);
  2552. }
  2553. else {
  2554. shutdown(ctx->peer_fd, SHUT_RD);
  2555. }
  2556. }
  2557. }
  2558. /*
  2559. * Start worker process
  2560. */
  2561. __attribute__((noreturn)) void
  2562. start_fuzzy(struct rspamd_worker *worker)
  2563. {
  2564. struct rspamd_fuzzy_storage_ctx *ctx = worker->ctx;
  2565. GError *err = NULL;
  2566. struct rspamd_srv_command srv_cmd;
  2567. struct rspamd_config *cfg = worker->srv->cfg;
  2568. g_assert(rspamd_worker_check_context(worker->ctx, rspamd_fuzzy_storage_magic));
  2569. ctx->event_loop = rspamd_prepare_worker(worker,
  2570. "fuzzy",
  2571. NULL);
  2572. ctx->peer_fd = -1;
  2573. ctx->worker = worker;
  2574. ctx->cfg = worker->srv->cfg;
  2575. ctx->resolver = rspamd_dns_resolver_init(worker->srv->logger,
  2576. ctx->event_loop,
  2577. worker->srv->cfg);
  2578. rspamd_upstreams_library_config(worker->srv->cfg, ctx->cfg->ups_ctx,
  2579. ctx->event_loop, ctx->resolver->r);
  2580. /* Since this worker uses maps it needs a valid HTTP context */
  2581. ctx->http_ctx = rspamd_http_context_create(ctx->cfg, ctx->event_loop,
  2582. ctx->cfg->ups_ctx);
  2583. if (ctx->keypair_cache_size > 0) {
  2584. /* Create keypairs cache */
  2585. ctx->keypair_cache = rspamd_keypair_cache_new(ctx->keypair_cache_size);
  2586. }
  2587. if ((ctx->backend = rspamd_fuzzy_backend_create(ctx->event_loop,
  2588. worker->cf->options, cfg, &err)) == NULL) {
  2589. msg_err("cannot open backend: %e", err);
  2590. if (err) {
  2591. g_error_free(err);
  2592. }
  2593. exit(EXIT_SUCCESS);
  2594. }
  2595. rspamd_fuzzy_backend_count(ctx->backend, fuzzy_count_callback, ctx);
  2596. if (worker->index == 0) {
  2597. ctx->updates_pending = g_array_sized_new(FALSE, FALSE,
  2598. sizeof(struct fuzzy_peer_cmd), 1024);
  2599. rspamd_fuzzy_backend_start_update(ctx->backend, ctx->sync_timeout,
  2600. rspamd_fuzzy_storage_periodic_callback, ctx);
  2601. if (ctx->dedicated_update_worker && worker->cf->count > 1) {
  2602. msg_info_config("stop serving clients request in dedicated update mode");
  2603. rspamd_worker_stop_accept(worker);
  2604. GList *cur = worker->cf->listen_socks;
  2605. while (cur) {
  2606. struct rspamd_worker_listen_socket *ls =
  2607. (struct rspamd_worker_listen_socket *) cur->data;
  2608. if (ls->fd != -1) {
  2609. close(ls->fd);
  2610. }
  2611. cur = g_list_next(cur);
  2612. }
  2613. }
  2614. }
  2615. ctx->stat_ev.data = ctx;
  2616. ev_timer_init(&ctx->stat_ev, rspamd_fuzzy_stat_callback, ctx->sync_timeout,
  2617. ctx->sync_timeout);
  2618. ev_timer_start(ctx->event_loop, &ctx->stat_ev);
  2619. /* Register custom reload and stat commands for the control socket */
  2620. rspamd_control_worker_add_cmd_handler(worker, RSPAMD_CONTROL_RELOAD,
  2621. rspamd_fuzzy_storage_reload, ctx);
  2622. rspamd_control_worker_add_cmd_handler(worker, RSPAMD_CONTROL_FUZZY_STAT,
  2623. rspamd_fuzzy_storage_stat, ctx);
  2624. rspamd_control_worker_add_cmd_handler(worker, RSPAMD_CONTROL_FUZZY_SYNC,
  2625. rspamd_fuzzy_storage_sync, ctx);
  2626. rspamd_control_worker_add_cmd_handler(worker, RSPAMD_CONTROL_FUZZY_BLOCKED,
  2627. rspamd_fuzzy_control_blocked, ctx);
  2628. if (ctx->update_map != NULL) {
  2629. rspamd_config_radix_from_ucl(worker->srv->cfg, ctx->update_map,
  2630. "Allow fuzzy updates from specified addresses",
  2631. &ctx->update_ips, NULL, worker, "fuzzy update");
  2632. }
  2633. if (ctx->update_keys_map != NULL) {
  2634. struct rspamd_map *m;
  2635. if ((m = rspamd_map_add_from_ucl(worker->srv->cfg, ctx->update_keys_map,
  2636. "Allow fuzzy updates from specified public keys",
  2637. rspamd_kv_list_read,
  2638. rspamd_kv_list_fin,
  2639. rspamd_kv_list_dtor,
  2640. (void **) &ctx->update_keys, worker, RSPAMD_MAP_DEFAULT)) == NULL) {
  2641. msg_warn_config("cannot load allow keys map from %s",
  2642. ucl_object_tostring(ctx->update_keys_map));
  2643. }
  2644. else {
  2645. m->active_http = TRUE;
  2646. }
  2647. }
  2648. if (ctx->skip_map != NULL) {
  2649. struct rspamd_map *m;
  2650. if ((m = rspamd_map_add_from_ucl(cfg, ctx->skip_map,
  2651. "Skip hashes",
  2652. rspamd_kv_list_read,
  2653. rspamd_kv_list_fin,
  2654. rspamd_kv_list_dtor,
  2655. (void **) &ctx->skip_hashes,
  2656. worker, RSPAMD_MAP_DEFAULT)) == NULL) {
  2657. msg_warn_config("cannot load hashes list from %s",
  2658. ucl_object_tostring(ctx->skip_map));
  2659. }
  2660. else {
  2661. m->active_http = TRUE;
  2662. }
  2663. }
  2664. if (ctx->blocked_map != NULL) {
  2665. rspamd_config_radix_from_ucl(worker->srv->cfg, ctx->blocked_map,
  2666. "Block fuzzy requests from the specific IPs",
  2667. &ctx->blocked_ips,
  2668. NULL,
  2669. worker, "fuzzy blocked");
  2670. }
  2671. /* Create radix trees */
  2672. if (ctx->ratelimit_whitelist_map != NULL) {
  2673. rspamd_config_radix_from_ucl(worker->srv->cfg, ctx->ratelimit_whitelist_map,
  2674. "Skip ratelimits from specific ip addresses/networks",
  2675. &ctx->ratelimit_whitelist,
  2676. NULL,
  2677. worker, "fuzzy ratelimit whitelist");
  2678. }
  2679. if (!isnan(ctx->delay) && ctx->delay_whitelist_map != NULL) {
  2680. rspamd_config_radix_from_ucl(worker->srv->cfg, ctx->delay_whitelist_map,
  2681. "Skip delay from the following ips",
  2682. &ctx->delay_whitelist, NULL, worker,
  2683. "fuzzy delayed whitelist");
  2684. }
  2685. /* Ratelimits */
  2686. if (!isnan(ctx->leaky_bucket_rate) && !isnan(ctx->leaky_bucket_burst)) {
  2687. ctx->ratelimit_buckets = rspamd_lru_hash_new_full(ctx->max_buckets,
  2688. NULL, fuzzy_rl_bucket_free,
  2689. rspamd_inet_address_hash, rspamd_inet_address_equal);
  2690. rspamd_fuzzy_maybe_load_ratelimits(ctx);
  2691. }
  2692. /* Maps events */
  2693. ctx->resolver = rspamd_dns_resolver_init(worker->srv->logger,
  2694. ctx->event_loop,
  2695. worker->srv->cfg);
  2696. rspamd_map_watch(worker->srv->cfg, ctx->event_loop,
  2697. ctx->resolver, worker, RSPAMD_MAP_WATCH_WORKER);
  2698. /* Get peer pipe */
  2699. memset(&srv_cmd, 0, sizeof(srv_cmd));
  2700. srv_cmd.type = RSPAMD_SRV_SOCKETPAIR;
  2701. srv_cmd.cmd.spair.af = SOCK_DGRAM;
  2702. srv_cmd.cmd.spair.pair_num = worker->index;
  2703. memset(srv_cmd.cmd.spair.pair_id, 0, sizeof(srv_cmd.cmd.spair.pair_id));
  2704. /* 6 bytes of id (including \0) and bind_conf id */
  2705. G_STATIC_ASSERT(sizeof(srv_cmd.cmd.spair.pair_id) >=
  2706. sizeof("fuzzy") + sizeof(guint64));
  2707. memcpy(srv_cmd.cmd.spair.pair_id, "fuzzy", sizeof("fuzzy"));
  2708. /* Distinguish workers from each others... */
  2709. if (worker->cf->bind_conf && worker->cf->bind_conf->bind_line) {
  2710. guint64 bind_hash = rspamd_cryptobox_fast_hash(worker->cf->bind_conf->bind_line,
  2711. strlen(worker->cf->bind_conf->bind_line), 0xdeadbabe);
  2712. /* 8 more bytes */
  2713. memcpy(srv_cmd.cmd.spair.pair_id + sizeof("fuzzy"), &bind_hash,
  2714. sizeof(bind_hash));
  2715. }
  2716. rspamd_srv_send_command(worker, ctx->event_loop, &srv_cmd, -1,
  2717. fuzzy_peer_rep, ctx);
  2718. /*
  2719. * Extra fields available for this particular worker
  2720. */
  2721. luaL_Reg fuzzy_lua_reg = {
  2722. .name = "add_fuzzy_pre_handler",
  2723. .func = lua_fuzzy_add_pre_handler,
  2724. };
  2725. rspamd_lua_add_metamethod(ctx->cfg->lua_state, "rspamd{worker}", &fuzzy_lua_reg);
  2726. fuzzy_lua_reg = (luaL_Reg){
  2727. .name = "add_fuzzy_post_handler",
  2728. .func = lua_fuzzy_add_post_handler,
  2729. };
  2730. rspamd_lua_add_metamethod(ctx->cfg->lua_state, "rspamd{worker}", &fuzzy_lua_reg);
  2731. fuzzy_lua_reg = (luaL_Reg){
  2732. .name = "add_fuzzy_blacklist_handler",
  2733. .func = lua_fuzzy_add_blacklist_handler,
  2734. };
  2735. rspamd_lua_add_metamethod(ctx->cfg->lua_state, "rspamd{worker}", &fuzzy_lua_reg);
  2736. rspamd_lua_run_postloads(ctx->cfg->lua_state, ctx->cfg, ctx->event_loop,
  2737. worker);
  2738. ev_loop(ctx->event_loop, 0);
  2739. rspamd_worker_block_signals();
  2740. if (ctx->peer_fd != -1) {
  2741. if (worker->index == 0) {
  2742. ev_io_stop(ctx->event_loop, &ctx->peer_ev);
  2743. }
  2744. close(ctx->peer_fd);
  2745. }
  2746. if (worker->index == 0 && ctx->updates_pending->len > 0) {
  2747. msg_info_config("start another event loop to sync fuzzy storage");
  2748. if (rspamd_fuzzy_process_updates_queue(ctx, local_db_name, TRUE)) {
  2749. ev_loop(ctx->event_loop, 0);
  2750. msg_info_config("sync cycle is done");
  2751. }
  2752. else {
  2753. msg_info_config("no need to sync");
  2754. }
  2755. }
  2756. rspamd_fuzzy_backend_close(ctx->backend);
  2757. if (worker->index == 0) {
  2758. g_array_free(ctx->updates_pending, TRUE);
  2759. ctx->updates_pending = NULL;
  2760. }
  2761. if (ctx->keypair_cache) {
  2762. rspamd_keypair_cache_destroy(ctx->keypair_cache);
  2763. }
  2764. if (ctx->ratelimit_buckets) {
  2765. /* Try the best to save ratelimits from the proper worker */
  2766. if ((!ctx->dedicated_update_worker && worker->index == 0) ||
  2767. (ctx->dedicated_update_worker && worker->index == 1)) {
  2768. rspamd_fuzzy_maybe_save_ratelimits(ctx);
  2769. }
  2770. rspamd_lru_hash_destroy(ctx->ratelimit_buckets);
  2771. }
  2772. if (ctx->lua_pre_handler_cbref != -1) {
  2773. luaL_unref(ctx->cfg->lua_state, LUA_REGISTRYINDEX, ctx->lua_pre_handler_cbref);
  2774. }
  2775. if (ctx->lua_post_handler_cbref != -1) {
  2776. luaL_unref(ctx->cfg->lua_state, LUA_REGISTRYINDEX, ctx->lua_post_handler_cbref);
  2777. }
  2778. if (ctx->lua_blacklist_cbref != -1) {
  2779. luaL_unref(ctx->cfg->lua_state, LUA_REGISTRYINDEX, ctx->lua_blacklist_cbref);
  2780. }
  2781. if (ctx->default_forbidden_ids) {
  2782. kh_destroy(fuzzy_key_ids_set, ctx->default_forbidden_ids);
  2783. }
  2784. if (ctx->weak_ids) {
  2785. kh_destroy(fuzzy_key_ids_set, ctx->weak_ids);
  2786. }
  2787. REF_RELEASE(ctx->cfg);
  2788. rspamd_log_close(worker->srv->logger);
  2789. rspamd_unset_crash_handler(worker->srv);
  2790. exit(EXIT_SUCCESS);
  2791. }