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

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