You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

rspamd.texi 79KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913
  1. \input texinfo
  2. @settitle "Rspamd Spam Filtering System"
  3. @titlepage
  4. @title Rspamd Spam Filtering System
  5. @subtitle A User's Guide for Rspamd
  6. @author Vsevolod Stakhov
  7. @end titlepage
  8. @contents
  9. @chapter Rspamd purposes and features.
  10. @section Introduction.
  11. Rspamd filtering system is created as a replacement of popular
  12. @code{spamassassin}
  13. spamd and is designed to be fast, modular and easily extendable system. Rspamd
  14. core is written in @code{C} language using event driven paradigma. Plugins for rspamd
  15. can be written in @code{lua}. Rspamd is designed to process connections
  16. completely asynchronous and do not block anywhere in code. Spam filtering system
  17. contains of several processes among them are:
  18. @itemize @bullet
  19. @item Main process
  20. @item Workers processes
  21. @item Controller process
  22. @item Other processes
  23. @end itemize
  24. Main process manages all other processes, accepting signals from OS (for example
  25. SIGHUP) and spawn all types of processes if any of them die. Workers processes
  26. do all tasks for filtering e-mail (or HTML messages in case of using rspamd as
  27. non-MIME filter). Controller process is designed to manage rspamd itself (for
  28. example get statistics or learning rspamd). Other processes can do different
  29. jobs among them now are implemented @code{LMTP} worker that implements
  30. @code{LMTP} protocol for filtering mail and fuzzy hashes storage server.
  31. @section Features.
  32. The main features of rspamd are:
  33. @itemize @bullet
  34. @item Completely asynchronous filtering that allows a big number of simultenious
  35. connections.
  36. @item Easily extendable architecture that can be extended by plugins written in
  37. @code{lua} and by dynamicaly loaded plugins written in @code{c}.
  38. @item Ability to work in cluster: rspamd is able to perform statfiles
  39. synchronization, dynamic load of lists via HTTP, to use distributed fuzzy hashes
  40. storage.
  41. @item Advanced statistics: rspamd now is shipped with winnow-osb classifier that
  42. provides more accurate statistics than traditional bayesian algorithms based on
  43. single words.
  44. @item Internal optimizer: rspamd first of all try to check rules that were met
  45. more often, so for huge spam storms it works very fast as it just checks only
  46. that rules that @emph{can} happen and skip all others.
  47. @item Ability to manage the whole cluster by using controller process.
  48. @item Compatibility with existing @code{spamassassin} SPAMC protocol.
  49. @item Extended @code{RSPAMC} protocol that allows to pass many additional data
  50. from SMTP dialog to rspamd filter.
  51. @item Internal support of IMAP in rspamc client for automated learning.
  52. @item Internal support of many anti-spam technologies, among them are
  53. @code{SPF} and @code{SURBL}.
  54. @item Active support and development of new features.
  55. @end itemize
  56. @chapter Installation of rspamd.
  57. @section Obtaining of rspamd.
  58. The main rspamd site is @url{http://rspamd.sourceforge.net/, sourceforge}. Here
  59. you can obtain source code package as well as pre-packed packages for different
  60. operating systems and architectures. Also, you can use SCM
  61. @url{http://mercurial.selenic.com, mercurial} for accessing rspamd development
  62. repository that can be found here:
  63. @url{http://rspamd.hg.sourceforge.net:8000/hgroot/rspamd/rspamd}. Rspamd is
  64. shipped with all modules and sample config by default. But there are some
  65. requirements for building and running rspamd.
  66. @section Requirements.
  67. For building rspamd from sources you need @code{CMake} system. CMake is very
  68. nice source building system and I decided to use it instead of GNU autotools.
  69. CMake can be obtained here: @url{http://cmake.org}. Also rspamd uses gmime and
  70. glib for MIME parsing and many other purposes (note that you are NOT required
  71. to install any GUI libraries - nor glib, nor gmime are GUI libraries). Gmime
  72. and glib can be obtained from gnome site: @url{http://ftp.gnome.org/}. For
  73. plugins and configuration system you also need lua language interpreter and
  74. libraries. They can be easily obtained from @url{http://lua.org, official lua
  75. site}. Also for rspamc client you need @code{perl} interpreter that could be
  76. installed from @url{http://www.perl.org}.
  77. @section Building and Installation.
  78. Build process of rspamd is rather simple:
  79. @itemize @bullet
  80. @item Configure rspamd build environment, using cmake:
  81. @example
  82. $ cmake .
  83. ...
  84. -- Configuring done
  85. -- Generating done
  86. -- Build files have been written to: /home/cebka/rspamd
  87. @end example
  88. @noindent
  89. For special configuring options you can use
  90. @example
  91. $ ccmake .
  92. CMAKE_BUILD_TYPE
  93. CMAKE_INSTALL_PREFIX /usr/local
  94. DEBUG_MODE ON
  95. ENABLE_GPERF_TOOLS OFF
  96. ENABLE_OPTIMIZATION OFF
  97. ENABLE_PERL OFF
  98. ENABLE_PROFILING OFF
  99. ENABLE_REDIRECTOR OFF
  100. ENABLE_STATIC OFF
  101. @end example
  102. @noindent
  103. Options allows building rspamd as static module (note that in this case
  104. dynamicaly loaded plugins are @strong{NOT} supported), linking rspamd with
  105. google performance tools for benchmarking and include some other flags while
  106. building.
  107. @item Build rspamd sources:
  108. @example
  109. $ make
  110. [ 6%] Built target rspamd_lua
  111. [ 11%] Built target rspamd_json
  112. [ 12%] Built target rspamd_evdns
  113. [ 12%] Built target perlmodule
  114. [ 58%] Built target rspamd
  115. [ 76%] Built target test/rspamd-test
  116. [ 85%] Built target utils/expression-parser
  117. [ 94%] Built target utils/url-extracter
  118. [ 97%] Built target rspamd_ipmark
  119. [100%] Built target rspamd_regmark
  120. @end example
  121. @noindent
  122. @item Install rspamd (as superuser):
  123. @example
  124. # make install
  125. Install the project...
  126. ...
  127. @end example
  128. @noindent
  129. @end itemize
  130. After installation you would have several new files installed:
  131. @itemize @bullet
  132. @item Binaries:
  133. @itemize @bullet
  134. @item PREFIX/bin/rspamd - main rspamd executable
  135. @item PREFIX/bin/rspamc - rspamd client program
  136. @end itemize
  137. @item Sample configuration files and rules:
  138. @itemize @bullet
  139. @item PREFIX/etc/rspamd.xml.sample - sample main config file
  140. @item PREFIX/etc/rspamd/lua/*.lua - rspamd rules
  141. @end itemize
  142. @item Lua plugins:
  143. @itemize @bullet
  144. @item PREFIX/etc/rspamd/plugins/lua/*.lua - lua plugins
  145. @end itemize
  146. @end itemize
  147. For @code{FreeBSD} system there also would be start script for running rspamd in
  148. @emph{PREFIX/etc/rc.d/rspamd.sh}.
  149. @section Running rspamd.
  150. Rspamd can be started by running main rspamd executable -
  151. @code{PREFIX/bin/rspamd}. There are several command-line options that can be
  152. passed to rspamd. All of them can be displayed by passing --help argument:
  153. @example
  154. $ rspamd --help
  155. Usage:
  156. rspamd [OPTION...] - run rspamd daemon
  157. Summary:
  158. Rspamd daemon version 0.3.0
  159. Help Options:
  160. -?, --help Show help options
  161. Application Options:
  162. -t, --config-test Do config test and exit
  163. -f, --no-fork Do not daemonize main process
  164. -c, --config Specify config file
  165. -u, --user User to run rspamd as
  166. -g, --group Group to run rspamd as
  167. -p, --pid Path to pidfile
  168. -V, --dump-vars Print all rspamd variables and exit
  169. -C, --dump-cache Dump symbols cache stats and exit
  170. -X, --convert-config Convert old style of config to xml one
  171. @end example
  172. @noindent
  173. All options are optional: by default rspamd would try to read
  174. @code{PREFIX/etc/rspamd.xml} config file and run as daemon. Also there is test
  175. mode that can be turned on by passing @option{-t} argument. In test mode rspamd
  176. would read config file and checks its syntax, if config file is OK, then exit
  177. code is zero and non zero otherwise. Test mode is useful for testing new config
  178. file without restarting of rspamd. With @option{-C} and @option{-V} arguments it is
  179. possible to dump variables or symbols cache data. The last ability can be used
  180. for determining which symbols are most often, which are most slow and to watch
  181. to real order of rules inside rspamd. @option{-X} option can be used to convert
  182. old style (pre 0.3.0) config to xml one:
  183. @example
  184. $ rspamd -c ./rspamd.conf -X ./rspamd.xml
  185. @end example
  186. @noindent
  187. After this command new xml config would be dumped to rspamd.xml file.
  188. @section Managing rspamd with signals.
  189. First of all it is important to note that all user's signals should be sent to
  190. rspamd main process and not to its children (as for child processes these
  191. signals may have other meanings). To determine which process is main you can use
  192. two ways:
  193. @itemize @bullet
  194. @item by reading pidfile:
  195. @example
  196. $ cat pidfile
  197. @end example
  198. @noindent
  199. @item by getting process info:
  200. @example
  201. $ ps auxwww | grep rspamd
  202. nobody 28378 0.0 0.2 49744 9424 rspamd: main process (rspamd)
  203. nobody 64082 0.0 0.2 50784 9520 rspamd: worker process (rspamd)
  204. nobody 64083 0.0 0.3 51792 11036 rspamd: worker process (rspamd)
  205. nobody 64084 0.0 2.7 158288 114200 rspamd: controller process (rspamd)
  206. nobody 64085 0.0 1.8 116304 75228 rspamd: fuzzy storage (rspamd)
  207. $ ps auxwww | grep rspamd | grep main
  208. nobody 28378 0.0 0.2 49744 9424 rspamd: main process (rspamd)
  209. @end example
  210. @noindent
  211. @end itemize
  212. After getting pid of main process it is possible to manage rspamd with signals:
  213. @itemize @bullet
  214. @item SIGHUP - restart rspamd: reread config file, start new workers (as well as
  215. controller and other processes), stop accepting connections by old workers,
  216. reopen all log files. Note that old workers would be terminated after one minute
  217. that should allow to process all pending requests. All new requests to rspamd
  218. would be processed by newly started workers.
  219. @item SIGTERM - terminate rspamd system.
  220. @end itemize
  221. These signals may be used in start scripts as it is done in @code{FreeBSD} start
  222. script. Restarting of rspamd is doing rather softly: no connections would be
  223. dropped and if new config is syntaxically incorrect old config would be used.
  224. @chapter Configuring of rspamd.
  225. @section Principles of work.
  226. We need to define several terms to explain configuration of rspamd. Rspamd
  227. operates with @strong{rules}, each rule defines some actions that should be done with
  228. message to obtain result. Result is called @strong{symbol} - a symbolic
  229. representation of rule. For example, if we have a rule to check DNS record for
  230. a url that contains in message we may insert resulting symbol if this DNS record
  231. is found. Each symbol has several attributes:
  232. @itemize @bullet
  233. @item name - symbolic name of symbol (usually uppercase, e.g. MIME_HTML_ONLY)
  234. @item weight - numeric weight of this symbol (this means how important this rule is), may
  235. be negative
  236. @item options - list of symbolic options that defines additional information about
  237. processing this rule
  238. @end itemize
  239. Weights of symbols are called @strong{factors}. Also when symbol is inserted it
  240. is possible to define additional multiplier to factor. This can be used for
  241. rules that have dynamic weights, for example statistical rules (when probability
  242. is higher weight must be higher as well).
  243. All symbols and corresponding rules are combined in @strong{metrics}. Metric
  244. defines a group of symbols that are designed for common purposes. Each metric
  245. has maximum weight: if sum of all rules' results (symbols) is bigger than this
  246. limit then this message is considered as spam in this metric. The default metric
  247. is called @emph{default} and rules that have not explicitly specified metric
  248. would insert their results to this default metric.
  249. Let's impress how this technics works:
  250. @enumerate 1
  251. @item First of all when rspamd is running each module (lua, internal or external
  252. dynamic module) can register symbols in any defined metric. After this process
  253. rspamd has a cache of symbols for each metric. This cache can be saved to file
  254. for speeding up process of optimizing order of calling of symbols.
  255. @item Rspamd gets a message from client and parse it with mime parsing and do
  256. other parsing jobs like extracting text parts, urls, and stripping html tags.
  257. @item For each metric rspamd is looking to metric's cache and select rules to
  258. check according to their order (this order depends on frequence of symbol, its
  259. weight and execution time).
  260. @item Rspamd calls rules of metric till the sum weight of symbols in metric is
  261. less than its limit.
  262. @item If sum weight of symbols is more than limit the processing of rules is
  263. stopped and message is counted as spam in this metric.
  264. @end enumerate
  265. After processing rules rspamd is also does statistic check of message. Rspamd
  266. statistic module is presented as a set of @strong{classifiers}. Each classifier
  267. defines algorithm of statistic checks of messages. Also classifier definition
  268. contains definition of @strong{statistic files} (or @strong{statfiles} shortly).
  269. Each statfile contains of number of patterns that are extracted from messages.
  270. These patterns are put into statfiles during learning process. A short example:
  271. you define classifier that contains two statfiles: @emph{ham} and @emph{spam}.
  272. Than you find 10000 messages that are spam and 10000 messages that contains ham.
  273. Then you learn rspamd with these messages. After this process @emph{ham}
  274. statfile contains patterns from ham messages and @emph{spam} statfile contains
  275. patterns from spam messages. Then when you are checking message via this
  276. statfiles messages that are like spam would have more probability/weight in
  277. @emph{spam} statfile than in @emph{ham} statfile and classifier would insert
  278. symbol of @emph{spam} statfile and would calculate how this message is like
  279. patterns that are contained in @emph{spam} statfile. But rspamd is not limiting
  280. you to define one classifier or two statfiles. It is possible to define a number
  281. of classifiers and a number of statfiles inside a classifier. It can be useful
  282. for personal statistic or for specific spam patterns. Note that each classifier
  283. can insert only one symbol - a symbol of statfile with max weight/probability.
  284. Also note that statfiles check is allways done after all rules. So statistic can
  285. @strong{correct} result of rules.
  286. Now some words about @strong{modules}. All rspamd rules are contained in
  287. modules. Modules can be internal (like SURBL, SPF, fuzzy check, email and
  288. others) and external written in @code{lua} language. In fact there is no differ
  289. in the way, how rules of these modules are called:
  290. @enumerate 1
  291. @item Rspamd loads config and loads specified modules.
  292. @item Rspamd calls init function for each module passing configurations
  293. arguments.
  294. @item Each module examines configuration arguments and register its rules (or
  295. not register depending on configuration) in rspamd metrics (or in a single
  296. metric).
  297. @item During metrics process rspamd calls registered callbacks for module's
  298. rules.
  299. @item These rules may insert results to metric.
  300. @end enumerate
  301. So there is no actual difference between lua and internal modules, each are just
  302. providing callbacks for processing messages. Also inside callback it is possible
  303. to change state of message's processing. For example this can be done when it is
  304. required to make DNS or other network request and to wait result. So modules can
  305. pause message's processing while waiting for some event. This is true for lua
  306. modules as well.
  307. @section Rspamd config file structure.
  308. Rspamd config file is placed in PREFIX/etc/rspamd.xml by default. You can
  309. specify other location by passing @option{-c} option to rspamd. Rspamd config file
  310. contains configuration parameters in XML format. XML was selected for rather
  311. simple manual editing config file and for simple automatic generation as well as
  312. for dynamic configuration. I've decided to move rules logic from XML file to
  313. keep it small and simple. So rules are defined in @code{lua} language and rspamd
  314. parameters are defined in xml file (rspamd.xml). Configuration rules are
  315. included by @strong{<lua>} tag that have @strong{src} attribute that defines
  316. relative path to lua file (relative to placement of rspamd.xml):
  317. @example
  318. <lua src="rspamd/lua/rspamd.lua">fake</lua>
  319. @end example
  320. @noindent
  321. Note that it is not currently possible to have empty tags. I hope this
  322. restriction would be fixed in future. Rspamd xml config consists of several
  323. sections:
  324. @itemize @bullet
  325. @item Main section - section where main config parameters are placed.
  326. @item Workers section - section where workers are described.
  327. @item Classifiers section - section where you define your classify logic
  328. @item Modules section - a set of sections that describes module's rules (in fact
  329. these rules should be in lua code)
  330. @item Metrics section - a section where you can set weights of symbols in metrics and metrics settings
  331. @item Logging section - a section that describes rspamd logging
  332. @item Views section - a section that defines rspamd views
  333. @end itemize
  334. So common structure of rspamd.xml can be described this way:
  335. @example
  336. <? xml version="1.0" encoding="utf-8" ?>
  337. <rspamd>
  338. <!-- Main section directives -->
  339. ...
  340. <!-- Workers directives -->
  341. <worker>
  342. ...
  343. </worker>
  344. ...
  345. <!-- Classifiers directives -->
  346. <classifier>
  347. ...
  348. </classifier>
  349. ...
  350. <!-- Logging section -->
  351. <logging>
  352. <type>console</type>
  353. <level>info</level>
  354. ...
  355. </logging>
  356. <!-- Views section -->
  357. <view>
  358. ...
  359. </view>
  360. ...
  361. <!-- Modules settings -->
  362. <module name="regexp">
  363. <option name="test">test</option>
  364. ...
  365. </module>
  366. ...
  367. </rspamd>
  368. @end example
  369. Each of these sections would be described further in details.
  370. @section Rspamd configuration atoms.
  371. There are several primitive types of rspamd configuration parameters:
  372. @itemize @bullet
  373. @item String - common string that defines option.
  374. @item Number - integer or fractional number (e.g.: 10 or -1.5).
  375. @item Time - ammount of time in milliseconds, may has suffixes:
  376. @itemize @bullet
  377. @item @emph{s} - for seconds (e.g. @emph{10s});
  378. @item @emph{m} - for minutes (e.g. @emph{10m});
  379. @item @emph{h} - for hours (e.g. @emph{10h});
  380. @item @emph{d} - for days (e.g. @emph{10d});
  381. @end itemize
  382. @item Size - like number numerci reprezentation of size, but may have a suffix:
  383. @itemize @bullet
  384. @item @emph{k} - 'kilo' - number * 1024 (e.g. @emph{10k});
  385. @item @emph{m} - 'mega' - number * 1024 * 1024 (e.g. @emph{10m});
  386. @item @emph{g} - 'giga' - number * 1024 * 1024 * 1024 (e.g. @emph{1g});
  387. @end itemize
  388. @noindent
  389. Size atoms are used for memory limits for example.
  390. @item Lists - path to dynamic rspamd list (e.g. @emph{http://some.host/some/path}).
  391. @end itemize
  392. While practically all atoms are rather trivial to understand rspamd lists may
  393. cause some confusion. Lists are widely used in rspamd for getting data that can
  394. be often changed for example white or black lists, lists of ip addresses, lists
  395. of domains. So for such purposes it is possible to use files that can be get
  396. either from local filesystem (e.g. @code{file:///var/run/rspamd/whitelsist}) or
  397. by HTTP (e.g. @code{http://some.host/some/path/list.txt}). Rspamd constantly
  398. looks for changes in this files, if using HTTP it also set
  399. @emph{If-Modified-Since} header and check for @emph{Not modified} reply. So it
  400. causes no overhead when lists are not modified and may allow to store huge lists
  401. and to distribute them over HTTP. Monitoring of lists is done with some random
  402. delay (jitter), so if you have many rspamd servers in cluster that are
  403. monitoring a single list they would come to check or download it in slightly different
  404. time. The two most common list formats are @emph{IP list} and @emph{domains
  405. list}. IP list contains of ip addresses in dot notation (e.g.
  406. @code{192.168.1.1}) or ip/network pairs in CIDR notation (e.g.
  407. @code{172.16.0.0/16}). Items in lists are separated by newline symbol. Lines
  408. that begin with @emph{#} symbol are considered as comments and are ignored while
  409. parsing. Domains list is very like ip list with difference that it contains
  410. domain names.
  411. @section Main rspamd configuration section.
  412. Main rspamd configurtion section contains several definitions that determine
  413. main parameters of rspamd for example path to pidfile, temporary directory, lua
  414. includes, several limits e.t.c. Here is list of this directives explained:
  415. @multitable @columnfractions .2 .8
  416. @headitem Tag @tab Mean
  417. @item @var{<tempdir>}
  418. @tab Defines temporary directory for rspamd. Default is to use @env{TEMP}
  419. environment variable or @code{/tmp}.
  420. @item @var{<pidfile>}
  421. @tab Path to rspamd pidfile. Here would be stored a pid of main process.
  422. Pidfile is used to manage rspamd from start scripts.
  423. @item @var{<statfile_pool_size>}
  424. @tab Limit of statfile pool size: a total number of bytes that can be used for
  425. mapping statistic files. Rspamd is using LRU system and would unmap the most
  426. unused statfile when this limit would be reached. The common sense is to set
  427. this variable equal to total size of all statfiles, but it can be less than this
  428. in case of dynamic statfiles (for per-user statistic).
  429. @item @var{<filters>}
  430. @tab List of enabled internal filters. Items in this list can be separated by
  431. spaces, semicolons or commas. If internal filter is not specified in this line
  432. it would not be loaded or enabled.
  433. @item @var{<raw_mode>}
  434. @tab Boolean flag that specify whether rspamd should try to convert all
  435. messages to UTF8 or not. If @var{raw_mode} is enabled all messages are
  436. processed @emph{as is} and are not converted. Raw mode is faster than utf mode
  437. but it may confuse statistics and regular expressions.
  438. @item @var{<lua>}
  439. @tab Defines path to lua file that should be loaded fro configuration. Path to
  440. this file is defined in @strong{src} attribute. Text inside tag is required but
  441. is not parsed (this is stupid limitation of parser's design).
  442. @end multitable
  443. @section Rspamd logging configuration.
  444. Rspamd has a number of logging variants. First of all there are three types of
  445. logs that are supported by rspamd: console loggging (just output log messages to
  446. console), file logging (output log messages to file) and logging via syslog.
  447. Also it is possible to filter logging to specific level:
  448. @itemize @bullet
  449. @item error - log only critical errors
  450. @item warning - log errors and warnings
  451. @item info - log all non-debug messages
  452. @item debug - log all including debug messages (huge amount of logging)
  453. @end itemize
  454. Also it is possible to turn on debug messages for specific ip addresses. This
  455. ability is usefull for testing.
  456. For each logging type there are special mandatory parameters: log facility for
  457. syslog (read @emph{syslog (3)} manual page for details about facilities), log
  458. file for file logging. Also file logging may be buffered for speeding up. For
  459. reducing logging noise rspamd detects for sequential identic log messages and
  460. replace them with total number of repeats:
  461. @example
  462. #81123(fuzzy): May 11 19:41:54 rspamd file_log_function: Last message repeated 155 times
  463. #81123(fuzzy): May 11 19:41:54 rspamd process_write_command: fuzzy hash was successfully added
  464. @end example
  465. Here is summary of logging parameters:
  466. @multitable @columnfractions .2 .8
  467. @headitem Tag @tab Mean
  468. @item @var{<type>}
  469. @tab Defines logging type (file, console or syslog). For each type mandatory
  470. attriute must be present:
  471. @itemize @bullet
  472. @item @emph{filename} - path to log file for file logging type;
  473. @item @emph{facility} - syslog logging facility.
  474. @end itemize
  475. @item @var{<level>}
  476. @tab Defines loggging level (error, warning, info or debug).
  477. @item @var{<log_buffer>}
  478. @tab For file and console logging defines buffer in bytes (kilo, mega or giga
  479. bytes) that would be used for logging output.
  480. @item @var{<log_urls>}
  481. @tab Flag that defines whether all urls in message would be logged. Useful for
  482. testing.
  483. @item @var{<debug_ip>}
  484. @tab List that contains ip addresses for which debugging would be turned on. For
  485. more information about ip lists look at config atoms section.
  486. @end multitable
  487. @section Metrics configuration.
  488. Setting of rspamd metrics is the main way to change rules' weights. You can set
  489. up weights for all rules: for those that have static weights (for example simple
  490. regexp rules) and for those that have dynamic weights (for example statistic
  491. rules). In all cases the base weight of rule is multiplied by metric's weight value.
  492. For static rules base weight is usually 1.0. So we have:
  493. @itemize @bullet
  494. @item @math{w_{symbol} = w_{static} * factor} - for static rules
  495. @item @math{w_{symbol} = w_{dynamic} * factor} - for dynamic rules
  496. @end itemize
  497. Also there is an ability to add so called "grow factor" - additional multiplier
  498. that would be used when we have more than one symbol in metric. So for each
  499. added symbol this factor would increment its power. This can be written as:
  500. @math{w_{total} = w_1 * gf ^ 0 + w_2 * gf ^ 1 + ... + w_n * gf ^ {n - 1}}
  501. Grow multiplier is used to increment weight of rules when message got many
  502. symbols (likely spammy). Note that only rules with positive weights would
  503. increase grow factor, those with negative weights would just be added. Also note
  504. that grow factor can be less than 1 but it is uncommon use (in this case we
  505. would have weight lowering when we have many symbols for this message). Metrics
  506. can be set up with config section(s) @emph{metric}:
  507. @example
  508. <metric>
  509. <name>test_metric</name>
  510. <action>reject</action>
  511. <symbol weight="0.1">MIME_HTML_ONLY</symbol>
  512. <grow_factor>1.1</grow_factor>
  513. </metric>
  514. @end example
  515. Note that you basically need to add symbols to metric when you add additional rules.
  516. The decision of weight of newly added rule basically depends on its importance. For
  517. example you are absolutely sure that some rule would add a symbol on only spam
  518. messages, so you can increase weight of such rule so it would filter such spam.
  519. But if you increase weight of rules you should be more or less sure that it
  520. would not increase false positive errors rate to unacceptable level (false
  521. positive errors are errors when good mail is treated as spam). Rspamd comes with
  522. a set of default rules and default weights of that rules are placed in
  523. rspamd.xml.sample. In most cases it is reasonable to change them for your mail
  524. system, for example increase weights of some rules or decrease for others. Also
  525. note that default grow factor is 1.0 that means that weights of rules do not
  526. depend on count of added symbols. For some situations it useful to set grow
  527. factor to value more than 1.0. Also by modifying weights it is possible to
  528. manage static multiplier for dynamic rules.
  529. @section Workers configuration.
  530. Workers are rspamd processes that are doing specific jobs. Now are supported 4
  531. types of workers:
  532. @enumerate 1
  533. @item Normal worker - a typical worker that process messages.
  534. @item Controller worker - a worker that manages rspamd, get statistics and do
  535. learning tasks.
  536. @item Fuzzy storage worker - a worker that contains a collection of fuzzy
  537. hashes.
  538. @item LMTP worker - experimental worker that acts as LMTP server.
  539. @end enumerate
  540. These types of workers has some common parameters:
  541. @multitable @columnfractions .2 .8
  542. @headitem Parameter @tab Mean
  543. @item @emph{<type>}
  544. @tab Type of worker (normal, controller, lmtp or fuzzy)
  545. @item @emph{<bind_socket>}
  546. @tab Socket credits to bind this worker to. Inet and unix sockets are supported:
  547. @example
  548. <bind_socket>localhost:11333</bind_socket>
  549. <bind_socket>/var/run/rspamd.sock</bind_socket>
  550. @end example
  551. @noindent
  552. Also for inet sockets you may specify @code{*} as address to bind to all
  553. available inet interfaces:
  554. @example
  555. <bind_socket>*:11333</bind_socket>
  556. @end example
  557. @noindent
  558. @item @emph{<count>}
  559. @tab Number of worker processes of this type. By default this number is
  560. equialent to number of logical processors in system.
  561. @item @emph{<maxfiles>}
  562. @tab Maximum number of file descriptors available to this worker process.
  563. @item @emph{<maxcore>}
  564. @tab Maximum size of core file that would be dumped in cause of critical errors
  565. (in mega/kilo/giga bytes).
  566. @end multitable
  567. Also each of workers types can have specific parameters:
  568. @itemize @bullet
  569. @item Normal worker:
  570. @itemize @bullet
  571. @item @var{<custom_filters>} - path to dynamically loaded plugins that would do real
  572. check of incoming messages. These modules are described further.
  573. @item @var{<mime>} - if this parameter is "no" than this worker assumes that incoming
  574. messages are in non-mime format (e.g. forum's messages) and standart mime
  575. headers are added to them.
  576. @end itemize
  577. @item Controller worker:
  578. @itemize @bullet
  579. @item @var{<password>} - a password that would be used to access to contorller's
  580. privilleged commands.
  581. @end itemize
  582. @item Fuzzy worker:
  583. @itemize @bullet
  584. @item @var{<hashfile>} - a path to file where fuzzy hashes would be permamently stored.
  585. @item @var{<use_judy>} - if libJudy is present in system use it for faster storage.
  586. @item @var{<frequent_score>} - if judy is not turned on use this score to place hashes
  587. with score that is more than this value to special faster list (this is designed
  588. to increase lookup speed for frequent hashes).
  589. @item @var{<expire>} - time to expire of fuzzy hashes after their placement in storage.
  590. @end itemize
  591. @end itemize
  592. These parameters can be set inside worker's definition:
  593. @example
  594. <worker>
  595. <type>fuzzy</type>
  596. <bind_socket>*:11335</bind_socket>
  597. <count>1</count>
  598. <maxfiles>2048</maxfiles>
  599. <maxcore>0</maxcore>
  600. <!-- Other params -->
  601. <param name="use_judy">yes</param>
  602. <param name="hashfile">/spool/rspamd/fuzzy.db</param>
  603. <param name="expire">10d</param>
  604. </worker>
  605. @end example
  606. @noindent
  607. The purpose of each worker's type would be described later. The main parameters
  608. that could be defined are bind sockets for workers, their count, password for
  609. controller's commands and parameters for fuzzy storage. Default config provides
  610. reasonable values of this parameters (except password of course), so for basic
  611. configuration you may just replace controller's password to more secure one.
  612. @section Classifiers configuration.
  613. @subsection Common classifiers options.
  614. Each classifier has mandatory option @var{type} that defines internal algorithm
  615. that is used for classifying. Currently only @code{winnow} is supported. You can
  616. read theoretical description of algorithm used here:
  617. @url{http://www.siefkes.net/papers/winnow-spam.pdf}
  618. The common classifier configuration consists of base classifier parameters and
  619. definitions of two (or more than two) statfiles. During classify process rspamd
  620. check each statfile in classifier and select those that has more
  621. probability/weight than others. If all statfiles has zero weight this classifier
  622. do not add any symbols. Among common classifiers options are:
  623. @multitable @columnfractions .2 .8
  624. @headitem Tag @tab Mean
  625. @item @var{<tokenizer>}
  626. @tab Tokenizer to extract tokens from messages. Currently only @emph{osb}
  627. tokenizer is supported
  628. @item @var{<metric>}
  629. @tab Metric to which this classifier would insert symbol.
  630. @end multitable
  631. Also option @var{min_tokens} is supported to specify minimum number of tokens to
  632. work with (this is usefull to avoid classifying of short messages as statistic
  633. is practically useless for small amount of tokens). Here is example of base
  634. classifier config:
  635. @example
  636. <classifier type="winnow">
  637. <tokenizer>osb-text</tokenizer>
  638. <metric>default</metric>
  639. <option name="min_tokens">20</option>
  640. <statfile>
  641. ...
  642. </statfile>
  643. </classifier>
  644. @end example
  645. @subsection Statfiles options.
  646. The most common statfile options are @var{symbol} and @var{size}. The first one defines
  647. which symbol would be inserted if this statfile would have maximal weight inside
  648. classifier and size defines statfile size on disk and in memory. Note that
  649. statfiles are mapped directly to memory and you should practically note
  650. parameter @var{statfile_pool_size} of main section which defines maximum ammount
  651. of memory for mapping statistic files. Also note that statistic files are
  652. of constant size: if you defines 100 megabytes statfile it would occupy 100
  653. megabytes of disc space and 100 megabytes of memory when it is used (mapped).
  654. Each statfile is indexed by tokens and contains so called "token chains". This
  655. mechanizm would be described further but note that each statfile has parameter
  656. "free tokens" that defines how much space is available for new tokens. If
  657. statfile has no free space the most unused tokens would be removed from
  658. statfile.
  659. Here is list of common options of statfiles:
  660. @multitable @columnfractions .2 .8
  661. @headitem Tag @tab Mean
  662. @item @var{<symbol>}
  663. @tab Defines symbol to insert for this statfile.
  664. @item @var{<size>}
  665. @tab Size of this statfile in bytes (kilo/mega/giga bytes).
  666. @item @var{<path>}
  667. @tab Filesystem path to statistic file.
  668. @item @var{<normalizer>}
  669. @tab Defines weight normalization structure. Can be lua function name or
  670. internal normalizer. Internal normalizer is defined in format:
  671. "internal:<max_weight>" where max_weight is fractional number that limits the
  672. maximum weight of this statfile's symbol (this is so called dynamic weight).
  673. @item @var{<binlog>}
  674. @tab Defines binlog affinity: master or slave. This option is used for statfiles
  675. binary sync that would be described further.
  676. @item @var{<binlog_master>}
  677. @tab Defines credits of binlog master for this statfile.
  678. @item @var{<binlog_rotate>}
  679. @tab Defines rotate time for binlog.
  680. @end multitable
  681. Internal normalization of statfile weight works in this way:
  682. @itemize @bullet
  683. @item @math{R_{score} = 1} when @math{W_{statfile} < 1}
  684. @item @math{R_{score} = W_statfile ^ 2} when @math{1 < W_{statfile} < max / 2}
  685. @item @math{R_{score} = W_statfile} when @math{max / 2 < W_{statfile} < max}
  686. @item @math{R_{score} = max} when @math{W_{statfile} > max}
  687. @end itemize
  688. The final result weight would be: @math{weight = R_{score} * W_{weight}}.
  689. Here is sample classifier configuration with two statfiles that can be used for
  690. spam/ham classifying:
  691. @example
  692. <symbol weight="-1.00">WINNOW_HAM</symbol>
  693. <symbol weight="1.00">WINNOW_SPAM</symbol>
  694. ...
  695. <!-- Classifiers section -->
  696. <classifier type="winnow">
  697. <tokenizer>osb-text</tokenizer>
  698. <metric>default</metric>
  699. <option name="min_tokens">20</option>
  700. <statfile>
  701. <symbol>WINNOW_HAM</symbol>
  702. <size>100M</size>
  703. <path>/var/run/rspamd/data.ham</path>
  704. <normalizer>internal:3</normalizer>
  705. </statfile>
  706. <statfile>
  707. <symbol>WINNOW_SPAM</symbol>
  708. <size>100M</size>
  709. <path>/var/run/rspamd/data.spam</path>
  710. <normalizer>internal:3</normalizer>
  711. </statfile>
  712. </classifier>
  713. <!-- End of classifiers section -->
  714. @end example
  715. @noindent
  716. In this sample we define classifier that contains two statfiles:
  717. @emph{WINNOW_SPAM} and @emph{WINNOW_HAM}. Each statfile has 100 megabytes size
  718. (so they would occupy 200Mb while classifying). Also each statfile has maximum
  719. weight of 3 so with such weights (-1 for WINNOW_HAM and 1 for WINNOW_SPAM) the
  720. result weight of symbols would be 0..3 for @emph{WINNOW_SPAM} and 0..-3 for
  721. @emph{WINNOW_HAM}.
  722. @section Modules config.
  723. @subsection Lua modules loading.
  724. For loading custom lua modules you should use @emph{<modules>} section:
  725. @example
  726. <modules>
  727. <module>/usr/local/etc/rspamd/plugins/lua</module>
  728. </modules>
  729. @end example
  730. @noindent
  731. Each @emph{<module>} directive defines path to lua modules. If this is a
  732. directory so all @code{*.lua} files inside that directory would be loaded. If
  733. this is a file it would be loaded directly.
  734. @subsection Modules configuration.
  735. Each module can have its own config section (this is true not only for internal
  736. module but also for lua modules). Such section is called @emph{<module>} with
  737. mandatory attribute @emph{"name"}. Each module can be configured by
  738. @emph{<option>} directives. These directives must also have @emph{"name"}
  739. attribute. So module configuration is done in @code{param = value} style:
  740. @example
  741. <module name="fuzzy_check">
  742. <option name="servers">localhost:11335</option>
  743. <option name="symbol">R_FUZZY</option>
  744. <option name="min_length">300</option>
  745. <option name="max_score">10</option>
  746. </module>
  747. @end example
  748. @noindent
  749. The common parameters are:
  750. @itemize @bullet
  751. @item symbol - symbol that this module should insert.
  752. @end itemize
  753. But each module can have its own unique parameters. So it would be discussed
  754. furhter in detailed modules description. Also note that for internal modules you
  755. should edit @emph{<filters>} parameter in main section: this parameter defines
  756. which internal modules would be turned on in this configuration.
  757. @section Views config.
  758. It is possible to make different rules for different
  759. networks/senders/recipients. For this purposes you can use rspamd views: maps of
  760. conditions (ip, sender, recipients) and actions, associated with them. For
  761. example you can turn rspamd off for specific conditions by using
  762. @emph{skip_check} action or check only specific rules. Views are defined inside
  763. @emph{<view>} xml section. Here is list of available tags inside section:
  764. @multitable @columnfractions .2 .8
  765. @headitem Tag @tab Mean
  766. @item @var{<skip_check>}
  767. @tab Boolean flag (yes or no) that specifies whether rspamd checks should be
  768. turned off for this ip
  769. @item @var{<symbols>}
  770. @tab Defines comma-separated list of symbols that should be checked for this
  771. view
  772. @item @var{<ip>}
  773. @tab Map argument that defines path to list of ip addresses (may be with CIDR
  774. masks) to which this view should be applied.
  775. @item @var{<client_ip>}
  776. @tab Map argument that defines path to list of ip addresses of rspamd clients
  777. to which this view should be applied. Note that this is ip of rspamd client not
  778. ip of message's sender.
  779. @item @var{<from>}
  780. @tab Map argument that defines path to list of senders to which this view should
  781. be applied.
  782. @end multitable
  783. Here is an example view definition
  784. @example
  785. <view>
  786. <skip_check>yes</skip_check>
  787. <ip>file:///usr/local/etc/rspamd/whitelist</ip>
  788. </view>
  789. @end example
  790. @chapter Rspamd clients interaction.
  791. @section Introduction.
  792. After you have basic config file you may test rspamd functionality by using
  793. whether telnet like utility or @emph{rspamc} client. For testing newly installed
  794. config it is possible to run config file test:
  795. @example
  796. $ rspamd -t
  797. syntax OK
  798. @end example
  799. Rspamc utility is written in @code{perl} language and uses perl modules that are
  800. shipped with rspamd: @emph{Mail::Rspamd::Client} for client's protocol and
  801. @emph{Mail::Rspamd::Config} for reading and writing configuration. The
  802. documentation for these modules can be found by commands:
  803. @example
  804. $ perldoc Mail::Rspamd::Client
  805. $ perldoc Mail::Rspamd::Config
  806. @end example
  807. So other way to access rspamd is to use perl client API:
  808. @example
  809. use Mail::Rspamd::Client;
  810. my $config = @{
  811. hosts => ['localhost:11333'],
  812. @};
  813. my $client = new Mail::Rspamd::Client(%config);
  814. if (! $client->ping()) @{
  815. die "Cannot ping rspamd: $client->@{error@}";
  816. @}
  817. my $result = $client->check($testmsg);
  818. if ($result->@{'default'@}->@{isspam@} eq 'True') @{
  819. # do something with spam message here
  820. @}
  821. @end example
  822. @section Rspamc protocol.
  823. Rspamc protocol is an extension over traditional spamc protocol that is used by
  824. spamassassin. This protocol looks like traditional HTTP session: first line is
  825. method with version, headers can be passed by next lines and the message itself
  826. is waited after empty line:
  827. @example
  828. <REQUEST>
  829. SYMBOLS RSPAMC/1.1
  830. Content-Length: 2200
  831. <message octets>
  832. <REPLY>
  833. RSPAMD/1.1 0 OK
  834. Metric: default; True; 10.40 / 10.00 / 0.00
  835. Symbol: R_UNDISC_RCPT
  836. Symbol: ONCE_RECEIVED
  837. Symbol: R_MISSING_CHARSET
  838. Urls:
  839. @end example
  840. @noindent
  841. The format of method line can be presented as:
  842. @example
  843. <COMMAND> RSPAMC/<version>
  844. @end example
  845. @noindent
  846. Version can be 1.0 and 1.1. The main difference that in 1.1 metrics output also
  847. has @emph{reject score} - hard limit of score for metric. This would be
  848. discussed while describing user's options. Commands are:
  849. @multitable @columnfractions .2 .8
  850. @headitem Command @tab Mean
  851. @item CHECK
  852. @tab Check a message and output results for each metric. But do not output
  853. symbols.
  854. @item SYMBOLS
  855. @tab Same as @emph{CHECK} but output symbols.
  856. @item PROCESS
  857. @tab Same as @emph{SYMBOLS} but output also original message with inserted
  858. X-Spam headers.
  859. @item PING
  860. @tab Do not do any processing, just check rspamd state:
  861. @example
  862. $ telnet localhost 11333
  863. Trying 127.0.0.1...
  864. Connected to localhost.
  865. Escape character is '^]'.
  866. PING RSPAMC/1.1
  867. RSPAMD/1.1 0 PONG
  868. Connection closed by foreign host.
  869. @end example
  870. @noindent
  871. @end multitable
  872. After command there should be one mandatory header: @strong{Content-Length} that
  873. defines message's length in bytes and optional headers:
  874. @multitable @columnfractions .2 .8
  875. @headitem Header @tab Mean
  876. @item @var{Deliver-To:}
  877. @tab Defines actual delivery recipient of message. Can be used for personalized
  878. statistic and for user specific options.
  879. @item @var{IP:}
  880. @tab Defines IP from which this message is received.
  881. @item @var{Helo:}
  882. @tab Defines SMTP helo.
  883. @item @var{From:}
  884. @tab Defines SMTP mail from command data.
  885. @item @var{Queue-Id:}
  886. @tab Defines SMTP queue id for message (can be used instead of message id in
  887. logging).
  888. @item @var{Rcpt:}
  889. @tab Defines SMTP recipient (it may be several @emph{Rcpt:} headers).
  890. @item @var{Pass:}
  891. @tab If this header has @emph{"all"} value, all filters would be checked for
  892. this message.
  893. @item @var{Subject:}
  894. @tab Defines subject of message (is used for non-mime messages).
  895. @item @var{User:}
  896. @tab Defines SMTP user (this is currently unused in rspamd however).
  897. @end multitable
  898. So rspamc protocol allows to pass many data from MTA to rspamd. This is used to
  899. increase speed of processing and for building filters (like SPF filter). Also
  900. note that rspamd support spamassassin spamc protocol and you can even pass
  901. rspamc headers in spamc mode, but reply of rspamd in spamc mode would be much
  902. shorter: it would only use "default" metric and won't show additional options
  903. for symbols. Rspamc reply looks like this:
  904. @example
  905. RSPAMD/1.1 0 OK
  906. Metric: default; True; 10.40 / 10.00 / 0.00
  907. Symbol: R_UNDISC_RCPT
  908. Symbol: ONCE_RECEIVED
  909. Symbol: R_MISSING_CHARSET
  910. Urls:
  911. @end example
  912. @noindent
  913. First line is method reply: @code{<PROTOCOL>/<VERSION> <ERROR_CODE> <ERROR_REPLY>}.
  914. Error code is 0 when no error occured. After first reply line there are metrics
  915. output. For @emph{SYMBOLS} and @emph{PROCESS} commands there are symbols lines
  916. after each metric. And for @emph{PROCESS} command there would be original
  917. message after all metrics results. Metric result line looks like this:
  918. @example
  919. Metric: <name>; <result>; <score> / <required_score> / <reject_score>
  920. @end example
  921. @noindent
  922. For 1.0 version of rspamc protocol @emph{reject_score} parameter is not printed.
  923. Symbol line looks like this:
  924. @example
  925. Symbol: <Name>[; param1[, param2...]]
  926. @end example
  927. @noindent
  928. Some symbols can have parameters attached. It is useful for example for RBL
  929. checks (you can insert additional data after symbol name), for statistic and
  930. fuzzy checks. Also rspamd inserts @emph{Urls} line in which all urls that are
  931. contained in message are printed in comma-separated list.
  932. Note that this protocol is used for normal workers. Controller, fuzzy storage
  933. and lmtp/smtp workers are using other protocols. For example controller's
  934. protocol is oriented on interactive sessions: you can pass many commands to
  935. controller before disconnecting. Fuzzy storage is using UDP for making
  936. interaction with storage faster. LMTP/SMTP workers are using lmtp and smtp
  937. protocols. All of these protocols would be described in further chapters about
  938. rspamd workers.
  939. @section Controller protocol.
  940. Rspamd controller can also be accessed by telnet, by rspamc client or by using
  941. perl module Mail::Rspamd::Client. Controller protocol accepts commands and it is
  942. possible to send several commands during a single session. Here is an example
  943. telnet session:
  944. @example
  945. >telnet localhost 11334
  946. Trying 127.0.0.1...
  947. Connected to localhost.
  948. Escape character is '^]'.
  949. Rspamd version 0.3.0 is running on spam1.rambler.ru
  950. stat
  951. Messages scanned: 1526901
  952. Messages treated as spam: 238171, 15.60%
  953. Messages treated as ham: 1288730, 84.40%
  954. Messages learned: 0
  955. Connections count: 1529758
  956. Control connections count: 15
  957. Pools allocated: 3059589
  958. Pools freed: 3056134
  959. Bytes allocated: 98545852799
  960. Memory chunks allocated: 8745374
  961. Shared chunks allocated: 7
  962. Chunks freed: 8737507
  963. Oversized chunks: 768784
  964. Fuzzy hashes stored: 0
  965. Fuzzy hashes expired: 0
  966. Statfile: WINNOW_SPAM (version 186); length: 100.0 MB; free blocks: 748504; total blocks: 6553581; free: 11.42%
  967. Statfile: WINNOW_HAM (version 186); length: 100.0 MB; free blocks: 748504; total blocks: 6553581; free: 11.42%
  968. END
  969. @end example
  970. @noindent
  971. So you can see that reply from controller is ended with line that contains word
  972. @strong{END}. It is also possible to get summary help for controller's commands:
  973. @example
  974. help
  975. Rspamd CLI commands (* - privilleged command):
  976. help - this help message
  977. (*) learn <statfile> <size> [-r recipient] [-m multiplier] [-f from] [-n] - learn message to specified statfile
  978. quit - quit CLI session
  979. (*) reload - reload rspamd
  980. (*) shutdown - shutdown rspamd
  981. stat - show different rspamd stat
  982. counters - show rspamd counters
  983. uptime - rspamd uptime
  984. END
  985. @end example
  986. @noindent
  987. Note that some commands are privilleged ones - you are required to enter a
  988. password for them:
  989. @example
  990. >telnet localhost 11334
  991. Trying 127.0.0.1...
  992. Connected to localhost.
  993. Escape character is '^]'.
  994. Rspamd version 0.3.0 is running on spam1.rambler.ru
  995. reload
  996. not authorized
  997. END
  998. password q1
  999. password accepted
  1000. END
  1001. reload
  1002. reload request sent
  1003. END
  1004. Connection closed by foreign host.
  1005. @end example
  1006. @noindent
  1007. This password is configured in rspamd.xml in worker section where you are
  1008. describing controller:
  1009. @example
  1010. <worker>
  1011. <type>controller</type>
  1012. ...
  1013. <!-- Other params -->
  1014. <param name="password">q1</param>
  1015. </worker>
  1016. @end example
  1017. In many cases it is more easy to use rspamc to access controller. Here is
  1018. example of learning statfiles using rspamc CLI:
  1019. @example
  1020. % rspamc -h localhost:11334 -P q1 -s WINNOW_HAM learn < /tmp/exim.eml
  1021. Results for host localhost:11334:
  1022. Learn succeed. Sum weight: 1.51
  1023. % rspamc -h localhost:11334 -P q1 -s WINNOW_SPAM learn < /tmp/bad.eml
  1024. Results for host localhost:11334:
  1025. Learn succeed. Sum weight: 1.51
  1026. @end example
  1027. Note that rspamc handles password issues and other things like timeouts and
  1028. error handling inside and makes this tasks rather easy.
  1029. @section More about rspamc client.
  1030. Rspamc is small and simple client that allows to simplify common tasks for
  1031. rspamd manage. Rspamc is written in perl language and requires some modules for
  1032. its work:
  1033. @itemize @bullet
  1034. @item Mail::Rspamd::Client - a module that contains common function for
  1035. accessing rspamd, shipped with rspamd and installed automatically
  1036. @item Term::Cap - a module that allows basic interaction with terminal, can be
  1037. obtained via @url{http://www.cpan.org, cpan}.
  1038. @end itemize
  1039. Rspamc accepts several command line options:
  1040. @example
  1041. % rspamc --help
  1042. Usage: rspamc.pl [-h host] [-H hosts_list] [-P password] [-c conf_file] [-s statfile] [-d user@@domain] [command] [path]
  1043. -h host to connect (in format host:port) or unix socket path
  1044. -H path to file that contains list of hosts
  1045. -P define control password
  1046. -c config file to parse
  1047. -s statfile to use for learn commands
  1048. Additional options:
  1049. -d define deliver-to header
  1050. -w define weight for fuzzy operations
  1051. -S define search string for IMAP operations
  1052. -i emulate that message was send from specified IP
  1053. -p pass message throught all filters
  1054. Notes:
  1055. imap format: imap:user:<username>:password:[<password>]:host:<hostname>:mbox:<mboxname>
  1056. Password may be omitted and then it would be asked in terminal
  1057. imaps requires IO::Socket::SSL
  1058. IMAP search strings samples:
  1059. ALL - All messages in the mailbox;
  1060. FROM <string> - Messages that contain the specified string in the envelope structure's FROM field;
  1061. HEADER <field-name> <string> - Messages that have a header with the specified field-name and that
  1062. contains the specified string in the text of the header (what comes after the colon);
  1063. NEW - Messages that have the Recent flag set but not the Seen flag.
  1064. This is functionally equivalent to "(RECENT UNSEEN)".
  1065. OLD - Messages that do not have the Recent flag set.
  1066. SEEN - Messages that have the Seen flag set.
  1067. SENTBEFORE <date> - Messages whose [RFC-2822] Date: header (disregarding time and timezone)
  1068. is earlier than the specified date.
  1069. TO <string> - Messages that contain the specified string in the envelope structure's TO field.
  1070. TEXT <string> - Messages that contain the specified string in the header or body of the message.
  1071. OR <search-key1> <search-key2> - Messages that match either search key (same for AND and NOT operations).
  1072. Version: 0.3.0
  1073. @end example
  1074. @noindent
  1075. After options you should specify command to execute, for example:
  1076. @example
  1077. % rspamc symbols < /tmp/exim.eml
  1078. @end example
  1079. @noindent
  1080. After command name you may specify objects to apply to: files, directories or
  1081. even imap folders:
  1082. @itemize @bullet
  1083. @item A single file:
  1084. @example
  1085. % rspamc symbols /tmp/exim.eml
  1086. @end example
  1087. @noindent
  1088. @item A list of files:
  1089. @example
  1090. % rspamc symbols /tmp/*.eml
  1091. @end example
  1092. @noindent
  1093. @item Directories:
  1094. @example
  1095. % rspamc symbols /tmp/*.eml /tmp/to_scan/
  1096. @end example
  1097. @noindent
  1098. @item IMAP folder:
  1099. @example
  1100. % rspamc symbols imap:user:username:password::host:localhost:mbox:INBOX
  1101. Enter IMAP password:
  1102. @end example
  1103. @noindent
  1104. Note that it is possible to specify empty password and be prompted for a
  1105. password during execution (you also need perl module Term::ReadKey for turning
  1106. on noecho input of password).
  1107. @end itemize
  1108. For fetching imap messages you may also use search string by specifying -S
  1109. option. Some examples of IMAP search strings can be found in a help message. For
  1110. more complex things you may read rfc3501 about imap4 search strings. This may be
  1111. found for example here: @url{http://www.faqs.org/rfcs/rfc3501.html}. IMAP access
  1112. may be usefull for setting up automatic learning scripts. Also it is possible to
  1113. use SSL version of imap by specifying @strong{imaps} instead @strong{imap} as
  1114. first component. Note that for SSL access you need @emph{IO::Socket::SSL} perl
  1115. module.
  1116. @chapter Statistics and hashes storage.
  1117. @section Introduction.
  1118. First of all we need to strictly define purposes of hashes and statistic. Hashes
  1119. are used to find very close messages (for example messages where there are only
  1120. several words changed), while statistic can find @strong{probability} of
  1121. belonging message to specified class of messages. So when you learn rspamd with
  1122. message's hash you just add this hash to storage and when you learn rspamd
  1123. statistic you add tokens from message to specified class. So statistic is
  1124. probabilistic method to filter message, while fuzzy hashes can detect specific
  1125. patterns in messages and filter them.
  1126. @section Classifiers and statistic.
  1127. @subsection Tokenization.
  1128. Now rspamd supports OSB-Winnow statistic algorithm. Let's describe it in
  1129. details. First of all message is separeted into a set of tokens. The algorithm
  1130. of extracting tokens is rather simple now:
  1131. @enumerate 1
  1132. @item Extract graph symbols till first non-graph symbol (whitespace, punctuation
  1133. etc), the group of graph symbols forms a token, non-graphs are separators.
  1134. @item Fill an array with token till @strong{window size} is reached (currently
  1135. this size is 5 tokens).
  1136. @item Get pairs of tokens from array and extract their hashes:
  1137. @itemize @bullet
  1138. @item * . . . * -> token1 (h1, h5);
  1139. @item . * . . * -> token2 (h2, h5);
  1140. @item . . * . * -> token3 (h3, h5);
  1141. @item . . . * * -> token4 (h4, h5);
  1142. @end itemize
  1143. @noindent
  1144. @item Insert these tokens to statfile (indexed by first hash).
  1145. @item Shift window on next word.
  1146. @end enumerate
  1147. So after tokenizing process we would have tokens each of that contains 2 hashes of 2
  1148. words from message. This mechanics allows to count not only words itself but
  1149. also its combinations into a message, so providing more accurate statistic.
  1150. @subsection Classifying.
  1151. For classifying process @strong{winnow} algorithm is used. In this statistic
  1152. algtorithm we operate not with probabilities but with weights. Each token has
  1153. its own weight and when we learn some statfile with tokens rspamd does several
  1154. things:
  1155. @enumerate 1
  1156. @item Try to find token inside statfile.
  1157. @item If a token found multiply its weight by so called @strong{promotion
  1158. factor} (that is now 1.23).
  1159. @item If token not found insert it into statfile with weight 1.
  1160. @end enumerate
  1161. If it is needed to lower token weight, so its weight is multiplied with
  1162. @strong{demotion factor} (currently 0.83). Classify process is even more simple:
  1163. @enumerate 1
  1164. @item Extract tokens from a message.
  1165. @item For each statfile check weight of obtained tokens and store summary
  1166. weight.
  1167. @item Compare sums for each statfile and select statfile with the most big sum.
  1168. @item Do weight normalization and insert symbol of selected statfile.
  1169. @end enumerate
  1170. @subsection Statfiles synchronization.
  1171. Rspamd allows to make master/slave statfiles synchronization. This is done by
  1172. writing changes to statfiles to special @emph{binary log}. Binary log is a file
  1173. on filesystem named like statfile but with @emph{.binlog} suffix. Binary log
  1174. consist of two level indexes and binary changes to each statfile. So after each
  1175. learning process the version of affected statfiles is increased by 1 and a
  1176. record is written to binary log. Binary logs have fixed size limit and may have
  1177. time limit (rotate time). The process of synchronization may be described as:
  1178. @enumerate 1
  1179. @item Slave rspamd periodically asks master for version of statfiles monitored.
  1180. @item If master has version that is larger than slave's one the synchronization
  1181. process starts.
  1182. @item During synchronization process master looks at version reported by client
  1183. in binary log.
  1184. @item If version is found all records that are @strong{after} client's version
  1185. are sent to client.
  1186. @item Client accepts changes and apply binary patches one-by-one incrementing
  1187. statfile's version.
  1188. @item If version that client reports is not found in binary log the completely
  1189. statfile is sent to client (slow way, but practically that would take place only
  1190. once for fresh slaves).
  1191. @end enumerate
  1192. Here is example configuration for master statfile:
  1193. @example
  1194. <statfile>
  1195. <symbol>WINNOW_HAM</symbol>
  1196. <size>100M</size>
  1197. <path>/spool/rspamd/data.ham</path>
  1198. <normalizer>internal:3</normalizer>
  1199. <binlog>master</binlog>
  1200. <binlog_rotate>1d</binlog_rotate>
  1201. </statfile>
  1202. @end example
  1203. @noindent
  1204. Here we define binlog affinity (master) that automatically create binlog file
  1205. @file{/spool/rspamd/data.ham.binlog} and set up time limit for it (1 day).
  1206. For slaves you should first of all set up controller worker to accept network
  1207. connections (statfile synchronization is done via controller workers). The
  1208. second task is to define affinity for slave and master's address:
  1209. @example
  1210. <statfile>
  1211. <symbol>WINNOW_HAM</symbol>
  1212. <size>100M</size>
  1213. <path>/spool/rspamd/data.ham</path>
  1214. <normalizer>internal:3</normalizer>
  1215. <binlog>slave</binlog>
  1216. <binlog_master>spam10:11334</binlog_master>
  1217. </statfile>
  1218. @end example
  1219. @subsection Conclusion.
  1220. Statfiles synchronization allows to set up rspamd cluster that uses the common
  1221. statfiles and easily learn the whole cluster without unnecessary overhead.
  1222. @section Hashes and hash storage.
  1223. @subsection Fuzzy hashes.
  1224. Hashes that are used in rspamd for messages are not cryptoghraphic. Instead of
  1225. them fuzzy hashes are used. Fuzzy hashes is technics that allows to obtain
  1226. common hashes for common messages (for cryptographic hashes you usually get very
  1227. different hashes even if input messages are very common but not identical). The
  1228. main principle of fuzzy hashing is to break up text parts of message into small
  1229. pieces (blocks) and calculate hash for each block using so called @emph{rolling
  1230. hash}. After this process the final hash is forming by setting bytes in it from
  1231. blocks. So if we have 2 messages each of that contains 100 blocks and 99 of them
  1232. are identical we would have 2 hashes that differs only in one byte. So we can
  1233. consider that one message is 99% like other message.
  1234. @subsection Fuzzy storage.
  1235. In rspamd hashes can be stored in fuzzy storage. Fuzzy storage is a special
  1236. worker that can store hashes and reply about score of hashes. Inside fuzzy
  1237. storage each hash has its own weight and list number. List number is integer
  1238. that specify to which list this hash is related. This number can be used in
  1239. fuzzy_check plugin inside rspamd to add custom symbol. There are two ways of
  1240. storing fuzzy hashes: store them in a set of linear linked lists and storing
  1241. hashes in very fast judy tree. First way is good for a relatively small number
  1242. of fuzzy hashes. Also in this case @emph{fuzzy match} is used, so you can find
  1243. not only identical hashes but also common hashes. But for large number of hashes
  1244. this method is very slow. The second way requires libJudy in system (can be
  1245. found at @url{http://judy.sourceforge.net}) and turns off @emph{fuzzy matching}
  1246. - only identical hashes would be found. On the other hand you may store millions
  1247. of hashes in judy tree not loosing nor memory, nor CPU.
  1248. @subsection Conclusion.
  1249. Fuzzy hashes is efficient way to make up different black or white lists. Fuzzy
  1250. storage can be distributed over several machines (if you specify several storage
  1251. servers rspamd would select upstream by hash of fuzzy hash). Also storage can
  1252. contain several lists identified by number. Each hash has its own weight that
  1253. allows to set up dynamic rules that add different score from different hashes.
  1254. @chapter Rspamd modules.
  1255. @section Introduction.
  1256. This chapter describes modules that are shipped with rspamd. Here you can find
  1257. details about modules configuration, principles of working, tricks to make spam
  1258. filtering effective. First sections describe internal modules written in C:
  1259. regexp (regular expressions), surbl (black list for URLs), fuzzy_check (checks
  1260. for fuzzy hashes), chartable (check for character sets in messages) and emails
  1261. (check for blacklisted email addresses in messages). Modules configuration can
  1262. be done in lua or in config file itself.
  1263. @subsection Lua configuration.
  1264. You may use lua for setting configuration options for modules. With lua you can
  1265. write rather complex rules that can contain not only text lines, but also some
  1266. lua functions that would be called while processing messages. For loading lua
  1267. configuration you should add line to rspamd.xml:
  1268. @example
  1269. <lua src="/usr/local/etc/rspamd/lua/my.lua">fake</lua>
  1270. @end example
  1271. @noindent
  1272. It is possible to load several scripts this way. Inside lua file there would be
  1273. defined global table with name @var{config}. This table should contain
  1274. configuration options for modules indexed by module. This can be written this
  1275. way:
  1276. @example
  1277. config['module_name'] = @{@}
  1278. local mconfig = config['module_name']
  1279. mconfig['option_name'] = 'option value'
  1280. local a = 'aa'
  1281. local b = 'bb'
  1282. mconfig['other_option'] = string.format('%s, %s', a, b)
  1283. @end example
  1284. @noindent
  1285. In this simple example we defines new element of table that is associated with
  1286. module named 'module_name'. Then we assign to it an empty table (@code{@{@}})
  1287. and associate local variable mconfig. Then we set some elements of this table,
  1288. that is equialent to setting module options like that:
  1289. @example
  1290. option_name = option_value
  1291. other_option = aa, bb
  1292. @end example
  1293. @noindent
  1294. Also you may assign to elements of modules tables some functions. That functions
  1295. should accept one argument - worker task object and return result specific for
  1296. that option: number, string, boolean. This can be shown on this simple example:
  1297. @example
  1298. local function test (task)
  1299. if task:get_ip() == '127.0.0.1' then
  1300. return 1
  1301. else
  1302. return 0
  1303. end
  1304. end
  1305. mconfig['some_option'] = test
  1306. @end example
  1307. In this example we assign to module option 'some_option' a function that check
  1308. for message's ip and return 1 if that ip is '127.0.0.1'.
  1309. So using lua for configuration can help for making complex rules and for
  1310. structuring rules - you can place options for specific modules to specific files
  1311. and use lua function @code{dofile} for loading them (or add other @code{<lua>}
  1312. tag to rspamd.xml).
  1313. @subsection XML configuration.
  1314. Options for rspamd modules can be set up from xml file too. This can be used for
  1315. simple and/or temporary rules and should not be used for complex rules as this
  1316. would make xml file too hard to read and edit. Thought it is surely possible but
  1317. not recommended from points of config file understanding. Here is a simple
  1318. example of module config options:
  1319. @example
  1320. <module name="module_name">
  1321. <option name="option_name">option_value</option>
  1322. <option name="other_option">aa, bb</option>
  1323. </module>
  1324. @end example
  1325. @noindent
  1326. Note that you need to encode xml entitles like @code{&} - @code{&amp;} and so
  1327. on. Also only utf8 encoding is allowed. In sample rspamd configuration all
  1328. modules except regexp module are configured via xml as they have only settings
  1329. and regexp module has rules that are sometimes rather complex.
  1330. @section Regexp module.
  1331. @subsection Introduction.
  1332. Regexp module is one of the most important rspamd modules. Regexp module can
  1333. load regular expressions and filter messages according to them. Also it is
  1334. possible to use logical expressions of regexps to create complex rules of
  1335. filtering. It is allowed to use logical operators:
  1336. @itemize @bullet
  1337. @item & - logical @strong{AND} function
  1338. @item | - logical @strong{OR} function
  1339. @item ! - logical @strong{NOT} function
  1340. @end itemize
  1341. Also it is possible to use brackets for making priorities in expressions. Regexp
  1342. module operates with @emph{regexp items} that can be combined with logical
  1343. operators into logical @emph{regexp expresions}. Each expression is associated
  1344. with its symbol and if it evaluates to true with this message the symbol would
  1345. be inserted. Note that rspamd uses internal optimization of logical expressions
  1346. (for example if we have expression 'rule1 & rule2' rule2 would not be evaluated
  1347. if rule1 is false) and internal regexp cache (so if rule1 and rule2 have common
  1348. items they would be evaluated only once). So if you need speed optimization of
  1349. your rules you should take this fact into consideration.
  1350. @subsection Regular expressions.
  1351. Rspamd uses perl compatible regular expressions. You may read about perl regular
  1352. expression syntax here: @url{http://perldoc.perl.org/perlre.html}. In rspamd
  1353. regular expressions must be enclosed in slashes:
  1354. @example
  1355. /^\\d+$/
  1356. @end example
  1357. @noindent
  1358. If '/' symbol must be placed into regular expression it should be escaped:
  1359. @example
  1360. /^\\/\\w+$/
  1361. @end example
  1362. @noindent
  1363. After last slash it is possible to place regular expression modificators:
  1364. @multitable @columnfractions 0.1 0.9
  1365. @headitem Modificator @tab Mean
  1366. @item @strong{i} @tab Ignore case for this expression.
  1367. @item @strong{m} @tab Assume this expression as multiline.
  1368. @item @strong{s} @tab Assume @emph{.} as all characters including newline
  1369. characters (should be used with @strong{m} flag).
  1370. @item @strong{x} @tab Assume this expression as extended regexp.
  1371. @item @strong{u} @tab Performs ungreedy matches.
  1372. @item @strong{o} @tab Optimize regular expression.
  1373. @item @strong{r} @tab Assume this expression as @emph{raw} (this is actual for
  1374. utf8 mode of rspamd).
  1375. @item @strong{H} @tab Search expression in message's headers.
  1376. @item @strong{X} @tab Search expression in raw message's headers (without mime
  1377. decoding).
  1378. @item @strong{M} @tab Search expression in the whole message (must be used
  1379. carefully as @strong{the whole message} would be checked with this expression).
  1380. @item @strong{P} @tab Search expression in all text parts.
  1381. @item @strong{U} @tab Search expression in all urls.
  1382. @end multitable
  1383. You can combine flags with each other:
  1384. @example
  1385. /^some text$/iP
  1386. @end example
  1387. @noindent
  1388. All regexp must be with type: H, X, M, P or U as rspamd should know where to
  1389. search for specified pattern. Header regexps (H and X) have special syntax if
  1390. you need to check specific header, for example @emph{From} header:
  1391. @example
  1392. From=/^evil.*$/Hi
  1393. @end example
  1394. @noindent
  1395. If header name is not specified all headers would be matched. Raw headers is
  1396. matching is usefull for searching for mime specific headers like MIME-Version.
  1397. The problem is that gmime that is used for mime parsing adds some headers
  1398. implicitly, for example @emph{MIME-Version} and you should match them using raw
  1399. headers. Also if header's value is encoded (base64 or quoted-printable encoding)
  1400. you can search for decoded version using H modificator and for raw using X
  1401. modificator. This is usefull for finding bad encodings types or for unnecessary
  1402. encoding.
  1403. @subsection Internal function.
  1404. Rspamd provides several internal functions for simplifying message processing.
  1405. You can use internal function as items in logical expressions as they like
  1406. regular expressions return logical value (true or false). Here is list of
  1407. internal functions with their arguments:
  1408. @multitable @columnfractions 0.3 0.2 0.5
  1409. @headitem Function @tab Arguments @tab Description
  1410. @item header_exists
  1411. @tab header name
  1412. @tab Returns true if specified header exists.
  1413. @item compare_parts_distance
  1414. @tab number
  1415. @tab If message has two parts (text/plain and text/html) compare how much they
  1416. differs (html messages are compared with stripped tags). The difference is
  1417. number in percents (0 is identically parts and 100 is totally different parts).
  1418. So if difference is more than number this function returns true.
  1419. @item compare_transfer_encoding
  1420. @tab string
  1421. @tab Compares header Content-Transfer-Encoding with specified string.
  1422. @item content_type_compare_param
  1423. @tab param_name, param_value
  1424. @tab Compares specified parameter of Content-Type header with regexp or certain
  1425. string:
  1426. @example
  1427. content_type_compare_param(Charset, /windows-\d+/)
  1428. content_type_compare_param(Charset, ascii)
  1429. @end example
  1430. @noindent
  1431. @item content_type_has_param
  1432. @tab param_name
  1433. @tab Returns true if content-type has specified parameter.
  1434. @item content_type_is_subtype
  1435. @tab subtype_name
  1436. @tab Return true if content-type is of specified subtype (for example for
  1437. text/plain subtype is 'plain').
  1438. @item content_type_is_type
  1439. @tab type_name
  1440. @tab Return true if content-type is of specified type (for example for
  1441. text/plain subtype is 'text'):
  1442. @example
  1443. content_type_is_type(text)
  1444. content_type_is_subtype(/?.html/)
  1445. @end example
  1446. @noindent
  1447. @item regexp_match_number
  1448. @tab number,[regexps list]
  1449. @tab Returns true if specified number of regexps matches for this message. This
  1450. can be used for making rules when you do not know which regexps should match but
  1451. if 2 of them matches the symbol shoul be inserted. For example:
  1452. @example
  1453. regexp_match_number(2, /^some evil text.*$/Pi, From=/^hacker.*$/H, header_exists(Subject))
  1454. @end example
  1455. @noindent
  1456. @item has_only_html_part
  1457. @tab nothing
  1458. @tab Returns true when message has only HTML part
  1459. @item compare_recipients_distance
  1460. @tab number
  1461. @tab Like compare_parts_distance calculate difference between recipients. Number
  1462. is used as minimum percent of difference. Note that this function would check
  1463. distance only when there are more than 5 recipients in message.
  1464. @item is_recipients_sorted
  1465. @tab nothing
  1466. @tab Returns true if recipients list is sorted. This function would also works
  1467. for more than 5 recipients.
  1468. @item is_html_balanced
  1469. @tab nothing
  1470. @tab Returns true when all HTML tags in message are balanced.
  1471. @item has_html_tag
  1472. @tab tag_name
  1473. @tab Returns true if tag 'tag_name' exists in message.
  1474. @item check_smtp_data
  1475. @tab item, regexp
  1476. @tab Returns true if specified part of smtp dialog matches specified regexp. Can
  1477. check HELO, FROM and RCPT items.
  1478. @end multitable
  1479. These internal functions can be easily implemented in lua but I've decided to
  1480. make them built-in as they are widely used in our rules. In fact this list may
  1481. be extended in future.
  1482. @subsection Dynamic rules.
  1483. Rspamd regexp module can use dynamic rules that can be written in json syntax.
  1484. Dynamic rules are loaded at runtime and can be modified while rspamd is working.
  1485. Also it is possible to turn dynamic rules for specific networks only and add rules
  1486. that does not contain any regexp (this can be usefull for dynamic lists for example).
  1487. Dynamic rules can be obtained like any other dynamic map via file monitoring or via
  1488. http. Here are examples of dynamic rules definitions:
  1489. @example
  1490. <module name="regexp">
  1491. <option name="dynamic_rules">file:///tmp/rules.json</option>
  1492. </module>
  1493. @end example
  1494. @noindent
  1495. or for http map:
  1496. @example
  1497. <module name="regexp">
  1498. <option name="dynamic_rules">http://somehost/rules.json</option>
  1499. </module>
  1500. @end example
  1501. @noindent
  1502. Rules are presented as json array (in brackets @emph{'[]'}). Each rule is json object.
  1503. This object can have several properties (properties with @strong{*} are required):
  1504. @multitable @columnfractions 0.3 0.7
  1505. @headitem Property @tab Mean
  1506. @item symbol(*)
  1507. @tab Symbol for rule.
  1508. @item factor(*)
  1509. @tab Factor for rule.
  1510. @item rule
  1511. @tab Rule itself (regexp expression).
  1512. @item enabled
  1513. @tab Boolean flag that define whether this rule is enabled (rule is enabled if
  1514. this flag is not present by default).
  1515. @item networks
  1516. @tab Json array of networks (in CIDR format, also it is possible to add negation
  1517. by prepending @emph{!} symbol before item.
  1518. @end multitable
  1519. Here is an example of dynamic rule:
  1520. @example
  1521. [
  1522. {
  1523. "rule": "/test/rP",
  1524. "symbol": "R_TMP_1",
  1525. "factor": 1.1,
  1526. "networks": ["!192.168.1.0/24", "172.16.0.0/16"],
  1527. "enabled": false
  1528. }
  1529. ]
  1530. @end example
  1531. Note that dynamic rules are constantly monitored for changes and are reloaded
  1532. completely when modification is detected. If you change dynamic rules they
  1533. would be reloaded in a minute and would be applied for new messages.
  1534. @subsection Conclusion.
  1535. Rspamd regexp module is powerfull tool for matching different patterns in
  1536. messages. You may use logical expressions of regexps and internal rspamd
  1537. functions to make rules. Rspamd is shipped with many rules for regexp module
  1538. (most of them are taken from spamassassin rules as rspamd originally was a
  1539. replacement of spamassassin) so you can look at them in ETCDIR/rspamd/lua/regexp
  1540. directory. There are many built-in rules with detailed comments. Also note that
  1541. if you add logical rule into XML file you need to escape all XML entitles (like
  1542. @emph{&} operators). When you make complex rules from many parts do not forget
  1543. to add brackets for parts inside expression as you would not predict order of
  1544. checks otherwise. Rspamd regexp module has internal logical optimization and
  1545. regexp cache, so you may use identical regexp many times - they would be matched
  1546. only once. And in logical expression you may optimize performance by putting
  1547. likely TRUE regexp first in @emph{OR} expression and likely FALSE expression
  1548. first in @emph{AND} expression. A number of internal functions can simplify
  1549. complex expressions and for making common filters. Lua functions can be added in
  1550. rules as well (they should return boolean value).
  1551. @section SURBL module.
  1552. Surbl module is designed for checking urls via blacklists. You may read about
  1553. surbls at @url{http://www.surbl.org}. Here is the sequence of operations that is
  1554. done by surbl module:
  1555. @enumerate 1
  1556. @item Extract all urls in message and get domains for each url.
  1557. @item Check to special list called '2tld' and extract 3 components for domains
  1558. from that list and 2 components for domains that are not listed:
  1559. @example
  1560. http://virtual.somehost.domain.com/some_path
  1561. -> somehost.domain.com if domain.com is in 2tld list
  1562. -> domain.com if not in 2tld
  1563. @end example
  1564. @noindent
  1565. @item Remove duplicates from domain lists
  1566. @item For each registered surbl do dns request in form @emph{domain.surbl_name}
  1567. @item Get result and insert symbol if that name resolves
  1568. @item It is possible to examine bits in returned IP address and insert different
  1569. symbol for each bit that is turned on in result.
  1570. @end enumerate
  1571. All DNS requests are done asynchronously so you may not bother about blocking.
  1572. SURBL module has several configuration options:
  1573. @itemize @bullet
  1574. @item @emph{metric} - metric to insert symbol to.
  1575. @item @emph{2tld} - list argument of domains for those 3 components of domain name
  1576. would be extracted.
  1577. @item @emph{max_urls} - maximum number of urls to check.
  1578. @item @emph{whitelist} - map of domains for which surbl checks would not be performed.
  1579. @item @emph{suffix} - a name of surbl. It is possible to add several suffixes:
  1580. @example
  1581. suffix_RAMBLER_URIBL = insecure-bl.rambler.ru
  1582. or in xml:
  1583. <param name="suffix_RAMBLER_URIBL">insecure-bl.rambler.ru</param>
  1584. @end example
  1585. @noindent
  1586. It is possible to add %b to symbol name for checking specific bits:
  1587. @example
  1588. suffix_%b_SURBL_MULTI = multi.surbl.org
  1589. then you may define replaces for %b in symbol name for each bit in result:
  1590. bit_2 = SC -> sc.surbl.org
  1591. bit_4 = WS -> ws.surbl.org
  1592. bit_8 = PH -> ph.surbl.org
  1593. bit_16 = OB -> ob.surbl.org
  1594. bit_32 = AB -> ab.surbl.org
  1595. bit_64 = JP -> jp.surbl.org
  1596. @end example
  1597. @noindent
  1598. So we make one DNS request and check for specific list by checking bits in
  1599. result ip. This is described in surbl page:
  1600. @url{http://www.surbl.org/lists.html#multi}. Note that result symbol would NOT
  1601. contain %b as it would be replaced by bit name. Also if several bits are set
  1602. several corresponding symbols would be added.
  1603. @end itemize
  1604. Also surbl module can use redirector - a special daemon that can check for
  1605. redirects. It uses HTTP/1.0 for requests and accepts a url and returns resolved
  1606. result. Redirector is shipped with rspamd but not enabled by default. You may
  1607. enable it on stage of configuring but note that it requires many perl modules
  1608. for its work. Rspamd redirector is described in details further. Here are surbl
  1609. options for working with redirector:
  1610. @itemize @bullet
  1611. @item @emph{redirector}: adress of redirector (in format host:port)
  1612. @item @emph{redirector_connect_timeout} (seconds): redirector connect timeout (default: 1s)
  1613. @item @emph{redirector_read_timeout} (seconds): timeout for reading data (default: 5s)
  1614. @item @emph{redirector_hosts_map} (map string): map that contains domains to check with redirector
  1615. @end itemize
  1616. So surbl module is an easy to use way to check message's urls and it may be used
  1617. in every configuration as it filters rather big ammount of email spam and scam.
  1618. @section SPF module.
  1619. SPF module is designed to make checks of spf records of sender's domains. SPF
  1620. records are placed in TXT DNS items for domains that have enabled spf. You may
  1621. read about SPF at @url{http://en.wikipedia.org/wiki/Sender_Policy_Framework}.
  1622. There are 3 results of spf check for domain:
  1623. @itemize @bullet
  1624. @item ALLOW - this ip is allowed to send messages for this domain
  1625. @item FAIL - this ip is @strong{not} allowed to send messages for this domain
  1626. @item SOFTFAIL - it is unknown whether this ip is allowed to send mail for this
  1627. domain
  1628. @end itemize
  1629. SPF supports different mechanizms for checking: dns subrequests, macroses,
  1630. includes, blacklists. Rspamd supports the most of them. Also for security
  1631. reasons there is internal limits for DNS subrequests and inclusions recursion.
  1632. SPF module support very small ammount of options:
  1633. @itemize @bullet
  1634. @item @emph{metric} (string): metric to insert symbol (default: 'default')
  1635. @item @emph{symbol_allow} (string): symbol to insert (default: 'R_SPF_ALLOW')
  1636. @item @emph{symbol_fail} (string): symbol to insert (default: 'R_SPF_FAIL')
  1637. @item @emph{symbol_softfail} (string): symbol to insert (default: 'R_SPF_SOFTFAIL')
  1638. @end itemize
  1639. @section Chartable module.
  1640. Chartable is a simple module that detects different charsets in a message. This
  1641. module is aimed to protect from emails that contains symbols from different
  1642. character sets that looks like each other. Chartable module works differently
  1643. for raw and utf modes: in utf modes it detects different characters from unicode
  1644. tables and in raw modes only ASCII and non-ASCII symbols. Configuration of whis
  1645. module is very simple:
  1646. @itemize @bullet
  1647. @item @emph{metric} (string): metric to insert symbol (default: 'default')
  1648. @item @emph{symbol} (string): symbol to insert (default: 'R_BAD_CHARSET')
  1649. @item @emph{threshold} (double): value that would be used as threshold in expression
  1650. @math{N_{charset-changes} / N_{chars}}
  1651. (e.g. if threshold is 0.1 than charset change should occure more often than in 10 symbols),
  1652. default: 0.1
  1653. @end itemize
  1654. @section Fuzzy check module.
  1655. Fuzzy check module provides a client for rspamd fuzzy storage. Fuzzy check can
  1656. work with a cluster of rspamd fuzzy storages and the specific storage is
  1657. selected by value of hash of message's hash. The available configuration options
  1658. are:
  1659. @itemize @bullet
  1660. @item @emph{metric} (string): metric to insert symbol (default: 'default')
  1661. @item @emph{symbol} (string): symbol to insert (default: 'R_FUZZY')
  1662. @item @emph{max_score} (double): maximum score to that weights of hashes would be
  1663. normalized (default: 0 - no normalization)
  1664. @item @emph{fuzzy_map} (string): a string that contains map in format @{ fuzzy_key => [
  1665. symbol, weight ] @} where fuzzy_key is number of fuzzy list. This string itself
  1666. should be in format 1:R_FUZZY_SAMPLE1:10,2:R_FUZZY_SAMPLE2:1 etc, where first
  1667. number is fuzzy key, second is symbol to insert and third - weight for
  1668. normalization
  1669. @item @emph{min_length} (integer): minimum length (in characters) for text part to be
  1670. checked for fuzzy hash (default: 0 - no limit)
  1671. @item @emph{whitelist} (map string): map of ip addresses that should not be checked
  1672. with this module
  1673. @item @emph{servers} (string): list of fuzzy servers in format
  1674. "server1:port,server2:port" - these servers would be used for checking and
  1675. storing fuzzy hashes
  1676. @end itemize
  1677. @section Forged recipients.
  1678. Forged recipients is a lua module that compares recipients provided by smtp
  1679. dialog and recipients from @emph{To:} header. Also it is possible to compare
  1680. @emph{From:} header with SMTP from. So you may set @strong{symbol_rcpt} option
  1681. to set up symbol that would be inserted when recipients differs and
  1682. @strong{symbol_sender} when senders differs.
  1683. @section Maillist.
  1684. Maillist is a module that detects whether this message is send by using one of
  1685. popular mailing list systems (among supported are ezmlm, mailman and
  1686. subscribe.ru systems). The module has only option @strong{symbol} that defines a
  1687. symbol that would be inserted if this message is sent via mailing list.
  1688. @section Once received.
  1689. This lua module checks received headers of message and insert symbol if only one
  1690. received header is presented in message (that usually signals that this mail is
  1691. sent directly to our MTA). Also it is possible to insert @emph{strict} symbol
  1692. that indicates that host from which we receive this message is either
  1693. unresolveable or has bad patterns (like 'dynamic', 'broadband' etc) that
  1694. indicates widely used botnets. Configuration options are:
  1695. @itemize @bullet
  1696. @item @emph{symbol}: symbol to insert for messages with one received header.
  1697. @item @emph{symbol_strict}: symbol to insert for messages with one received
  1698. header and containing bad patterns or unresolveable sender.
  1699. @item @emph{bad_host}: defines pattern that would be count as "bad".
  1700. @item @emph{good_host}: defines pattern that would be count as "good" (no strict
  1701. symbol would be inserted), note that "good" has a priority over "bad" pattern.
  1702. @end itemize
  1703. You can define several "good" and "bad" patterns for this module.
  1704. @section Received rbl.
  1705. Received rbl module checks for all received headers and make dns requests to IP
  1706. black lists. This can be used for checking whether this email was transfered by
  1707. some blacklisted gateway. Here are options available:
  1708. @itemize @bullet
  1709. @item @emph{symbol}: symbol to insert if message contains blacklisted received
  1710. headers
  1711. @item @emph{rbl}: a name of rbl to check, it is possible to define specific
  1712. symbol for this rbl by adding symbol name after semicolon:
  1713. @example
  1714. rbl = pbl.spamhaus.org:RECEIVED_PBL
  1715. @end example
  1716. @end itemize
  1717. @section Conclusion.
  1718. Rspamd is shipped with some ammount of modules that provides basic functionality
  1719. fro checking emails. You are allowed to add custom rules for regexp module and
  1720. to set up available parameters for other modules. Also you may write your own
  1721. modules (in C or Lua) but this would be described further in this documentation.
  1722. You may set configuration options for modules from lua or from xml depends on
  1723. its complexity. Internal modules are enabled and disabled by @strong{filters}
  1724. configuration option. Lua modules are loaded and usually can be disabled by
  1725. removing their configuration section from xml file or by removing corresponding
  1726. line from @strong{modules} section.
  1727. @bye