blib/lib/Mail/SpamAssassin/Contrib/Plugin/IPFilter.pm untested

filter: Statementstmt 0.0% 0 / 907 Branchbran 0.0% 0 / 464 Conditioncond 0.0% 0 / 498 MC/DCmcdc 0.0% 0 / 272 Subroutinesub 0.0% 0 / 82 Podpod 0.0% 0 / 57 totaltotal 0.0% 0 / 2280 CC 233 SCAR 70.2
CC
233
Cov
0%
check_end
3782.0
finish_parsing_end
2352.0
dbconnect
110.0
CRAP 1116.5
1 package Mail::SpamAssassin::Contrib::Plugin::IPFilter;
2  
3 # ABSTRACT: Blocks bad MTA behavior using IPTables.
4  
5 # <@LICENSE>
6 #
7 # Copyright 2016 Tamer Rizk, Inficron Inc. <foss[at]inficron.com>
8 # All rights reserved
9 #
10 # Redistribution and use in source and binary forms, with or without
11 # modification, are permitted provided that the following conditions are
12 # met:
13 #
14 # * Redistributions of source code must retain the above copyright
15 # notice, this list of conditions and the following disclaimer.
16 #
17 # * Redistributions in binary form must reproduce the above copyright
18 # notice, this list of conditions and the following disclaimer in the
19 # documentation and/or other materials provided with the distribution.
20 #
21 # * Neither the name of Tamer Rizk, Inficron Inc, nor the names of its
22 # contributors may be used to endorse or promote products derived from
23 # this software without specific prior written permission.
24 #
25 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
26 # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
27 # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
28 # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
29 # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
30 # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
31 # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
32 # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
34 # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
35 # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 #
37 # </@LICENSE>
38  
39 # Author: Tamer Rizk <foss[at]inficron.com>
40  
41  
42 use strict;
43 use Cwd;
44 use DBI;
45 use Redis;
46 use Date::Parse;
47 use JSON::XS;
48 use Mail::SpamAssassin;
49 use MIME::Lite;
50 use Sys::SigAction qw( timeout_call );
51 use MIME::Base64 qw(encode_base64 decode_base64);
52 use Math::Round qw(nearest round);
53 use Hash::Util qw(lock_hashref);
54 use Fcntl qw(:flock SEEK_END SEEK_SET);
55 use POSIX qw(strftime);
56 use IPTables::ChainMgr;
57 use Config::Crontab;
58 use Text::Document;
59 use Lingua::StopWords qw( getStopWords );
60 use Storable qw(freeze thaw);
61  
62 #use Data::Dumper;
63 use vars qw($VERSION @ISA);
64 my ($Verbose, %Regex, $Logfile, %Cronjobs);
65 $Verbose = 1;
66  
67 $VERSION = 1.2;
68  
69 #stub
70 sub p2p {
71 #Roughly: After some history of a user trading messages with another user, that network becomes a candidate. Agree to share blocklist on new well known port for this service if both consider each other candidates. A number of those agreeing on any given block, append the entry to local as an unsharable entry. Limit network user density from effecting operation. Extend to other firewalls/platforms.
72 }
73  
74 sub inform {
75 return if ($Verbose != 1);
76 sub_exists('info') ? info('IPFilter: '.$_[0]) : warn('IPFilter: '.$_[0]);
77 }
78  
79 sub error {
80 info('IPFilter: '.$_[0]) if(sub_exists('info'));
81 warn('IPFilter: '.$_[0]);
82 return 0;
83 }
84  
85 sub fatal {
86 error($_[0]);
87 exit;
88 }
89  
90 sub find_bin {
91 my $path;
92 foreach $path (@{['/bin','/sbin','/usr/bin','/usr/sbin','/usr/local/bin','/usr/local/sbin']}){
93 return $path.'/'.$_[0] if (-e $path.'/'.$_[0]);
94 }
95 }
96  
97 sub sub_exists {
98 no strict 'refs';
99 return defined &{$_[0]} ? 1 : 0;
100 }
101  
102 $dbconnect_mysql::name = 'dbconnect_mysql';
103  
104 sub dbconnect{
105 my ($db,$conf);
106 $conf = shift;
107 if($conf->{db_type} eq 'redis'){
108 $conf->{db_port} = 6379 if(1>int($conf->{db_port}));
109 $db = length($conf->{db_auth})>0 ? Redis->new(server => $conf->{db_host}.':'.$conf->{db_port}, password => $conf->{db_auth}) : Redis->new(server => $conf->{db_host}.':'.$conf->{db_port});
110 fatal('Could not establish connection to redis') if (!$db->ping);
111 }elsif($conf->{db_type} eq 'mysql'){
112  
113 fatal('Could not establish connection to mysql:'. $DBI::errstr) if (!($db = DBI->connect('DBI:mysql::'.(0<int($conf->{db_port})?'@'.$conf->{db_host}.':'.$conf->{db_port}:'localhost'), $conf->{db_user}, $conf->{db_auth}, {PrintError => 1})));
114  
115 $db->{PrintError} = 0;
116 ($db->do('create database if not exists '.$conf->{db_name}) && $db->do('use '.$conf->{db_name})) if (!$db->do('use '.$conf->{db_name}));
117 $db->do('create table if not exists `'.$conf->{db_name}.'`.`ent` (k varchar(128) NOT NULL,v TEXT NOT NULL,modified timestamp NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP, PRIMARY KEY (k(128))) ENGINE=InnoDB DEFAULT CHARSET=utf8') if(!$db->do('select 1 from '.$conf->{db_name}.'.ent limit 1'));
118 $db->{PrintError} = 1;
119 $db = sub { my $self = { db => $db }; bless $self, *dbconnect_mysql; return $self; }->();
120 }
121 return $db;
122 }
123  
124 sub Mail::SpamAssassin::Contrib::Plugin::IPFilter::dbconnect_mysql::exists {
125 my ($h,$r,$db);
126 $db = (shift)->{db};
127 $h = $db->prepare(sprintf('select k from ent where k=%s limit 1', length($_[0]) >0 ? $db->quote($_[0]) : "''"));
128 $h->execute();
129 $r = $h->fetchrow_hashref('NAME_lc');
130 $h->finish();
131 return ((defined $r) && $r && (exists $r->{k})) ? 1 : 0;
132 };
133  
134 sub Mail::SpamAssassin::Contrib::Plugin::IPFilter::dbconnect_mysql::get {
135 my ($h,$r,$db);
136 $db = (shift)->{db};
137 #$k =~ tr/\x00-\x09\x0b\x0c\x0e-\x1f//d;
138 $h = $db->prepare(sprintf('select v from ent where k=%s limit 1', length($_[0]) >0 ? $db->quote($_[0]) : "''"));
139 $h->execute();
140 $r = $h->fetchrow_hashref('NAME_lc');
141 $h->finish();
142 return ((defined $r) && $r && (defined $r->{v})) ? $r->{v} : '';
143 };
144  
145 sub Mail::SpamAssassin::Contrib::Plugin::IPFilter::dbconnect_mysql::set {
146 my ($v,$r,$db);
147 $db = (shift)->{db};
148 $v = length($_[1]) >0 ? $db->quote($_[1]) : "''";
149 $db->do(sprintf('insert into ent (k, v) values (%s, %s) on duplicate key update v=%s', length($_[0]) >0 ? $db->quote($_[0]) : "''", $v, $v));
150 };
151  
152 sub Mail::SpamAssassin::Contrib::Plugin::IPFilter::dbconnect_mysql::mget {
153 my ($h,@k,@o,$db);
154 $db = (shift)->{db};
155 @o = ();
156 map{ push @k, (length($_) >0 ? $db->quote($_) : "''") } @_;
157 return @o if(@k==0);
158 $h = $db->prepare('select v from ent where k in ('.join(', ',@k).') order by field(k, '.join(', ',@k).') limit '.int(@k+0));
159 $h->execute();
160 map { push @o, $_->{v} } @{$h->fetchall_arrayref({})};
161 $h->finish();
162 return @o;
163 };
164  
165 sub Mail::SpamAssassin::Contrib::Plugin::IPFilter::dbconnect_mysql::keys {
166 my ($h,$db,@o,$v);
167 $db = (shift)->{db};
168 @o = ();
169 $v=shift;
170 $v=~s/\*/\%/g;
171 $h = $db->prepare(sprintf('select k from ent where k like %s limit 256000',length($v) >0 ? $db->quote($v) : "''"));
172 $h->execute();
173 map { push @o, $_->{k} } @{$h->fetchall_arrayref({})};
174 $h->finish();
175 return @o;
176 };
177  
178 sub Mail::SpamAssassin::Contrib::Plugin::IPFilter::dbconnect_mysql::del {
179 my $db = (shift)->{db};
180 $db->do(sprintf('delete from ent where k=%s limit 1', length($_[0]) >0 ? $db->quote($_[0]) : "''"));
181 };
182  
183 sub Mail::SpamAssassin::Contrib::Plugin::IPFilter::dbconnect_mysql::quit {
184 my $db = (shift)->{db};
185 $db->disconnect if($db);
186 }
187  
188 sub Mail::SpamAssassin::Contrib::Plugin::IPFilter::dbconnect_mysql::AUTOLOAD {
189 my ($self, @args, $name);
190 $name = $dbconnect_mysql::AUTOLOAD;
191 ($self, @args) = @_;
192 return 0;
193 }
194  
195 sub Mail::SpamAssassin::Contrib::Plugin::IPFilter::dbconnect_mysql::DESTROY {
196 my $db = (shift)->{db};
197 $db->disconnect if($db);
198 }
199  
200 sub c_param {
201 fatal('[c_params]: missing conf') if (!$_[0]);
202 my $conf = JSON::XS->new->utf8->decode(decode_base64($_[0]));
203 fatal('[c_params]: Invalid number of params '.join(',', keys %{$conf})) if (int(split('\x7C', sprintf('%s',$Regex{param}))) > int(keys %{$conf}));
204  
205 re_config($conf);
206 $conf->{re} = \%Regex;
207 return $conf;
208 }
209  
210 sub c_logfile {
211 fatal('[c_logfile] Could not find log dir '.$_[0]->{log_dir}) if (!$_[0]->{log_dir} || !-d $_[0]->{log_dir});
212 $Logfile = $_[0]->{log_dir}.'/spamipfilter_'.strftime('%d-%m-%Y', localtime);
213 if(!-e $Logfile){
214 lock($Logfile);
215 fatal('[c_logfile] Could not create log file '.$Logfile) if(!open(IPFILTERLOGSTATS, '+>>'.$Logfile));
216 close(IPFILTERLOGSTATS);
217 chmod(0600, $Logfile);
218 chown(int($1),-1, $Logfile) if ($_[0]->{username} && getpwnam($_[0]->{username})=~/^([0-9]+)$/);
219 }
220 }
221  
222 sub c_ipfilter_update {
223  
224 my ($conf, @buffer, $db, $expires, $iptables, $sa);
225  
226 $expires = time();
227 $conf = c_param(shift);
228  
229 $sa = Mail::SpamAssassin->new($conf);
230  
231 @buffer = iptables_cmd('-L '.$conf->{filter_name}.' -n -v -x', $conf);
232 $iptables = join('', @{$buffer[1]}) if(@buffer && defined $buffer[1] && @{$buffer[1]});
233  
234 $db = dbconnect($conf);
235 if($conf->{admin_email}){
236 @buffer = localtime();
237 clean_notifications($db, {conf => $conf}) if ($buffer[6]==6 && $buffer[2]==2);
238 notify_blacklist($db, {conf => $conf});
239 }
240 refresh_iptables($db, {conf => $conf, iptables => $iptables});
241 refresh_list($db, {conf => $conf, mailsa => $sa});
242 $db->quit;
243  
244 map{ (@buffer = $_ =~ $conf->{re}->{expires}) && ($buffer[0]) && ($buffer[0]=sanitize($buffer[0], $conf->{re}->{ipn}, '198.51.100.0')) && $expires > int($buffer[1]) && iptables_cmd('-t filter -D '.$conf->{filter_name}.' -i eth+ -s '.$buffer[0].' -p tcp -m multiport --dports 25,587,110,143,465,993,995 -j REJECT -m comment --comment \'expires='.int($buffer[1]).'\'', $conf) && iptables_cmd('-t filter -D '.$conf->{filter_name}.' -i eth+ -s '. ip6tables_normalize((index($buffer[0],'/')==-1?expand_ipv6($buffer[0]):expand_ipv6( shift @{[split('/',$buffer[0])]} ).'/'.cidr_16( pop @{[split('/',$buffer[0])]} )), $conf) .' -p tcp -m multiport --dports 25,587,110,143,465,993,995 -j REJECT -m comment --comment \'expires='.int($buffer[1]).'\'', $conf, 6) } split("\n", $iptables);
245  
246 exit;
247 }
248  
249 sub c_maintenance {
250  
251 my ($conf, $db);
252 $conf = c_param(shift);
253 $db = dbconnect($conf);
254 op_rkeys('-*', \&cache_decay_op, $db, { conf => $conf, cache_decay_secs => $conf->{cache_decay_days}*86400, trigger_messages => $conf->{trigger_messages}+0, average_score_for_rule => $conf->{average_score_for_rule}+0 });
255 $db->quit;
256 exit;
257 }
258  
259 sub c_log_format {
260  
261 my (@data, $conf);
262 $conf = c_param(shift);
263  
264 fatal('[c_log_format] Could not read log dir: '.$conf->{log_dir}) if (!$conf->{log_dir} || !-d $conf->{log_dir});
265  
266 $data[0] = 0;
267 if(opendir(IPFILTERLOGDIR, $conf->{log_dir})){
268 map{ $_ =~ /spamipfilter\_([0-9]+)\-([0-9]+)\-(2[0-9][0-9][0-9])/i && ($data[1]=int(str2time($2.'/'.$1.'/'.$3))) && ($data[0]<$data[1]) && ($data[0]=$data[1]) && ($Logfile=$conf->{log_dir}.'/'.$_) } readdir IPFILTERLOGDIR;
269 closedir(IPFILTERLOGDIR);
270 }
271 inform('[c_log_format] '.$Logfile);
272 if($Logfile && -e $Logfile && index($Logfile, $conf->{log_dir}.'/spamipfilter')==0 && index(substr($Logfile,0,len($Logfile)+1),'/')==-1){
273 lock($Logfile);
274 rename($Logfile, $conf->{log_dir}.'/.'. pop @{[split('/', $Logfile)]});
275 }
276 c_logfile($conf);
277  
278 exit;
279 }
280  
281 sub c_log_piwik {
282 my (@data, $conf);
283  
284 $conf = c_param(shift);
285 fatal('[c_log_piwik] Could not find piwik host or path: '.$conf->{piwik_host}.' '.$conf->{piwik_path}) if (!$conf->{piwik_host} || !$conf->{piwik_path} || !-d $conf->{piwik_path} || !$conf->{log_dir});
286  
287 if(opendir(IPFILTERLOGDIR, $conf->{log_dir})){
288 @data = grep /\.spamipfilter\_[0-9]+\-[0-9]+\-2[0-9][0-9][0-9]$/i, readdir IPFILTERLOGDIR;
289 closedir(IPFILTERLOGDIR);
290 }
291 exit if (@data<1 || !find_bin('python'));
292 map{system(find_bin('python').' '.$conf->{piwik_path}.'/misc/log-analytics/import_logs.py -d --url=\''.$conf->{piwik_host}.'\' --idsite='.$conf->{piwik_idsite}.' --recorders=4 --enable-http-errors --enable-http-redirects --enable-static --enable-bots '.$conf->{log_dir}.'/'.$_.' >> '.$conf->{log_dir}.'/import_logs.py.'.strftime('%m-%Y', localtime).'.log 2>&1')==0 && index($_, '.spamipfilter')==0 && index($_, '/')==-1 && unlink($conf->{log_dir}.'/'.$_)} @data;
293 exit;
294 }
295  
296 sub log_stats {
297 return if(!$Logfile);
298 my $s = shift;
299  
300 {
301 lock($Logfile);
302 if (!-e $Logfile){
303 $Logfile = substr($Logfile,0,rindex($Logfile,'/')+1).'spamipfilter_'.strftime('%d-%m-%Y', localtime);
304 select(undef, undef, undef, int(rand(24) + 8)/128);
305 lock($Logfile);
306 return if(!-e $Logfile);
307 close(IPFILTERLOGSTATS) if(defined fileno(IPFILTERLOGSTATS));
308 return if(!open(IPFILTERLOGSTATS, '>>'.$Logfile));
309 }
310 return if(!defined fileno(IPFILTERLOGSTATS) && !open(IPFILTERLOGSTATS, '>>'.$Logfile));
311 }
312  
313 timeout_call( 10 ,sub {
314 return if(!flock(IPFILTERLOGSTATS, LOCK_EX) || !seek(IPFILTERLOGSTATS, 0, SEEK_END));
315 print IPFILTERLOGSTATS $s."\n";
316 error('[log_stats] Could not unlock log file '.$Logfile) if(!flock(IPFILTERLOGSTATS, LOCK_UN));
317 });
318  
319 }
320  
321 sub finish {
322 close(IPFILTERLOGSTATS) if(defined fileno(IPFILTERLOGSTATS));
323 close(IPTABLESLOCKFILE) if(defined fileno(IPTABLESLOCKFILE));
324 close(IPFILTERCACHELOCK) if(defined fileno(IPFILTERCACHELOCK));
325 }
326  
327 # Thanks to the authors of Net::IP: Manuel Valente, Monica Cortes Sack,
328 # and Lee Wilmot for the implementation concepts behind expand_ipv6()
329 sub expand_ipv6 {
330 my ($a, $b, $c, $i, @d, @ip, $addr);
331 $addr = shift;
332  
333 $addr =~ s/::/: :/g;
334 @ip = split('\:', $addr);
335  
336 $c = $a = int(@ip + 0);
337 for($i=-1;++$i<$a;){
338 if(index($ip[$i], '.')!=-1){
339 $b = unpack('B32', pack('C4C4C4C4', split('\.', $ip[$i])));
340 $ip[$i] = substr(join(':', unpack('H4H4H4H4H4H4H4H4', pack('B128', '0' x (128 - length($b)) . $b))), -9);
341 ++$c;
342 next;
343 }
344 $ip[$i] = ('0' x (4 - length($ip[$i]))) . $ip[$i];
345 }
346  
347 @d = ('0000','0000','0000','0000','0000','0000','0000','0000');
348  
349 return (index($addr,'.')!=-1?'0:0:0:0:0:ffff:':'').join(':', (map{ $_ eq '000 ' ? join(':', @d[0 .. (8 - $c)]) : lc($_) } @ip));
350 }
351  
352 sub cidr_2 {
353 my (@octet, $ipv6, $cidr);
354 (@octet, $ipv6) = @_;
355 $cidr = $ipv6 ? 128 : 32;
356 while(0!=($octet[0] ^ $octet[1])){
357 $octet[0] = $octet[0] >> 1;
358 $octet[1] = $octet[1] >> 1;
359 --$cidr;
360 }
361 return $cidr;
362 }
363  
364 sub cidr_16 {
365 return ($_[0]>-1 && $_[0]<33) ? (128-(32-$_[0])) : 128;
366 }
367  
368 sub network_octet {
369 # (octet, cidr) = @_
370 return $_[2] ? sprintf('%02x', hex($_[0]) & (256 - (1<<(128-$_[1])))) : $_[0] & (256 - (1<<(32-$_[1])));
371 }
372  
373 sub consolidate_network {
374 my (%var, $cidr, $pre, $conf, $db, $params);
375 ($db, $params) = @_;
376  
377 $conf = $params->{conf};
378  
379 $pre = $params->{ip}.$params->{host};
380 $params->{cidr} = 32;
381 $var{$pre} = int($params->{host});
382 if($params->{ipv6}){
383 $params->{cidr} = 128;
384 $var{$pre} = hex($params->{host});
385 }
386  
387 map{$_=~$conf->{re}->{ipfromkey} && ($var{$1.$2} = ($params->{ipv6}) ? hex($2):int($2))} @{[$db->keys($conf->{db_name}.'-'.$params->{ip}.'*')]};
388 $cidr = int( cidr_2( @var{@{[sort { $var{$a} <=> $var{$b} } keys(%var)]}[0,-1]}, $params->{ipv6} ));
389 $params->{host} = network_octet($params->{host}, $cidr, $params->{ipv6});
390 $params->{network} = int($db->get($conf->{db_name}.';network-'.$params->{ip}.$params->{host}) || $params->{cidr});
391  
392 #an edge case may exist due to concurrency where multiple IPs within the same network overwrite one another
393 if($cidr < $params->{cidr}){
394  
395 $pre = $params->{ip}.$params->{host};
396  
397 if($cidr < $params->{network}){
398 %var = (def => {%{$params->{def_var}}, expires => 0});
399 map{ $var{def} = { avg => 0<($var{def}->{avg}+0.0) ? ($var{def}->{avg} + $_->{avg})/2 : $_->{avg}, total => $var{def}->{total} + $_->{total}, spamhits => $var{def}->{spamhits} + $_->{spamhits}, lastspam => int($var{def}->{lastspam})>int($_->{lastspam}) ? $var{def}->{lastspam} : $_->{lastspam}, expires => int($var{def}->{expires})>int($_->{expires}) ? $var{def}->{expires} : $_->{expires} } } @{[ op_rkeys('-'.$params->{ip}.'*', \&consolidate_network_op, $db, {def_var => $params->{def_var}, conf => $conf}) ]};
400  
401 $db->set($conf->{db_name}.';network-'.$pre => $cidr);
402 $db->set($conf->{db_name}.'-'.$pre => $var{def}->{avg}.','.$var{def}->{total}.','.$var{def}->{spamhits}.','.$var{def}->{lastspam}.','.$params->{sender});
403 $db->set($conf->{db_name}.';expires-'.$pre => $var{def}->{expires}) if(int($var{def}->{expires})>0);
404 }
405 }
406 return $pre;
407 }
408  
409 sub op_rkeys {
410 my ($n, $i, $c, @buffer, @acc, $re, $pattern, $code, $db, $params);
411 ($pattern, $code, $db, $params) = @_;
412  
413 $re = $params->{conf}->{re};
414  
415 @buffer = @{[$db->keys($params->{conf}->{db_name}.$pattern)]};
416  
417 $n = int(@buffer + 0);
418 while(0!=$n%4){
419 push @buffer, '';
420 ++$n;
421 }
422  
423 for($i=0; $i<$n; $i+=4){
424 $c = -1;
425 map { push @acc, $code->($buffer[$i + ++$c], $_, $db, $params) } @{[$db->mget( grep /$re->{alnumchar}/, @{[@buffer[$i..($i+3)]]} )]};
426 }
427  
428 return @acc;
429 }
430  
431 sub op_batch {
432 my ($n, $i, $c, @acc, $re, $buffer, $code, $params);
433 ($buffer, $code, $params) = @_;
434  
435 $re = $params->{conf}->{re};
436  
437 $n = int(@$buffer + 0);
438 while(0!=$n%4){
439 push @$buffer, '';
440 ++$n;
441 }
442  
443 for($i=0; $i<$n; $i+=4){
444 $c = -1;
445 push @acc, $code->(\@{[ grep /$re->{alnumchar}/, @{[@$buffer[$i..($i+3)]]} ]}, $params);
446 }
447  
448 return @acc;
449 }
450  
451 sub tr_ascii {
452 grep tr/\x00-\x09\x0b\x0c\x0e-\x1f\x7f-\xff//d, @_;
453 return @_ == 1 ? $_[0] : @_;
454 }
455  
456 sub sanitize {
457 my ($var, $re, $def) = @_;
458 $def = '' if (!defined $def);
459 $var =~ tr/\x00-\x09\x0b\x0c\x0e-\x1f\x7f-\xff//d;
460 return $var =~ $re ? $1 : ($def ? sanitize($def, $re) : '');
461 }
462  
463 sub iptables_mgr {
464 my ($iptables, @res, $ipv6);
465 $ipv6 = (defined $_[1] && $_[1] == 6) ? 1 : 0;
466 return 0 if($_[0]->{iptables_support}==0 || ($ipv6 && $_[0]->{iptables_support}!=6));
467 $iptables = IPTables::ChainMgr->new(ipt_bin_name => ($ipv6 ? $_[0]->{ip6tables_bin} : $_[0]->{iptables_bin}), use_ipv6 => $ipv6, ipt_rules_file => '', iptout => '', ipterr => '', debug => 0, verbose => 0, ipt_alarm => 5, ipt_exec_style => 'popen', ipt_exec_sleep => 0);
468 $iptables->{'parse_obj'}->{'_lockless_ipt_exec'} = 0 if($iptables && $iptables->{'parse_obj'} && $iptables->{'parse_obj'}->{'_lockless_ipt_exec'});
469 fatal(($ipv6?'[ip6tables]':'[iptables]').'Could not determine if chain '.$_[0]->{filter_name}.' exists') if(!(@res = $iptables->chain_exists('filter', $_[0]->{filter_name})));
470 if($res[0]!=1){
471 $iptables->create_chain('filter', $_[0]->{filter_name});
472 $iptables->add_jump_rule('filter', 'INPUT', 4, $_[0]->{filter_name});
473 }
474  
475 return $iptables;
476 }
477  
478 sub iptables_cmd {
479 my ($args, $conf, @res, $iptables);
480 ($args, $conf, $iptables) = @_;
481  
482 return 1 if($conf->{iptables_support}==0);
483  
484 $iptables = 'iptables';
485 if(defined $_[2] && $_[2] == 6){
486 return 1 if($conf->{iptables_support}!=6);
487 $iptables = 'ip6tables';
488 }
489  
490 @res = (0, [], []);
491 timeout_call( 5 ,sub {
492  
493 if((defined fileno(IPTABLESLOCKFILE) || open(IPTABLESLOCKFILE, '+>>'.$conf->{iptables_lockfile})) && flock(IPTABLESLOCKFILE, LOCK_EX)){
494 @res = ();
495 @res = $conf->{$iptables}->run_ipt_cmd($conf->{$iptables.'_bin'}.' '.$1) if($args !~ $conf->{re}->{martian_ip} && $args =~ $conf->{re}->{iptables_arg});
496 flock(IPTABLESLOCKFILE, LOCK_UN);
497 (@res && $res[0]==1) ? inform('['.$iptables.'] '.$conf->{$iptables.'_bin'}.' '.$args) : error('['.$iptables.'] Error: '.$conf->{$iptables.'_bin'}.' '.$args);
498 }
499 });
500  
501 return @res;
502 }
503  
504 sub ip6tables_normalize {
505 return $_[1]->{iptables_support} == 6 ? $_[1]->{ip6tables}->normalize_net($_[0]) : ''; #s/b default ip
506 }
507  
508 sub service_cmd {
509  
510 my ($service, $initd, $arg, $cmd);
511  
512 $service = shift;
513 $arg = join (' ', @_);
514  
515 if(($initd = find_bin('service'))){
516 $cmd = "$initd $service $arg";
517 }elsif(($initd = find_bin('initctl')) || ($initd = find_bin('svcadm')) || ($initd = find_bin('systemctl'))){
518 $cmd = "$initd $arg $service";
519 }elsif(( $service=~/\// && -e $service && ($initd=$service)) && (($initd="/etc/init.d/$service") && -e $initd) || (($initd="/sbin/init.d/$service") && -e $initd) ){
520 $cmd = "$initd $arg";
521 }
522  
523 return (!$cmd || system($cmd)!=0 || $? == -1 || $? & 127) ? 0 : 1;
524 }
525  
526 sub clean_notifications {
527 op_rkeys(';warning-*', \&clean_notifications_op, $_[0], $_[1]);
528 }
529  
530 sub notify_blacklist {
531 my $params = $_[1];
532 return if ($_[1]->{conf}->{admin_email} !~ $_[1]->{conf}->{re}->{envelope});
533 $_[1]->{admin_email_address} = $1.'@'.$2;
534 op_rkeys(';warning0-*', \&notify_blacklist_op, $_[0], $_[1]);
535 }
536  
537 sub refresh_iptables {
538 $_[1]->{iptables} = '' if(!$_[1]->{iptables});
539 op_rkeys(';expires-*', \&refresh_iptables_op, $_[0], $_[1]);
540 }
541  
542 sub notify_blacklist_op {
543 my ($re, %var, $msg, $res, $message, $k, $v, $db, $params);
544 ($k, $v, $db, $params) = @_;
545  
546 $re = $params->{conf}->{re};
547 %var = (user => '', domain => '', email => '', ip => '', recipient => '', admin => $params->{admin_email_address});
548  
549 $db->del($k);
550 $k =~ s/$re->{subkey}/;warning-/;
551 return if($db->exists($k));
552 $db->set($k => time());
553  
554 ($v, $var{recipient}) = split("\n", $v);
555 if($v =~ $re->{ip} && $k =~ $re->{emailfromkey}){
556 $var{user} = decode_base64($1);
557 $var{domain} = $2;
558 $var{ip} = $v;
559 }elsif($k =~ $re->{ipfromkey}){
560 $var{ip} = $1.$2;
561 return if($v !~ $re->{email});
562 $var{user} = decode_base64($1);
563 $var{domain} = $2;
564  
565 }else{
566 return;
567 }
568  
569 require Net::DNS;
570 $res = Net::DNS::Resolver->new(udp_timeout=>10, tcp_timeout=>20);
571  
572 $v = $var{ip};
573 $k = $v =~ $re->{colon} ? 1 : 0;
574 $v =~ s/(\.|\:)(?:(?:[0-9]+\.[0-9]+)|(?:[0-9a-fA-F]+))$/$1/; #re
575  
576 $k = ' '.join(' ', map{ sub{ return join(' ', map{ $_->address } rr($res, $_[0], $k ? 'AAAA':'A')); }->($_->exchange) } rr($res, $var{domain}, 'MX'));
577  
578 return inform('[notify_blacklist] Failed') if($k!~/[ ]\Q$v\E(?:[ ]|$)/i);
579  
580 inform('[notify_blacklist] warning to '.$var{domain}.' '.$var{ip});
581  
582 $v = $var{email} = $var{user}.'@'.$var{domain};
583 map{ $var{$_} = substr($var{$_}, 0,56) } keys %var;
584 $message = $params->{conf}->{admin_message};
585 $message =~ s/$re->{admintpl}/$var{lc($1)}/ig;
586  
587 $msg = MIME::Lite->new(
588 'From' => $params->{conf}->{admin_email},
589 'To' => $v,
590 'Subject' => 'Delivery Failure Notification: blocked',
591 'Type' => 'text/plain',
592 'Data' => $message,
593 );
594  
595 $msg->send;
596 }
597  
598 sub clean_notifications_op {
599 return if ((int($_[1]) + 2592000) > time());
600 $_[2]->del($_[0]);
601 }
602  
603 sub refresh_iptables_op {
604 my ($re, $t, $ip, $cidr, $nm, $k, $v, $db, $params);
605 ($k, $v, $db, $params) = @_;
606  
607 $re = $params->{conf}->{re};
608  
609 $t = time();
610 return if ( $t > int($v) || $k =~ $re->{martian_ip} || $k !~ $re->{ipfromkey});
611  
612 $ip = $1.$2;
613  
614 return if($params->{iptables} =~ /[^0-9]\Q$ip\E[^0-9]/sm);
615 $nm = $ip =~ $re->{colon} ? 128 : 32;
616 $cidr = $db->get($params->{conf}->{db_name}.';network-'.$ip) || $nm;
617  
618 $ip = sanitize($ip, $re->{ip}, '');
619 $nm = sanitize($cidr, $re->{integer}, $nm);
620 $v = sanitize($v, $re->{integer}, $t+864000);
621 iptables_cmd('-t filter -I '.$params->{conf}->{filter_name}.' -i eth+ -s '.ip6tables_normalize((expand_ipv6($ip).'/'.cidr_16($nm)), $params->{conf}).' -p tcp -m multiport --dports 25,587,110,143,465,993,995 -j REJECT -m comment --comment \'expires='.$v.'\'', $params->{conf}, 6) if(($ip) && iptables_cmd('-t filter -I '.$params->{conf}->{filter_name}.' -i eth+ -s '.$ip.'/'.$nm.' -p tcp -m multiport --dports 25,587,110,143,465,993,995 -j REJECT -m comment --comment \'expires='.$v.'\'', $params->{conf}));
622  
623 }
624  
625 sub refresh_list {
626 op_rkeys(';expires-*', \&refresh_list_op, $_[0], $_[1]);
627 }
628  
629 sub refresh_list_op {
630 my ($k, $v, $db, $params) = @_;
631  
632 return if ($v > time());
633 $db->del($k);
634  
635 return if($k !~ $params->{conf}->{re}->{emailfromkey});
636 $v = decode_base64($1).'@'.$2;
637 #$params->{mailsa}->remove_address_from_whitelist($v);
638 inform('[maintenance] removed from blacklist: '.$v);
639 }
640  
641 sub consolidate_network_op {
642 my ($k, $v, $db, $params, $re, %var, $ip);
643  
644 ($k, $v, $db, $params) = @_;
645  
646 $re = $params->{conf}->{re};
647 %var = $v =~ $re->{record} ? (avg => $1 + 0.0, total => $2 + 0.0, spamhits => int($3), lastspam => int($4), cachehit => 1) : %{$params->{def_var}};
648 $var{expires} = 0;
649 if($k =~ $re->{ipfromkey}){
650 $ip = $1.$2;
651 $var{expires} = $db->get($params->{conf}->{db_name}.';expires-'.$ip) || 0;
652 $db->del($params->{conf}->{db_name}.';network-'.$ip);
653 $db->del($params->{conf}->{db_name}.';expires-'.$ip);
654 }
655 $db->del($k);
656 return \%var;
657 }
658  
659 sub cache_decay_op {
660 my ($re, $time, %a, $k, $v, $db, $params);
661  
662 ($k, $v, $db, $params) = @_;
663  
664 $time = time();
665 $re = $params->{conf}->{re};
666  
667 $v =~ s/$re->{spaces}//g;
668 return if($v !~ $re->{record});
669  
670 %a = (avg => $1 + 0.0, total => $2 + 0.0, spamhits => int($3), lastspam => int($4), morf => $5);
671 $a{lastspam_delta} = $time - $a{lastspam};
672  
673 return if($a{lastspam_delta}<60);
674  
675 if($params->{cache_decay_secs} < $a{lastspam_delta}){
676 $db->del($k);
677 inform('[maintenance] removed from cache: '.$k.' => '.$v);
678 return;
679 }
680  
681 $a{total} = nearest(0.01, $a{total} * exp(-3.2*$a{lastspam_delta}/$params->{cache_decay_secs}));
682 $a{spamhits} = nearest(1, $a{total}/$params->{average_score_for_rule});
683 $a{spamhits} = $params->{trigger_messages} if($a{spamhits} > $params->{trigger_messages});
684 $a{spamhits} = 1 if($a{spamhits}<1);
685 $a{avg} = nearest(0.01, $a{total}/$a{spamhits});
686  
687 $db->set($k => $a{avg}.','.$a{total}.','.$a{spamhits}.','.$a{lastspam}.','.$a{morf});
688 inform('[maintenance] decay updated cache: '.$k.' => from: '.$v. ' to: '. $a{avg}.','.$a{total}.','.$a{spamhits}.','.$a{lastspam}.','.$a{morf});
689  
690 }
691  
692 sub get_config {
693 return {
694 iptables_bin => '/sbin/iptables',
695 ip6tables_bin => '/sbin/ip6tables',
696 iptables_support => 6,
697 filter_name => 'spamipfilter',
698 db_type => 'redis',
699 db_host => '127.0.0.1',
700 db_port => 0,
701 db_user => '',
702 db_auth => '',
703 db_name => 'spamipfilter',
704 piwik_host =>'',
705 piwik_path=>,'',
706 piwik_idsite=>1,
707 log_dir => '/var/log',
708 trigger_score => 6,
709 trigger_messages => 3,
710 trigger_sensitivity => 4,
711 average_score_for_rule => 7,
712 expire_rule_seconds => 172800,
713 seconds_to_decay_penalty => 300,
714 seconds_between_messages => 30,
715 expires_multiplier_penalty => 1.5,
716 cache_decay_days => 60,
717 blacklist_score => 30,
718 verbose => 0,
719 whitelist => '',
720 admin_email => '',
721 admin_message => "\nYour message to \$recipient from \$email was blocked and your IP address \$ip blacklisted due to excessive unsolicited bulk email. \n\nTo reinstate your ability to send email to \$recipient, please reply to \$admin using a different off-network email, including the body of this message with a request for reinstatement.",
722 common_hosts => 'gmail.com, google.com, yahoo.com, hotmail.com, live.com',
723 iptables_lockfile => '',
724 ua => '',
725 username => '',
726 lang => 'en',
727 stopwords => ''
728  
729 };
730 }
731  
732 sub re_config {
733 my $k;
734 $k = (($k = find_bin('lsmod')) && `$k 2>&1` !~ /iptable[s\-_ ]+filter/i && ($k = find_bin('modprobe')) && $> == 0) ? `$k -a ip_tables iptable-filter 2>&1` : '';
735 $k =~ s/$Regex{spaces}//g;
736 if($k){
737 $_[0]->{iptables_support} = 0;
738 error('iptables-filter kernel module not loaded... iptables functionality disabled');
739 }
740 $k = $_[0]->{db_name};
741  
742 $_[0]->{iptables} = iptables_mgr($_[0], 4);
743 $_[0]->{ip6tables} = iptables_mgr($_[0], 6);
744  
745 $Regex{key} = qr/^(\Q$k\E)/;
746 $Regex{emailfromkey} = qr/^\Q$k\E(?:;(?:(?:expires)|(?:warning[0-9]*)))?-([^\@]+)\@([^\@]+)$/;
747  
748 #similarity cache
749 $_[0]->{stopwords} = $_[0]->{stopwords} ? ' '.lc($_[0]->{stopwords}).' ' : ' '.join(' ',keys %{getStopWords($_[0]->{lang})}).' ';
750  
751 }
752  
753 sub similarity {
754  
755 my ($v,$t,$c,$i,$add,$tmp,$cache);
756 $add = $_[2] ? 1 : 0;
757  
758 $c = 0;
759 $v = join("\n", grep{ ($_) && $c==0 && substr($_,0,1) ne '<' && !(index('<', $_)==-1 && $_=~/\:[ \t]*>/ ) && !(substr($_,0,2) eq "--" && length($_)<4 && ($c=1)) } split("\n", substr($_[0],0,32768) ));
760 $v =~ s/<[>]*>/ /gsm;
761 $v =~ s/(?:^|[\r\n\t ]+)[^\r\n\t ]+(?:(?:\:\/\/)|\@)[^\r\n\t ]+(?:[\r\n\t ]|$)/ /g;
762 $v =~ s/[\x00-\x1F\x3D\x2C\x2D]/ /g;
763 $v =~ s/[\x21-\x40\x5B-\x60\x7B-\xBF]//g;
764 $v =~ s/[ ][ ][ ]*/ /g;
765  
766 $v = join(' ', grep { index($_[1]->{stopwords},' '.$_.' ')==-1 && length($_)>2 } split(' ', lc(substr($v,0,8192)) ));
767 return 0 if(length($v)<5);
768  
769 $t = Text::Document->new();
770 $t->AddContent($v);
771
772 return inform('[similarity] could not acquire cache lock')+0 unless (defined fileno(IPFILTERCACHELOCK) && flock(IPFILTERCACHELOCK, LOCK_EX));
773  
774 $cache = thaw($_[1]->{db}->get($_[1]->{db_name}.';similarity-cache') || freeze({}));
775  
776 $i = 0;
777 $c = time() - 172800;
778 for(keys %{$cache}){
779  
780 $v = $t->CosineSimilarity($cache->{$_}->[1]) + 0;
781 if(0.7<$v){
782  
783 if($_[1]->{seconds_between_duplicates}>int(time()-int($_))){
784 flock(IPFILTERCACHELOCK, LOCK_UN);
785 return -1;
786 }
787  
788 $cache->{$_}->[0]+=1;
789  
790 $v = nearest(0.01,$v+$cache->{$_}->[0]);
791  
792 inform('[similarity] '.$v);
793 $_[1]->{db}->set($_[1]->{db_name}.';similarity-cache' => freeze($cache));
794  
795 flock(IPFILTERCACHELOCK, LOCK_UN);
796 return $v;
797 }
798 ($_ < $c && $cache->{$_}->[0]==0) ? delete $cache->{$_} : ++$i;
799  
800 }
801  
802 return flock(IPFILTERCACHELOCK, LOCK_UN)*0 if(!$add);
803  
804 map{ delete $cache->{$_} }@{[sort {$a <=> $b} keys %{$cache}]}[0 .. 128] if(1024<$i);
805  
806 $c = int(keys %{$cache})+0;
807 inform('[similarity] (cache size '.$c.') adding...');
808  
809 do{
810 $c = time().'.'.int(rand(65536));
811 }while(exists $cache->{$c});
812  
813 $cache->{$c} = [0, $t, $tmp];
814  
815 $_[1]->{db}->set($_[1]->{db_name}.';similarity-cache' => freeze($cache));
816  
817 #inform('[similarity] '. join(',',keys %{thaw($_[1]->{db}->get($_[1]->{db_name}.';similarity-cache'))}) );
818  
819 flock(IPFILTERCACHELOCK, LOCK_UN);
820  
821 return 0;
822 }
823  
824 sub compile_regex {
825 my $k = get_config()->{db_name};
826 # Although SA preprocesses much of the data captured, this should be tightened
827 return (
828 from => qr/(?:^|\n)[\t ]*from\:([^\r\n\@]+\@[^\r\n]+)[\r\n]/i,
829 envelope => qr/(?:^|(?:[^\x3C]*\x3C))([^\x3C\x3E\@]+)\@([^\x3C\x3E\@]+)(?:\x3E|$)/,
830 alnumchar => qr/[a-z0-9]/i,
831 isint => qr/^[0-9]+$/i,
832 spaces => qr/[\r\n\t ]+/,
833 trim => qr/(?:^['",\r\n\t ]+)|(?:['",\r\n\t ]+$)/,
834 email => qr/^(.+)\@(.+)$/,
835 n_domainchars => qr/[^0-9.\-a-zA-Z]/,
836 n_dbchars => qr/[^0-9.,\@a-z_\-+\/=]/i,
837 integer => qr/^([0-9]+)$/,
838 colon => qr/\:/,
839 iptables_arg => qr/^([ -;=A-_a-~]+)$/,
840 record => qr/^([0-9.]+),([0-9.]+),([0-9.]+),([0-9.]+)(?:(?:,(.*))|$)/,
841 subkey => qr/;[a-zA-Z0-9]+\-/,
842 ip => qr/^(?:([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)|(?:[0-9a-f]{4}\:[0-9a-f]{4}\:[0-9a-f]{4}\:[0-9a-f]{4}\:[0-9a-f]{4}\:[0-9a-f]{4}\:[0-9a-f]{4}\:[0-9a-f]{4}))$/i,
843 ipn => qr/^((?:(?:[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)|(?:[0-9a-f]{4}\:[0-9a-f]{4}\:[0-9a-f]{4}\:[0-9a-f]{4}\:[0-9a-f]{4}\:[0-9a-f]{4}\:[0-9a-f]{4}\:[0-9a-f]{4}))(?:\/[0-9]+)?)$/i,
844 key => qr/^(\Q$k\E)/,
845 ipfromkey => qr/(?:^|-)((?:[0-9]+\.[0-9]+\.[0-9]+\.)|(?:[0-9a-f]{4}\:[0-9a-f]{4}\:[0-9a-f]{4}\:[0-9a-f]{4}\:[0-9a-f]{4}\:[0-9a-f]{4}\:[0-9a-f]{4}\:[0-9a-f]{2}))([0-9a-f]+)(?:[^0-9a-f]|$)/i,
846 emailfromkey => qr/^\Q$k\E(?:;(?:(?:expires)|(?:warning[0-9]*)))?-([^\@]+)\@([^\@]+)$/,
847 admintpl => qr/\$((?:user)|(?:domain)|(?:ip)|(?:email)|(?:recipient)|(?:admin))/i,
848 expires => qr/[^0-9]([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+(?:\/[0-9]+)?)[^0-9]+0\.0\.0\.0\/0[^0-9]+.*?\bexpires=([0-9]+)[^0-9]/sm,
849 #Thanks to Salvador Fandino's Regexp::IPv6
850 rcvd_header => qr/from[ \t]+([^ \t]+)[ \t]+\(.*?\[[\t ]*((?:[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)|(?::(?::[0-9a-fA-F]{1,4}){0,5}(?:(?::[0-9a-fA-F]{1,4}){1,2}|:(?:(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})[.](?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})[.](?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})[.](?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})))|[0-9a-fA-F]{1,4}:(?:[0-9a-fA-F]{1,4}:(?:[0-9a-fA-F]{1,4}:(?:[0-9a-fA-F]{1,4}:(?:[0-9a-fA-F]{1,4}:(?:[0-9a-fA-F]{1,4}:(?:[0-9a-fA-F]{1,4}:(?:[0-9a-fA-F]{1,4}|:)|(?::(?:[0-9a-fA-F]{1,4})?|(?:(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})[.](?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})[.](?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})[.](?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2}))))|:(?:(?:(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})[.](?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})[.](?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})[.](?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2}))|[0-9a-fA-F]{1,4}(?::[0-9a-fA-F]{1,4})?|))|(?::(?:(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})[.](?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})[.](?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})[.](?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2}))|:[0-9a-fA-F]{1,4}(?::(?:(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})[.](?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})[.](?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})[.](?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2}))|(?::[0-9a-fA-F]{1,4}){0,2})|:))|(?:(?::[0-9a-fA-F]{1,4}){0,2}(?::(?:(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})[.](?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})[.](?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})[.](?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2}))|(?::[0-9a-fA-F]{1,4}){1,2})|:))|(?:(?::[0-9a-fA-F]{1,4}){0,3}(?::(?:(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})[.](?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})[.](?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})[.](?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2}))|(?::[0-9a-fA-F]{1,4}){1,2})|:))|(?:(?::[0-9a-fA-F]{1,4}){0,4}(?::(?:(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})[.](?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})[.](?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})[.](?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2}))|(?::[0-9a-fA-F]{1,4}){1,2})|:))))[ \t]*\]/i,
851  
852 param => sub { my $r = '^(?:(?:'.join(')|(?:',keys %{get_config()}).'))$'; $r=~s/\_/\\_/g; return qr/$r/sm; }->(),
853 martian_ip => sub {
854 my ($r, @buffer);
855 $r = find_bin('route');
856 map{ $_=~/^[ ]*([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)[ ]+([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)[ ]+(?:[0-9]+\.[0-9]+\.[0-9]+\.([0-9]+))[ ]/ && ((0<length($2) && ($2 ne '0.0.0.0') && push @buffer, $2) xor (0<length($1) && ($1 ne '0.0.0.0') && push @buffer, sub{ return $_[0].'([0-9]*[0-9])(?(?{int($+)<'.$_[1].' || int($+)>'.($_[1]+$_[2]).';})X)'; }->(substr($1, 0, rindex($1,'.')+1), int(substr($1, rindex($1,'.')+1)), 256-int($3)))) } split("\n", `$r -nA inet`);
857 map{ $_=~/^[ ]*([0-9a-f\:]+)[^0-9a-f\:]/i && sub { $_[1] =~ /[0-9a-f]\:[0-9a-f]/i && $_[1] !~ /^(?:(?:0000\:)|(?:fc00\:)|(?:fe80\:)|(?:ff00\:)|(?:2001\:0db8\:)|(?:2001\:0010\:)|(?:3ffe\:))/i && (push @{$_[0]}, lc($_[1]).'[a-f0-9]{2}') }->(\@buffer, substr(expand_ipv6($1), 0, -2) ) } split("\n", `$r -nA inet6`);
858 $r = '(?:'.join (')|(?:', @buffer).')';
859 $r =~ s/\Q.\E/\\./g;
860 $r =~ s/([0-9])\:/$1\\:/g;
861 use re 'eval';
862 #ipv6 needs *some* work
863 return qr/(?:^|[^0-9a-f])(?:(?:0000\:)|(?:fc00\:)|(?:fe80\:)|(?:ff00\:)|(?:2001\:0db8\:)|(?:2001\:0010\:)|(?:3ffe\:)|(?:127\.)|(?:192\.168\.)|(?:0\.)|(?:10\.)|(?:100\.64\.)|(?:224\.)|(?:192\.0\.0\.)|(?:169\.254\.)|$r)(?:[^0-9a-f]|$)/i;
864  
865 }->()
866 );
867 }
868  
869 BEGIN {
870  
871 %Regex = compile_regex();
872 %Cronjobs = (IPFilterUpdate => \&c_ipfilter_update, Maintenance => \&c_maintenance, LogFormat => \&c_log_format, LogPiwik => \&c_log_piwik);
873 $Cronjobs{$1}->($2) if(do {local $/; STDIN->blocking(0); <STDIN>} =~ /^([a-zA-Z_]+)[ ][ ]*(.*)$/ && (STDIN->blocking(1)||1) && ($1) && ($2) && (exists $Cronjobs{$1}) );
874  
875 require Mail::SpamAssassin::Plugin;
876 Mail::SpamAssassin::Plugin->import();
877 require Mail::SpamAssassin::Logger;
878 Mail::SpamAssassin::Logger->import();
879 @ISA = qw(Mail::SpamAssassin::Plugin);
880  
881 } # ...
882  
883  
884 sub new {
885 my ($class, $mailsa, $self);
886 ($class, $mailsa) = @_;
887 $class = ref($class) || $class;
888 $self = $class->SUPER::new($mailsa);
889 bless ($self, $class);
890 $self->{mailsa} = $mailsa;
891 $self->set_config($mailsa->{conf});
892 return $self;
893 }
894  
895 sub set_config {
896 my (@cmds, $c, $self, $conf);
897 ($self, $conf) = @_;
898 $self->{conf} = get_config();
899 foreach $c (keys %{$self->{conf}}){
900 push(@cmds, {
901 'setting' => 'ipfilter_'.$c,
902 'default' => $self->{conf}->{$c},
903 'type' => $self->{conf}->{$c} =~ /^[0-9]+(?:\.[0-9]+)?$/ ? $Mail::SpamAssassin::Conf::CONF_TYPE_NUMERIC : $Mail::SpamAssassin::Conf::CONF_TYPE_STRING
904 }
905 );
906 }
907 $self->register_eval_rule('check_spamipfilter');
908 $conf->{parser}->register_commands(\@cmds);
909 }
910  
911 sub finish_parsing_end {
912  
913 my ($c, $v, $ini, $db, $self, $params);
914  
915 ($self, $params) = @_;
916 $self->{conf}->{whitelist} = {};
917 $ini = get_config(); #should == $self->{conf}
918  
919 foreach $c (keys %{$self->{conf}}){
920 if(defined $params->{conf}->{'ipfilter_'.$c} && exists $ini->{$c} && $c=~$Regex{param}){
921 $v = $params->{conf}->{'ipfilter_'.$c};
922 $v =~ s/(?:^[\r\n\t ]+)|(?:[\x00])|(?:[\r\n\t ]+$)//g;
923 $v =~ s/\/$//g if($c =~ /(?:(?:\_bin)|(?:\_dir)|(?:\_path))$/);
924 if($v =~ /^([0-9]+(?:\.[0-9]+)?)$/ || $ini->{$c} =~ /^([0-9]+(?:\.[0-9]+)?)$/){
925 $self->{conf}->{$c} = $1 + 0;
926 }elsif($c =~ /whitelist$/i){
927 $v =~ s/[ \r\n\t]*//g;
928 map{($v =~ /^([^\x00-\x32]+\@[a-zA-Z0-9\-.]+)$/ || $v =~ /^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]*)$/) && (${$self->{conf}->{whitelist}}{lc($1)} = 1)} split(',', $v);
929 }elsif(($c =~ /(?:(?:\_host))$/i && ($v =~ /^((?:[a-z]+\:\/\/)?[a-zA-Z0-9\-.]+)$/ || $v =~ /^((?:[a-z]+\:\/\/)?[0-9]+\.[0-9]+\.[0-9]+\.[0-9]*)$/)) || ($c =~ /(?:(?:\_bin)|(?:\_dir)|(?:\_path))$/i && $v =~ /^[^\x00-\x31]+$/ && (-e $v || -d $v)) || ($c =~ /(?:(?:\_email))$/i && ($v =~ /^([^\x00-\x32]+\@[a-zA-Z0-9\-.]+)$/ || $v =~ /^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]*)$/)) || ($c =~ /common_hosts$/i && $v =~ /^([a-zA-Z0-9\-.,]+)$/) || ($c =~ /\_(?:(?:name)|(?:type))$/i && $v =~ /^([a-zA-Z0-9_]+)$/) || ($c =~ /\_((?:message))$/i && $v =~ /^([^\x00-\x09\x0b\x0c\x0e-\x1f]+)$/) || $v =~ /^([\x20\x21\x23\x24\x25\x26-\x5b\x5d\x5e\x5f\x61-\x7e]*)$/){
930  
931 $self->{conf}->{$c} = $1;
932 }else{
933 inform('[finish_parsing_end] unknown configuration '.$c.' => '.$v);
934 }
935 }
936 }
937  
938 $Verbose = 1 if(int($self->{conf}->{verbose})>0);
939  
940 $self->{conf}->{lang} = $self->{conf}->{lang} ? lc(substr($self->{conf}->{lang},0,2)) : 'en';
941  
942 $self->{conf}->{ua} = 'SpamAssassinIPFilter/'.$VERSION.' (compatible; foobot/2.0; +http://www.foo.com/foobot.htm)' if(!$self->{conf}->{ua});
943 $self->{conf}->{username} = (((-e "/proc/$$/cmdline" && open(PROCCMDLINE,"/proc/$$/cmdline") && ($c=do{local $/; <PROCCMDLINE>}) && ($c=sub{ return $_[0] =~/[ \t\r\n]\-(?:(?:u)|(?:\-user))[='" ]*([^'" \t\r\n]+)(?:(?:[ \t\r\n'"])|$)/ ? $1 : '' }->($c, close(PROCCMDLINE)))) || (($c = $params->{username}) && $c!~/^root$/i) || (($c = $params->{home_dir_for_helpers}) && $c!~/(?:^|\/)root\/+?$/i) || (($c = find_bin('id')) && -e $c && (`$c spamd 2>&1`=~/[0-9]+/) && ($c='spamd')) ) && $c =~/^([a-z_][a-z0-9_-]*)$/i) ? $1 : 'root' if(!$self->{conf}->{username});
944  
945 $self->{conf}->{filter_name} = 'spamipfilter' if ($self->{conf}->{filter_name} !~ /^[a-z0-9\-_.]+$/i);
946 $self->{conf}->{iptables_support} = $self->{conf}->{iptables_support} + 0;
947 $self->{conf}->{iptables_support} = 4 if($self->{conf}->{iptables_support}!=0 && $self->{conf}->{iptables_support}!=4 && $self->{conf}->{iptables_support}!=6);
948 if($self->{conf}->{iptables_support}>0){
949 $self->{conf}->{iptables_bin} = ($self->{conf}->{iptables_bin} && -e $self->{conf}->{iptables_bin}) ? $self->{conf}->{iptables_bin} : (find_bin('iptables') ? find_bin('iptables') : '');
950 $self->{conf}->{iptables_lockfile} = (-d '/var/lock' && -w '/var/lock') ? '/var/lock/spamipfilter' : (-d '/tmp' ? '/tmp/spamipfilter.lock' : getcwd().'/spamipfilter') if(!$self->{conf}->{iptables_lockfile});
951 $self->{conf}->{ip6tables_bin} = ($self->{conf}->{ip6tables_bin} && -e $self->{conf}->{ip6tables_bin}) ? $self->{conf}->{ip6tables_bin} : (find_bin('ip6tables') ? find_bin('ip6tables') : '') if($self->{conf}->{iptables_support}>4);
952 }
953  
954 $self->{conf}->{iptables_support} = 4 if(!$self->{conf}->{ip6tables_bin});
955 $self->{conf}->{iptables_support} = 0 if(!$self->{conf}->{iptables_bin});
956  
957 $self->{conf}->{db_host} =~ s/^.*?\:\/\///g;
958 $self->{conf}->{db_port} = int($self->{conf}->{db_port});
959 $self->{conf}->{db_port} = 0 if ($self->{conf}->{db_port}<1);
960  
961 $self->{conf}->{piwik_idsite} = int($self->{conf}->{piwik_idsite}+0);
962 $self->{conf}->{piwik_host} = 'http://'.$self->{conf}->{piwik_host} if ($self->{conf}->{piwik_host} && $self->{conf}->{piwik_host}!~/^[^\/]+\:\/\//);
963  
964 $self->{conf}->{expire_rule_seconds} = $self->{conf}->{expire_rule_seconds} + 0.0;
965 $self->{conf}->{expire_rule_seconds} = 300 if(300 > $self->{conf}->{expire_rule_seconds});
966 $self->{conf}->{cache_decay_days} = $self->{conf}->{expire_rule_seconds}*90/86400;
967 $self->{conf}->{cache_decay_days} = 1 if(0.2 > $self->{conf}->{cache_decay_days});
968 $self->{conf}->{seconds_to_decay_penalty} = 2 if(2 > $self->{conf}->{seconds_to_decay_penalty});
969 $self->{conf}->{seconds_between_messages} = 0.99 if(1 > $self->{conf}->{seconds_between_messages});
970 $self->{conf}->{trigger_messages} = 1 if(1 > $self->{conf}->{trigger_messages});
971 $self->{conf}->{average_score_for_rule} = 1 if(0.2 > $self->{conf}->{average_score_for_rule});
972 $self->{conf}->{trigger_sensitivity} = 1 if(0.2 > $self->{conf}->{trigger_sensitivity});
973  
974 $self->{conf}->{common_hosts} =~ s/[ \r\n\t]*//g;
975 $c = $self->{conf}->{common_hosts};
976 $c =~ s/\Q.\E/\\./g;
977 $c = ($self->{conf}->{common_hosts}) ? '(?:^|\.)((?:'.join(')|(?:', split(',', lc($c))).'))(?:[^a-z]|$)' : '^$';
978 $Regex{common_hosts} = qr/$c/i;
979  
980 ($self->{conf}->{log_dir} = -d '/tmp' ? '/tmp' : getcwd()) if(!-d $self->{conf}->{log_dir} || !-w $self->{conf}->{log_dir});
981  
982  
983 if(-d $self->{conf}->{log_dir}){
984 mkdir($self->{conf}->{log_dir}.'/'.$self->{conf}->{filter_name}) if(!-d $self->{conf}->{log_dir});
985 $self->{conf}->{log_dir} = $self->{conf}->{log_dir}.'/'.$self->{conf}->{filter_name} if(-d $self->{conf}->{log_dir}.'/'.$self->{conf}->{filter_name} && -w $self->{conf}->{log_dir}.'/'.$self->{conf}->{filter_name});
986 }
987  
988 fatal('Could not find log directory '.$self->{conf}->{log_dir}) if(!-d $self->{conf}->{log_dir} || !-w $self->{conf}->{log_dir});
989 c_logfile($self->{conf});
990 chown(int($1),-1, $self->{conf}->{log_dir}.'/.cache.lock' ) if ((defined fileno(IPFILTERCACHELOCK) || open(IPFILTERCACHELOCK, '+>>'.$self->{conf}->{log_dir}.'/.cache.lock' )) && $self->{conf}->{username} && getpwnam($self->{conf}->{username})=~/^([0-9]+)$/);
991  
992 map { ($_ =~ /(?:(?:\_bin)|(?:\_dir)|(?:\_path))$/) && (!-e $self->{conf}->{$_} && !-d $self->{conf}->{$_}) && ($self->{conf}->{$_}='')} (keys %{$self->{conf}});
993  
994  
995 $v = sub {
996  
997 my ($cron, $cfg);
998 $cron = $_[1] ? new Config::Crontab(-owner => $_[1], -strict => 0) : new Config::Crontab();
999  
1000 #see caveats: http://search.cpan.org/~scottw/Config-Crontab-1.40/Crontab.pm#CAVEATS
1001 $cron->remove($cron->select(-command_re => 'Mail::SpamAssassin::Contrib::Plugin::IPFilter'));
1002 $cron->remove($cron->select(-name => 'MAIL_SPAMASSASSIN_CONTRIB_PLUGIN_IPFILTER'));
1003  
1004 $cron->write;
1005  
1006 $c = new Config::Crontab::Block;
1007 $cfg = encode_base64(JSON::XS->new->utf8->encode($self->{conf}),'');
1008  
1009
1010 #$c->last( new Config::Crontab::Env( -name => 'MAIL_SPAMASSASSIN_CONTRIB_PLUGIN_IPFILTER', -value=> '"'.encode_base64(JSON::XS->new->utf8->encode($self->{conf}), '').'"') );
1011  
1012 #TODO: better $cfg handling... env. var or r/o file
1013 $c->last( new Config::Crontab::Event( -data => '*/15 * * * * '.$_[0].' \'IPFilterUpdate '.$cfg.'\' | '.$^X." '-MMail::SpamAssassin::Contrib::Plugin::IPFilter' > /dev/null 2>&1") );
1014 $c->last( new Config::Crontab::Event( -data => '15 00 * * * '.$_[0].' \'LogFormat '.$cfg.'\' | '.$^X." '-MMail::SpamAssassin::Contrib::Plugin::IPFilter' > /dev/null 2>&1") );
1015 $c->last( new Config::Crontab::Event( -data => '00 23 * * * '.$_[0].' \'Maintenance '.$cfg.'\' | '.$^X." '-MMail::SpamAssassin::Contrib::Plugin::IPFilter' > /dev/null 2>&1") );
1016 $c->last( new Config::Crontab::Event( -data => '00 01 * * * '.$_[0].' \'LogPiwik '.$cfg.'\' | '.$^X." '-MMail::SpamAssassin::Contrib::Plugin::IPFilter' > /dev/null 2>&1") ) if ($self->{conf}->{piwik_host} && $self->{conf}->{piwik_path} && -d $self->{conf}->{piwik_path});
1017 $cron->last($c);
1018 $cron->write;
1019  
1020 undef $cron;
1021 $cron = $_[1] ? new Config::Crontab(-owner => $_[1], -strict => 0) : new Config::Crontab();
1022 $cron->read;
1023  
1024 return $c->dump;
1025  
1026 };
1027  
1028 error('[finish_parsing_end] Could not setup cron jobs') if($v->(find_bin('echo'), 'root') !~ /MAIL[_:]+SPAMASSASSIN[_:]+CONTRIB[_:]+PLUGIN[_:]+IPFILTER/i && $v->(find_bin('echo')) !~ /MAIL[_:]+SPAMASSASSIN[_:]+CONTRIB[_:]+PLUGIN[_:]+IPFILTER/i);
1029  
1030  
1031 re_config($self->{conf});
1032 $self->{conf}->{iptables}->flush_chain('filter', $self->{conf}->{filter_name}) if($self->{conf}->{iptables_support}>0);
1033 $self->{conf}->{ip6tables}->flush_chain('filter', $self->{conf}->{filter_name}) if($self->{conf}->{iptables_support}>4);
1034  
1035 $self->{conf}->{re} = \%Regex;
1036 lock_hashref($self->{conf});
1037 #service_cmd('crond', 'reload') || service_cmd('cron', 'reload');
1038 $self->inhibit_further_callbacks();
1039 return 1;
1040 }
1041
1042 sub check_spamipfilter() {
1043 my ( $self, $pms ) = @_;
1044 return 0;
1045 }
1046  
1047 sub check_end {
1048  
1049 my ($msg, $conf, $msg_score, $spam_score, $nonspam_trigger, $spam_trigger, $db, $key, $pre, $re, %var, %def_var, %sender, %whitelist, $self, $params, $tmp);
1050 ($self, $params) = @_;
1051 $_ = '';
1052 %sender = (ip => '', host => '', ipv6 => 0, to => '', envelope => '', from => '', fkey => '', user => '', domain => '', is_common_domain => 0, extra => '');
1053 %def_var = (avg => 0, total => 0, spamhits => 0, lastspam => 0, extra => '');
1054  
1055 $msg = $params->{permsgstatus};
1056 $conf = $self->{conf};
1057  
1058 $re = $self->{conf}->{re};
1059 %whitelist = %{$self->{conf}->{whitelist}};
1060  
1061 $msg_score = $msg->get_score() + 0.0;
1062 $spam_score = $msg->get_required_score() + 0.0;
1063 $spam_trigger = $spam_score + 1;
1064 $nonspam_trigger = $spam_score - 1;
1065  
1066 if($conf->{trigger_score} > $spam_score){
1067 $spam_trigger = $conf->{trigger_score};
1068 $nonspam_trigger = $spam_score - ($conf->{trigger_score} - $spam_score);
1069 }
1070  
1071 inform('[check_end] processing message with score='.$msg_score.' (spam_score:'.$spam_score.', spam_trigger:'.$spam_trigger.', nonspam_trigger:'.$nonspam_trigger.')');
1072  
1073 $pre = substr($msg->get('ALL-INTERNAL'), 0, 4096);
1074 $sender{envelope} = $msg->get('EnvelopeFrom:addr') || $msg->get('From:addr');
1075 $sender{envelope} =~ s/$re->{trim}//g;
1076  
1077 /()/;
1078 if($sender{envelope} !~ $re->{envelope}){
1079 return error('[check_end] Could not find "envelope" in msg') if($pre !~ $re->{from} && substr($msg->get('ALL'), 0, 4096) !~ $re->{from});
1080 $sender{envelope} = $1;
1081 $sender{envelope} =~ s/$re->{trim}//g;
1082 }
1083  
1084 if((($1) && ($2)) || $sender{envelope} =~ $re->{envelope}){
1085 $sender{from} = substr("$1\@$2", 0, 512);
1086 $sender{from} =~ s/$re->{spaces}//g;
1087 }
1088  
1089 return error('[check_end] Could not find "from" in envelope '.$sender{envelope}) if($sender{from} !~ $re->{email});
1090  
1091 $sender{user} = $1;
1092 $sender{domain} = $2;
1093 $sender{domain} =~ s/$re->{n_domainchars}//g;
1094 $sender{fkey} = encode_base64($sender{user}, '').'@'.$sender{domain};
1095 $sender{extra} = $sender{fkey};
1096  
1097 $sender{to} = lc($msg->get('To:addr') || '');
1098 $sender{to} =~ s/$re->{spaces}//g;
1099 tr_ascii($sender{from}, $sender{to});
1100  
1101 /()/;
1102 $pre = substr($msg->get('Received'), 0, 4096) if($pre !~ $re->{rcvd_header});
1103  
1104 if((($1) && ($2)) || $pre =~ $re->{rcvd_header}){
1105 $sender{host} = lc($1);
1106 $sender{ip} = $2;
1107 inform('[check_end] Received header: '.tr_ascii(substr($pre,0,32)));
1108 }else{
1109 %var = (pre=>'');
1110 #inform('[check_end] Could not match rcvd host/ip');
1111  
1112  
1113 while ( $var{pre} = pop @{$msg->{relays_untrusted}} ){
1114  
1115 if($var{pre}->{ip} && !$var{pre}->{ip_private}){
1116 $sender{ip} = $var{pre}->{ip};
1117 $sender{host} = $var{pre}->{rdns} ? lc($var{pre}->{rdns}) : 'unknown';
1118 last;
1119 }
1120 }
1121 if (!$sender{ip}){
1122 #inform('[check_end] Could not determine IP '.tr_ascii($pre));
1123 return 0;
1124 }
1125 }
1126  
1127 tr_ascii($sender{ip}, $sender{host});
1128 if($sender{ip} =~ $re->{colon}){
1129 $sender{ipv6}= 1;
1130 inform('[check_end] Expanding IP '.$sender{ip});
1131 $sender{ip} = expand_ipv6($sender{ip});
1132 }
1133  
1134 if ($sender{ip} !~ $re->{ip}){
1135 inform('[check_end] Could not determine IP '.$sender{ip});
1136 return 0;
1137 }
1138  
1139 inform('[check_end] user/domain/ip/host: '.$sender{user}.'/'.$sender{domain}.'/'.$sender{ip}.'/'.$sender{host});
1140  
1141 $key = $conf->{db_name}.'-'.$sender{ip};
1142  
1143 if($sender{host} =~ $re->{common_hosts}){
1144 $sender{is_common_domain} = 1;
1145 $sender{domain} = $1 if(!$sender{envelope});
1146 inform('[check_end] domain is common');
1147 if(!$sender{user} || !$sender{domain}){
1148 $sender{from} = 'no user specified' if (!$sender{from});
1149 return error('[check_end] Could not find envelope user from: '.$sender{domain}.' ('.$sender{from}.')');
1150 }
1151  
1152 $sender{from} = $sender{user}.'@'.$sender{domain};
1153 if(exists $whitelist{'@'.$sender{domain}} || exists $whitelist{$sender{from}}){
1154 $msg->got_hit(uc($conf->{filter_name}), 'HEADER: ', score => -1*$conf->{blacklist_score});
1155 inform('[check_end] done '.$sender{from}.' whitelisted ('.$msg->get_score().')');
1156 return 1;
1157 }
1158 $sender{extra} = $sender{ip};
1159 $sender{fkey} = encode_base64($sender{user}, '').'@'.$sender{domain};
1160 $key = $conf->{db_name}.'-'.$sender{fkey};
1161 }
1162  
1163 inform('[check_end] key: '.$key);
1164  
1165 if(exists $whitelist{$sender{ip}}){
1166 $msg->got_hit(uc($conf->{filter_name}), 'HEADER: ', score => -1*$conf->{blacklist_score});
1167 inform('[check_end] done '.$sender{ip}.' whitelisted ('.$msg->get_score().')');
1168 return 1;
1169 }
1170  
1171 return error('[check_end] Could not establish connection to database') if(!($db = dbconnect($conf)));
1172  
1173 $sender{host} = $sender{ip};
1174 if($key=~$re->{ipfromkey}){
1175 $sender{ip} = consolidate_network($db, {ip => $1, host => $2, sender => $sender{fkey}, ipv6 => $sender{ipv6}, conf => $conf, def_var => \%def_var});
1176 if(exists $whitelist{$sender{ip}}){
1177 inform('[check_end] done '.$sender{ip}.' whitelisted');
1178 return 1;
1179 }
1180 $key = $conf->{db_name}.'-'.$sender{ip};
1181 }
1182  
1183 $pre = $key;
1184 $pre =~ s/$re->{key}/$1;expires/;
1185 if($pre ne $key && ($pre = $db->get($key)) && $pre =~ $re->{isint} && time()<int($pre)){
1186 $msg->got_hit(uc($conf->{filter_name}), 'HEADER: ', score => $conf->{blacklist_score});
1187 #$msg->{conf}->{scoreset}->[0]->{uc($conf->{filter_name})} = sprintf("%0.3f", $conf->{blacklist_score});
1188 inform('[check_end] done '.$sender{from}.' is blacklisted ('.$msg->get_score().')');
1189 return 1;
1190 }
1191  
1192 $pre = $db->get($key) || '';
1193 $pre =~ s/$re->{n_dbchars}//g;
1194 inform('[check_end] cached record: '.$pre);
1195 %var = $pre =~ $re->{record} ? (avg => $1 + 0.0, total => $2 + 0.0, spamhits => int($3), lastspam => int($4), extra => $5, cachehit => 1) : %def_var;
1196  
1197 $var{lastspam_delta} = $var{lastspam}>0 ? time() - $var{lastspam} : 0;
1198  
1199 if(exists $var{cachehit} && $var{lastspam}!=0 && $sender{extra} eq $var{extra} && $conf->{seconds_between_messages}>$var{lastspam_delta}){
1200  
1201 if(0!=($var{score}=similarity(join("\n\n",@{$msg->get_decoded_stripped_body_text_array()}), {stopwords=>$conf->{stopwords}, db=>$db, db_name=>$conf->{db_name}, seconds_between_duplicates => $conf->{seconds_between_messages}>>1}, $msg_score >= $spam_score))){
1202  
1203 $var{score} = $var{score}>$conf->{trigger_messages} ? $var{score} - $conf->{trigger_messages} : $var{score}/$conf->{trigger_messages};
1204 $var{x} = $conf->{seconds_to_decay_penalty}<$var{lastspam_delta} ? 5.436 : $var{lastspam_delta}/$conf->{seconds_to_decay_penalty};
1205 $var{score} = nearest(0.01, exp(-1*$var{x}/10)*abs($var{score}));
1206 $msg->got_hit(uc($conf->{filter_name}), 'HEADER: ', score => $var{score}>$conf->{blacklist_score}?$conf->{blacklist_score}:$var{score});
1207 }
1208  
1209 inform('[check_end] skipping duplicate msg with score '.$msg->get_score());
1210 return 1;
1211 }
1212 $var{score} = 0;
1213 if($msg_score < $spam_trigger){
1214 inform('[check_end] processing nonspam') if($msg_score < $spam_score);
1215  
1216 $var{score} = similarity(join("\n\n",@{$msg->get_decoded_stripped_body_text_array()}), {stopwords=>$conf->{stopwords}, db=>$db, db_name=>$conf->{db_name}, seconds_between_duplicates => $conf->{seconds_between_messages}>>1}, $msg_score >= $spam_score);
1217 if($var{score}==-1){
1218 inform('[check_end] skipping duplicate msg');
1219 return 1;
1220 }
1221  
1222 $var{score} = $var{score}>$conf->{trigger_messages} ? $var{score} - $conf->{trigger_messages} : $var{score}/$conf->{trigger_messages};
1223 if($msg_score < $nonspam_trigger && $var{score}==0){
1224 if(exists $var{cachehit}){
1225 $var{total} = $var{total} - ($var{avg} + ($spam_score - $msg_score));
1226 --$var{spamhits};
1227 if($var{total}<1){
1228 %var = (%def_var, lastspam => $var{lastspam}, score => $var{score});
1229 }else{
1230 $var{total} = nearest(0.01, $var{total});
1231 $var{avg} = $var{spamhits}>1 ? nearest(0.01, $var{total}/$var{spamhits}) : $var{total};
1232 $var{spamhits} = 0 if($var{spamhits}<1);
1233 }
1234 $db->set($key => $var{avg}.','.$var{total}.','.$var{spamhits}.','.$var{lastspam}.','.$sender{extra});
1235 inform('[check_end:nonspam] updated cache: '.$key.' => from: '.$pre.' to: '.$var{avg}.','.$var{total}.','.$var{spamhits}.','.$var{lastspam}.','.$sender{extra});
1236 }
1237 }
1238 }
1239 return inform('[check_end] done')+0 if($var{score}+$msg_score < $spam_trigger);
1240  
1241 inform('[check_end] processing as spam candidate');
1242  
1243 $var{w} = $var{spamhits} < 1 ? $conf->{trigger_sensitivity} : ($conf->{trigger_sensitivity}-1)/$var{spamhits};
1244 $var{x} = (!exists $var{cachehit} || $var{cachehit}==0 || $conf->{seconds_to_decay_penalty}<$var{lastspam_delta}) ? 5.436 : $var{lastspam_delta}/$conf->{seconds_to_decay_penalty};
1245  
1246 if($var{score}==0){
1247 $var{score} = ($msg_score<($spam_trigger*3)) ? similarity(join("\n\n",@{$msg->get_decoded_stripped_body_text_array()}), {stopwords=>$conf->{stopwords}, db=>$db, db_name=>$conf->{db_name}, seconds_between_duplicates => $conf->{seconds_between_messages}>>1}, 1) : $conf->{trigger_messages}+1;
1248 if($var{score}>0){
1249 $var{score} = $var{score}>$conf->{trigger_messages} ? $var{score} - $conf->{trigger_messages} : $var{score}/$conf->{trigger_messages};
1250 $var{score} = nearest(0.01, exp(-1*$var{x}/10)*abs($var{score}));
1251 $msg->got_hit(uc($conf->{filter_name}), 'HEADER: ', score => $var{score}>$conf->{blacklist_score}?$conf->{blacklist_score}:$var{score});
1252 inform('[check_end] updated score '.$msg->get_score());
1253 }elsif($var{score}==-1){
1254 inform('[check_end] skipping duplicate spam msg');
1255 return 1;
1256 }
1257 }else{
1258 $var{score} = exp(-1*$var{x}/10)*abs($var{score});
1259 $var{score}=$conf->{blacklist_score} if($conf->{blacklist_score}<$var{score});
1260  
1261 }
1262  
1263 #inform('[check_end:spam] '.$var{score} .','.$var{x}.','.$var{w}.','.($var{cachehit}?1:0).','.$conf->{seconds_to_decay_penalty}.'<'.$var{lastspam_delta});
1264  
1265  
1266 $var{y} = exp(-1*$var{x}) + exp(-3.2*$var{w});
1267 $var{score} = nearest(0.01, $var{score} + $var{y});
1268  
1269 inform('[check_end] penalty '.$var{score});
1270  
1271 $var{spamhits} = 1 if(++$var{spamhits}<1);
1272 $var{total} = nearest(0.01, $var{total} + $var{score} + $msg_score);
1273 $var{avg} = nearest(0.01, $var{total}/$var{spamhits});
1274 $var{lastspam} = time();
1275  
1276 $db->set($key => $var{avg}.','.$var{total}.','.$var{spamhits}.','.$var{lastspam}.','.$sender{extra});
1277 inform('[check_end:spam] updated cache: '.$key.' => from: '.$pre.' to: '.$var{avg}.','.$var{total}.','.$var{spamhits}.','.$var{lastspam}.','.$sender{extra});
1278  
1279 $sender{to_user} = '-';
1280 $sender{to_domain} = $sender{to};
1281 if($sender{to} =~ $re->{email} && ($1) && ($2)){
1282 $sender{to_user} = $1;
1283 $sender{to_domain} = $2;
1284 }
1285 $sender{user} =~ s/$re->{n_dbchars}//g;
1286 $sender{domain} =~ s/$re->{n_domainchars}//g;
1287 $sender{to_user} =~ s/$re->{n_dbchars}//g;
1288 $sender{to_domain} =~ s/$re->{n_domainchars}//g;
1289 $sender{user} = '-' if (!$sender{user});
1290 $sender{domain} = 'null.invalid' if (!$sender{domain});
1291 $sender{to_user} = '-' if (!$sender{to_user});
1292 $sender{to_domain} = 'null.invalid' if (!$sender{to_domain});
1293  
1294 log_stats($sender{ip}.' - - ['.strftime("%d/%b/%Y:%H:%M:%S %z", localtime).'] "GET /'.$sender{to_domain}.'/'.$sender{to_user}.'?pk_spam='. nearest(10, $var{score}).' HTTP/1.1" 200 1024 "http://'.$sender{domain}.'/'.$sender{user}.'" "'.$conf->{ua}.'"');
1295  
1296 if($var{avg} >= $conf->{average_score_for_rule} && $var{spamhits} >= $conf->{trigger_messages}){
1297  
1298 $var{z} = $var{y} * ($var{score}/$conf->{average_score_for_rule});
1299 $var{z} = $conf->{expires_multiplier_penalty}*(1 + $var{z}) if($var{z} >= $conf->{expires_multiplier_penalty});
1300 inform('[check_end] expires penalty '.$var{z});
1301  
1302 $var{expires} = $var{lastspam} + int($conf->{expire_rule_seconds} * $var{z});
1303  
1304 $msg->got_hit(uc($conf->{filter_name}), 'HEADER: ', score => $conf->{blacklist_score});
1305  
1306 if($sender{is_common_domain}){
1307 $db->set($conf->{db_name}.';expires-'.$sender{fkey} => $var{expires});
1308 $db->set($conf->{db_name}.';warning0-'.$sender{fkey} => $sender{ip}."\n".$sender{to}) if($conf->{admin_email} && !$db->exists($conf->{db_name}.';warning-'.$sender{fkey}));
1309 }else{
1310 $db->set($conf->{db_name}.';expires-'.$sender{ip} => $var{expires});
1311 $db->set($conf->{db_name}.';warning0-'.$sender{ip} => $sender{fkey}."\n".$sender{to}) if($conf->{admin_email} && !$db->exists($conf->{db_name}.';warning-'.$sender{ip}));
1312 }
1313 inform('[check_end] added to blacklist: '.$sender{from}.' '.$sender{ip});
1314 log_stats($sender{ip}.' - - ['.strftime("%d/%b/%Y:%H:%M:%S %z", localtime).'] "GET /blacklist/'.$sender{to_domain}.'/'.$sender{to_user}.'?pk_total='. nearest(10, $var{total}).' HTTP/1.1" 200 1024 "http://'.$sender{domain}.'/'.$sender{user}.'" "'.$conf->{ua}.'"');
1315  
1316 }elsif($var{score}>10){
1317 $msg->got_hit(uc($conf->{filter_name}), 'HEADER: ', score => nearest(0.01, 0.1*$var{score}));
1318 }
1319  
1320 inform('[check_end] done ('.$msg->get_score().')');
1321 return 1;
1322  
1323 }
1324  
1325 1;
1326  
1327 __END__