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

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