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_check.c 86KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590
  1. /*-
  2. * Copyright 2016 Vsevolod Stakhov
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. /***MODULE:fuzzy
  17. * rspamd module that checks fuzzy checksums for messages
  18. *
  19. * Allowed options:
  20. * - symbol (string): symbol to insert (default: 'R_FUZZY')
  21. * - max_score (double): maximum score to that weights of hashes would be normalized (default: 0 - no normalization)
  22. *
  23. * - fuzzy_map (string): a string that contains map in format { fuzzy_key => [ symbol, weight ] } where fuzzy_key is number of
  24. * fuzzy list. This string itself should be in format 1:R_FUZZY_SAMPLE1:10,2:R_FUZZY_SAMPLE2:1 etc, where first number is fuzzy
  25. * key, second is symbol to insert and third - weight for normalization
  26. *
  27. * - min_length (integer): minimum length (in characters) for text part to be checked for fuzzy hash (default: 0 - no limit)
  28. * - whitelist (map string): map of ip addresses that should not be checked with this module
  29. * - servers (string): list of fuzzy servers in format "server1:port,server2:port" - these servers would be used for checking and storing
  30. * fuzzy hashes
  31. */
  32. #include "config.h"
  33. #include "libmime/message.h"
  34. #include "libutil/map.h"
  35. #include "libutil/map_helpers.h"
  36. #include "libmime/images.h"
  37. #include "libserver/worker_util.h"
  38. #include "libserver/mempool_vars_internal.h"
  39. #include "fuzzy_wire.h"
  40. #include "utlist.h"
  41. #include "ottery.h"
  42. #include "lua/lua_common.h"
  43. #include "unix-std.h"
  44. #include "libutil/http_private.h"
  45. #include "libutil/http_router.h"
  46. #include "libstat/stat_api.h"
  47. #include <math.h>
  48. #include <src/libmime/message.h>
  49. #include "libutil/libev_helper.h"
  50. #define DEFAULT_SYMBOL "R_FUZZY_HASH"
  51. #define DEFAULT_IO_TIMEOUT 500
  52. #define DEFAULT_RETRANSMITS 3
  53. #define DEFAULT_MAX_ERRORS 4
  54. #define DEFAULT_REVIVE_TIME 60
  55. #define DEFAULT_PORT 11335
  56. #define RSPAMD_FUZZY_PLUGIN_VERSION RSPAMD_FUZZY_VERSION
  57. static const gint rspamd_fuzzy_hash_len = 5;
  58. static const gchar *M = "fuzzy check";
  59. struct fuzzy_ctx;
  60. struct fuzzy_mapping {
  61. guint64 fuzzy_flag;
  62. const gchar *symbol;
  63. double weight;
  64. };
  65. struct fuzzy_rule {
  66. struct upstream_list *servers;
  67. const gchar *symbol;
  68. const gchar *algorithm_str;
  69. const gchar *name;
  70. const ucl_object_t *ucl_obj;
  71. enum rspamd_shingle_alg alg;
  72. GHashTable *mappings;
  73. GPtrArray *fuzzy_headers;
  74. GString *hash_key;
  75. GString *shingles_key;
  76. struct rspamd_cryptobox_keypair *local_key;
  77. struct rspamd_cryptobox_pubkey *peer_key;
  78. double max_score;
  79. gboolean read_only;
  80. gboolean skip_unknown;
  81. gint learn_condition_cb;
  82. struct rspamd_hash_map_helper *skip_map;
  83. struct fuzzy_ctx *ctx;
  84. gint lua_id;
  85. };
  86. struct fuzzy_ctx {
  87. struct module_ctx ctx;
  88. rspamd_mempool_t *fuzzy_pool;
  89. GPtrArray *fuzzy_rules;
  90. struct rspamd_config *cfg;
  91. const gchar *default_symbol;
  92. struct rspamd_radix_map_helper *whitelist;
  93. struct rspamd_keypair_cache *keypairs_cache;
  94. guint32 io_timeout;
  95. guint32 retransmits;
  96. guint max_errors;
  97. gdouble revive_time;
  98. gint check_mime_part_ref; /* Lua callback */
  99. gint process_rule_ref; /* Lua callback */
  100. gint cleanup_rules_ref;
  101. gboolean enabled;
  102. };
  103. enum fuzzy_result_type {
  104. FUZZY_RESULT_TXT,
  105. FUZZY_RESULT_IMG,
  106. FUZZY_RESULT_BIN
  107. };
  108. struct fuzzy_client_result {
  109. const gchar *symbol;
  110. gchar *option;
  111. gdouble score;
  112. gdouble prob;
  113. enum fuzzy_result_type type;
  114. };
  115. struct fuzzy_client_session {
  116. GPtrArray *commands;
  117. GPtrArray *results;
  118. struct rspamd_task *task;
  119. struct rspamd_symcache_item *item;
  120. struct upstream *server;
  121. struct fuzzy_rule *rule;
  122. struct ev_loop *event_loop;
  123. struct rspamd_io_ev ev;
  124. gint state;
  125. gint fd;
  126. guint retransmits;
  127. };
  128. struct fuzzy_learn_session {
  129. GPtrArray *commands;
  130. gint *saved;
  131. GError **err;
  132. struct rspamd_http_connection_entry *http_entry;
  133. struct rspamd_async_session *session;
  134. struct upstream *server;
  135. struct fuzzy_rule *rule;
  136. struct rspamd_task *task;
  137. struct ev_loop *event_loop;
  138. struct rspamd_io_ev ev;
  139. gint fd;
  140. guint retransmits;
  141. };
  142. #define FUZZY_CMD_FLAG_REPLIED (1 << 0)
  143. #define FUZZY_CMD_FLAG_SENT (1 << 1)
  144. #define FUZZY_CMD_FLAG_IMAGE (1 << 2)
  145. #define FUZZY_CHECK_FLAG_NOIMAGES (1 << 0)
  146. #define FUZZY_CHECK_FLAG_NOATTACHMENTS (1 << 1)
  147. #define FUZZY_CHECK_FLAG_NOTEXT (1 << 2)
  148. struct fuzzy_cmd_io {
  149. guint32 tag;
  150. guint32 flags;
  151. struct iovec io;
  152. struct rspamd_mime_part *part;
  153. struct rspamd_fuzzy_cmd cmd;
  154. };
  155. static const char *default_headers = "Subject,Content-Type,Reply-To,X-Mailer";
  156. static void fuzzy_symbol_callback (struct rspamd_task *task,
  157. struct rspamd_symcache_item *item,
  158. void *unused);
  159. /* Initialization */
  160. gint fuzzy_check_module_init (struct rspamd_config *cfg,
  161. struct module_ctx **ctx);
  162. gint fuzzy_check_module_config (struct rspamd_config *cfg);
  163. gint fuzzy_check_module_reconfig (struct rspamd_config *cfg);
  164. static gint fuzzy_attach_controller (struct module_ctx *ctx,
  165. GHashTable *commands);
  166. static gint fuzzy_lua_learn_handler (lua_State *L);
  167. static gint fuzzy_lua_unlearn_handler (lua_State *L);
  168. module_t fuzzy_check_module = {
  169. "fuzzy_check",
  170. fuzzy_check_module_init,
  171. fuzzy_check_module_config,
  172. fuzzy_check_module_reconfig,
  173. fuzzy_attach_controller,
  174. RSPAMD_MODULE_VER,
  175. (guint)-1,
  176. };
  177. static inline struct fuzzy_ctx *
  178. fuzzy_get_context (struct rspamd_config *cfg)
  179. {
  180. return (struct fuzzy_ctx *)g_ptr_array_index (cfg->c_modules,
  181. fuzzy_check_module.ctx_offset);
  182. }
  183. static void
  184. parse_flags (struct fuzzy_rule *rule,
  185. struct rspamd_config *cfg,
  186. const ucl_object_t *val,
  187. gint cb_id)
  188. {
  189. const ucl_object_t *elt;
  190. struct fuzzy_mapping *map;
  191. const gchar *sym = NULL;
  192. if (val->type == UCL_STRING) {
  193. msg_err_config (
  194. "string mappings are deprecated and no longer supported, use new style configuration");
  195. }
  196. else if (val->type == UCL_OBJECT) {
  197. elt = ucl_object_lookup (val, "symbol");
  198. if (elt == NULL || !ucl_object_tostring_safe (elt, &sym)) {
  199. sym = ucl_object_key (val);
  200. }
  201. if (sym != NULL) {
  202. map =
  203. rspamd_mempool_alloc (cfg->cfg_pool,
  204. sizeof (struct fuzzy_mapping));
  205. map->symbol = sym;
  206. elt = ucl_object_lookup (val, "flag");
  207. if (elt != NULL) {
  208. map->fuzzy_flag = ucl_obj_toint (elt);
  209. elt = ucl_object_lookup (val, "max_score");
  210. if (elt != NULL) {
  211. map->weight = ucl_obj_todouble (elt);
  212. }
  213. else {
  214. map->weight = rule->max_score;
  215. }
  216. /* Add flag to hash table */
  217. g_hash_table_insert (rule->mappings,
  218. GINT_TO_POINTER (map->fuzzy_flag), map);
  219. rspamd_symcache_add_symbol (cfg->cache,
  220. map->symbol, 0,
  221. NULL, NULL,
  222. SYMBOL_TYPE_VIRTUAL | SYMBOL_TYPE_FINE,
  223. cb_id);
  224. }
  225. else {
  226. msg_err_config ("fuzzy_map parameter has no flag definition");
  227. }
  228. }
  229. else {
  230. msg_err_config ("fuzzy_map parameter has no symbol definition");
  231. }
  232. }
  233. else {
  234. msg_err_config ("fuzzy_map parameter is of an unsupported type");
  235. }
  236. }
  237. static GPtrArray *
  238. parse_fuzzy_headers (struct rspamd_config *cfg, const gchar *str)
  239. {
  240. gchar **strvec;
  241. gint num, i;
  242. GPtrArray *res;
  243. strvec = g_strsplit_set (str, ",", 0);
  244. num = g_strv_length (strvec);
  245. res = g_ptr_array_sized_new (num);
  246. for (i = 0; i < num; i++) {
  247. g_strstrip (strvec[i]);
  248. g_ptr_array_add (res, rspamd_mempool_strdup (
  249. cfg->cfg_pool, strvec[i]));
  250. }
  251. g_strfreev (strvec);
  252. return res;
  253. }
  254. static double
  255. fuzzy_normalize (gint32 in, double weight)
  256. {
  257. if (weight == 0) {
  258. return 0;
  259. }
  260. #ifdef HAVE_TANH
  261. return tanh (G_E * (double)in / weight);
  262. #else
  263. return (in < weight ? in / weight : weight);
  264. #endif
  265. }
  266. static struct fuzzy_rule *
  267. fuzzy_rule_new (const char *default_symbol, rspamd_mempool_t *pool)
  268. {
  269. struct fuzzy_rule *rule;
  270. rule = rspamd_mempool_alloc0 (pool, sizeof (struct fuzzy_rule));
  271. rule->mappings = g_hash_table_new (g_direct_hash, g_direct_equal);
  272. rule->symbol = default_symbol;
  273. rspamd_mempool_add_destructor (pool,
  274. (rspamd_mempool_destruct_t)g_hash_table_unref,
  275. rule->mappings);
  276. rule->read_only = FALSE;
  277. return rule;
  278. }
  279. static void
  280. fuzzy_free_rule (gpointer r)
  281. {
  282. struct fuzzy_rule *rule = (struct fuzzy_rule *)r;
  283. g_string_free (rule->hash_key, TRUE);
  284. g_string_free (rule->shingles_key, TRUE);
  285. if (rule->local_key) {
  286. rspamd_keypair_unref (rule->local_key);
  287. }
  288. if (rule->peer_key) {
  289. rspamd_pubkey_unref (rule->peer_key);
  290. }
  291. }
  292. static gint
  293. fuzzy_parse_rule (struct rspamd_config *cfg, const ucl_object_t *obj,
  294. const gchar *name, gint cb_id)
  295. {
  296. const ucl_object_t *value, *cur;
  297. struct fuzzy_rule *rule;
  298. ucl_object_iter_t it = NULL;
  299. const char *k = NULL, *key_str = NULL, *shingles_key_str = NULL, *lua_script;
  300. struct fuzzy_ctx *fuzzy_module_ctx = fuzzy_get_context (cfg);
  301. if (obj->type != UCL_OBJECT) {
  302. msg_err_config ("invalid rule definition");
  303. return -1;
  304. }
  305. rule = fuzzy_rule_new (fuzzy_module_ctx->default_symbol,
  306. cfg->cfg_pool);
  307. rule->ucl_obj = obj;
  308. rule->ctx = fuzzy_module_ctx;
  309. rule->learn_condition_cb = -1;
  310. rule->alg = RSPAMD_SHINGLES_OLD;
  311. rule->skip_map = NULL;
  312. if ((value = ucl_object_lookup (obj, "skip_hashes")) != NULL) {
  313. rspamd_map_add_from_ucl (cfg, value,
  314. "Fuzzy hashes whitelist",
  315. rspamd_kv_list_read,
  316. rspamd_kv_list_fin,
  317. rspamd_kv_list_dtor,
  318. (void **)&rule->skip_map);
  319. }
  320. if ((value = ucl_object_lookup (obj, "headers")) != NULL) {
  321. it = NULL;
  322. while ((cur = ucl_object_iterate (value, &it, value->type == UCL_ARRAY))
  323. != NULL) {
  324. GPtrArray *tmp;
  325. guint i;
  326. gpointer ptr;
  327. tmp = parse_fuzzy_headers (cfg, ucl_obj_tostring (cur));
  328. if (tmp) {
  329. if (rule->fuzzy_headers) {
  330. PTR_ARRAY_FOREACH (tmp, i, ptr) {
  331. g_ptr_array_add (rule->fuzzy_headers, ptr);
  332. }
  333. g_ptr_array_free (tmp, TRUE);
  334. }
  335. else {
  336. rule->fuzzy_headers = tmp;
  337. }
  338. }
  339. }
  340. }
  341. else {
  342. rule->fuzzy_headers = parse_fuzzy_headers (cfg, default_headers);
  343. }
  344. if (rule->fuzzy_headers != NULL) {
  345. rspamd_mempool_add_destructor (cfg->cfg_pool,
  346. (rspamd_mempool_destruct_t) rspamd_ptr_array_free_hard,
  347. rule->fuzzy_headers);
  348. }
  349. if ((value = ucl_object_lookup (obj, "max_score")) != NULL) {
  350. rule->max_score = ucl_obj_todouble (value);
  351. }
  352. if ((value = ucl_object_lookup (obj, "symbol")) != NULL) {
  353. rule->symbol = ucl_obj_tostring (value);
  354. }
  355. if (name) {
  356. rule->name = name;
  357. }
  358. else {
  359. rule->name = rule->symbol;
  360. }
  361. if ((value = ucl_object_lookup (obj, "read_only")) != NULL) {
  362. rule->read_only = ucl_obj_toboolean (value);
  363. }
  364. if ((value = ucl_object_lookup (obj, "skip_unknown")) != NULL) {
  365. rule->skip_unknown = ucl_obj_toboolean (value);
  366. }
  367. if ((value = ucl_object_lookup (obj, "algorithm")) != NULL) {
  368. rule->algorithm_str = ucl_object_tostring (value);
  369. if (rule->algorithm_str) {
  370. if (g_ascii_strcasecmp (rule->algorithm_str, "old") == 0 ||
  371. g_ascii_strcasecmp (rule->algorithm_str, "siphash") == 0) {
  372. rule->alg = RSPAMD_SHINGLES_OLD;
  373. }
  374. else if (g_ascii_strcasecmp (rule->algorithm_str, "xxhash") == 0) {
  375. rule->alg = RSPAMD_SHINGLES_XXHASH;
  376. }
  377. else if (g_ascii_strcasecmp (rule->algorithm_str, "mumhash") == 0) {
  378. rule->alg = RSPAMD_SHINGLES_MUMHASH;
  379. }
  380. else if (g_ascii_strcasecmp (rule->algorithm_str, "fasthash") == 0 ||
  381. g_ascii_strcasecmp (rule->algorithm_str, "fast") == 0) {
  382. rule->alg = RSPAMD_SHINGLES_FAST;
  383. }
  384. else {
  385. msg_warn_config ("unknown algorithm: %s, use siphash by default",
  386. rule->algorithm_str);
  387. }
  388. }
  389. }
  390. /* Set a consistent and short string name */
  391. switch (rule->alg) {
  392. case RSPAMD_SHINGLES_OLD:
  393. rule->algorithm_str = "sip";
  394. break;
  395. case RSPAMD_SHINGLES_XXHASH:
  396. rule->algorithm_str = "xx";
  397. break;
  398. case RSPAMD_SHINGLES_MUMHASH:
  399. rule->algorithm_str = "mum";
  400. break;
  401. case RSPAMD_SHINGLES_FAST:
  402. rule->algorithm_str = "fast";
  403. break;
  404. }
  405. if ((value = ucl_object_lookup (obj, "servers")) != NULL) {
  406. rule->servers = rspamd_upstreams_create (cfg->ups_ctx);
  407. /* pass max_error and revive_time configuration in upstream for fuzzy storage
  408. * it allows to configure error_rate threshold and upstream dead timer
  409. */
  410. rspamd_upstreams_set_limits (rule->servers, (gdouble) fuzzy_module_ctx->revive_time, NAN, NAN, NAN, (guint) fuzzy_module_ctx->max_errors, NAN);
  411. rspamd_mempool_add_destructor (cfg->cfg_pool,
  412. (rspamd_mempool_destruct_t)rspamd_upstreams_destroy,
  413. rule->servers);
  414. if (!rspamd_upstreams_from_ucl (rule->servers, value, DEFAULT_PORT, NULL)) {
  415. msg_err_config ("cannot read servers definition");
  416. return -1;
  417. }
  418. }
  419. if ((value = ucl_object_lookup (obj, "fuzzy_map")) != NULL) {
  420. it = NULL;
  421. while ((cur = ucl_object_iterate (value, &it, true)) != NULL) {
  422. parse_flags (rule, cfg, cur, cb_id);
  423. }
  424. }
  425. if ((value = ucl_object_lookup (obj, "encryption_key")) != NULL) {
  426. /* Create key from user's input */
  427. k = ucl_object_tostring (value);
  428. if (k == NULL || (rule->peer_key =
  429. rspamd_pubkey_from_base32 (k, 0, RSPAMD_KEYPAIR_KEX,
  430. RSPAMD_CRYPTOBOX_MODE_25519)) == NULL) {
  431. msg_err_config ("bad encryption key value: %s",
  432. k);
  433. return -1;
  434. }
  435. rule->local_key = rspamd_keypair_new (RSPAMD_KEYPAIR_KEX,
  436. RSPAMD_CRYPTOBOX_MODE_25519);
  437. }
  438. if ((value = ucl_object_lookup (obj, "learn_condition")) != NULL) {
  439. lua_script = ucl_object_tostring (value);
  440. if (lua_script) {
  441. if (luaL_dostring (cfg->lua_state, lua_script) != 0) {
  442. msg_err_config ("cannot execute lua script for fuzzy "
  443. "learn condition: %s", lua_tostring (cfg->lua_state, -1));
  444. }
  445. else {
  446. if (lua_type (cfg->lua_state, -1) == LUA_TFUNCTION) {
  447. rule->learn_condition_cb = luaL_ref (cfg->lua_state,
  448. LUA_REGISTRYINDEX);
  449. msg_info_config ("loaded learn condition script for fuzzy rule:"
  450. " %s", rule->name);
  451. }
  452. else {
  453. msg_err_config ("lua script must return "
  454. "function(task) and not %s",
  455. lua_typename (cfg->lua_state,
  456. lua_type (cfg->lua_state, -1)));
  457. }
  458. }
  459. }
  460. }
  461. key_str = NULL;
  462. if ((value = ucl_object_lookup (obj, "fuzzy_key")) != NULL) {
  463. /* Create key from user's input */
  464. key_str = ucl_object_tostring (value);
  465. }
  466. /* Setup keys */
  467. if (key_str == NULL) {
  468. /* Use some default key for all ops */
  469. key_str = "rspamd";
  470. }
  471. rule->hash_key = g_string_sized_new (rspamd_cryptobox_HASHBYTES);
  472. rspamd_cryptobox_hash (rule->hash_key->str, key_str, strlen (key_str), NULL, 0);
  473. rule->hash_key->len = rspamd_cryptobox_HASHKEYBYTES;
  474. shingles_key_str = NULL;
  475. if ((value = ucl_object_lookup (obj, "fuzzy_shingles_key")) != NULL) {
  476. shingles_key_str = ucl_object_tostring (value);
  477. }
  478. if (shingles_key_str == NULL) {
  479. shingles_key_str = "rspamd";
  480. }
  481. rule->shingles_key = g_string_sized_new (rspamd_cryptobox_HASHBYTES);
  482. rspamd_cryptobox_hash (rule->shingles_key->str, shingles_key_str,
  483. strlen (shingles_key_str), NULL, 0);
  484. rule->shingles_key->len = 16;
  485. if (rspamd_upstreams_count (rule->servers) == 0) {
  486. msg_err_config ("no servers defined for fuzzy rule with name: %s",
  487. rule->name);
  488. return -1;
  489. }
  490. else {
  491. g_ptr_array_add (fuzzy_module_ctx->fuzzy_rules, rule);
  492. if (rule->symbol != fuzzy_module_ctx->default_symbol) {
  493. rspamd_symcache_add_symbol (cfg->cache, rule->symbol,
  494. 0,
  495. NULL, NULL,
  496. SYMBOL_TYPE_VIRTUAL | SYMBOL_TYPE_FINE,
  497. cb_id);
  498. }
  499. msg_info_config ("added fuzzy rule %s, key: %*xs, "
  500. "shingles_key: %*xs, algorithm: %s",
  501. rule->symbol,
  502. 6, rule->hash_key->str,
  503. 6, rule->shingles_key->str,
  504. rule->algorithm_str);
  505. }
  506. /*
  507. * Process rule in Lua
  508. */
  509. gint err_idx, ret;
  510. lua_State *L = (lua_State *)cfg->lua_state;
  511. lua_pushcfunction (L, &rspamd_lua_traceback);
  512. err_idx = lua_gettop (L);
  513. lua_rawgeti (L, LUA_REGISTRYINDEX, fuzzy_module_ctx->process_rule_ref);
  514. ucl_object_push_lua (L, obj, true);
  515. if ((ret = lua_pcall (L, 1, 1, err_idx)) != 0) {
  516. msg_err_config ("call to process_rule lua "
  517. "script failed (%d): %s", ret, lua_tostring (L, -1));
  518. rule->lua_id = -1;
  519. }
  520. else {
  521. rule->lua_id = lua_tonumber (L, -1);
  522. }
  523. lua_settop (L, 0);
  524. rspamd_mempool_add_destructor (cfg->cfg_pool, fuzzy_free_rule,
  525. rule);
  526. return 0;
  527. }
  528. gint
  529. fuzzy_check_module_init (struct rspamd_config *cfg, struct module_ctx **ctx)
  530. {
  531. struct fuzzy_ctx *fuzzy_module_ctx;
  532. fuzzy_module_ctx = rspamd_mempool_alloc0 (cfg->cfg_pool,
  533. sizeof (struct fuzzy_ctx));
  534. fuzzy_module_ctx->fuzzy_pool = rspamd_mempool_new (rspamd_mempool_suggest_size (), NULL);
  535. /* TODO: this should match rules count actually */
  536. fuzzy_module_ctx->keypairs_cache = rspamd_keypair_cache_new (32);
  537. fuzzy_module_ctx->fuzzy_rules = g_ptr_array_new ();
  538. fuzzy_module_ctx->cfg = cfg;
  539. fuzzy_module_ctx->process_rule_ref = -1;
  540. fuzzy_module_ctx->check_mime_part_ref = -1;
  541. fuzzy_module_ctx->cleanup_rules_ref = -1;
  542. rspamd_mempool_add_destructor (cfg->cfg_pool,
  543. (rspamd_mempool_destruct_t)rspamd_mempool_delete,
  544. fuzzy_module_ctx->fuzzy_pool);
  545. rspamd_mempool_add_destructor (cfg->cfg_pool,
  546. (rspamd_mempool_destruct_t)rspamd_keypair_cache_destroy,
  547. fuzzy_module_ctx->keypairs_cache);
  548. rspamd_mempool_add_destructor (cfg->cfg_pool,
  549. (rspamd_mempool_destruct_t)rspamd_ptr_array_free_hard,
  550. fuzzy_module_ctx->fuzzy_rules);
  551. *ctx = (struct module_ctx *)fuzzy_module_ctx;
  552. rspamd_rcl_add_doc_by_path (cfg,
  553. NULL,
  554. "Fuzzy check plugin",
  555. "fuzzy_check",
  556. UCL_OBJECT,
  557. NULL,
  558. 0,
  559. NULL,
  560. 0);
  561. rspamd_rcl_add_doc_by_path (cfg,
  562. "fuzzy_check",
  563. "Default symbol",
  564. "symbol",
  565. UCL_STRING,
  566. NULL,
  567. 0,
  568. NULL,
  569. 0);
  570. rspamd_rcl_add_doc_by_path (cfg,
  571. "fuzzy_check",
  572. "Minimum number of *words* to check a text part",
  573. "min_length",
  574. UCL_INT,
  575. NULL,
  576. 0,
  577. NULL,
  578. 0);
  579. rspamd_rcl_add_doc_by_path (cfg,
  580. "fuzzy_check",
  581. "Minimum number of *bytes* to check a non-text part",
  582. "min_bytes",
  583. UCL_INT,
  584. NULL,
  585. 0,
  586. NULL,
  587. 0);
  588. rspamd_rcl_add_doc_by_path (cfg,
  589. "fuzzy_check",
  590. "Multiplier for bytes limit when checking for text parts",
  591. "text_multiplier",
  592. UCL_FLOAT,
  593. NULL,
  594. 0,
  595. NULL,
  596. 0);
  597. rspamd_rcl_add_doc_by_path (cfg,
  598. "fuzzy_check",
  599. "Minimum height in pixels for embedded images to check using fuzzy storage",
  600. "min_height",
  601. UCL_INT,
  602. NULL,
  603. 0,
  604. NULL,
  605. 0);
  606. rspamd_rcl_add_doc_by_path (cfg,
  607. "fuzzy_check",
  608. "Minimum width in pixels for embedded images to check using fuzzy storage",
  609. "min_width",
  610. UCL_INT,
  611. NULL,
  612. 0,
  613. NULL,
  614. 0);
  615. rspamd_rcl_add_doc_by_path (cfg,
  616. "fuzzy_check",
  617. "Timeout for waiting reply from a fuzzy server",
  618. "timeout",
  619. UCL_TIME,
  620. NULL,
  621. 0,
  622. NULL,
  623. 0);
  624. rspamd_rcl_add_doc_by_path (cfg,
  625. "fuzzy_check",
  626. "Maximum number of retransmits for a single request",
  627. "retransmits",
  628. UCL_INT,
  629. NULL,
  630. 0,
  631. NULL,
  632. 0);
  633. rspamd_rcl_add_doc_by_path (cfg,
  634. "fuzzy_check",
  635. "Maximum number of upstream errors, affects error rate threshold",
  636. "max_errors",
  637. UCL_INT,
  638. NULL,
  639. 0,
  640. NULL,
  641. 0);
  642. rspamd_rcl_add_doc_by_path (cfg,
  643. "fuzzy_check",
  644. "Time to lapse before re-resolve faulty upstream",
  645. "revive_time",
  646. UCL_FLOAT,
  647. NULL,
  648. 0,
  649. NULL,
  650. 0);
  651. rspamd_rcl_add_doc_by_path (cfg,
  652. "fuzzy_check",
  653. "Whitelisted IPs map",
  654. "whitelist",
  655. UCL_STRING,
  656. NULL,
  657. 0,
  658. NULL,
  659. 0);
  660. /* Rules doc strings */
  661. rspamd_rcl_add_doc_by_path (cfg,
  662. "fuzzy_check",
  663. "Fuzzy check rule",
  664. "rule",
  665. UCL_OBJECT,
  666. NULL,
  667. 0,
  668. NULL,
  669. 0);
  670. rspamd_rcl_add_doc_by_path (cfg,
  671. "fuzzy_check.rule",
  672. "Headers that are used to make a separate hash",
  673. "headers",
  674. UCL_ARRAY,
  675. NULL,
  676. 0,
  677. NULL,
  678. 0);
  679. rspamd_rcl_add_doc_by_path (cfg,
  680. "fuzzy_check.rule",
  681. "Whitelisted hashes map",
  682. "skip_hashes",
  683. UCL_STRING,
  684. NULL,
  685. 0,
  686. NULL,
  687. 0);
  688. rspamd_rcl_add_doc_by_path (cfg,
  689. "fuzzy_check.rule",
  690. "Set of mime types (in form type/subtype, or type/*, or *) to check with fuzzy",
  691. "mime_types",
  692. UCL_ARRAY,
  693. NULL,
  694. 0,
  695. NULL,
  696. 0);
  697. rspamd_rcl_add_doc_by_path (cfg,
  698. "fuzzy_check.rule",
  699. "Maximum value for fuzzy hash when weight of symbol is exactly 1.0 (if value is higher then score is still 1.0)",
  700. "max_score",
  701. UCL_INT,
  702. NULL,
  703. 0,
  704. NULL,
  705. 0);
  706. rspamd_rcl_add_doc_by_path (cfg,
  707. "fuzzy_check.rule",
  708. "List of servers to check (or learn)",
  709. "servers",
  710. UCL_STRING,
  711. NULL,
  712. 0,
  713. NULL,
  714. 0);
  715. rspamd_rcl_add_doc_by_path (cfg,
  716. "fuzzy_check.rule",
  717. "If true then never try to learn this fuzzy storage",
  718. "read_only",
  719. UCL_BOOLEAN,
  720. NULL,
  721. 0,
  722. NULL,
  723. 0);
  724. rspamd_rcl_add_doc_by_path (cfg,
  725. "fuzzy_check.rule",
  726. "If true then ignore unknown flags and not add the default fuzzy symbol",
  727. "skip_unknown",
  728. UCL_BOOLEAN,
  729. NULL,
  730. 0,
  731. NULL,
  732. 0);
  733. rspamd_rcl_add_doc_by_path (cfg,
  734. "fuzzy_check.rule",
  735. "Default symbol for rule (if no flags defined or matched)",
  736. "symbol",
  737. UCL_STRING,
  738. NULL,
  739. 0,
  740. NULL,
  741. 0);
  742. rspamd_rcl_add_doc_by_path (cfg,
  743. "fuzzy_check.rule",
  744. "Base32 value for the protocol encryption public key",
  745. "encryption_key",
  746. UCL_STRING,
  747. NULL,
  748. 0,
  749. NULL,
  750. 0);
  751. rspamd_rcl_add_doc_by_path (cfg,
  752. "fuzzy_check.rule",
  753. "Base32 value for the hashing key (for private storages)",
  754. "fuzzy_key",
  755. UCL_STRING,
  756. NULL,
  757. 0,
  758. NULL,
  759. 0);
  760. rspamd_rcl_add_doc_by_path (cfg,
  761. "fuzzy_check.rule",
  762. "Base32 value for the shingles hashing key (for private storages)",
  763. "fuzzy_shingles_key",
  764. UCL_STRING,
  765. NULL,
  766. 0,
  767. NULL,
  768. 0);
  769. rspamd_rcl_add_doc_by_path (cfg,
  770. "fuzzy_check.rule",
  771. "Lua script that returns boolean function to check if this task "
  772. "should be considered when learning fuzzy storage",
  773. "learn_condition",
  774. UCL_STRING,
  775. NULL,
  776. 0,
  777. NULL,
  778. 0);
  779. rspamd_rcl_add_doc_by_path (cfg,
  780. "fuzzy_check.rule",
  781. "Map of SYMBOL -> data for flags configuration",
  782. "fuzzy_map",
  783. UCL_OBJECT,
  784. NULL,
  785. 0,
  786. NULL,
  787. 0);
  788. rspamd_rcl_add_doc_by_path (cfg,
  789. "fuzzy_check.rule",
  790. "Use direct hash for short texts",
  791. "short_text_direct_hash",
  792. UCL_BOOLEAN,
  793. NULL,
  794. 0,
  795. NULL,
  796. 0);
  797. rspamd_rcl_add_doc_by_path (cfg,
  798. "fuzzy_check.rule",
  799. "Override module default min bytes for this rule",
  800. "min_bytes",
  801. UCL_INT,
  802. NULL,
  803. 0,
  804. NULL,
  805. 0);
  806. /* Fuzzy map doc strings */
  807. rspamd_rcl_add_doc_by_path (cfg,
  808. "fuzzy_check.rule.fuzzy_map",
  809. "Maximum score for this flag",
  810. "max_score",
  811. UCL_INT,
  812. NULL,
  813. 0,
  814. NULL,
  815. 0);
  816. rspamd_rcl_add_doc_by_path (cfg,
  817. "fuzzy_check.rule.fuzzy_map",
  818. "Flag number",
  819. "flag",
  820. UCL_INT,
  821. NULL,
  822. 0,
  823. NULL,
  824. 0);
  825. return 0;
  826. }
  827. gint
  828. fuzzy_check_module_config (struct rspamd_config *cfg)
  829. {
  830. const ucl_object_t *value, *cur, *elt;
  831. ucl_object_iter_t it;
  832. gint res = TRUE, cb_id, nrules = 0;
  833. lua_State *L = cfg->lua_state;
  834. struct fuzzy_ctx *fuzzy_module_ctx = fuzzy_get_context (cfg);
  835. if (!rspamd_config_is_module_enabled (cfg, "fuzzy_check")) {
  836. return TRUE;
  837. }
  838. fuzzy_module_ctx->enabled = TRUE;
  839. fuzzy_module_ctx->check_mime_part_ref = -1;
  840. fuzzy_module_ctx->process_rule_ref = -1;
  841. fuzzy_module_ctx->cleanup_rules_ref = -1;
  842. /* Interact with lua_fuzzy */
  843. if (luaL_dostring (L, "return require \"lua_fuzzy\"") != 0) {
  844. msg_err_config ("cannot require lua_fuzzy: %s",
  845. lua_tostring (L, -1));
  846. fuzzy_module_ctx->enabled = FALSE;
  847. }
  848. else {
  849. if (lua_type (L, -1) != LUA_TTABLE) {
  850. msg_err_config ("lua fuzzy must return "
  851. "table and not %s",
  852. lua_typename (L, lua_type (L, -1)));
  853. fuzzy_module_ctx->enabled = FALSE;
  854. } else {
  855. lua_pushstring (L, "process_rule");
  856. lua_gettable (L, -2);
  857. if (lua_type (L, -1) != LUA_TFUNCTION) {
  858. msg_err_config ("process_rule must return "
  859. "function and not %s",
  860. lua_typename (L, lua_type (L, -1)));
  861. fuzzy_module_ctx->enabled = FALSE;
  862. }
  863. else {
  864. fuzzy_module_ctx->process_rule_ref = luaL_ref (L, LUA_REGISTRYINDEX);
  865. }
  866. lua_pushstring (L, "check_mime_part");
  867. lua_gettable (L, -2);
  868. if (lua_type (L, -1) != LUA_TFUNCTION) {
  869. msg_err_config ("check_mime_part must return "
  870. "function and not %s",
  871. lua_typename (L, lua_type (L, -1)));
  872. fuzzy_module_ctx->enabled = FALSE;
  873. }
  874. else {
  875. fuzzy_module_ctx->check_mime_part_ref = luaL_ref (L, LUA_REGISTRYINDEX);
  876. }
  877. lua_pushstring (L, "cleanup_rules");
  878. lua_gettable (L, -2);
  879. if (lua_type (L, -1) != LUA_TFUNCTION) {
  880. msg_err_config ("cleanup_rules must return "
  881. "function and not %s",
  882. lua_typename (L, lua_type (L, -1)));
  883. fuzzy_module_ctx->enabled = FALSE;
  884. }
  885. else {
  886. fuzzy_module_ctx->cleanup_rules_ref = luaL_ref (L, LUA_REGISTRYINDEX);
  887. }
  888. }
  889. }
  890. lua_settop (L, 0);
  891. if (!fuzzy_module_ctx->enabled) {
  892. return TRUE;
  893. }
  894. if ((value =
  895. rspamd_config_get_module_opt (cfg, "fuzzy_check", "symbol")) != NULL) {
  896. fuzzy_module_ctx->default_symbol = ucl_obj_tostring (value);
  897. }
  898. else {
  899. fuzzy_module_ctx->default_symbol = DEFAULT_SYMBOL;
  900. }
  901. if ((value =
  902. rspamd_config_get_module_opt (cfg, "fuzzy_check", "timeout")) != NULL) {
  903. fuzzy_module_ctx->io_timeout = ucl_obj_todouble (value) * 1000;
  904. }
  905. else {
  906. fuzzy_module_ctx->io_timeout = DEFAULT_IO_TIMEOUT;
  907. }
  908. if ((value =
  909. rspamd_config_get_module_opt (cfg,
  910. "fuzzy_check",
  911. "retransmits")) != NULL) {
  912. fuzzy_module_ctx->retransmits = ucl_obj_toint (value);
  913. }
  914. else {
  915. fuzzy_module_ctx->retransmits = DEFAULT_RETRANSMITS;
  916. }
  917. if ((value =
  918. rspamd_config_get_module_opt (cfg, "fuzzy_check",
  919. "max_errors")) != NULL) {
  920. fuzzy_module_ctx->max_errors = ucl_obj_toint (value);
  921. }
  922. else {
  923. fuzzy_module_ctx->max_errors = DEFAULT_MAX_ERRORS;
  924. }
  925. if ((value =
  926. rspamd_config_get_module_opt (cfg, "fuzzy_check",
  927. "revive_time")) != NULL) {
  928. fuzzy_module_ctx->revive_time = ucl_obj_todouble (value);
  929. }
  930. else {
  931. fuzzy_module_ctx->revive_time = DEFAULT_REVIVE_TIME;
  932. }
  933. if ((value =
  934. rspamd_config_get_module_opt (cfg, "fuzzy_check",
  935. "whitelist")) != NULL) {
  936. rspamd_config_radix_from_ucl (cfg, value, "Fuzzy whitelist",
  937. &fuzzy_module_ctx->whitelist, NULL);
  938. }
  939. else {
  940. fuzzy_module_ctx->whitelist = NULL;
  941. }
  942. if ((value =
  943. rspamd_config_get_module_opt (cfg, "fuzzy_check", "rule")) != NULL) {
  944. cb_id = rspamd_symcache_add_symbol (cfg->cache,
  945. "FUZZY_CALLBACK", 0, fuzzy_symbol_callback, NULL,
  946. SYMBOL_TYPE_CALLBACK | SYMBOL_TYPE_FINE,
  947. -1);
  948. rspamd_config_add_symbol (cfg,
  949. "FUZZY_CALLBACK",
  950. 0.0,
  951. "Fuzzy check callback",
  952. "fuzzy",
  953. RSPAMD_SYMBOL_FLAG_IGNORE,
  954. 1,
  955. 1);
  956. /*
  957. * Here we can have 2 possibilities:
  958. *
  959. * unnamed rules:
  960. *
  961. * rule {
  962. * ...
  963. * }
  964. * rule {
  965. * ...
  966. * }
  967. *
  968. * - or - named rules:
  969. *
  970. * rule {
  971. * "rule1": {
  972. * ...
  973. * }
  974. * "rule2": {
  975. * ...
  976. * }
  977. * }
  978. *
  979. * So, for each element, we check, if there 'servers' key. If 'servers' is
  980. * presented, then we treat it as unnamed rule, otherwise we treat it as
  981. * named rule.
  982. */
  983. LL_FOREACH (value, cur) {
  984. if (ucl_object_lookup (cur, "servers")) {
  985. /* Unnamed rule */
  986. fuzzy_parse_rule (cfg, cur, NULL, cb_id);
  987. nrules ++;
  988. }
  989. else {
  990. /* Named rule */
  991. it = NULL;
  992. while ((elt = ucl_object_iterate (cur, &it, true)) != NULL) {
  993. fuzzy_parse_rule (cfg, elt, ucl_object_key (elt), cb_id);
  994. nrules ++;
  995. }
  996. }
  997. }
  998. /* We want that to check bad mime attachments */
  999. rspamd_symcache_add_delayed_dependency (cfg->cache,
  1000. "FUZZY_CALLBACK", "MIME_TYPES_CALLBACK");
  1001. }
  1002. if (fuzzy_module_ctx->fuzzy_rules == NULL) {
  1003. msg_warn_config ("fuzzy module is enabled but no rules are defined");
  1004. }
  1005. msg_info_config ("init internal fuzzy_check module, %d rules loaded",
  1006. nrules);
  1007. /* Register global methods */
  1008. lua_getglobal (L, "rspamd_plugins");
  1009. if (lua_type (L, -1) == LUA_TTABLE) {
  1010. lua_pushstring (L, "fuzzy_check");
  1011. lua_createtable (L, 0, 2);
  1012. /* Set methods */
  1013. lua_pushstring (L, "unlearn");
  1014. lua_pushcfunction (L, fuzzy_lua_unlearn_handler);
  1015. lua_settable (L, -3);
  1016. lua_pushstring (L, "learn");
  1017. lua_pushcfunction (L, fuzzy_lua_learn_handler);
  1018. lua_settable (L, -3);
  1019. /* Finish fuzzy_check key */
  1020. lua_settable (L, -3);
  1021. }
  1022. lua_settop (L, 0);
  1023. return res;
  1024. }
  1025. gint
  1026. fuzzy_check_module_reconfig (struct rspamd_config *cfg)
  1027. {
  1028. struct fuzzy_ctx *fuzzy_module_ctx = fuzzy_get_context (cfg);
  1029. if (fuzzy_module_ctx->cleanup_rules_ref != -1) {
  1030. /* Sync lua_fuzzy rules */
  1031. gint err_idx, ret;
  1032. lua_State *L = (lua_State *)cfg->lua_state;
  1033. lua_pushcfunction (L, &rspamd_lua_traceback);
  1034. err_idx = lua_gettop (L);
  1035. lua_rawgeti (L, LUA_REGISTRYINDEX, fuzzy_module_ctx->cleanup_rules_ref);
  1036. if ((ret = lua_pcall (L, 0, 0, err_idx)) != 0) {
  1037. msg_err_config ("call to cleanup_rules lua "
  1038. "script failed (%d): %s", ret, lua_tostring (L, -1));
  1039. }
  1040. luaL_unref (cfg->lua_state, LUA_REGISTRYINDEX,
  1041. fuzzy_module_ctx->cleanup_rules_ref);
  1042. lua_settop (L, 0);
  1043. }
  1044. if (fuzzy_module_ctx->check_mime_part_ref != -1) {
  1045. luaL_unref (cfg->lua_state, LUA_REGISTRYINDEX,
  1046. fuzzy_module_ctx->check_mime_part_ref);
  1047. }
  1048. if (fuzzy_module_ctx->process_rule_ref != -1) {
  1049. luaL_unref (cfg->lua_state, LUA_REGISTRYINDEX,
  1050. fuzzy_module_ctx->process_rule_ref);
  1051. }
  1052. return fuzzy_check_module_config (cfg);
  1053. }
  1054. /* Finalize IO */
  1055. static void
  1056. fuzzy_io_fin (void *ud)
  1057. {
  1058. struct fuzzy_client_session *session = ud;
  1059. if (session->commands) {
  1060. g_ptr_array_free (session->commands, TRUE);
  1061. }
  1062. if (session->results) {
  1063. g_ptr_array_free (session->results, TRUE);
  1064. }
  1065. rspamd_ev_watcher_stop (session->event_loop, &session->ev);
  1066. close (session->fd);
  1067. }
  1068. static GArray *
  1069. fuzzy_preprocess_words (struct rspamd_mime_text_part *part, rspamd_mempool_t *pool)
  1070. {
  1071. return part->utf_words;
  1072. }
  1073. static void
  1074. fuzzy_encrypt_cmd (struct fuzzy_rule *rule,
  1075. struct rspamd_fuzzy_encrypted_req_hdr *hdr,
  1076. guchar *data, gsize datalen)
  1077. {
  1078. const guchar *pk;
  1079. guint pklen;
  1080. g_assert (hdr != NULL);
  1081. g_assert (data != NULL);
  1082. g_assert (rule != NULL);
  1083. /* Encrypt data */
  1084. memcpy (hdr->magic,
  1085. fuzzy_encrypted_magic,
  1086. sizeof (hdr->magic));
  1087. ottery_rand_bytes (hdr->nonce, sizeof (hdr->nonce));
  1088. pk = rspamd_keypair_component (rule->local_key,
  1089. RSPAMD_KEYPAIR_COMPONENT_PK, &pklen);
  1090. memcpy (hdr->pubkey, pk, MIN (pklen, sizeof (hdr->pubkey)));
  1091. pk = rspamd_pubkey_get_pk (rule->peer_key, &pklen);
  1092. memcpy (hdr->key_id, pk, MIN (sizeof (hdr->key_id), pklen));
  1093. rspamd_keypair_cache_process (rule->ctx->keypairs_cache,
  1094. rule->local_key, rule->peer_key);
  1095. rspamd_cryptobox_encrypt_nm_inplace (data, datalen,
  1096. hdr->nonce, rspamd_pubkey_get_nm (rule->peer_key, rule->local_key),
  1097. hdr->mac,
  1098. rspamd_pubkey_alg (rule->peer_key));
  1099. }
  1100. static struct fuzzy_cmd_io *
  1101. fuzzy_cmd_stat (struct fuzzy_rule *rule,
  1102. int c,
  1103. gint flag,
  1104. guint32 weight,
  1105. rspamd_mempool_t *pool)
  1106. {
  1107. struct rspamd_fuzzy_cmd *cmd;
  1108. struct rspamd_fuzzy_encrypted_cmd *enccmd = NULL;
  1109. struct fuzzy_cmd_io *io;
  1110. if (rule->peer_key) {
  1111. enccmd = rspamd_mempool_alloc0 (pool, sizeof (*enccmd));
  1112. cmd = &enccmd->cmd;
  1113. }
  1114. else {
  1115. cmd = rspamd_mempool_alloc0 (pool, sizeof (*cmd));
  1116. }
  1117. cmd->cmd = c;
  1118. cmd->version = RSPAMD_FUZZY_PLUGIN_VERSION;
  1119. cmd->shingles_count = 0;
  1120. cmd->tag = ottery_rand_uint32 ();
  1121. io = rspamd_mempool_alloc (pool, sizeof (*io));
  1122. io->flags = 0;
  1123. io->tag = cmd->tag;
  1124. memcpy (&io->cmd, cmd, sizeof (io->cmd));
  1125. if (rule->peer_key && enccmd) {
  1126. fuzzy_encrypt_cmd (rule, &enccmd->hdr, (guchar *)cmd, sizeof (*cmd));
  1127. io->io.iov_base = enccmd;
  1128. io->io.iov_len = sizeof (*enccmd);
  1129. }
  1130. else {
  1131. io->io.iov_base = cmd;
  1132. io->io.iov_len = sizeof (*cmd);
  1133. }
  1134. return io;
  1135. }
  1136. static struct fuzzy_cmd_io *
  1137. fuzzy_cmd_hash (struct fuzzy_rule *rule,
  1138. int c,
  1139. const rspamd_ftok_t *hash,
  1140. gint flag,
  1141. guint32 weight,
  1142. rspamd_mempool_t *pool)
  1143. {
  1144. struct rspamd_fuzzy_cmd *cmd;
  1145. struct rspamd_fuzzy_encrypted_cmd *enccmd = NULL;
  1146. struct fuzzy_cmd_io *io;
  1147. if (rule->peer_key) {
  1148. enccmd = rspamd_mempool_alloc0 (pool, sizeof (*enccmd));
  1149. cmd = &enccmd->cmd;
  1150. }
  1151. else {
  1152. cmd = rspamd_mempool_alloc0 (pool, sizeof (*cmd));
  1153. }
  1154. if (hash->len == sizeof (cmd->digest) * 2) {
  1155. /* It is hex encoding */
  1156. if (rspamd_decode_hex_buf (hash->begin, hash->len, cmd->digest,
  1157. sizeof (cmd->digest)) == -1) {
  1158. msg_err_pool ("cannot decode hash, wrong encoding");
  1159. return NULL;
  1160. }
  1161. }
  1162. else {
  1163. msg_err_pool ("cannot decode hash, wrong length: %z", hash->len);
  1164. return NULL;
  1165. }
  1166. cmd->cmd = c;
  1167. cmd->version = RSPAMD_FUZZY_PLUGIN_VERSION;
  1168. cmd->shingles_count = 0;
  1169. cmd->tag = ottery_rand_uint32 ();
  1170. io = rspamd_mempool_alloc (pool, sizeof (*io));
  1171. io->flags = 0;
  1172. io->tag = cmd->tag;
  1173. memcpy (&io->cmd, cmd, sizeof (io->cmd));
  1174. if (rule->peer_key && enccmd) {
  1175. fuzzy_encrypt_cmd (rule, &enccmd->hdr, (guchar *)cmd, sizeof (*cmd));
  1176. io->io.iov_base = enccmd;
  1177. io->io.iov_len = sizeof (*enccmd);
  1178. }
  1179. else {
  1180. io->io.iov_base = cmd;
  1181. io->io.iov_len = sizeof (*cmd);
  1182. }
  1183. return io;
  1184. }
  1185. struct rspamd_cached_shingles {
  1186. struct rspamd_shingle *sh;
  1187. guchar digest[rspamd_cryptobox_HASHBYTES];
  1188. };
  1189. static struct rspamd_cached_shingles *
  1190. fuzzy_cmd_get_cached (struct fuzzy_rule *rule,
  1191. rspamd_mempool_t *pool,
  1192. gpointer p)
  1193. {
  1194. gchar key[32];
  1195. gint key_part;
  1196. memcpy (&key_part, rule->shingles_key->str, sizeof (key_part));
  1197. rspamd_snprintf (key, sizeof (key), "%p%s%d", p, rule->algorithm_str,
  1198. key_part);
  1199. return rspamd_mempool_get_variable (pool, key);
  1200. }
  1201. static void
  1202. fuzzy_cmd_set_cached (struct fuzzy_rule *rule,
  1203. rspamd_mempool_t *pool,
  1204. gpointer p,
  1205. struct rspamd_cached_shingles *data)
  1206. {
  1207. gchar key[32];
  1208. gint key_part;
  1209. memcpy (&key_part, rule->shingles_key->str, sizeof (key_part));
  1210. rspamd_snprintf (key, sizeof (key), "%p%s%d", p, rule->algorithm_str,
  1211. key_part);
  1212. /* Key is copied */
  1213. rspamd_mempool_set_variable (pool, key, data, NULL);
  1214. }
  1215. static gboolean
  1216. fuzzy_rule_check_mimepart (struct rspamd_task *task,
  1217. struct fuzzy_rule *rule,
  1218. struct rspamd_mime_part *part,
  1219. gboolean *need_check,
  1220. gboolean *fuzzy_check)
  1221. {
  1222. if (rule->lua_id != -1 && rule->ctx->check_mime_part_ref != -1) {
  1223. gint err_idx, ret;
  1224. lua_State *L = (lua_State *)task->cfg->lua_state;
  1225. struct rspamd_task **ptask;
  1226. struct rspamd_mime_part **ppart;
  1227. lua_pushcfunction (L, &rspamd_lua_traceback);
  1228. err_idx = lua_gettop (L);
  1229. lua_rawgeti (L, LUA_REGISTRYINDEX, rule->ctx->check_mime_part_ref);
  1230. ptask = lua_newuserdata (L, sizeof (*ptask));
  1231. *ptask = task;
  1232. rspamd_lua_setclass (L, "rspamd{task}", -1);
  1233. ppart = lua_newuserdata (L, sizeof (*ppart));
  1234. *ppart = part;
  1235. rspamd_lua_setclass (L, "rspamd{mimepart}", -1);
  1236. lua_pushnumber (L, rule->lua_id);
  1237. if ((ret = lua_pcall (L, 3, 2, err_idx)) != 0) {
  1238. msg_err_task ("call to check_mime_part lua "
  1239. "script failed (%d): %s", ret, lua_tostring (L, -1));
  1240. ret = FALSE;
  1241. }
  1242. else {
  1243. ret = TRUE;
  1244. *need_check = lua_toboolean (L, -2);
  1245. *fuzzy_check = lua_toboolean (L, -1);
  1246. }
  1247. lua_settop (L, 0);
  1248. return ret;
  1249. }
  1250. return FALSE;
  1251. }
  1252. /*
  1253. * Create fuzzy command from a text part
  1254. */
  1255. static struct fuzzy_cmd_io *
  1256. fuzzy_cmd_from_text_part (struct rspamd_task *task,
  1257. struct fuzzy_rule *rule,
  1258. int c,
  1259. gint flag,
  1260. guint32 weight,
  1261. gboolean short_text,
  1262. rspamd_mempool_t *pool,
  1263. struct rspamd_mime_text_part *part,
  1264. struct rspamd_mime_part *mp)
  1265. {
  1266. struct rspamd_fuzzy_shingle_cmd *shcmd = NULL;
  1267. struct rspamd_fuzzy_cmd *cmd = NULL;
  1268. struct rspamd_fuzzy_encrypted_shingle_cmd *encshcmd = NULL;
  1269. struct rspamd_fuzzy_encrypted_cmd *enccmd = NULL;
  1270. struct rspamd_cached_shingles *cached = NULL;
  1271. struct rspamd_shingle *sh = NULL;
  1272. guint i;
  1273. rspamd_cryptobox_hash_state_t st;
  1274. rspamd_stat_token_t *word;
  1275. GArray *words;
  1276. struct fuzzy_cmd_io *io;
  1277. cached = fuzzy_cmd_get_cached (rule, pool, mp);
  1278. if (cached) {
  1279. /* Copy cached */
  1280. if (short_text) {
  1281. enccmd = rspamd_mempool_alloc0 (pool, sizeof (*enccmd));
  1282. cmd = &enccmd->cmd;
  1283. memcpy (cmd->digest, cached->digest,
  1284. sizeof (cached->digest));
  1285. cmd->shingles_count = 0;
  1286. }
  1287. else if (cached->sh) {
  1288. encshcmd = rspamd_mempool_alloc0 (pool, sizeof (*encshcmd));
  1289. shcmd = &encshcmd->cmd;
  1290. memcpy (&shcmd->sgl, cached->sh, sizeof (struct rspamd_shingle));
  1291. memcpy (shcmd->basic.digest, cached->digest,
  1292. sizeof (cached->digest));
  1293. shcmd->basic.shingles_count = RSPAMD_SHINGLE_SIZE;
  1294. }
  1295. else {
  1296. return NULL;
  1297. }
  1298. }
  1299. else {
  1300. cached = rspamd_mempool_alloc (pool, sizeof (*cached));
  1301. if (short_text) {
  1302. enccmd = rspamd_mempool_alloc0 (pool, sizeof (*encshcmd));
  1303. cmd = &enccmd->cmd;
  1304. rspamd_cryptobox_hash_init (&st, rule->hash_key->str,
  1305. rule->hash_key->len);
  1306. rspamd_cryptobox_hash_update (&st, part->utf_stripped_content->data,
  1307. part->utf_stripped_content->len);
  1308. if (MESSAGE_FIELD (task, subject)) {
  1309. /* We also include subject */
  1310. rspamd_cryptobox_hash_update (&st, MESSAGE_FIELD (task, subject),
  1311. strlen (MESSAGE_FIELD (task, subject)));
  1312. }
  1313. rspamd_cryptobox_hash_final (&st, cmd->digest);
  1314. memcpy (cached->digest, cmd->digest, sizeof (cached->digest));
  1315. cached->sh = NULL;
  1316. }
  1317. else {
  1318. encshcmd = rspamd_mempool_alloc0 (pool, sizeof (*encshcmd));
  1319. shcmd = &encshcmd->cmd;
  1320. /*
  1321. * Generate hash from all words in the part
  1322. */
  1323. rspamd_cryptobox_hash_init (&st, rule->hash_key->str, rule->hash_key->len);
  1324. words = fuzzy_preprocess_words (part, pool);
  1325. for (i = 0; i < words->len; i ++) {
  1326. word = &g_array_index (words, rspamd_stat_token_t, i);
  1327. if (!((word->flags & RSPAMD_STAT_TOKEN_FLAG_SKIPPED)
  1328. || word->stemmed.len == 0)) {
  1329. rspamd_cryptobox_hash_update (&st, word->stemmed.begin,
  1330. word->stemmed.len);
  1331. }
  1332. }
  1333. rspamd_cryptobox_hash_final (&st, shcmd->basic.digest);
  1334. msg_debug_pool ("loading shingles of type %s with key %*xs",
  1335. rule->algorithm_str,
  1336. 16, rule->shingles_key->str);
  1337. sh = rspamd_shingles_from_text (words,
  1338. rule->shingles_key->str, pool,
  1339. rspamd_shingles_default_filter, NULL,
  1340. rule->alg);
  1341. if (sh != NULL) {
  1342. memcpy (&shcmd->sgl, sh, sizeof (shcmd->sgl));
  1343. shcmd->basic.shingles_count = RSPAMD_SHINGLE_SIZE;
  1344. }
  1345. cached->sh = sh;
  1346. memcpy (cached->digest, shcmd->basic.digest, sizeof (cached->digest));
  1347. }
  1348. /*
  1349. * We always save encrypted command as it can handle both
  1350. * encrypted and unencrypted requests.
  1351. *
  1352. * Since it is copied when obtained from the cache, it is safe to use
  1353. * it this way.
  1354. */
  1355. fuzzy_cmd_set_cached (rule, pool, mp, cached);
  1356. }
  1357. io = rspamd_mempool_alloc (pool, sizeof (*io));
  1358. io->part = mp;
  1359. if (!short_text) {
  1360. shcmd->basic.tag = ottery_rand_uint32 ();
  1361. shcmd->basic.cmd = c;
  1362. shcmd->basic.version = RSPAMD_FUZZY_PLUGIN_VERSION;
  1363. if (c != FUZZY_CHECK) {
  1364. shcmd->basic.flag = flag;
  1365. shcmd->basic.value = weight;
  1366. }
  1367. io->tag = shcmd->basic.tag;
  1368. memcpy (&io->cmd, &shcmd->basic, sizeof (io->cmd));
  1369. }
  1370. else {
  1371. cmd->tag = ottery_rand_uint32 ();
  1372. cmd->cmd = c;
  1373. cmd->version = RSPAMD_FUZZY_PLUGIN_VERSION;
  1374. if (c != FUZZY_CHECK) {
  1375. cmd->flag = flag;
  1376. cmd->value = weight;
  1377. }
  1378. io->tag = cmd->tag;
  1379. memcpy (&io->cmd, cmd, sizeof (io->cmd));
  1380. }
  1381. io->flags = 0;
  1382. if (rule->peer_key) {
  1383. /* Encrypt data */
  1384. if (!short_text) {
  1385. fuzzy_encrypt_cmd (rule, &encshcmd->hdr, (guchar *) shcmd,
  1386. sizeof (*shcmd));
  1387. io->io.iov_base = encshcmd;
  1388. io->io.iov_len = sizeof (*encshcmd);
  1389. }
  1390. else {
  1391. fuzzy_encrypt_cmd (rule, &enccmd->hdr, (guchar *)cmd,
  1392. sizeof (*cmd));
  1393. io->io.iov_base = enccmd;
  1394. io->io.iov_len = sizeof (*enccmd);
  1395. }
  1396. }
  1397. else {
  1398. if (!short_text) {
  1399. io->io.iov_base = shcmd;
  1400. io->io.iov_len = sizeof (*shcmd);
  1401. }
  1402. else {
  1403. io->io.iov_base = cmd;
  1404. io->io.iov_len = sizeof (*cmd);
  1405. }
  1406. }
  1407. return io;
  1408. }
  1409. static struct fuzzy_cmd_io *
  1410. fuzzy_cmd_from_image_part (struct fuzzy_rule *rule,
  1411. int c,
  1412. gint flag,
  1413. guint32 weight,
  1414. rspamd_mempool_t *pool,
  1415. struct rspamd_image *img,
  1416. struct rspamd_mime_part *mp)
  1417. {
  1418. struct rspamd_fuzzy_shingle_cmd *shcmd;
  1419. struct rspamd_fuzzy_encrypted_shingle_cmd *encshcmd;
  1420. struct fuzzy_cmd_io *io;
  1421. struct rspamd_shingle *sh;
  1422. struct rspamd_cached_shingles *cached;
  1423. cached = fuzzy_cmd_get_cached (rule, pool, mp);
  1424. if (cached) {
  1425. /* Copy cached */
  1426. encshcmd = rspamd_mempool_alloc0 (pool, sizeof (*encshcmd));
  1427. shcmd = &encshcmd->cmd;
  1428. memcpy (&shcmd->sgl, cached->sh, sizeof (struct rspamd_shingle));
  1429. memcpy (shcmd->basic.digest, cached->digest,
  1430. sizeof (cached->digest));
  1431. shcmd->basic.shingles_count = RSPAMD_SHINGLE_SIZE;
  1432. }
  1433. else {
  1434. encshcmd = rspamd_mempool_alloc0 (pool, sizeof (*encshcmd));
  1435. shcmd = &encshcmd->cmd;
  1436. /*
  1437. * Generate shingles
  1438. */
  1439. sh = rspamd_shingles_from_image (img->dct,
  1440. rule->shingles_key->str, pool,
  1441. rspamd_shingles_default_filter, NULL,
  1442. rule->alg);
  1443. if (sh != NULL) {
  1444. memcpy (&shcmd->sgl, sh->hashes, sizeof (shcmd->sgl));
  1445. shcmd->basic.shingles_count = RSPAMD_SHINGLE_SIZE;
  1446. #if 0
  1447. for (unsigned int i = 0; i < RSPAMD_SHINGLE_SIZE; i ++) {
  1448. msg_err ("shingle %d: %L", i, sh->hashes[i]);
  1449. }
  1450. #endif
  1451. }
  1452. rspamd_cryptobox_hash (shcmd->basic.digest,
  1453. (const guchar *)img->dct, RSPAMD_DCT_LEN / NBBY,
  1454. rule->hash_key->str, rule->hash_key->len);
  1455. msg_debug_pool ("loading shingles of type %s with key %*xs",
  1456. rule->algorithm_str,
  1457. 16, rule->shingles_key->str);
  1458. /*
  1459. * We always save encrypted command as it can handle both
  1460. * encrypted and unencrypted requests.
  1461. *
  1462. * Since it is copied when obtained from the cache, it is safe to use
  1463. * it this way.
  1464. */
  1465. cached = rspamd_mempool_alloc (pool, sizeof (*cached));
  1466. cached->sh = sh;
  1467. memcpy (cached->digest, shcmd->basic.digest, sizeof (cached->digest));
  1468. fuzzy_cmd_set_cached (rule, pool, mp, cached);
  1469. }
  1470. shcmd->basic.tag = ottery_rand_uint32 ();
  1471. shcmd->basic.cmd = c;
  1472. shcmd->basic.version = RSPAMD_FUZZY_PLUGIN_VERSION;
  1473. if (c != FUZZY_CHECK) {
  1474. shcmd->basic.flag = flag;
  1475. shcmd->basic.value = weight;
  1476. }
  1477. io = rspamd_mempool_alloc (pool, sizeof (*io));
  1478. io->part = mp;
  1479. io->tag = shcmd->basic.tag;
  1480. io->flags = FUZZY_CMD_FLAG_IMAGE;
  1481. memcpy (&io->cmd, &shcmd->basic, sizeof (io->cmd));
  1482. if (rule->peer_key) {
  1483. /* Encrypt data */
  1484. fuzzy_encrypt_cmd (rule, &encshcmd->hdr, (guchar *) shcmd, sizeof (*shcmd));
  1485. io->io.iov_base = encshcmd;
  1486. io->io.iov_len = sizeof (*encshcmd);
  1487. }
  1488. else {
  1489. io->io.iov_base = shcmd;
  1490. io->io.iov_len = sizeof (*shcmd);
  1491. }
  1492. return io;
  1493. }
  1494. static struct fuzzy_cmd_io *
  1495. fuzzy_cmd_from_data_part (struct fuzzy_rule *rule,
  1496. int c,
  1497. gint flag,
  1498. guint32 weight,
  1499. rspamd_mempool_t *pool,
  1500. guchar digest[rspamd_cryptobox_HASHBYTES],
  1501. struct rspamd_mime_part *mp)
  1502. {
  1503. struct rspamd_fuzzy_cmd *cmd;
  1504. struct rspamd_fuzzy_encrypted_cmd *enccmd = NULL;
  1505. struct fuzzy_cmd_io *io;
  1506. if (rule->peer_key) {
  1507. enccmd = rspamd_mempool_alloc0 (pool, sizeof (*enccmd));
  1508. cmd = &enccmd->cmd;
  1509. }
  1510. else {
  1511. cmd = rspamd_mempool_alloc0 (pool, sizeof (*cmd));
  1512. }
  1513. cmd->cmd = c;
  1514. cmd->version = RSPAMD_FUZZY_PLUGIN_VERSION;
  1515. if (c != FUZZY_CHECK) {
  1516. cmd->flag = flag;
  1517. cmd->value = weight;
  1518. }
  1519. cmd->shingles_count = 0;
  1520. cmd->tag = ottery_rand_uint32 ();
  1521. memcpy (cmd->digest, digest, sizeof (cmd->digest));
  1522. io = rspamd_mempool_alloc (pool, sizeof (*io));
  1523. io->flags = 0;
  1524. io->tag = cmd->tag;
  1525. io->part = mp;
  1526. memcpy (&io->cmd, cmd, sizeof (io->cmd));
  1527. if (rule->peer_key) {
  1528. g_assert (enccmd != NULL);
  1529. fuzzy_encrypt_cmd (rule, &enccmd->hdr, (guchar *) cmd, sizeof (*cmd));
  1530. io->io.iov_base = enccmd;
  1531. io->io.iov_len = sizeof (*enccmd);
  1532. }
  1533. else {
  1534. io->io.iov_base = cmd;
  1535. io->io.iov_len = sizeof (*cmd);
  1536. }
  1537. return io;
  1538. }
  1539. static gboolean
  1540. fuzzy_cmd_to_wire (gint fd, struct iovec *io)
  1541. {
  1542. struct msghdr msg;
  1543. memset (&msg, 0, sizeof (msg));
  1544. msg.msg_iov = io;
  1545. msg.msg_iovlen = 1;
  1546. while (sendmsg (fd, &msg, 0) == -1) {
  1547. if (errno == EINTR) {
  1548. continue;
  1549. }
  1550. return FALSE;
  1551. }
  1552. return TRUE;
  1553. }
  1554. static gboolean
  1555. fuzzy_cmd_vector_to_wire (gint fd, GPtrArray *v)
  1556. {
  1557. guint i;
  1558. gboolean all_sent = TRUE, all_replied = TRUE;
  1559. struct fuzzy_cmd_io *io;
  1560. gboolean processed = FALSE;
  1561. /* First try to resend unsent commands */
  1562. for (i = 0; i < v->len; i ++) {
  1563. io = g_ptr_array_index (v, i);
  1564. if (io->flags & FUZZY_CMD_FLAG_REPLIED) {
  1565. continue;
  1566. }
  1567. all_replied = FALSE;
  1568. if (!(io->flags & FUZZY_CMD_FLAG_SENT)) {
  1569. if (!fuzzy_cmd_to_wire (fd, &io->io)) {
  1570. return FALSE;
  1571. }
  1572. processed = TRUE;
  1573. io->flags |= FUZZY_CMD_FLAG_SENT;
  1574. all_sent = FALSE;
  1575. }
  1576. }
  1577. if (all_sent && !all_replied) {
  1578. /* Now try to resend each command in the vector */
  1579. for (i = 0; i < v->len; i++) {
  1580. io = g_ptr_array_index (v, i);
  1581. if (!(io->flags & FUZZY_CMD_FLAG_REPLIED)) {
  1582. io->flags &= ~FUZZY_CMD_FLAG_SENT;
  1583. }
  1584. }
  1585. return fuzzy_cmd_vector_to_wire (fd, v);
  1586. }
  1587. return processed;
  1588. }
  1589. /*
  1590. * Read replies one-by-one and remove them from req array
  1591. */
  1592. static const struct rspamd_fuzzy_reply *
  1593. fuzzy_process_reply (guchar **pos, gint *r, GPtrArray *req,
  1594. struct fuzzy_rule *rule, struct rspamd_fuzzy_cmd **pcmd,
  1595. struct fuzzy_cmd_io **pio)
  1596. {
  1597. guchar *p = *pos;
  1598. gint remain = *r;
  1599. guint i, required_size;
  1600. struct fuzzy_cmd_io *io;
  1601. const struct rspamd_fuzzy_reply *rep;
  1602. struct rspamd_fuzzy_encrypted_reply encrep;
  1603. gboolean found = FALSE;
  1604. if (rule->peer_key) {
  1605. required_size = sizeof (encrep);
  1606. }
  1607. else {
  1608. required_size = sizeof (*rep);
  1609. }
  1610. if (remain <= 0 || (guint)remain < required_size) {
  1611. return NULL;
  1612. }
  1613. if (rule->peer_key) {
  1614. memcpy (&encrep, p, sizeof (encrep));
  1615. *pos += required_size;
  1616. *r -= required_size;
  1617. /* Try to decrypt reply */
  1618. rspamd_keypair_cache_process (rule->ctx->keypairs_cache,
  1619. rule->local_key, rule->peer_key);
  1620. if (!rspamd_cryptobox_decrypt_nm_inplace ((guchar *)&encrep.rep,
  1621. sizeof (encrep.rep),
  1622. encrep.hdr.nonce,
  1623. rspamd_pubkey_get_nm (rule->peer_key, rule->local_key),
  1624. encrep.hdr.mac,
  1625. rspamd_pubkey_alg (rule->peer_key))) {
  1626. msg_info ("cannot decrypt reply");
  1627. return NULL;
  1628. }
  1629. /* Copy decrypted over the input wire */
  1630. memcpy (p, &encrep.rep, sizeof (encrep.rep));
  1631. }
  1632. else {
  1633. *pos += required_size;
  1634. *r -= required_size;
  1635. }
  1636. rep = (const struct rspamd_fuzzy_reply *) p;
  1637. /*
  1638. * Search for tag
  1639. */
  1640. for (i = 0; i < req->len; i ++) {
  1641. io = g_ptr_array_index (req, i);
  1642. if (io->tag == rep->v1.tag) {
  1643. if (!(io->flags & FUZZY_CMD_FLAG_REPLIED)) {
  1644. io->flags |= FUZZY_CMD_FLAG_REPLIED;
  1645. if (pcmd) {
  1646. *pcmd = &io->cmd;
  1647. }
  1648. if (pio) {
  1649. *pio = io;
  1650. }
  1651. return rep;
  1652. }
  1653. found = TRUE;
  1654. }
  1655. }
  1656. if (!found) {
  1657. msg_info ("unexpected tag: %ud", rep->v1.tag);
  1658. }
  1659. return NULL;
  1660. }
  1661. static void
  1662. fuzzy_insert_result (struct fuzzy_client_session *session,
  1663. const struct rspamd_fuzzy_reply *rep,
  1664. struct rspamd_fuzzy_cmd *cmd,
  1665. struct fuzzy_cmd_io *io,
  1666. guint flag)
  1667. {
  1668. const gchar *symbol;
  1669. struct fuzzy_mapping *map;
  1670. struct rspamd_task *task = session->task;
  1671. double weight;
  1672. double nval;
  1673. guchar buf[2048];
  1674. const gchar *type = "bin";
  1675. struct fuzzy_client_result *res;
  1676. gboolean is_fuzzy = FALSE;
  1677. gchar hexbuf[rspamd_cryptobox_HASHBYTES * 2 + 1];
  1678. /* Discriminate scores for small images */
  1679. static const guint short_image_limit = 32 * 1024;
  1680. /* Get mapping by flag */
  1681. if ((map =
  1682. g_hash_table_lookup (session->rule->mappings,
  1683. GINT_TO_POINTER (rep->v1.flag))) == NULL) {
  1684. /* Default symbol and default weight */
  1685. symbol = session->rule->symbol;
  1686. weight = session->rule->max_score;
  1687. }
  1688. else {
  1689. /* Get symbol and weight from map */
  1690. symbol = map->symbol;
  1691. weight = map->weight;
  1692. }
  1693. res = rspamd_mempool_alloc0 (task->task_pool, sizeof (*res));
  1694. res->prob = rep->v1.prob;
  1695. res->symbol = symbol;
  1696. /*
  1697. * Hash is assumed to be found if probability is more than 0.5
  1698. * In that case `value` means number of matches
  1699. * Otherwise `value` means error code
  1700. */
  1701. nval = fuzzy_normalize (rep->v1.value, weight);
  1702. if (io && (io->flags & FUZZY_CMD_FLAG_IMAGE)) {
  1703. if (!io->part || io->part->parsed_data.len <= short_image_limit) {
  1704. nval *= rspamd_normalize_probability (rep->v1.prob, 0.5);
  1705. }
  1706. type = "img";
  1707. res->type = FUZZY_RESULT_IMG;
  1708. }
  1709. else {
  1710. /* Calc real probability */
  1711. nval *= sqrtf (rep->v1.prob);
  1712. if (cmd->shingles_count > 0) {
  1713. type = "txt";
  1714. res->type = FUZZY_RESULT_TXT;
  1715. }
  1716. else {
  1717. res->type = FUZZY_RESULT_BIN;
  1718. }
  1719. }
  1720. res->score = nval;
  1721. if (memcmp (rep->digest, cmd->digest, sizeof (rep->digest)) != 0) {
  1722. is_fuzzy = TRUE;
  1723. }
  1724. if (map != NULL || !session->rule->skip_unknown) {
  1725. GList *fuzzy_var;
  1726. rspamd_fstring_t *hex_result;
  1727. if (session->rule->skip_map) {
  1728. rspamd_encode_hex_buf (cmd->digest, sizeof (cmd->digest),
  1729. hexbuf, sizeof (hexbuf) - 1);
  1730. hexbuf[sizeof (hexbuf) - 1] = '\0';
  1731. if (rspamd_match_hash_map (session->rule->skip_map, hexbuf)) {
  1732. return;
  1733. }
  1734. }
  1735. rspamd_encode_hex_buf (rep->digest, sizeof (rep->digest),
  1736. hexbuf, sizeof (hexbuf) - 1);
  1737. hexbuf[sizeof (hexbuf) - 1] = '\0';
  1738. if (is_fuzzy) {
  1739. msg_info_task (
  1740. "found fuzzy hash(%s) %s (%*xs requested) with weight: "
  1741. "%.2f, probability %.2f, in list: %s:%d%s",
  1742. type,
  1743. hexbuf,
  1744. (gint) sizeof (cmd->digest), cmd->digest,
  1745. nval,
  1746. (gdouble) rep->v1.prob,
  1747. symbol,
  1748. rep->v1.flag,
  1749. map == NULL ? "(unknown)" : "");
  1750. }
  1751. else {
  1752. msg_info_task (
  1753. "found exact fuzzy hash(%s) %s with weight: "
  1754. "%.2f, probability %.2f, in list: %s:%d%s",
  1755. type,
  1756. hexbuf,
  1757. nval,
  1758. (gdouble) rep->v1.prob,
  1759. symbol,
  1760. rep->v1.flag,
  1761. map == NULL ? "(unknown)" : "");
  1762. }
  1763. rspamd_snprintf (buf,
  1764. sizeof (buf),
  1765. "%d:%*s:%.2f:%s",
  1766. rep->v1.flag,
  1767. (gint)MIN(rspamd_fuzzy_hash_len * 2, sizeof (rep->digest) * 2), hexbuf,
  1768. rep->v1.prob,
  1769. type);
  1770. res->option = rspamd_mempool_strdup (task->task_pool, buf);
  1771. g_ptr_array_add (session->results, res);
  1772. /* Store hex string in pool variable */
  1773. hex_result = rspamd_mempool_alloc (task->task_pool,
  1774. sizeof (rspamd_fstring_t) + sizeof (hexbuf));
  1775. memcpy (hex_result->str, hexbuf, sizeof (hexbuf));
  1776. hex_result->len = sizeof (hexbuf) - 1;
  1777. hex_result->allocated = (gsize)-1;
  1778. fuzzy_var = rspamd_mempool_get_variable (task->task_pool,
  1779. RSPAMD_MEMPOOL_FUZZY_RESULT);
  1780. if (fuzzy_var == NULL) {
  1781. fuzzy_var = g_list_prepend (NULL, hex_result);
  1782. rspamd_mempool_set_variable (task->task_pool,
  1783. RSPAMD_MEMPOOL_FUZZY_RESULT, fuzzy_var,
  1784. (rspamd_mempool_destruct_t)g_list_free);
  1785. }
  1786. else {
  1787. /* Not very efficient, but we don't really use it intensively */
  1788. fuzzy_var = g_list_append (fuzzy_var, hex_result);
  1789. }
  1790. }
  1791. }
  1792. static gint
  1793. fuzzy_check_try_read (struct fuzzy_client_session *session)
  1794. {
  1795. struct rspamd_task *task;
  1796. const struct rspamd_fuzzy_reply *rep;
  1797. struct rspamd_fuzzy_cmd *cmd = NULL;
  1798. struct fuzzy_cmd_io *io = NULL;
  1799. gint r, ret;
  1800. guchar buf[2048], *p;
  1801. task = session->task;
  1802. if ((r = read (session->fd, buf, sizeof (buf) - 1)) == -1) {
  1803. if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) {
  1804. return 0;
  1805. }
  1806. else {
  1807. return -1;
  1808. }
  1809. }
  1810. else {
  1811. p = buf;
  1812. ret = 0;
  1813. while ((rep = fuzzy_process_reply (&p, &r,
  1814. session->commands, session->rule, &cmd, &io)) != NULL) {
  1815. if (rep->v1.prob > 0.5) {
  1816. if (cmd->cmd == FUZZY_CHECK) {
  1817. fuzzy_insert_result (session, rep, cmd, io, rep->v1.flag);
  1818. }
  1819. else if (cmd->cmd == FUZZY_STAT) {
  1820. /* Just set pool variable to extract it in further */
  1821. struct rspamd_fuzzy_stat_entry *pval;
  1822. GList *res;
  1823. pval = rspamd_mempool_alloc (task->task_pool, sizeof (*pval));
  1824. pval->fuzzy_cnt = rep->v1.flag;
  1825. pval->name = session->rule->name;
  1826. res = rspamd_mempool_get_variable (task->task_pool, "fuzzy_stat");
  1827. if (res == NULL) {
  1828. res = g_list_append (NULL, pval);
  1829. rspamd_mempool_set_variable (task->task_pool, "fuzzy_stat",
  1830. res, (rspamd_mempool_destruct_t)g_list_free);
  1831. }
  1832. else {
  1833. res = g_list_append (res, pval);
  1834. }
  1835. }
  1836. }
  1837. else if (rep->v1.value == 403) {
  1838. rspamd_task_insert_result (task, "FUZZY_BLOCKED", 0.0,
  1839. session->rule->name);
  1840. }
  1841. else if (rep->v1.value == 401) {
  1842. if (cmd->cmd != FUZZY_CHECK) {
  1843. msg_info_task (
  1844. "fuzzy check error for %d: skipped by server",
  1845. rep->v1.flag);
  1846. }
  1847. }
  1848. else if (rep->v1.value != 0) {
  1849. msg_info_task (
  1850. "fuzzy check error for %d: unknown error (%d)",
  1851. rep->v1.flag,
  1852. rep->v1.value);
  1853. }
  1854. ret = 1;
  1855. }
  1856. }
  1857. return ret;
  1858. }
  1859. static void
  1860. fuzzy_insert_metric_results (struct rspamd_task *task, GPtrArray *results)
  1861. {
  1862. struct fuzzy_client_result *res;
  1863. guint i;
  1864. gboolean seen_text_hash = FALSE,
  1865. seen_img_hash = FALSE,
  1866. seen_text_part = FALSE,
  1867. seen_long_text = FALSE;
  1868. gdouble prob_txt = 0.0, mult;
  1869. struct rspamd_mime_text_part *tp;
  1870. /* About 5 words */
  1871. static const unsigned int text_length_cutoff = 25;
  1872. PTR_ARRAY_FOREACH (results, i, res) {
  1873. if (res->type == FUZZY_RESULT_TXT) {
  1874. seen_text_hash = TRUE;
  1875. prob_txt = MAX (prob_txt, res->prob);
  1876. }
  1877. else if (res->type == FUZZY_RESULT_IMG) {
  1878. seen_img_hash = TRUE;
  1879. }
  1880. }
  1881. if (task->message) {
  1882. PTR_ARRAY_FOREACH (MESSAGE_FIELD (task, text_parts), i, tp) {
  1883. if (!IS_PART_EMPTY (tp) && tp->utf_words->len > 0) {
  1884. seen_text_part = TRUE;
  1885. if (tp->utf_stripped_text.magic == UTEXT_MAGIC) {
  1886. if (utext_isLengthExpensive (&tp->utf_stripped_text)) {
  1887. seen_long_text =
  1888. utext_nativeLength (&tp->utf_stripped_text) >
  1889. text_length_cutoff;
  1890. }
  1891. else {
  1892. /* Cannot directly calculate length */
  1893. seen_long_text =
  1894. (tp->utf_stripped_content->len / 2) >
  1895. text_length_cutoff;
  1896. }
  1897. }
  1898. }
  1899. }
  1900. }
  1901. PTR_ARRAY_FOREACH (results, i, res) {
  1902. mult = 1.0;
  1903. if (res->type == FUZZY_RESULT_IMG) {
  1904. if (!seen_text_hash) {
  1905. if (seen_long_text) {
  1906. mult *= 0.25;
  1907. }
  1908. else if (seen_text_part) {
  1909. /* We have some short text + image */
  1910. mult *= 0.9;
  1911. }
  1912. /* Otherwise apply full score */
  1913. }
  1914. else if (prob_txt < 0.75) {
  1915. /* Penalize sole image without matching text */
  1916. if (prob_txt > 0.5) {
  1917. mult *= prob_txt;
  1918. }
  1919. else {
  1920. mult *= 0.5; /* cutoff */
  1921. }
  1922. }
  1923. }
  1924. else if (res->type == FUZZY_RESULT_TXT) {
  1925. if (seen_img_hash) {
  1926. /* Slightly increase score */
  1927. mult = 1.1;
  1928. }
  1929. }
  1930. rspamd_task_insert_result_single (task, res->symbol,
  1931. res->score * mult, res->option);
  1932. }
  1933. }
  1934. static gboolean
  1935. fuzzy_check_session_is_completed (struct fuzzy_client_session *session)
  1936. {
  1937. struct fuzzy_cmd_io *io;
  1938. guint nreplied = 0, i;
  1939. rspamd_upstream_ok (session->server);
  1940. for (i = 0; i < session->commands->len; i++) {
  1941. io = g_ptr_array_index (session->commands, i);
  1942. if (io->flags & FUZZY_CMD_FLAG_REPLIED) {
  1943. nreplied++;
  1944. }
  1945. }
  1946. if (nreplied == session->commands->len) {
  1947. fuzzy_insert_metric_results (session->task, session->results);
  1948. if (session->item) {
  1949. rspamd_symcache_item_async_dec_check (session->task, session->item, M);
  1950. }
  1951. rspamd_session_remove_event (session->task->s, fuzzy_io_fin, session);
  1952. return TRUE;
  1953. }
  1954. return FALSE;
  1955. }
  1956. /* Fuzzy check timeout callback */
  1957. static void
  1958. fuzzy_check_timer_callback (gint fd, short what, void *arg)
  1959. {
  1960. struct fuzzy_client_session *session = arg;
  1961. struct rspamd_task *task;
  1962. task = session->task;
  1963. /* We might be here because of other checks being slow */
  1964. if (fuzzy_check_try_read (session) > 0) {
  1965. if (fuzzy_check_session_is_completed (session)) {
  1966. return;
  1967. }
  1968. }
  1969. if (session->retransmits >= session->rule->ctx->retransmits) {
  1970. msg_err_task ("got IO timeout with server %s(%s), after %d retransmits",
  1971. rspamd_upstream_name (session->server),
  1972. rspamd_inet_address_to_string_pretty (
  1973. rspamd_upstream_addr_cur (session->server)),
  1974. session->retransmits);
  1975. rspamd_upstream_fail (session->server, TRUE);
  1976. if (session->item) {
  1977. rspamd_symcache_item_async_dec_check (session->task, session->item, M);
  1978. }
  1979. rspamd_session_remove_event (session->task->s, fuzzy_io_fin, session);
  1980. }
  1981. else {
  1982. /* Plan write event */
  1983. rspamd_ev_watcher_reschedule (session->event_loop,
  1984. &session->ev, EV_READ|EV_WRITE);
  1985. session->retransmits ++;
  1986. }
  1987. }
  1988. /* Fuzzy check callback */
  1989. static void
  1990. fuzzy_check_io_callback (gint fd, short what, void *arg)
  1991. {
  1992. struct fuzzy_client_session *session = arg;
  1993. struct rspamd_task *task;
  1994. gint r;
  1995. enum {
  1996. return_error = 0,
  1997. return_want_more,
  1998. return_finished
  1999. } ret = return_error;
  2000. task = session->task;
  2001. if ((what & EV_READ) || session->state == 1) {
  2002. /* Try to read reply */
  2003. r = fuzzy_check_try_read (session);
  2004. switch (r) {
  2005. case 0:
  2006. if (what & EV_READ) {
  2007. ret = return_want_more;
  2008. }
  2009. else {
  2010. /* It is actually time out */
  2011. fuzzy_check_timer_callback (fd, what, arg);
  2012. return;
  2013. }
  2014. break;
  2015. case 1:
  2016. ret = return_finished;
  2017. break;
  2018. default:
  2019. ret = return_error;
  2020. break;
  2021. }
  2022. }
  2023. else if (what & EV_WRITE) {
  2024. if (!fuzzy_cmd_vector_to_wire (fd, session->commands)) {
  2025. ret = return_error;
  2026. }
  2027. else {
  2028. session->state = 1;
  2029. ret = return_want_more;
  2030. }
  2031. }
  2032. else {
  2033. fuzzy_check_timer_callback (fd, what, arg);
  2034. return;
  2035. }
  2036. if (ret == return_want_more) {
  2037. /* Processed write, switch to reading */
  2038. rspamd_ev_watcher_reschedule (session->event_loop,
  2039. &session->ev, EV_READ);
  2040. }
  2041. else if (ret == return_error) {
  2042. /* Error state */
  2043. msg_err_task ("got error on IO with server %s(%s), on %s, %d, %s",
  2044. rspamd_upstream_name (session->server),
  2045. rspamd_inet_address_to_string_pretty (
  2046. rspamd_upstream_addr_cur (session->server)),
  2047. session->state == 1 ? "read" : "write",
  2048. errno,
  2049. strerror (errno));
  2050. rspamd_upstream_fail (session->server, TRUE);
  2051. if (session->item) {
  2052. rspamd_symcache_item_async_dec_check (session->task, session->item, M);
  2053. }
  2054. rspamd_session_remove_event (session->task->s, fuzzy_io_fin, session);
  2055. }
  2056. else {
  2057. /* Read something from network */
  2058. if (!fuzzy_check_session_is_completed (session)) {
  2059. /* Need to read more */
  2060. rspamd_ev_watcher_reschedule (session->event_loop,
  2061. &session->ev, EV_READ);
  2062. }
  2063. }
  2064. }
  2065. static void
  2066. fuzzy_lua_fin (void *ud)
  2067. {
  2068. struct fuzzy_learn_session *session = ud;
  2069. (*session->saved)--;
  2070. rspamd_ev_watcher_stop (session->event_loop, &session->ev);
  2071. close (session->fd);
  2072. }
  2073. /* Controller IO */
  2074. static void
  2075. fuzzy_controller_timer_callback (gint fd, short what, void *arg)
  2076. {
  2077. struct fuzzy_learn_session *session = arg;
  2078. struct rspamd_task *task;
  2079. task = session->task;
  2080. if (session->retransmits >= session->rule->ctx->retransmits) {
  2081. rspamd_upstream_fail (session->server, TRUE);
  2082. msg_err_task_check ("got IO timeout with server %s(%s), "
  2083. "after %d retransmits",
  2084. rspamd_upstream_name (session->server),
  2085. rspamd_inet_address_to_string_pretty (
  2086. rspamd_upstream_addr_cur (session->server)),
  2087. session->retransmits);
  2088. if (session->session) {
  2089. rspamd_session_remove_event (session->session, fuzzy_lua_fin,
  2090. session);
  2091. }
  2092. else {
  2093. if (session->http_entry) {
  2094. rspamd_controller_send_error (session->http_entry,
  2095. 500, "IO timeout with fuzzy storage");
  2096. }
  2097. if (*session->saved > 0 ) {
  2098. (*session->saved)--;
  2099. if (*session->saved == 0) {
  2100. if (session->http_entry) {
  2101. rspamd_task_free (session->task);
  2102. }
  2103. session->task = NULL;
  2104. }
  2105. }
  2106. if (session->http_entry) {
  2107. rspamd_http_connection_unref (session->http_entry->conn);
  2108. }
  2109. rspamd_ev_watcher_stop (session->event_loop,
  2110. &session->ev);
  2111. close (session->fd);
  2112. }
  2113. }
  2114. else {
  2115. /* Plan write event */
  2116. rspamd_ev_watcher_reschedule (session->event_loop,
  2117. &session->ev, EV_READ|EV_WRITE);
  2118. session->retransmits ++;
  2119. }
  2120. }
  2121. static void
  2122. fuzzy_controller_io_callback (gint fd, short what, void *arg)
  2123. {
  2124. struct fuzzy_learn_session *session = arg;
  2125. const struct rspamd_fuzzy_reply *rep;
  2126. struct fuzzy_mapping *map;
  2127. struct rspamd_task *task;
  2128. guchar buf[2048], *p;
  2129. struct fuzzy_cmd_io *io;
  2130. struct rspamd_fuzzy_cmd *cmd = NULL;
  2131. const gchar *symbol, *ftype;
  2132. gint r;
  2133. enum {
  2134. return_error = 0,
  2135. return_want_more,
  2136. return_finished
  2137. } ret = return_want_more;
  2138. guint i, nreplied;
  2139. const gchar *op = "process";
  2140. task = session->task;
  2141. if (what & EV_READ) {
  2142. if ((r = read (fd, buf, sizeof (buf) - 1)) == -1) {
  2143. if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) {
  2144. rspamd_ev_watcher_reschedule (session->event_loop,
  2145. &session->ev, EV_READ);
  2146. return;
  2147. }
  2148. msg_info_task ("cannot process fuzzy hash for message: %s",
  2149. strerror (errno));
  2150. if (*(session->err) == NULL) {
  2151. g_set_error (session->err,
  2152. g_quark_from_static_string (M),
  2153. errno, "read socket error: %s", strerror (errno));
  2154. }
  2155. ret = return_error;
  2156. }
  2157. else {
  2158. p = buf;
  2159. ret = return_want_more;
  2160. while ((rep = fuzzy_process_reply (&p, &r,
  2161. session->commands, session->rule, &cmd, &io)) != NULL) {
  2162. if ((map =
  2163. g_hash_table_lookup (session->rule->mappings,
  2164. GINT_TO_POINTER (rep->v1.flag))) == NULL) {
  2165. /* Default symbol and default weight */
  2166. symbol = session->rule->symbol;
  2167. }
  2168. else {
  2169. /* Get symbol and weight from map */
  2170. symbol = map->symbol;
  2171. }
  2172. ftype = "bin";
  2173. if (io && (io->flags & FUZZY_CMD_FLAG_IMAGE)) {
  2174. ftype = "img";
  2175. }
  2176. else if (cmd->shingles_count > 0) {
  2177. ftype = "txt";
  2178. }
  2179. if (io->cmd.cmd == FUZZY_WRITE) {
  2180. op = "added";
  2181. }
  2182. else if (io->cmd.cmd == FUZZY_DEL) {
  2183. op = "deleted";
  2184. }
  2185. if (rep->v1.prob > 0.5) {
  2186. msg_info_task ("%s fuzzy hash (%s) %*xs, list: %s:%d for "
  2187. "message <%s>",
  2188. op,
  2189. ftype,
  2190. (gint)sizeof (rep->digest), rep->digest,
  2191. symbol,
  2192. rep->v1.flag,
  2193. MESSAGE_FIELD_CHECK (session->task, message_id));
  2194. }
  2195. else {
  2196. if (rep->v1.value == 401) {
  2197. msg_info_task (
  2198. "fuzzy hash (%s) for message cannot be %s"
  2199. "<%s>, %*xs, "
  2200. "list %s:%d, skipped by server",
  2201. ftype,
  2202. op,
  2203. MESSAGE_FIELD (session->task, message_id),
  2204. (gint)sizeof (rep->digest), rep->digest,
  2205. symbol,
  2206. rep->v1.flag);
  2207. if (*(session->err) == NULL) {
  2208. g_set_error (session->err,
  2209. g_quark_from_static_string (M),
  2210. rep->v1.value, "fuzzy hash is skipped");
  2211. }
  2212. }
  2213. else {
  2214. msg_info_task (
  2215. "fuzzy hash (%s) for message cannot be %s"
  2216. "<%s>, %*xs, "
  2217. "list %s:%d, error: %d",
  2218. ftype,
  2219. op,
  2220. MESSAGE_FIELD (session->task, message_id),
  2221. (gint)sizeof (rep->digest), rep->digest,
  2222. symbol,
  2223. rep->v1.flag,
  2224. rep->v1.value);
  2225. if (*(session->err) == NULL) {
  2226. g_set_error (session->err,
  2227. g_quark_from_static_string (M),
  2228. rep->v1.value, "process fuzzy error");
  2229. }
  2230. }
  2231. ret = return_finished;
  2232. }
  2233. }
  2234. nreplied = 0;
  2235. for (i = 0; i < session->commands->len; i++) {
  2236. io = g_ptr_array_index (session->commands, i);
  2237. if (io->flags & FUZZY_CMD_FLAG_REPLIED) {
  2238. nreplied++;
  2239. }
  2240. }
  2241. if (nreplied == session->commands->len) {
  2242. ret = return_finished;
  2243. }
  2244. }
  2245. }
  2246. else if (what & EV_WRITE) {
  2247. /* Send commands to storage */
  2248. if (!fuzzy_cmd_vector_to_wire (fd, session->commands)) {
  2249. if (*(session->err) == NULL) {
  2250. g_set_error (session->err,
  2251. g_quark_from_static_string (M),
  2252. errno, "write socket error: %s", strerror (errno));
  2253. }
  2254. ret = return_error;
  2255. }
  2256. }
  2257. else {
  2258. fuzzy_controller_timer_callback (fd, what, arg);
  2259. return;
  2260. }
  2261. if (ret == return_want_more) {
  2262. rspamd_ev_watcher_reschedule (session->event_loop,
  2263. &session->ev, EV_READ);
  2264. return;
  2265. }
  2266. else if (ret == return_error) {
  2267. msg_err_task ("got error in IO with server %s(%s), %d, %s",
  2268. rspamd_upstream_name (session->server),
  2269. rspamd_inet_address_to_string_pretty (
  2270. rspamd_upstream_addr_cur (session->server)),
  2271. errno, strerror (errno));
  2272. rspamd_upstream_fail (session->server, FALSE);
  2273. }
  2274. /*
  2275. * XXX: actually, we check merely a single reply, which is not correct...
  2276. * XXX: when we send a command, we do not check if *all* commands have been
  2277. * written
  2278. * XXX: please, please, change this code some day
  2279. */
  2280. if (session->session == NULL) {
  2281. (*session->saved)--;
  2282. if (session->http_entry) {
  2283. rspamd_http_connection_unref (session->http_entry->conn);
  2284. }
  2285. rspamd_ev_watcher_stop (session->event_loop, &session->ev);
  2286. close (session->fd);
  2287. if (*session->saved == 0) {
  2288. goto cleanup;
  2289. }
  2290. }
  2291. else {
  2292. /* Lua handler */
  2293. rspamd_session_remove_event (session->session, fuzzy_lua_fin, session);
  2294. }
  2295. return;
  2296. cleanup:
  2297. /*
  2298. * When we send learn commands to fuzzy storages, this code is executed
  2299. * *once* when we have queried all storages. We also don't know which
  2300. * storage has been failed.
  2301. *
  2302. * Therefore, we cleanup sessions earlier and actually this code is wrong.
  2303. */
  2304. if (*(session->err) != NULL) {
  2305. if (session->http_entry) {
  2306. rspamd_controller_send_error (session->http_entry,
  2307. (*session->err)->code, (*session->err)->message);
  2308. }
  2309. g_error_free (*session->err);
  2310. }
  2311. else {
  2312. rspamd_upstream_ok (session->server);
  2313. if (session->http_entry) {
  2314. ucl_object_t *reply, *hashes;
  2315. gchar hexbuf[rspamd_cryptobox_HASHBYTES * 2 + 1];
  2316. reply = ucl_object_typed_new (UCL_OBJECT);
  2317. ucl_object_insert_key (reply, ucl_object_frombool (true),
  2318. "success", 0, false);
  2319. hashes = ucl_object_typed_new (UCL_ARRAY);
  2320. for (i = 0; i < session->commands->len; i ++) {
  2321. io = g_ptr_array_index (session->commands, i);
  2322. rspamd_snprintf (hexbuf, sizeof (hexbuf), "%*xs",
  2323. (gint)sizeof (io->cmd.digest), io->cmd.digest);
  2324. ucl_array_append (hashes, ucl_object_fromstring (hexbuf));
  2325. }
  2326. ucl_object_insert_key (reply, hashes, "hashes", 0, false);
  2327. rspamd_controller_send_ucl (session->http_entry, reply);
  2328. ucl_object_unref (reply);
  2329. }
  2330. }
  2331. if (session->task != NULL) {
  2332. if (session->http_entry) {
  2333. rspamd_task_free (session->task);
  2334. }
  2335. session->task = NULL;
  2336. }
  2337. }
  2338. static GPtrArray *
  2339. fuzzy_generate_commands (struct rspamd_task *task, struct fuzzy_rule *rule,
  2340. gint c, gint flag, guint32 value, guint flags)
  2341. {
  2342. struct rspamd_mime_text_part *part;
  2343. struct rspamd_mime_part *mime_part;
  2344. struct rspamd_image *image;
  2345. struct fuzzy_cmd_io *io, *cur;
  2346. guint i, j;
  2347. GPtrArray *res = NULL;
  2348. gboolean check_part, fuzzy_check;
  2349. if (c == FUZZY_STAT) {
  2350. res = g_ptr_array_sized_new (1);
  2351. io = fuzzy_cmd_stat (rule, c, flag, value, task->task_pool);
  2352. if (io) {
  2353. g_ptr_array_add (res, io);
  2354. }
  2355. goto end;
  2356. }
  2357. if (task->message == NULL) {
  2358. goto end;
  2359. }
  2360. res = g_ptr_array_sized_new (MESSAGE_FIELD (task, parts)->len + 1);
  2361. PTR_ARRAY_FOREACH (MESSAGE_FIELD (task, parts), i, mime_part) {
  2362. check_part = FALSE;
  2363. fuzzy_check = FALSE;
  2364. if (fuzzy_rule_check_mimepart (task, rule, mime_part, &check_part,
  2365. &fuzzy_check)) {
  2366. io = NULL;
  2367. if (check_part) {
  2368. if (mime_part->flags & RSPAMD_MIME_PART_TEXT &&
  2369. !(flags & FUZZY_CHECK_FLAG_NOTEXT)) {
  2370. part = mime_part->specific.txt;
  2371. io = fuzzy_cmd_from_text_part (task, rule,
  2372. c,
  2373. flag,
  2374. value,
  2375. !fuzzy_check,
  2376. task->task_pool,
  2377. part,
  2378. mime_part);
  2379. }
  2380. else if (mime_part->flags & RSPAMD_MIME_PART_IMAGE &&
  2381. !(flags & FUZZY_CHECK_FLAG_NOIMAGES)) {
  2382. image = mime_part->specific.img;
  2383. io = fuzzy_cmd_from_data_part (rule, c, flag, value,
  2384. task->task_pool,
  2385. image->parent->digest,
  2386. mime_part);
  2387. io->flags |= FUZZY_CMD_FLAG_IMAGE;
  2388. }
  2389. else {
  2390. io = fuzzy_cmd_from_data_part (rule, c, flag, value,
  2391. task->task_pool,
  2392. mime_part->digest, mime_part);
  2393. }
  2394. if (io) {
  2395. gboolean skip_existing = FALSE;
  2396. PTR_ARRAY_FOREACH (res, j, cur) {
  2397. if (memcmp (cur->cmd.digest, io->cmd.digest,
  2398. sizeof (io->cmd.digest)) == 0) {
  2399. skip_existing = TRUE;
  2400. break;
  2401. }
  2402. }
  2403. if (!skip_existing) {
  2404. g_ptr_array_add (res, io);
  2405. }
  2406. }
  2407. }
  2408. }
  2409. }
  2410. end:
  2411. if (res && res->len == 0) {
  2412. g_ptr_array_free (res, TRUE);
  2413. return NULL;
  2414. }
  2415. return res;
  2416. }
  2417. static inline void
  2418. register_fuzzy_client_call (struct rspamd_task *task,
  2419. struct fuzzy_rule *rule,
  2420. GPtrArray *commands)
  2421. {
  2422. struct fuzzy_client_session *session;
  2423. struct upstream *selected;
  2424. rspamd_inet_addr_t *addr;
  2425. gint sock;
  2426. if (!rspamd_session_blocked (task->s)) {
  2427. /* Get upstream */
  2428. selected = rspamd_upstream_get (rule->servers, RSPAMD_UPSTREAM_ROUND_ROBIN,
  2429. NULL, 0);
  2430. if (selected) {
  2431. addr = rspamd_upstream_addr_next (selected);
  2432. if ((sock = rspamd_inet_address_connect (addr, SOCK_DGRAM, TRUE)) == -1) {
  2433. msg_warn_task ("cannot connect to %s(%s), %d, %s",
  2434. rspamd_upstream_name (selected),
  2435. rspamd_inet_address_to_string_pretty (addr),
  2436. errno,
  2437. strerror (errno));
  2438. rspamd_upstream_fail (selected, TRUE);
  2439. g_ptr_array_free (commands, TRUE);
  2440. } else {
  2441. /* Create session for a socket */
  2442. session =
  2443. rspamd_mempool_alloc0 (task->task_pool,
  2444. sizeof (struct fuzzy_client_session));
  2445. session->state = 0;
  2446. session->commands = commands;
  2447. session->task = task;
  2448. session->fd = sock;
  2449. session->server = selected;
  2450. session->rule = rule;
  2451. session->results = g_ptr_array_sized_new (32);
  2452. session->event_loop = task->event_loop;
  2453. rspamd_ev_watcher_init (&session->ev,
  2454. sock,
  2455. EV_WRITE,
  2456. fuzzy_check_io_callback,
  2457. session);
  2458. rspamd_ev_watcher_start (session->event_loop, &session->ev,
  2459. ((double)rule->ctx->io_timeout) / 1000.0);
  2460. rspamd_session_add_event (task->s, fuzzy_io_fin, session, M);
  2461. session->item = rspamd_symcache_get_cur_item (task);
  2462. if (session->item) {
  2463. rspamd_symcache_item_async_inc (task, session->item, M);
  2464. }
  2465. }
  2466. }
  2467. }
  2468. }
  2469. /* This callback is called when we check message in fuzzy hashes storage */
  2470. static void
  2471. fuzzy_symbol_callback (struct rspamd_task *task,
  2472. struct rspamd_symcache_item *item,
  2473. void *unused)
  2474. {
  2475. struct fuzzy_rule *rule;
  2476. guint i;
  2477. GPtrArray *commands;
  2478. struct fuzzy_ctx *fuzzy_module_ctx = fuzzy_get_context (task->cfg);
  2479. if (!fuzzy_module_ctx->enabled) {
  2480. rspamd_symcache_finalize_item (task, item);
  2481. return;
  2482. }
  2483. /* Check whitelist */
  2484. if (fuzzy_module_ctx->whitelist) {
  2485. if (rspamd_match_radix_map_addr (fuzzy_module_ctx->whitelist,
  2486. task->from_addr) != NULL) {
  2487. msg_info_task ("<%s>, address %s is whitelisted, skip fuzzy check",
  2488. MESSAGE_FIELD (task, message_id),
  2489. rspamd_inet_address_to_string (task->from_addr));
  2490. rspamd_symcache_finalize_item (task, item);
  2491. return;
  2492. }
  2493. }
  2494. rspamd_symcache_item_async_inc (task, item, M);
  2495. PTR_ARRAY_FOREACH (fuzzy_module_ctx->fuzzy_rules, i, rule) {
  2496. commands = fuzzy_generate_commands (task, rule, FUZZY_CHECK, 0, 0, 0);
  2497. if (commands != NULL) {
  2498. register_fuzzy_client_call (task, rule, commands);
  2499. }
  2500. }
  2501. rspamd_symcache_item_async_dec_check (task, item, M);
  2502. }
  2503. void
  2504. fuzzy_stat_command (struct rspamd_task *task)
  2505. {
  2506. struct fuzzy_rule *rule;
  2507. guint i;
  2508. GPtrArray *commands;
  2509. struct fuzzy_ctx *fuzzy_module_ctx = fuzzy_get_context (task->cfg);
  2510. if (!fuzzy_module_ctx->enabled) {
  2511. return;
  2512. }
  2513. PTR_ARRAY_FOREACH (fuzzy_module_ctx->fuzzy_rules, i, rule) {
  2514. commands = fuzzy_generate_commands (task, rule, FUZZY_STAT, 0, 0, 0);
  2515. if (commands != NULL) {
  2516. register_fuzzy_client_call (task, rule, commands);
  2517. }
  2518. }
  2519. }
  2520. static inline gint
  2521. register_fuzzy_controller_call (struct rspamd_http_connection_entry *entry,
  2522. struct fuzzy_rule *rule,
  2523. struct rspamd_task *task,
  2524. GPtrArray *commands,
  2525. gint *saved,
  2526. GError **err)
  2527. {
  2528. struct fuzzy_learn_session *s;
  2529. struct upstream *selected;
  2530. rspamd_inet_addr_t *addr;
  2531. struct rspamd_controller_session *session = entry->ud;
  2532. gint sock;
  2533. gint ret = -1;
  2534. /* Get upstream */
  2535. while ((selected = rspamd_upstream_get_forced (rule->servers,
  2536. RSPAMD_UPSTREAM_SEQUENTIAL, NULL, 0))) {
  2537. /* Create UDP socket */
  2538. addr = rspamd_upstream_addr_next (selected);
  2539. if ((sock = rspamd_inet_address_connect (addr,
  2540. SOCK_DGRAM, TRUE)) == -1) {
  2541. rspamd_upstream_fail (selected, TRUE);
  2542. }
  2543. else {
  2544. s =
  2545. rspamd_mempool_alloc0 (session->pool,
  2546. sizeof (struct fuzzy_learn_session));
  2547. s->task = task;
  2548. s->commands = commands;
  2549. s->http_entry = entry;
  2550. s->server = selected;
  2551. s->saved = saved;
  2552. s->fd = sock;
  2553. s->err = err;
  2554. s->rule = rule;
  2555. s->event_loop = task->event_loop;
  2556. /* We ref connection to avoid freeing before we process fuzzy rule */
  2557. rspamd_http_connection_ref (entry->conn);
  2558. rspamd_ev_watcher_init (&s->ev,
  2559. sock,
  2560. EV_WRITE,
  2561. fuzzy_controller_io_callback,
  2562. s);
  2563. rspamd_ev_watcher_start (s->event_loop, &s->ev,
  2564. ((double)rule->ctx->io_timeout) / 1000.0);
  2565. (*saved)++;
  2566. ret = 1;
  2567. }
  2568. }
  2569. return ret;
  2570. }
  2571. static void
  2572. fuzzy_process_handler (struct rspamd_http_connection_entry *conn_ent,
  2573. struct rspamd_http_message *msg, gint cmd, gint value, gint flag,
  2574. struct fuzzy_ctx *ctx, gboolean is_hash, guint flags)
  2575. {
  2576. struct fuzzy_rule *rule;
  2577. struct rspamd_controller_session *session = conn_ent->ud;
  2578. struct rspamd_task *task, **ptask;
  2579. gboolean processed = FALSE, res = TRUE, skip = FALSE;
  2580. guint i;
  2581. GError **err;
  2582. GPtrArray *commands;
  2583. lua_State *L;
  2584. gint r, *saved, rules = 0, err_idx;
  2585. struct fuzzy_ctx *fuzzy_module_ctx;
  2586. /* Prepare task */
  2587. task = rspamd_task_new (session->wrk, session->cfg, NULL,
  2588. session->lang_det, conn_ent->rt->event_loop);
  2589. task->cfg = ctx->cfg;
  2590. saved = rspamd_mempool_alloc0 (session->pool, sizeof (gint));
  2591. err = rspamd_mempool_alloc0 (session->pool, sizeof (GError *));
  2592. fuzzy_module_ctx = fuzzy_get_context (ctx->cfg);
  2593. if (!is_hash) {
  2594. /* Allocate message from string */
  2595. /* XXX: what about encrypted messages ? */
  2596. task->msg.begin = msg->body_buf.begin;
  2597. task->msg.len = msg->body_buf.len;
  2598. r = rspamd_message_parse (task);
  2599. if (r == -1) {
  2600. msg_warn_task ("<%s>: cannot process message for fuzzy",
  2601. MESSAGE_FIELD (task, message_id));
  2602. rspamd_task_free (task);
  2603. rspamd_controller_send_error (conn_ent, 400,
  2604. "Message processing error");
  2605. return;
  2606. }
  2607. rspamd_message_process (task);
  2608. }
  2609. PTR_ARRAY_FOREACH (fuzzy_module_ctx->fuzzy_rules, i, rule) {
  2610. if (rule->read_only) {
  2611. continue;
  2612. }
  2613. /* Check for flag */
  2614. if (g_hash_table_lookup (rule->mappings,
  2615. GINT_TO_POINTER (flag)) == NULL) {
  2616. msg_info_task ("skip rule %s as it has no flag %d defined"
  2617. " false", rule->name, flag);
  2618. continue;
  2619. }
  2620. /* Check learn condition */
  2621. if (rule->learn_condition_cb != -1) {
  2622. skip = FALSE;
  2623. L = session->cfg->lua_state;
  2624. lua_pushcfunction (L, &rspamd_lua_traceback);
  2625. err_idx = lua_gettop (L);
  2626. lua_rawgeti (L, LUA_REGISTRYINDEX, rule->learn_condition_cb);
  2627. ptask = lua_newuserdata (L, sizeof (struct rspamd_task *));
  2628. *ptask = task;
  2629. rspamd_lua_setclass (L, "rspamd{task}", -1);
  2630. if (lua_pcall (L, 1, LUA_MULTRET, err_idx) != 0) {
  2631. msg_err_task ("call to fuzzy learn condition failed: %s",
  2632. lua_tostring (L, -1));
  2633. }
  2634. else {
  2635. if (lua_gettop (L) > err_idx + 1) {
  2636. /* 2 return values */
  2637. skip = !(lua_toboolean (L, err_idx + 1));
  2638. if (lua_isnumber (L, err_idx + 2)) {
  2639. msg_info_task ("learn condition changed flag from %d to "
  2640. "%d", flag,
  2641. (gint)lua_tonumber (L, err_idx + 2));
  2642. flag = lua_tonumber (L, err_idx + 2);
  2643. }
  2644. }
  2645. else {
  2646. if (lua_isboolean (L, err_idx + 1)) {
  2647. skip = !(lua_toboolean (L, err_idx + 1));
  2648. }
  2649. else {
  2650. msg_warn_task ("set skip for rule %s as its condition "
  2651. "callback returned"
  2652. " a valid boolean", rule->name);
  2653. skip = TRUE;
  2654. }
  2655. }
  2656. }
  2657. /* Result + error function */
  2658. lua_settop (L, 0);
  2659. if (skip) {
  2660. msg_info_task ("skip rule %s by condition callback",
  2661. rule->name);
  2662. continue;
  2663. }
  2664. }
  2665. rules ++;
  2666. res = 0;
  2667. if (is_hash) {
  2668. GPtrArray *args;
  2669. const rspamd_ftok_t *arg;
  2670. guint j;
  2671. args = rspamd_http_message_find_header_multiple (msg, "Hash");
  2672. if (args) {
  2673. struct fuzzy_cmd_io *io;
  2674. commands = g_ptr_array_sized_new (args->len);
  2675. for (j = 0; j < args->len; j ++) {
  2676. arg = g_ptr_array_index (args, j);
  2677. io = fuzzy_cmd_hash (rule, cmd, arg, flag, value,
  2678. task->task_pool);
  2679. if (io) {
  2680. g_ptr_array_add (commands, io);
  2681. }
  2682. }
  2683. res = register_fuzzy_controller_call (conn_ent,
  2684. rule,
  2685. task,
  2686. commands,
  2687. saved,
  2688. err);
  2689. rspamd_mempool_add_destructor (task->task_pool,
  2690. rspamd_ptr_array_free_hard, commands);
  2691. g_ptr_array_free (args, TRUE);
  2692. }
  2693. else {
  2694. rspamd_controller_send_error (conn_ent, 400,
  2695. "No hash defined");
  2696. rspamd_task_free (task);
  2697. return;
  2698. }
  2699. }
  2700. else {
  2701. commands = fuzzy_generate_commands (task, rule, cmd, flag, value,
  2702. flags);
  2703. if (commands != NULL) {
  2704. res = register_fuzzy_controller_call (conn_ent,
  2705. rule,
  2706. task,
  2707. commands,
  2708. saved,
  2709. err);
  2710. rspamd_mempool_add_destructor (task->task_pool,
  2711. rspamd_ptr_array_free_hard, commands);
  2712. }
  2713. }
  2714. if (res) {
  2715. processed = TRUE;
  2716. }
  2717. }
  2718. if (res == -1) {
  2719. msg_warn_task ("cannot send fuzzy request: %s",
  2720. strerror (errno));
  2721. rspamd_controller_send_error (conn_ent, 400, "Message sending error");
  2722. rspamd_task_free (task);
  2723. return;
  2724. }
  2725. else if (!processed) {
  2726. if (rules) {
  2727. msg_warn_task ("no content to generate fuzzy");
  2728. rspamd_controller_send_error (conn_ent, 404,
  2729. "No content to generate fuzzy for flag %d", flag);
  2730. }
  2731. else {
  2732. if (skip) {
  2733. rspamd_controller_send_error (conn_ent, 403,
  2734. "Message is conditionally skipped for flag %d", flag);
  2735. }
  2736. else {
  2737. msg_warn_task ("no fuzzy rules found for flag %d", flag);
  2738. rspamd_controller_send_error (conn_ent, 404,
  2739. "No fuzzy rules matched for flag %d", flag);
  2740. }
  2741. }
  2742. rspamd_task_free (task);
  2743. }
  2744. }
  2745. static int
  2746. fuzzy_controller_handler (struct rspamd_http_connection_entry *conn_ent,
  2747. struct rspamd_http_message *msg, struct module_ctx *ctx, gint cmd,
  2748. gboolean is_hash)
  2749. {
  2750. const rspamd_ftok_t *arg;
  2751. glong value = 1, flag = 0, send_flags = 0;
  2752. struct fuzzy_ctx *fuzzy_module_ctx = (struct fuzzy_ctx *)ctx;
  2753. if (!fuzzy_module_ctx->enabled) {
  2754. msg_err ("fuzzy_check module is not enabled");
  2755. rspamd_controller_send_error (conn_ent, 500, "Module disabled");
  2756. return 0;
  2757. }
  2758. if (fuzzy_module_ctx->fuzzy_rules == NULL) {
  2759. msg_err ("fuzzy_check module has no rules defined");
  2760. rspamd_controller_send_error (conn_ent, 500, "Module has no rules");
  2761. return 0;
  2762. }
  2763. /* Get size */
  2764. arg = rspamd_http_message_find_header (msg, "Weight");
  2765. if (arg) {
  2766. errno = 0;
  2767. if (!rspamd_strtol (arg->begin, arg->len, &value)) {
  2768. msg_info ("error converting numeric argument %T", arg);
  2769. }
  2770. }
  2771. arg = rspamd_http_message_find_header (msg, "Flag");
  2772. if (arg) {
  2773. errno = 0;
  2774. if (!rspamd_strtol (arg->begin, arg->len, &flag)) {
  2775. msg_info ("error converting numeric argument %T", arg);
  2776. flag = 0;
  2777. }
  2778. }
  2779. else {
  2780. flag = 0;
  2781. arg = rspamd_http_message_find_header (msg, "Symbol");
  2782. /* Search flag by symbol */
  2783. if (arg) {
  2784. struct fuzzy_rule *rule;
  2785. guint i;
  2786. GHashTableIter it;
  2787. gpointer k, v;
  2788. struct fuzzy_mapping *map;
  2789. PTR_ARRAY_FOREACH (fuzzy_module_ctx->fuzzy_rules, i, rule) {
  2790. if (flag != 0) {
  2791. break;
  2792. }
  2793. g_hash_table_iter_init (&it, rule->mappings);
  2794. while (g_hash_table_iter_next (&it, &k, &v)) {
  2795. map = v;
  2796. if (strlen (map->symbol) == arg->len &&
  2797. rspamd_lc_cmp (map->symbol, arg->begin, arg->len) == 0) {
  2798. flag = map->fuzzy_flag;
  2799. break;
  2800. }
  2801. }
  2802. }
  2803. }
  2804. }
  2805. if (flag == 0) {
  2806. msg_err ("no flag defined to learn fuzzy");
  2807. rspamd_controller_send_error (conn_ent, 404, "Unknown or missing flag");
  2808. return 0;
  2809. }
  2810. arg = rspamd_http_message_find_header (msg, "Skip-Images");
  2811. if (arg) {
  2812. send_flags |= FUZZY_CHECK_FLAG_NOIMAGES;
  2813. }
  2814. arg = rspamd_http_message_find_header (msg, "Skip-Attachments");
  2815. if (arg) {
  2816. send_flags |= FUZZY_CHECK_FLAG_NOATTACHMENTS;
  2817. }
  2818. arg = rspamd_http_message_find_header (msg, "Skip-Text");
  2819. if (arg) {
  2820. send_flags |= FUZZY_CHECK_FLAG_NOTEXT;
  2821. }
  2822. fuzzy_process_handler (conn_ent, msg, cmd, value, flag,
  2823. (struct fuzzy_ctx *)ctx, is_hash, send_flags);
  2824. return 0;
  2825. }
  2826. static inline gint
  2827. fuzzy_check_send_lua_learn (struct fuzzy_rule *rule,
  2828. struct rspamd_task *task,
  2829. GPtrArray *commands,
  2830. gint *saved,
  2831. GError **err)
  2832. {
  2833. struct fuzzy_learn_session *s;
  2834. struct upstream *selected;
  2835. rspamd_inet_addr_t *addr;
  2836. gint sock;
  2837. gint ret = -1;
  2838. /* Get upstream */
  2839. if (!rspamd_session_blocked (task->s)) {
  2840. while ((selected = rspamd_upstream_get (rule->servers,
  2841. RSPAMD_UPSTREAM_SEQUENTIAL, NULL, 0))) {
  2842. /* Create UDP socket */
  2843. addr = rspamd_upstream_addr_next (selected);
  2844. if ((sock = rspamd_inet_address_connect (addr,
  2845. SOCK_DGRAM, TRUE)) == -1) {
  2846. rspamd_upstream_fail (selected, TRUE);
  2847. } else {
  2848. s =
  2849. rspamd_mempool_alloc0 (task->task_pool,
  2850. sizeof (struct fuzzy_learn_session));
  2851. s->task = task;
  2852. s->commands = commands;
  2853. s->http_entry = NULL;
  2854. s->server = selected;
  2855. s->saved = saved;
  2856. s->fd = sock;
  2857. s->err = err;
  2858. s->rule = rule;
  2859. s->session = task->s;
  2860. s->event_loop = task->event_loop;
  2861. rspamd_ev_watcher_init (&s->ev,
  2862. sock,
  2863. EV_WRITE,
  2864. fuzzy_controller_io_callback,
  2865. s);
  2866. rspamd_ev_watcher_start (s->event_loop, &s->ev,
  2867. ((double)rule->ctx->io_timeout) / 1000.0);
  2868. rspamd_session_add_event (task->s,
  2869. fuzzy_lua_fin,
  2870. s,
  2871. M);
  2872. (*saved)++;
  2873. ret = 1;
  2874. }
  2875. }
  2876. }
  2877. return ret;
  2878. }
  2879. static gboolean
  2880. fuzzy_check_lua_process_learn (struct rspamd_task *task,
  2881. gint cmd, gint value, gint flag, guint send_flags)
  2882. {
  2883. struct fuzzy_rule *rule;
  2884. gboolean processed = FALSE, res = TRUE;
  2885. guint i;
  2886. GError **err;
  2887. GPtrArray *commands;
  2888. gint *saved, rules = 0;
  2889. struct fuzzy_ctx *fuzzy_module_ctx = fuzzy_get_context (task->cfg);
  2890. saved = rspamd_mempool_alloc0 (task->task_pool, sizeof (gint));
  2891. err = rspamd_mempool_alloc0 (task->task_pool, sizeof (GError *));
  2892. PTR_ARRAY_FOREACH (fuzzy_module_ctx->fuzzy_rules, i, rule) {
  2893. if (!res) {
  2894. break;
  2895. }
  2896. if (rule->read_only) {
  2897. continue;
  2898. }
  2899. /* Check for flag */
  2900. if (g_hash_table_lookup (rule->mappings,
  2901. GINT_TO_POINTER (flag)) == NULL) {
  2902. msg_info_task ("skip rule %s as it has no flag %d defined"
  2903. " false", rule->name, flag);
  2904. continue;
  2905. }
  2906. rules ++;
  2907. res = 0;
  2908. commands = fuzzy_generate_commands (task, rule, cmd, flag,
  2909. value, send_flags);
  2910. if (commands != NULL) {
  2911. res = fuzzy_check_send_lua_learn (rule, task, commands,
  2912. saved, err);
  2913. rspamd_mempool_add_destructor (task->task_pool,
  2914. rspamd_ptr_array_free_hard, commands);
  2915. }
  2916. if (res) {
  2917. processed = TRUE;
  2918. }
  2919. }
  2920. if (res == -1) {
  2921. msg_warn_task ("cannot send fuzzy request: %s",
  2922. strerror (errno));
  2923. }
  2924. else if (!processed) {
  2925. if (rules) {
  2926. msg_warn_task ("no content to generate fuzzy");
  2927. return FALSE;
  2928. }
  2929. else {
  2930. msg_warn_task ("no fuzzy rules found for flag %d", flag);
  2931. return FALSE;
  2932. }
  2933. }
  2934. return TRUE;
  2935. }
  2936. static gint
  2937. fuzzy_lua_learn_handler (lua_State *L)
  2938. {
  2939. struct rspamd_task *task = lua_check_task (L, 1);
  2940. guint flag = 0, weight = 1, send_flags = 0;
  2941. const gchar *symbol;
  2942. struct fuzzy_ctx *fuzzy_module_ctx = fuzzy_get_context (task->cfg);
  2943. if (task) {
  2944. if (lua_type (L, 2) == LUA_TNUMBER) {
  2945. flag = lua_tonumber (L, 2);
  2946. }
  2947. else if (lua_type (L, 2) == LUA_TSTRING) {
  2948. struct fuzzy_rule *rule;
  2949. guint i;
  2950. GHashTableIter it;
  2951. gpointer k, v;
  2952. struct fuzzy_mapping *map;
  2953. symbol = lua_tostring (L, 2);
  2954. PTR_ARRAY_FOREACH (fuzzy_module_ctx->fuzzy_rules, i, rule) {
  2955. if (flag != 0) {
  2956. break;
  2957. }
  2958. g_hash_table_iter_init (&it, rule->mappings);
  2959. while (g_hash_table_iter_next (&it, &k, &v)) {
  2960. map = v;
  2961. if (g_ascii_strcasecmp (symbol, map->symbol) == 0) {
  2962. flag = map->fuzzy_flag;
  2963. break;
  2964. }
  2965. }
  2966. }
  2967. }
  2968. if (flag == 0) {
  2969. return luaL_error (L, "bad flag");
  2970. }
  2971. if (lua_type (L, 3) == LUA_TNUMBER) {
  2972. weight = lua_tonumber (L, 3);
  2973. }
  2974. if (lua_type (L, 4) == LUA_TTABLE) {
  2975. const gchar *sf;
  2976. for (lua_pushnil (L); lua_next (L, -2); lua_pop (L, 1)) {
  2977. sf = lua_tostring (L, -1);
  2978. if (sf) {
  2979. if (g_ascii_strcasecmp (sf, "noimages") == 0) {
  2980. send_flags |= FUZZY_CHECK_FLAG_NOIMAGES;
  2981. }
  2982. else if (g_ascii_strcasecmp (sf, "noattachments") == 0) {
  2983. send_flags |= FUZZY_CHECK_FLAG_NOATTACHMENTS;
  2984. }
  2985. else if (g_ascii_strcasecmp (sf, "notext") == 0) {
  2986. send_flags |= FUZZY_CHECK_FLAG_NOTEXT;
  2987. }
  2988. }
  2989. }
  2990. }
  2991. lua_pushboolean (L,
  2992. fuzzy_check_lua_process_learn (task, FUZZY_WRITE, weight, flag,
  2993. send_flags));
  2994. }
  2995. else {
  2996. return luaL_error (L, "invalid arguments");
  2997. }
  2998. return 1;
  2999. }
  3000. static gint
  3001. fuzzy_lua_unlearn_handler (lua_State *L)
  3002. {
  3003. struct rspamd_task *task = lua_check_task (L, 1);
  3004. guint flag = 0, weight = 1.0, send_flags = 0;
  3005. const gchar *symbol;
  3006. struct fuzzy_ctx *fuzzy_module_ctx = fuzzy_get_context (task->cfg);
  3007. if (task) {
  3008. if (lua_type (L, 2) == LUA_TNUMBER) {
  3009. flag = lua_tonumber (L, 1);
  3010. }
  3011. else if (lua_type (L, 2) == LUA_TSTRING) {
  3012. struct fuzzy_rule *rule;
  3013. guint i;
  3014. GHashTableIter it;
  3015. gpointer k, v;
  3016. struct fuzzy_mapping *map;
  3017. symbol = lua_tostring (L, 2);
  3018. PTR_ARRAY_FOREACH (fuzzy_module_ctx->fuzzy_rules, i, rule) {
  3019. if (flag != 0) {
  3020. break;
  3021. }
  3022. g_hash_table_iter_init (&it, rule->mappings);
  3023. while (g_hash_table_iter_next (&it, &k, &v)) {
  3024. map = v;
  3025. if (g_ascii_strcasecmp (symbol, map->symbol) == 0) {
  3026. flag = map->fuzzy_flag;
  3027. break;
  3028. }
  3029. }
  3030. }
  3031. }
  3032. if (flag == 0) {
  3033. return luaL_error (L, "bad flag");
  3034. }
  3035. if (lua_type (L, 3) == LUA_TNUMBER) {
  3036. weight = lua_tonumber (L, 3);
  3037. }
  3038. if (lua_type (L, 4) == LUA_TTABLE) {
  3039. const gchar *sf;
  3040. for (lua_pushnil (L); lua_next (L, -2); lua_pop (L, 1)) {
  3041. sf = lua_tostring (L, -1);
  3042. if (sf) {
  3043. if (g_ascii_strcasecmp (sf, "noimages") == 0) {
  3044. send_flags |= FUZZY_CHECK_FLAG_NOIMAGES;
  3045. }
  3046. else if (g_ascii_strcasecmp (sf, "noattachments") == 0) {
  3047. send_flags |= FUZZY_CHECK_FLAG_NOATTACHMENTS;
  3048. }
  3049. else if (g_ascii_strcasecmp (sf, "notext") == 0) {
  3050. send_flags |= FUZZY_CHECK_FLAG_NOTEXT;
  3051. }
  3052. }
  3053. }
  3054. }
  3055. lua_pushboolean (L,
  3056. fuzzy_check_lua_process_learn (task, FUZZY_DEL, weight, flag,
  3057. send_flags));
  3058. }
  3059. else {
  3060. return luaL_error (L, "invalid arguments");
  3061. }
  3062. return 1;
  3063. }
  3064. static gboolean
  3065. fuzzy_add_handler (struct rspamd_http_connection_entry *conn_ent,
  3066. struct rspamd_http_message *msg, struct module_ctx *ctx)
  3067. {
  3068. return fuzzy_controller_handler (conn_ent, msg,
  3069. ctx, FUZZY_WRITE, FALSE);
  3070. }
  3071. static gboolean
  3072. fuzzy_delete_handler (struct rspamd_http_connection_entry *conn_ent,
  3073. struct rspamd_http_message *msg, struct module_ctx *ctx)
  3074. {
  3075. return fuzzy_controller_handler (conn_ent, msg,
  3076. ctx, FUZZY_DEL, FALSE);
  3077. }
  3078. static gboolean
  3079. fuzzy_deletehash_handler (struct rspamd_http_connection_entry *conn_ent,
  3080. struct rspamd_http_message *msg, struct module_ctx *ctx)
  3081. {
  3082. return fuzzy_controller_handler (conn_ent, msg,
  3083. ctx, FUZZY_DEL, TRUE);
  3084. }
  3085. static int
  3086. fuzzy_attach_controller (struct module_ctx *ctx, GHashTable *commands)
  3087. {
  3088. struct fuzzy_ctx *fctx = (struct fuzzy_ctx *)ctx;
  3089. struct rspamd_custom_controller_command *cmd;
  3090. cmd = rspamd_mempool_alloc (fctx->fuzzy_pool, sizeof (*cmd));
  3091. cmd->privilleged = TRUE;
  3092. cmd->require_message = TRUE;
  3093. cmd->handler = fuzzy_add_handler;
  3094. cmd->ctx = ctx;
  3095. g_hash_table_insert (commands, "/fuzzyadd", cmd);
  3096. cmd = rspamd_mempool_alloc (fctx->fuzzy_pool, sizeof (*cmd));
  3097. cmd->privilleged = TRUE;
  3098. cmd->require_message = TRUE;
  3099. cmd->handler = fuzzy_delete_handler;
  3100. cmd->ctx = ctx;
  3101. g_hash_table_insert (commands, "/fuzzydel", cmd);
  3102. cmd = rspamd_mempool_alloc (fctx->fuzzy_pool, sizeof (*cmd));
  3103. cmd->privilleged = TRUE;
  3104. cmd->require_message = FALSE;
  3105. cmd->handler = fuzzy_deletehash_handler;
  3106. cmd->ctx = ctx;
  3107. g_hash_table_insert (commands, "/fuzzydelhash", cmd);
  3108. return 0;
  3109. }