Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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