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

filter: Statementstmt 0.0% 0 / 802 Branchbran 0.0% 0 / 398 Conditioncond 0.0% 0 / 450 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 76 Podpod 0.0% 0 / 55 totaltotal 0.0% 0 / 1781 SCAR 106.0
CC
200
Cov
0%
finish_parsing_end
2162.0
check_end
1892.0
dbconnect
110.0
CRAP 40200.0
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);
55 use POSIX qw(strftime);
56 use IPTables::ChainMgr;
57 use Config::Crontab;
58  
59 #use Data::Dumper;
60 use vars qw($VERSION @ISA);
61 my ($Verbose, %Regex, $Logfile, %Cronjobs);
62 $Verbose = 1;
63  
64 $VERSION = 1.1;
65  
66 #stub
67 sub p2p {
68 #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.
69 }
70  
71 sub inform {
72 return if ($Verbose != 1);
73 sub_exists('info') ? info('IPFilter: '.$_[0]) : warn('IPFilter: '.$_[0]);
74 }
75  
76 sub error {
77 info('IPFilter: '.$_[0]) if(sub_exists('info'));
78 warn('IPFilter: '.$_[0]);
79 return 0;
80 }
81  
82 sub fatal {
83 error($_[0]);
84 exit;
85 }
86  
87 sub find_bin {
88 my $path;
89 foreach $path (@{['/bin','/sbin','/usr/bin','/usr/sbin','/usr/local/bin','/usr/local/sbin']}){
90 return $path.'/'.$_[0] if (-e $path.'/'.$_[0]);
91 }
92 }
93  
94 sub sub_exists {
95 no strict 'refs';
96 return defined &{$_[0]} ? 1 : 0;
97 }
98  
99 $dbconnect_mysql::name = 'dbconnect_mysql';
100  
101 sub dbconnect{
102 my ($db,$conf);
103 $conf = shift;
104 if($conf->{db_type} eq 'redis'){
105 $conf->{db_port} = 6379 if(1>int($conf->{db_port}));
106 $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});
107 fatal('Could not establish connection to redis') if (!$db->ping);
108 }elsif($conf->{db_type} eq 'mysql'){
109  
110 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})));
111  
112 $db->{PrintError} = 0;
113 ($db->do('create database if not exists '.$conf->{db_name}) && $db->do('use '.$conf->{db_name})) if (!$db->do('use '.$conf->{db_name}));
114 $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'));
115 $db->{PrintError} = 1;
116 $db = sub { my $self = { db => $db }; bless $self, *dbconnect_mysql; return $self; }->();
117 }
118 return $db;
119 }
120  
121 sub Mail::SpamAssassin::Contrib::Plugin::IPFilter::dbconnect_mysql::exists {
122 my ($h,$r,$db);
123 $db = (shift)->{db};
124 $h = $db->prepare(sprintf('select k from ent where k=%s limit 1', length($_[0]) >0 ? $db->quote($_[0]) : "''"));
125 $h->execute();
126 $r = $h->fetchrow_hashref('NAME_lc');
127 $h->finish();
128 return ((defined $r) && $r && (exists $r->{k})) ? 1 : 0;
129 };
130  
131 sub Mail::SpamAssassin::Contrib::Plugin::IPFilter::dbconnect_mysql::get {
132 my ($h,$r,$db);
133 $db = (shift)->{db};
134 #$k =~ tr/\x00-\x09\x0b\x0c\x0e-\x1f//d;
135 $h = $db->prepare(sprintf('select v from ent where k=%s limit 1', length($_[0]) >0 ? $db->quote($_[0]) : "''"));
136 $h->execute();
137 $r = $h->fetchrow_hashref('NAME_lc');
138 $h->finish();
139 return ((defined $r) && $r && (defined $r->{v})) ? $r->{v} : '';
140 };
141  
142 sub Mail::SpamAssassin::Contrib::Plugin::IPFilter::dbconnect_mysql::set {
143 my ($v,$r,$db);
144 $db = (shift)->{db};
145 $v = length($_[1]) >0 ? $db->quote($_[1]) : "''";
146 $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));
147 };
148  
149 sub Mail::SpamAssassin::Contrib::Plugin::IPFilter::dbconnect_mysql::mget {
150 my ($h,@k,@o,$db);
151 $db = (shift)->{db};
152 @o = ();
153 map{ push @k, (length($_) >0 ? $db->quote($_) : "''") } @_;
154 return @o if(@k==0);
155 $h = $db->prepare('select v from ent where k in ('.join(', ',@k).') order by field(k, '.join(', ',@k).') limit '.int(@k+0));
156 $h->execute();
157 map { push @o, $_->{v} } @{$h->fetchall_arrayref({})};
158 $h->finish();
159 return @o;
160 };
161  
162 sub Mail::SpamAssassin::Contrib::Plugin::IPFilter::dbconnect_mysql::keys {
163 my ($h,$db,@o,$v);
164 $db = (shift)->{db};
165 @o = ();
166 $v=shift;
167 $v=~s/\*/\%/g;
168 $h = $db->prepare(sprintf('select k from ent where k like %s limit 256000',length($v) >0 ? $db->quote($v) : "''"));
169 $h->execute();
170 map { push @o, $_->{k} } @{$h->fetchall_arrayref({})};
171 $h->finish();
172 return @o;
173 };
174  
175 sub Mail::SpamAssassin::Contrib::Plugin::IPFilter::dbconnect_mysql::del {
176 my $db = (shift)->{db};
177 $db->do(sprintf('delete from ent where k=%s limit 1', length($_[0]) >0 ? $db->quote($_[0]) : "''"));
178 };
179  
180 sub Mail::SpamAssassin::Contrib::Plugin::IPFilter::dbconnect_mysql::quit {
181 my $db = (shift)->{db};
182 $db->disconnect if($db);
183 }
184  
185 sub Mail::SpamAssassin::Contrib::Plugin::IPFilter::dbconnect_mysql::AUTOLOAD {
186 my ($self, @args, $name);
187 $name = $dbconnect_mysql::AUTOLOAD;
188 ($self, @args) = @_;
189 return 0;
190 }
191  
192 sub Mail::SpamAssassin::Contrib::Plugin::IPFilter::dbconnect_mysql::DESTROY {
193 my $db = (shift)->{db};
194 $db->disconnect if($db);
195 }
196  
197 sub c_param {
198 fatal('[c_params]: missing conf') if (!$_[0]);
199 my $conf = JSON::XS->new->utf8->decode(decode_base64($_[0]));
200 fatal('[c_params]: Invalid number of params '.join(',', keys %{$conf})) if (int(split('\x7C', sprintf('%s',$Regex{param}))) > int(keys %{$conf}));
201  
202 re_config($conf);
203 $conf->{re} = \%Regex;
204 return $conf;
205 }
206  
207 sub c_logfile {
208 fatal('[c_logfile] Could not find log dir '.$_[0]->{log_dir}) if (!$_[0]->{log_dir} || !-d $_[0]->{log_dir});
209 $Logfile = $_[0]->{log_dir}.'/spamipfilter_'.strftime('%d-%m-%Y', localtime);
210 if(!-e $Logfile){
211 lock($Logfile);
212 fatal('[c_logfile] Could not create log file '.$Logfile) if(!open(IPFILTERLOGSTATS, '+>>'.$Logfile));
213 close(IPFILTERLOGSTATS);
214 chmod(0600, $Logfile);
215 chown(int($1),-1, $Logfile) if ($_[0]->{username} && getpwnam($_[0]->{username})=~/^([0-9]+)$/);
216 }
217 }
218  
219 sub c_ipfilter_update {
220  
221 my ($conf, @buffer, $db, $expires, $iptables, $sa);
222  
223 $expires = time();
224 $conf = c_param(shift);
225  
226 $sa = Mail::SpamAssassin->new($conf);
227  
228 @buffer = iptables_cmd('-L '.$conf->{filter_name}.' -n -v -x', $conf);
229 $iptables = join('', @{$buffer[1]}) if(@buffer && defined $buffer[1] && @{$buffer[1]});
230  
231 $db = dbconnect($conf);
232 if($conf->{admin_email}){
233 @buffer = localtime();
234 clean_notifications($db, {conf => $conf}) if ($buffer[6]==6 && $buffer[2]==2);
235 notify_blacklist($db, {conf => $conf});
236 }
237 refresh_iptables($db, {conf => $conf, iptables => $iptables});
238 refresh_list($db, {conf => $conf, mailsa => $sa});
239 $db->quit;
240  
241 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);
242  
243 exit;
244 }
245  
246 sub c_maintenance {
247  
248 my ($conf, $db);
249 $conf = c_param(shift);
250 $db = dbconnect($conf);
251 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 });
252 $db->quit;
253 exit;
254 }
255  
256 sub c_log_format {
257  
258 my (@data, $conf);
259 $conf = c_param(shift);
260  
261 fatal('[c_log_format] Could not read log dir: '.$conf->{log_dir}) if (!$conf->{log_dir} || !-d $conf->{log_dir});
262  
263 $data[0] = 0;
264 if(opendir(IPFILTERLOGDIR, $conf->{log_dir})){
265 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;
266 closedir(IPFILTERLOGDIR);
267 }
268 inform('[c_log_format] '.$Logfile);
269 if($Logfile && -e $Logfile && index($Logfile, $conf->{log_dir}.'/spamipfilter')==0 && index(substr($Logfile,0,len($Logfile)+1),'/')==-1){
270 lock($Logfile);
271 rename($Logfile, $conf->{log_dir}.'/.'. pop @{[split('/', $Logfile)]});
272 }
273 c_logfile($conf);
274  
275 exit;
276 }
277  
278 sub c_log_piwik {
279 my (@data, $conf);
280  
281 $conf = c_param(shift);
282 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});
283  
284 if(opendir(IPFILTERLOGDIR, $conf->{log_dir})){
285 @data = grep /\.spamipfilter\_[0-9]+\-[0-9]+\-2[0-9][0-9][0-9]$/i, readdir IPFILTERLOGDIR;
286 closedir(IPFILTERLOGDIR);
287 }
288 exit if (@data<1 || !find_bin('python'));
289 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;
290 exit;
291 }
292  
293 sub log_stats {
294 return if(!$Logfile);
295 my $s = shift;
296  
297 {
298 lock($Logfile);
299 if (!-e $Logfile){
300 $Logfile = substr($Logfile,0,rindex($Logfile,'/')+1).'spamipfilter_'.strftime('%d-%m-%Y', localtime);
301 select(undef, undef, undef, int(rand(24) + 8)/128);
302 lock($Logfile);
303 return if(!-e $Logfile);
304 close(IPFILTERLOGSTATS) if(defined fileno(IPFILTERLOGSTATS));
305 return if(!open(IPFILTERLOGSTATS, '>>'.$Logfile));
306 }
307 return if(!defined fileno(IPFILTERLOGSTATS) && !open(IPFILTERLOGSTATS, '>>'.$Logfile));
308 }
309  
310 timeout_call( 10 ,sub {
311 return if(!flock(IPFILTERLOGSTATS, LOCK_EX) || !seek(IPFILTERLOGSTATS, 0, SEEK_END));
312 print IPFILTERLOGSTATS $s."\n";
313 error('[log_stats] Could not unlock log file '.$Logfile) if(!flock(IPFILTERLOGSTATS, LOCK_UN));
314 });
315  
316 }
317  
318 sub finish {
319 close(IPFILTERLOGSTATS) if(defined fileno(IPFILTERLOGSTATS));
320 close(IPFILTERLOGSTATS) if(defined fileno(IPTABLESLOCKFILE));
321 }
322  
323 # Thanks to the authors of Net::IP: Manuel Valente, Monica Cortes Sack,
324 # and Lee Wilmot for the implementation concepts behind expand_ipv6()
325 sub expand_ipv6 {
326 my ($a, $b, $c, $i, @d, @ip, $addr);
327 $addr = shift;
328  
329 $addr =~ s/::/: :/g;
330 @ip = split('\:', $addr);
331  
332 $c = $a = int(@ip + 0);
333 for($i=-1;++$i<$a;){
334 if(index($ip[$i], '.')!=-1){
335 $b = unpack('B32', pack('C4C4C4C4', split('\.', $ip[$i])));
336 $ip[$i] = substr(join(':', unpack('H4H4H4H4H4H4H4H4', pack('B128', '0' x (128 - length($b)) . $b))), -9);
337 ++$c;
338 next;
339 }
340 $ip[$i] = ('0' x (4 - length($ip[$i]))) . $ip[$i];
341 }
342  
343 @d = ('0000','0000','0000','0000','0000','0000','0000','0000');
344  
345 return (index($addr,'.')!=-1?'0:0:0:0:0:ffff:':'').join(':', (map{ $_ eq '000 ' ? join(':', @d[0 .. (8 - $c)]) : lc($_) } @ip));
346 }
347  
348 sub cidr_2 {
349 my (@octet, $ipv6, $cidr);
350 (@octet, $ipv6) = @_;
351 $cidr = $ipv6 ? 128 : 32;
352 while(0!=($octet[0] ^ $octet[1])){
353 $octet[0] = $octet[0] >> 1;
354 $octet[1] = $octet[1] >> 1;
355 --$cidr;
356 }
357 return $cidr;
358 }
359  
360 sub cidr_16 {
361 return ($_[0]>-1 && $_[0]<33) ? (128-(32-$_[0])) : 128;
362 }
363  
364 sub network_octet {
365 # (octet, cidr) = @_
366 return $_[2] ? sprintf('%02x', hex($_[0]) & (256 - (1<<(128-$_[1])))) : $_[0] & (256 - (1<<(32-$_[1])));
367 }
368  
369 sub consolidate_network {
370 my (%var, $cidr, $pre, $conf, $db, $params);
371 ($db, $params) = @_;
372  
373 $conf = $params->{conf};
374  
375 $pre = $params->{ip}.$params->{host};
376 $params->{cidr} = 32;
377 $var{$pre} = int($params->{host});
378 if($params->{ipv6}){
379 $params->{cidr} = 128;
380 $var{$pre} = hex($params->{host});
381 }
382  
383 map{$_=~$conf->{re}->{ipfromkey} && ($var{$1.$2} = ($params->{ipv6}) ? hex($2):int($2))} @{[$db->keys($conf->{db_name}.'-'.$params->{ip}.'*')]};
384 $cidr = int( cidr_2( @var{@{[sort { $var{$a} <=> $var{$b} } keys(%var)]}[0,-1]}, $params->{ipv6} ));
385 $params->{host} = network_octet($params->{host}, $cidr, $params->{ipv6});
386 $params->{network} = int($db->get($conf->{db_name}.';network-'.$params->{ip}.$params->{host}) || $params->{cidr});
387  
388 #an edge case may exist due to concurrency where multiple IPs within the same network overwrite one another
389 if($cidr < $params->{cidr}){
390  
391 $pre = $params->{ip}.$params->{host};
392  
393 if($cidr < $params->{network}){
394 %var = (def => {%{$params->{def_var}}, expires => 0});
395 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}) ]};
396  
397 $db->set($conf->{db_name}.';network-'.$pre => $cidr);
398 $db->set($conf->{db_name}.'-'.$pre => $var{def}->{avg}.','.$var{def}->{total}.','.$var{def}->{spamhits}.','.$var{def}->{lastspam}.','.$params->{sender});
399 $db->set($conf->{db_name}.';expires-'.$pre => $var{def}->{expires}) if(int($var{def}->{expires})>0);
400 }
401 }
402 return $pre;
403 }
404  
405 sub op_rkeys {
406 my ($n, $i, $c, @buffer, @acc, $re, $pattern, $code, $db, $params);
407 ($pattern, $code, $db, $params) = @_;
408  
409 $re = $params->{conf}->{re};
410  
411 @buffer = @{[$db->keys($params->{conf}->{db_name}.$pattern)]};
412  
413 $n = int(@buffer + 0);
414 while(0!=$n%4){
415 push @buffer, '';
416 ++$n;
417 }
418  
419 for($i=0; $i<$n; $i+=4){
420 $c = -1;
421 map { push @acc, $code->($buffer[$i + ++$c], $_, $db, $params) } @{[$db->mget( grep /$re->{alnumchar}/, @{[@buffer[$i..($i+3)]]} )]};
422 }
423  
424 return @acc;
425 }
426  
427 sub op_batch {
428 my ($n, $i, $c, @acc, $re, $buffer, $code, $params);
429 ($buffer, $code, $params) = @_;
430  
431 $re = $params->{conf}->{re};
432  
433 $n = int(@$buffer + 0);
434 while(0!=$n%4){
435 push @$buffer, '';
436 ++$n;
437 }
438  
439 for($i=0; $i<$n; $i+=4){
440 $c = -1;
441 push @acc, $code->(\@{[ grep /$re->{alnumchar}/, @{[@$buffer[$i..($i+3)]]} ]}, $params);
442 }
443  
444 return @acc;
445 }
446  
447 sub tr_ascii {
448 grep tr/\x00-\x09\x0b\x0c\x0e-\x1f\x7f-\xff//d, @_;
449 return @_ == 1 ? $_[0] : @_;
450 }
451  
452 sub sanitize {
453 my ($var, $re, $def) = @_;
454 $def = '' if (!defined $def);
455 $var =~ tr/\x00-\x09\x0b\x0c\x0e-\x1f\x7f-\xff//d;
456 return $var =~ $re ? $1 : ($def ? sanitize($def, $re) : '');
457 }
458  
459 sub iptables_mgr {
460 my ($iptables, @res, $ipv6);
461 $ipv6 = (defined $_[1] && $_[1] == 6) ? 1 : 0;
462 return 0 if($_[0]->{iptables_support}==0 || ($ipv6 && $_[0]->{iptables_support}!=6));
463 $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);
464 $iptables->{'parse_obj'}->{'_lockless_ipt_exec'} = 0 if($iptables && $iptables->{'parse_obj'} && $iptables->{'parse_obj'}->{'_lockless_ipt_exec'});
465 fatal(($ipv6?'[ip6tables]':'[iptables]').'Could not determine if chain '.$_[0]->{filter_name}.' exists') if(!(@res = $iptables->chain_exists('filter', $_[0]->{filter_name})));
466 if($res[0]!=1){
467 $iptables->create_chain('filter', $_[0]->{filter_name});
468 $iptables->add_jump_rule('filter', 'INPUT', 4, $_[0]->{filter_name});
469 }
470  
471 return $iptables;
472 }
473  
474 sub iptables_cmd {
475 my ($args, $conf, @res, $iptables);
476 ($args, $conf, $iptables) = @_;
477  
478 return 1 if($conf->{iptables_support}==0);
479  
480 $iptables = 'iptables';
481 if(defined $_[2] && $_[2] == 6){
482 return 1 if($conf->{iptables_support}!=6);
483 $iptables = 'ip6tables';
484 }
485  
486 @res = (0, [], []);
487 timeout_call( 5 ,sub {
488  
489 if((defined fileno(IPTABLESLOCKFILE) || open(IPTABLESLOCKFILE, '+>>'.$conf->{iptables_lockfile})) && flock(IPTABLESLOCKFILE, LOCK_EX)){
490 @res = ();
491 @res = $conf->{$iptables}->run_ipt_cmd($conf->{$iptables.'_bin'}.' '.$1) if($args !~ $conf->{re}->{martian_ip} && $args =~ $conf->{re}->{iptables_arg});
492 flock(IPTABLESLOCKFILE, LOCK_UN);
493 (@res && $res[0]==1) ? inform('['.$iptables.'] '.$conf->{$iptables.'_bin'}.' '.$args) : error('['.$iptables.'] Error: '.$conf->{$iptables.'_bin'}.' '.$args);
494 }
495 });
496  
497 return @res;
498 }
499  
500 sub ip6tables_normalize {
501 return $_[1]->{iptables_support} == 6 ? $_[1]->{ip6tables}->normalize_net($_[0]) : ''; #s/b default ip
502 }
503  
504 sub service_cmd {
505  
506 my ($service, $initd, $arg, $cmd);
507  
508 $service = shift;
509 $arg = join (' ', @_);
510  
511 if(($initd = find_bin('service'))){
512 $cmd = "$initd $service $arg";
513 }elsif(($initd = find_bin('initctl')) || ($initd = find_bin('svcadm')) || ($initd = find_bin('systemctl'))){
514 $cmd = "$initd $arg $service";
515 }elsif(( $service=~/\// && -e $service && ($initd=$service)) && (($initd="/etc/init.d/$service") && -e $initd) || (($initd="/sbin/init.d/$service") && -e $initd) ){
516 $cmd = "$initd $arg";
517 }
518  
519 return (!$cmd || system($cmd)!=0 || $? == -1 || $? & 127) ? 0 : 1;
520 }
521  
522 sub clean_notifications {
523 op_rkeys(';warning-*', \&clean_notifications_op, $_[0], $_[1]);
524 }
525  
526 sub notify_blacklist {
527 my $params = $_[1];
528 return if ($_[1]->{conf}->{admin_email} !~ $_[1]->{conf}->{re}->{envelope});
529 $_[1]->{admin_email_address} = $1.'@'.$2;
530 op_rkeys(';warning0-*', \&notify_blacklist_op, $_[0], $_[1]);
531 }
532  
533 sub refresh_iptables {
534 $_[1]->{iptables} = '' if(!$_[1]->{iptables});
535 op_rkeys(';expires-*', \&refresh_iptables_op, $_[0], $_[1]);
536 }
537  
538 sub notify_blacklist_op {
539 my ($re, %var, $msg, $message, $k, $v, $db, $params);
540 ($k, $v, $db, $params) = @_;
541  
542 $re = $params->{conf}->{re};
543 %var = (user => '', domain => '', email => '', ip => '', recipient => '', admin => $params->{admin_email_address});
544  
545 $db->del($k);
546 $k =~ s/$re->{subkey}/;warning-/;
547 return if($db->exists($k));
548 $db->set($k => time());
549  
550 ($v, $var{recipient}) = split("\n", $v);
551 if($v =~ $re->{ip} && $k =~ $re->{emailfromkey}){
552 $var{user} = decode_base64($1);
553 $var{domain} = $2;
554 $var{ip} = $v;
555 }elsif($k =~ $re->{ipfromkey}){
556 $var{ip} = $1.$2;
557 return if($v !~ $re->{email});
558 $var{user} = decode_base64($1);
559 $var{domain} = $2;
560  
561 }else{
562 return;
563 }
564  
565 $v = $var{email} = $var{user}.'@'.$var{domain};
566 map{ $var{$_} = substr($var{$_}, 0,56) } keys %var;
567 $message = $params->{conf}->{admin_message};
568 $message =~ s/$re->{admintpl}/$var{lc($1)}/ig;
569  
570 $msg = MIME::Lite->new(
571 'From' => $params->{conf}->{admin_email},
572 'To' => $v,
573 'Subject' => 'Delivery Failure Notification: blocked',
574 'Type' => 'text/plain',
575 'Data' => $message,
576 );
577  
578 $msg->send;
579 }
580  
581 sub clean_notifications_op {
582 return if ((int($_[1]) + 2592000) > time());
583 $_[2]->del($_[0]);
584 }
585  
586 sub refresh_iptables_op {
587 my ($re, $t, $ip, $cidr, $nm, $k, $v, $db, $params);
588 ($k, $v, $db, $params) = @_;
589  
590 $re = $params->{conf}->{re};
591  
592 $t = time();
593 return if ( $t > int($v) || $k =~ $re->{martian_ip} || $k !~ $re->{ipfromkey});
594  
595 $ip = $1.$2;
596  
597 return if($params->{iptables} =~ /[^0-9]\Q$ip\E[^0-9]/sm);
598 $nm = $ip =~ $re->{colon} ? 128 : 32;
599 $cidr = $db->get($params->{conf}->{db_name}.';network-'.$ip) || $nm;
600  
601 $ip = sanitize($ip, $re->{ip}, '');
602 $nm = sanitize($cidr, $re->{integer}, $nm);
603 $v = sanitize($v, $re->{integer}, $t+864000);
604 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}));
605  
606 }
607  
608 sub refresh_list {
609 op_rkeys(';expires-*', \&refresh_list_op, $_[0], $_[1]);
610 }
611  
612 sub refresh_list_op {
613 my ($k, $v, $db, $params) = @_;
614  
615 return if ($v > time());
616 $db->del($k);
617  
618 return if($k !~ $params->{conf}->{re}->{emailfromkey});
619 $v = decode_base64($1).'@'.$2;
620 #$params->{mailsa}->remove_address_from_whitelist($v);
621 inform('[maintenance] removed from blacklist: '.$v);
622 }
623  
624 sub consolidate_network_op {
625 my ($k, $v, $db, $params, $re, %var, $ip);
626  
627 ($k, $v, $db, $params) = @_;
628  
629 $re = $params->{conf}->{re};
630 %var = $v =~ $re->{record} ? (avg => $1 + 0.0, total => $2 + 0.0, spamhits => int($3), lastspam => int($4), cachehit => 1) : %{$params->{def_var}};
631 $var{expires} = 0;
632 if($k =~ $re->{ipfromkey}){
633 $ip = $1.$2;
634 $var{expires} = $db->get($params->{conf}->{db_name}.';expires-'.$ip) || 0;
635 $db->del($params->{conf}->{db_name}.';network-'.$ip);
636 $db->del($params->{conf}->{db_name}.';expires-'.$ip);
637 }
638 $db->del($k);
639 return \%var;
640 }
641  
642 sub cache_decay_op {
643 my ($re, $time, %a, $k, $v, $db, $params);
644  
645 ($k, $v, $db, $params) = @_;
646  
647 $time = time();
648 $re = $params->{conf}->{re};
649  
650 $v =~ s/$re->{spaces}//g;
651 return if($v !~ $re->{record});
652  
653 %a = (avg => $1 + 0.0, total => $2 + 0.0, spamhits => int($3), lastspam => int($4), morf => $5);
654 $a{lastspam_delta} = $time - $a{lastspam};
655  
656 return if($a{lastspam_delta}<60);
657  
658 if($params->{cache_decay_secs} < $a{lastspam_delta}){
659 $db->del($k);
660 inform('[maintenance] removed from cache: '.$k.' => '.$v);
661 return;
662 }
663  
664 $a{total} = nearest(0.01, $a{total} * exp(-3.2*$a{lastspam_delta}/$params->{cache_decay_secs}));
665 $a{spamhits} = nearest(1, $a{total}/$params->{average_score_for_rule});
666 $a{spamhits} = $params->{trigger_messages} if($a{spamhits} > $params->{trigger_messages});
667 $a{spamhits} = 1 if($a{spamhits}<1);
668 $a{avg} = nearest(0.01, $a{total}/$a{spamhits});
669  
670 $db->set($k => $a{avg}.','.$a{total}.','.$a{spamhits}.','.$a{lastspam}.','.$a{morf});
671 inform('[maintenance] decay updated cache: '.$k.' => from: '.$v. ' to: '. $a{avg}.','.$a{total}.','.$a{spamhits}.','.$a{lastspam}.','.$a{morf});
672  
673 }
674  
675 sub get_config {
676 return {
677 iptables_bin => '/sbin/iptables',
678 ip6tables_bin => '/sbin/ip6tables',
679 iptables_support => 6,
680 filter_name => 'spamipfilter',
681 db_type => 'redis',
682 db_host => '127.0.0.1',
683 db_port => 0,
684 db_user => '',
685 db_auth => '',
686 db_name => 'spamipfilter',
687 piwik_host =>'',
688 piwik_path=>,'',
689 piwik_idsite=>1,
690 log_dir => '/var/log',
691 trigger_score => 6,
692 trigger_messages => 3,
693 trigger_sensitivity => 4,
694 average_score_for_rule => 7,
695 expire_rule_seconds => 172800,
696 seconds_to_decay_penalty => 300,
697 seconds_between_messages => 30,
698 expires_multiplier_penalty => 1.5,
699 cache_decay_days => 60,
700 blacklist_score => 30,
701 verbose => 0,
702 whitelist => '',
703 admin_email => '',
704 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.",
705 common_hosts => 'gmail.com, google.com, yahoo.com, hotmail.com, live.com',
706 iptables_lockfile => '',
707 ua => '',
708 username => ''
709  
710 };
711 }
712  
713 sub re_config {
714 my $k;
715 $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` : '';
716 $k =~ s/$Regex{spaces}//g;
717 if($k){
718 $_[0]->{iptables_support} = 0;
719 error('iptables-filter kernel module not loaded... iptables functionality disabled');
720 }
721 $k = $_[0]->{db_name};
722  
723 $_[0]->{iptables} = iptables_mgr($_[0], 4);
724 $_[0]->{ip6tables} = iptables_mgr($_[0], 6);
725  
726 $Regex{key} = qr/^(\Q$k\E)/;
727 $Regex{emailfromkey} = qr/^\Q$k\E(?:;(?:(?:expires)|(?:warning[0-9]*)))?-([^\@]+)\@([^\@]+)$/;
728  
729 }
730  
731 sub compile_regex {
732 my $k = get_config()->{db_name};
733 # Although SA preprocesses much of the data captured, this should be tightened
734 return (
735 from => qr/(?:^|\n)[\t ]*from\:([^\r\n\@]+\@[^\r\n]+)[\r\n]/i,
736 envelope => qr/(?:^|(?:[^\x3C]*\x3C))([^\x3C\x3E\@]+)\@([^\x3C\x3E\@]+)(?:\x3E|$)/,
737 alnumchar => qr/[a-z0-9]/i,
738 isint => qr/^[0-9]+$/i,
739 spaces => qr/[\r\n\t ]+/,
740 trim => qr/(?:^['",\r\n\t ]+)|(?:['",\r\n\t ]+$)/,
741 email => qr/^(.+)\@(.+)$/,
742 n_domainchars => qr/[^0-9.\-a-zA-Z]/,
743 n_dbchars => qr/[^0-9.,\@a-z_\-+\/=]/i,
744 integer => qr/^([0-9]+)$/,
745 colon => qr/\:/,
746 iptables_arg => qr/^([ -;=A-_a-~]+)$/,
747 record => qr/^([0-9.]+),([0-9.]+),([0-9.]+),([0-9.]+)(?:(?:,(.*))|$)/,
748 subkey => qr/;[a-zA-Z0-9]+\-/,
749 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,
750 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,
751 key => qr/^(\Q$k\E)/,
752 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,
753 emailfromkey => qr/^\Q$k\E(?:;(?:(?:expires)|(?:warning[0-9]*)))?-([^\@]+)\@([^\@]+)$/,
754 admintpl => qr/\$((?:user)|(?:domain)|(?:ip)|(?:email)|(?:recipient)|(?:admin))/i,
755 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,
756 #Thanks to Salvador Fandino's Regexp::IPv6
757 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,
758  
759 param => sub { my $r = '^(?:(?:'.join(')|(?:',keys %{get_config()}).'))$'; $r=~s/\_/\\_/g; return qr/$r/sm; }->(),
760 martian_ip => sub {
761 my ($r, @buffer);
762 $r = find_bin('route');
763 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`);
764 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`);
765 $r = '(?:'.join (')|(?:', @buffer).')';
766 $r =~ s/\Q.\E/\\./g;
767 $r =~ s/([0-9])\:/$1\\:/g;
768 use re 'eval';
769 #ipv6 needs *some* work
770 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;
771  
772 }->()
773 );
774 }
775  
776 BEGIN {
777  
778 %Regex = compile_regex();
779 %Cronjobs = (IPFilterUpdate => \&c_ipfilter_update, Maintenance => \&c_maintenance, LogFormat => \&c_log_format, LogPiwik => \&c_log_piwik);
780 $Cronjobs{$1}->($2) if(do {local $/; STDIN->blocking(0); <STDIN>} =~ /^([a-zA-Z_]+)[ ][ ]*(.*)$/ && (STDIN->blocking(1)||1) && ($1) && ($2) && (exists $Cronjobs{$1}) );
781  
782 require Mail::SpamAssassin::Plugin;
783 Mail::SpamAssassin::Plugin->import();
784 require Mail::SpamAssassin::Logger;
785 Mail::SpamAssassin::Logger->import();
786 @ISA = qw(Mail::SpamAssassin::Plugin);
787  
788 } # ...
789  
790  
791 sub new {
792 my ($class, $mailsa, $self);
793 ($class, $mailsa) = @_;
794 $class = ref($class) || $class;
795 $self = $class->SUPER::new($mailsa);
796 bless ($self, $class);
797 $self->{mailsa} = $mailsa;
798 $self->set_config($mailsa->{conf});
799 return $self;
800 }
801  
802 sub set_config {
803 my (@cmds, $c, $self, $conf);
804 ($self, $conf) = @_;
805 $self->{conf} = get_config();
806 foreach $c (keys %{$self->{conf}}){
807 push(@cmds, {
808 'setting' => 'ipfilter_'.$c,
809 'default' => $self->{conf}->{$c},
810 'type' => $self->{conf}->{$c} =~ /^[0-9]+(?:\.[0-9]+)?$/ ? $Mail::SpamAssassin::Conf::CONF_TYPE_NUMERIC : $Mail::SpamAssassin::Conf::CONF_TYPE_STRING
811 }
812 );
813 }
814  
815 $conf->{parser}->register_commands(\@cmds);
816 }
817  
818 sub finish_parsing_end {
819  
820 my ($c, $v, $ini, $db, $self, $params);
821  
822 ($self, $params) = @_;
823 $self->{conf}->{whitelist} = {};
824 $ini = get_config(); #should == $self->{conf}
825  
826 foreach $c (keys %{$self->{conf}}){
827 if(defined $params->{conf}->{'ipfilter_'.$c} && exists $ini->{$c} && $c=~$Regex{param}){
828 $v = $params->{conf}->{'ipfilter_'.$c};
829 $v =~ s/(?:^[\r\n\t ]+)|(?:[\x00])|(?:[\r\n\t ]+$)//g;
830 $v =~ s/\/$//g if($c =~ /(?:(?:\_bin)|(?:\_dir)|(?:\_path))$/);
831 if($v =~ /^([0-9]+(?:\.[0-9]+)?)$/ || $ini->{$c} =~ /^([0-9]+(?:\.[0-9]+)?)$/){
832 $self->{conf}->{$c} = $1 + 0;
833 }elsif($c =~ /whitelist$/i){
834 $v =~ s/[ \r\n\t]*//g;
835 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);
836 }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]*)$/){
837  
838 $self->{conf}->{$c} = $1;
839 }else{
840 inform('[finish_parsing_end] unknown configuration '.$c.' => '.$v);
841 }
842 }
843 }
844  
845 $Verbose = 1 if(int($self->{conf}->{verbose})>0);
846  
847 $self->{conf}->{ua} = 'Mozilla/5.0 (compatible; foobot/2.0; +http://www.foo.com/foobot.htm)' if(!$self->{conf}->{ua});
848 $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});
849  
850 $self->{conf}->{filter_name} = 'spamipfilter' if ($self->{conf}->{filter_name} !~ /^[a-z0-9\-_.]+$/i);
851 $self->{conf}->{iptables_support} = $self->{conf}->{iptables_support} + 0;
852 $self->{conf}->{iptables_support} = 4 if($self->{conf}->{iptables_support}!=0 && $self->{conf}->{iptables_support}!=4 && $self->{conf}->{iptables_support}!=6);
853 if($self->{conf}->{iptables_support}>0){
854 $self->{conf}->{iptables_bin} = ($self->{conf}->{iptables_bin} && -e $self->{conf}->{iptables_bin}) ? $self->{conf}->{iptables_bin} : (find_bin('iptables') ? find_bin('iptables') : '');
855 $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});
856 $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);
857 }
858  
859 $self->{conf}->{iptables_support} = 4 if(!$self->{conf}->{ip6tables_bin});
860 $self->{conf}->{iptables_support} = 0 if(!$self->{conf}->{iptables_bin});
861  
862 $self->{conf}->{db_host} =~ s/^.*?\:\/\///g;
863 $self->{conf}->{db_port} = int($self->{conf}->{db_port});
864 $self->{conf}->{db_port} = 0 if ($self->{conf}->{db_port}<1);
865  
866 $self->{conf}->{piwik_idsite} = int($self->{conf}->{piwik_idsite}+0);
867 $self->{conf}->{piwik_host} = 'http://'.$self->{conf}->{piwik_host} if ($self->{conf}->{piwik_host} && $self->{conf}->{piwik_host}!~/^[^\/]+\:\/\//);
868  
869 $self->{conf}->{expire_rule_seconds} = $self->{conf}->{expire_rule_seconds} + 0.0;
870 $self->{conf}->{expire_rule_seconds} = 300 if(300 > $self->{conf}->{expire_rule_seconds});
871 $self->{conf}->{cache_decay_days} = $self->{conf}->{expire_rule_seconds}*90/86400;
872 $self->{conf}->{cache_decay_days} = 1 if(0.2 > $self->{conf}->{cache_decay_days});
873 $self->{conf}->{seconds_to_decay_penalty} = 2 if(2 > $self->{conf}->{seconds_to_decay_penalty});
874 $self->{conf}->{seconds_between_messages} = 0.99 if(1 > $self->{conf}->{seconds_between_messages});
875 $self->{conf}->{trigger_messages} = 1 if(1 > $self->{conf}->{trigger_messages});
876 $self->{conf}->{average_score_for_rule} = 1 if(0.2 > $self->{conf}->{average_score_for_rule});
877 $self->{conf}->{trigger_sensitivity} = 1 if(0.2 > $self->{conf}->{trigger_sensitivity});
878  
879 $self->{conf}->{common_hosts} =~ s/[ \r\n\t]*//g;
880 $c = $self->{conf}->{common_hosts};
881 $c =~ s/\Q.\E/\\./g;
882 $c = ($self->{conf}->{common_hosts}) ? '(?:^|\.)((?:'.join(')|(?:', split(',', lc($c))).'))(?:[^a-z]|$)' : '^$';
883 $Regex{common_hosts} = qr/$c/i;
884  
885 ($self->{conf}->{log_dir} = -d '/tmp' ? '/tmp' : getcwd()) if(!-d $self->{conf}->{log_dir} || !-w $self->{conf}->{log_dir});
886  
887  
888 if(-d $self->{conf}->{log_dir}){
889 mkdir($self->{conf}->{log_dir}.'/'.$self->{conf}->{filter_name}) if(!-d $self->{conf}->{log_dir});
890 $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});
891 }
892  
893 fatal('Could not find log directory '.$self->{conf}->{log_dir}) if(!-d $self->{conf}->{log_dir} || !-w $self->{conf}->{log_dir});
894 c_logfile($self->{conf});
895  
896 map { ($_ =~ /(?:(?:\_bin)|(?:\_dir)|(?:\_path))$/) && (!-e $self->{conf}->{$_} && !-d $self->{conf}->{$_}) && ($self->{conf}->{$_}='')} (keys %{$self->{conf}});
897  
898  
899 $v = sub {
900  
901 my ($cron, $cfg);
902 $cron = $_[1] ? new Config::Crontab(-owner => $_[1], -strict => 0) : new Config::Crontab();
903  
904 #see caveats: http://search.cpan.org/~scottw/Config-Crontab-1.40/Crontab.pm#CAVEATS
905 $cron->remove($cron->select(-command_re => 'Mail::SpamAssassin::Contrib::Plugin::IPFilter'));
906 $cron->remove($cron->select(-name => 'MAIL_SPAMASSASSIN_CONTRIB_PLUGIN_IPFILTER'));
907  
908 $cron->write;
909  
910 $c = new Config::Crontab::Block;
911 $cfg = encode_base64(JSON::XS->new->utf8->encode($self->{conf}),'');
912  
913
914 #$c->last( new Config::Crontab::Env( -name => 'MAIL_SPAMASSASSIN_CONTRIB_PLUGIN_IPFILTER', -value=> '"'.encode_base64(JSON::XS->new->utf8->encode($self->{conf}), '').'"') );
915  
916 #TODO: better $cfg handling... env. var or r/o file
917 $c->last( new Config::Crontab::Event( -data => '*/15 * * * * '.$_[0].' \'IPFilterUpdate '.$cfg.'\' | '.$^X." '-MMail::SpamAssassin::Contrib::Plugin::IPFilter' > /dev/null 2>&1") );
918 $c->last( new Config::Crontab::Event( -data => '15 00 * * * '.$_[0].' \'LogFormat '.$cfg.'\' | '.$^X." '-MMail::SpamAssassin::Contrib::Plugin::IPFilter' > /dev/null 2>&1") );
919 $c->last( new Config::Crontab::Event( -data => '00 23 * * * '.$_[0].' \'Maintenance '.$cfg.'\' | '.$^X." '-MMail::SpamAssassin::Contrib::Plugin::IPFilter' > /dev/null 2>&1") );
920 $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});
921 $cron->last($c);
922 $cron->write;
923  
924 undef $cron;
925 $cron = $_[1] ? new Config::Crontab(-owner => $_[1], -strict => 0) : new Config::Crontab();
926 $cron->read;
927  
928 return $c->dump;
929  
930 };
931  
932 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);
933  
934  
935 re_config($self->{conf});
936 $self->{conf}->{iptables}->flush_chain('filter', $self->{conf}->{filter_name}) if($self->{conf}->{iptables_support}>0);
937 $self->{conf}->{ip6tables}->flush_chain('filter', $self->{conf}->{filter_name}) if($self->{conf}->{iptables_support}>4);
938  
939 $self->{conf}->{re} = \%Regex;
940 lock_hashref($self->{conf});
941 #service_cmd('crond', 'reload') || service_cmd('cron', 'reload');
942 $self->inhibit_further_callbacks();
943 return 1;
944 }
945  
946 sub check_end {
947  
948 my ($msg, $conf, $msg_score, $spam_score, $ham_trigger, $spam_trigger, $db, $key, $pre, $re, %var, %def_var, %sender, %whitelist, $self, $params);
949 ($self, $params) = @_;
950 $_ = '';
951 %sender = (ip => '', host => '', ipv6 => 0, to => '', envelope => '', from => '', fkey => '', user => '', domain => '', is_common_domain => 0, extra => '');
952 %def_var = (avg => 0, total => 0, spamhits => 0, lastspam => 0, extra => '');
953  
954 $msg = $params->{permsgstatus};
955 $conf = $self->{conf};
956  
957 $re = $self->{conf}->{re};
958 %whitelist = %{$self->{conf}->{whitelist}};
959  
960 $msg_score = $msg->get_score() + 0.0;
961 $spam_score = $msg->get_required_score() + 0.0;
962 $spam_trigger = $spam_score + 1;
963 $ham_trigger = $spam_score - 1;
964  
965 if($conf->{trigger_score} > $spam_score){
966 $spam_trigger = $conf->{trigger_score};
967 $ham_trigger = $spam_score - ($conf->{trigger_score} - $spam_score);
968 }
969  
970 inform('[check_end] processing message with score='.$msg_score.' (spam_score:'.$spam_score.', spam_trigger:'.$spam_trigger.', ham_trigger:'.$ham_trigger.')');
971 return 0 if($msg_score > $ham_trigger && $msg_score < $spam_trigger);
972  
973 $pre = substr($msg->get('ALL-INTERNAL'), 0, 4096);
974 $sender{envelope} = $msg->get('EnvelopeFrom:addr') || $msg->get('From:addr');
975 $sender{envelope} =~ s/$re->{trim}//g;
976  
977 /()/;
978 if($sender{envelope} !~ $re->{envelope}){
979 return error('[check_end] Could not find "envelope" in msg') if($pre !~ $re->{from} && substr($msg->get('ALL'), 0, 4096) !~ $re->{from});
980 $sender{envelope} = $1;
981 $sender{envelope} =~ s/$re->{trim}//g;
982 }
983  
984 if((($1) && ($2)) || $sender{envelope} =~ $re->{envelope}){
985 $sender{from} = substr("$1\@$2", 0, 512);
986 $sender{from} =~ s/$re->{spaces}//g;
987 }
988  
989 return error('[check_end] Could not find "from" in envelope '.$sender{envelope}) if($sender{from} !~ $re->{email});
990  
991 $sender{user} = $1;
992 $sender{domain} = $2;
993 $sender{domain} =~ s/$re->{n_domainchars}//g;
994 $sender{fkey} = encode_base64($sender{user}, '').'@'.$sender{domain};
995 $sender{extra} = $sender{fkey};
996  
997 $sender{to} = lc($msg->get('To:addr') || '');
998 $sender{to} =~ s/$re->{spaces}//g;
999 tr_ascii($sender{from}, $sender{to});
1000  
1001 /()/;
1002 if($pre !~ $re->{rcvd_header}){
1003 $pre = substr($msg->get('Received'), 0, 4096);
1004 inform('[check_end] Received header may be external');
1005 }
1006  
1007 if((($1) && ($2)) || $pre =~ $re->{rcvd_header}){
1008 $sender{host} = lc($1);
1009 $sender{ip} = $2;
1010 inform('[check_end] Received header: '.tr_ascii(substr($pre,0,32)));
1011 }else{
1012 %var = (pre=>'');
1013 inform('[check_end] Could not match rcvd host/ip');
1014 while ( $var{pre} = pop @{$msg->{relays_untrusted}} ){
1015  
1016 if($var{pre}->{ip} && !$var{pre}->{ip_private}){
1017 $sender{ip} = $var{pre}->{ip};
1018 $sender{host} = $var{pre}->{rdns} ? lc($var{pre}->{rdns}) : 'unknown';
1019 last;
1020 }
1021 }
1022 if (!$sender{ip}){
1023 inform('[check_end] Could not determine IP '.tr_ascii($pre));
1024 return 0;
1025 }
1026 }
1027  
1028 tr_ascii($sender{ip}, $sender{host});
1029 if($sender{ip} =~ $re->{colon}){
1030 $sender{ipv6}= 1;
1031 inform('[check_end] Expanding IP '.$sender{ip});
1032 $sender{ip} = expand_ipv6($sender{ip});
1033 }
1034  
1035 if ($sender{ip} !~ $re->{ip}){
1036 inform('[check_end] Could not determine IP '.$sender{ip});
1037 return 0;
1038 }
1039  
1040 inform('[check_end] user/domain/ip/host: '.$sender{user}.'/'.$sender{domain}.'/'.$sender{ip}.'/'.$sender{host});
1041  
1042 $key = $conf->{db_name}.'-'.$sender{ip};
1043  
1044 if($sender{host} =~ $re->{common_hosts}){
1045 $sender{is_common_domain} = 1;
1046 $sender{domain} = $1 if(!$sender{envelope});
1047 inform('[check_end] domain is common');
1048 if(!$sender{user} || !$sender{domain}){
1049 $sender{from} = 'no user specified' if (!$sender{from});
1050 return error('[check_end] Could not find envelope user from: '.$sender{domain}.' ('.$sender{from}.')');
1051 }
1052  
1053 $sender{from} = $sender{user}.'@'.$sender{domain};
1054 if(exists $whitelist{'@'.$sender{domain}} || exists $whitelist{$sender{from}}){
1055 inform('[check_end] done '.$sender{from}.' whitelisted');
1056 return 1;
1057 }
1058 $sender{extra} = $sender{ip};
1059 $sender{fkey} = encode_base64($sender{user}, '').'@'.$sender{domain};
1060 $key = $conf->{db_name}.'-'.$sender{fkey};
1061 }
1062  
1063 inform('[check_end] key: '.$key);
1064  
1065 if(exists $whitelist{$sender{ip}}){
1066 inform('[check_end] done '.$sender{ip}.' whitelisted');
1067 return 1;
1068 }
1069  
1070 return error('[check_end] Could not establish connection to database') if(!($db = dbconnect($conf)));
1071  
1072 $sender{host} = $sender{ip};
1073 if($key=~$re->{ipfromkey}){
1074 $sender{ip} = consolidate_network($db, {ip => $1, host => $2, sender => $sender{fkey}, ipv6 => $sender{ipv6}, conf => $conf, def_var => \%def_var});
1075 if(exists $whitelist{$sender{ip}}){
1076 inform('[check_end] done '.$sender{ip}.' whitelisted');
1077 return 1;
1078 }
1079 $key = $conf->{db_name}.'-'.$sender{ip};
1080 }
1081  
1082 $pre = $key;
1083 $pre =~ s/$re->{key}/$1;expires/;
1084 if($pre ne $key && ($pre = $db->get($key)) && $pre =~ $re->{isint} && time()<int($pre)){
1085 $msg->got_hit(uc($conf->{filter_name}), 'HEADER: ', score => $conf->{blacklist_score});
1086 inform('[check_end] done '.$sender{from}.' is blacklisted');
1087 return 1;
1088 }
1089  
1090 $pre = $db->get($key) || '';
1091 $pre =~ s/$re->{n_dbchars}//g;
1092 inform('[check_end] cached record: '.$pre);
1093 %var = $pre =~ $re->{record} ? (avg => $1 + 0.0, total => $2 + 0.0, spamhits => int($3), lastspam => int($4), extra => $5, cachehit => 1) : %def_var;
1094  
1095 $var{lastspam_delta} = time() - $var{lastspam};
1096  
1097 if(exists $var{cachehit} && $var{lastspam}!=0 && $sender{extra} eq $var{extra} && $conf->{seconds_between_messages}>$var{lastspam_delta}){
1098 inform('[check_end] skipping duplicate msg');
1099 return 1;
1100 }
1101 if($msg_score < $ham_trigger){
1102 inform('[check_end] processing as ham');
1103 if(exists $var{cachehit}){
1104 $var{total} = $var{total} - ($var{avg} + ($spam_score - $msg_score));
1105 --$var{spamhits};
1106 if($var{total}<1){
1107 %var = (%def_var, lastspam => $var{lastspam});
1108 }else{
1109 $var{spamhits} = 1 if($var{spamhits}<1);
1110 $var{avg} = nearest(0.01, $var{total}/$var{spamhits});
1111 $var{total} = nearest(0.01, $var{total});
1112 }
1113  
1114 $db->set($key => $var{avg}.','.$var{total}.','.$var{spamhits}.','.$var{lastspam}.','.$sender{extra});
1115 inform('[check_end:ham] updated cache: '.$key.' => from: '.$pre.' to: '.$var{avg}.','.$var{total}.','.$var{spamhits}.','.$var{lastspam}.','.$sender{extra});
1116 }
1117  
1118 inform('[check_end] done');
1119 return 1;
1120 }
1121  
1122 inform('[check_end] processing as spam');
1123  
1124 $var{w} = $var{spamhits} < 1 ? $conf->{trigger_sensitivity} : $conf->{trigger_sensitivity}/$var{spamhits};
1125 $var{x} = $conf->{seconds_to_decay_penalty}>$var{lastspam_delta} ? 0 : $var{lastspam_delta}/$conf->{seconds_to_decay_penalty};
1126 $var{y} = 1 + exp(-1*$var{x}/10) + exp(-3.2*$var{w});
1127  
1128 inform('[check_end] penalty '.$var{y});
1129  
1130 ++$var{spamhits};
1131 $var{spamhits} = 1 if($var{spamhits}<1);
1132  
1133 $var{score} = $msg_score * $var{y};
1134 $var{total} = nearest(0.01, $var{total} + $var{score});
1135 $var{avg} = nearest(0.01, $var{total}/$var{spamhits});
1136 $var{lastspam} = time();
1137  
1138 $db->set($key => $var{avg}.','.$var{total}.','.$var{spamhits}.','.$var{lastspam}.','.$sender{extra});
1139 inform('[check_end:spam] updated cache: '.$key.' => from: '.$pre.' to: '.$var{avg}.','.$var{total}.','.$var{spamhits}.','.$var{lastspam}.','.$sender{extra});
1140  
1141 $sender{to_user} = '-';
1142 $sender{to_domain} = $sender{to};
1143 if($sender{to} =~ $re->{email} && ($1) && ($2)){
1144 $sender{to_user} = $1;
1145 $sender{to_domain} = $2;
1146 }
1147 $sender{user} =~ s/$re->{n_dbchars}//g;
1148 $sender{domain} =~ s/$re->{n_domainchars}//g;
1149 $sender{to_user} =~ s/$re->{n_dbchars}//g;
1150 $sender{to_domain} =~ s/$re->{n_domainchars}//g;
1151 $sender{user} = '-' if (!$sender{user});
1152 $sender{domain} = 'null.invalid' if (!$sender{domain});
1153 $sender{to_user} = '-' if (!$sender{to_user});
1154 $sender{to_domain} = 'null.invalid' if (!$sender{to_domain});
1155  
1156 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}.'"');
1157  
1158 if($var{avg} >= $conf->{average_score_for_rule} && $var{spamhits} >= $conf->{trigger_messages}){
1159  
1160 $var{z} = $var{y} * ($var{score}/$conf->{average_score_for_rule});
1161 $var{z} = $conf->{expires_multiplier_penalty}*(1 + $var{z}) if($var{z} >= $conf->{expires_multiplier_penalty});
1162 inform('[check_end] expires penalty '.$var{z});
1163  
1164 $var{expires} = $var{lastspam} + int($conf->{expire_rule_seconds} * $var{z});
1165  
1166 if($sender{is_common_domain}){
1167 $msg->got_hit(uc($conf->{filter_name}), 'HEADER: ', score => 100);
1168 #$self->{mailsa}->add_address_to_blacklist($sender{from});
1169 $db->set($conf->{db_name}.';expires-'.$sender{fkey} => $var{expires});
1170 $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}));
1171 }else{
1172 $db->set($conf->{db_name}.';expires-'.$sender{ip} => $var{expires});
1173 $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}));
1174 }
1175 inform('[check_end] added to blacklist: '.$sender{from}.' '.$sender{ip});
1176 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}.'"');
1177  
1178 }
1179  
1180 inform('[check_end] done');
1181 return 1;
1182  
1183 }
1184  
1185 1;
1186  
1187 __END__
1188  
1189 =pod
1190  
1191 =encoding UTF-8
1192  
1193 =head1 NAME
1194  
1195 Mail::SpamAssassin::Contrib::Plugin::IPFilter - Blocks bad MTA behavior using IPTables.
1196  
1197 =head1 VERSION
1198  
1199 version 1.1
1200  
1201 =head1 SYNOPSIS
1202  
1203 To try this out, add this or uncomment this line in init.pre:
1204  
1205 LoadPlugin Mail::SpamAssassin::Contrib::Plugin::IPFilter
1206  
1207 I<Configuration defaults>
1208  
1209 iptables_support 6
1210 iptables_bin $PATH/iptables
1211 ip6tables_bin $PATH/ip6tables
1212 filter_name spamipfilter
1213 db_type redis
1214 db_host 127.0.0.1
1215 db_port 6387
1216 db_user ''
1217 db_auth ''
1218 db_name sa_ipf
1219 trigger_score 6
1220 trigger_messages 3
1221 trigger_sensitivity 4
1222 average_score_for_rule 7
1223 expire_rule_seconds 172800
1224 seconds_between_messages 30
1225 seconds_to_decay_penalty 300
1226 expires_multiplier_penalty 1.5
1227 cache_decay_days 60
1228 blacklist_score 30
1229 common_hosts gmail.com, google.com, yahoo.com, hotmail.com, live.com
1230 admin_email ''
1231 admin_message Your message to $recipient from $email was blocked and
1232 your IP address $ip blacklisted due to excessive unsolicited
1233 bulk email. To reinstate your ability to send email to $recipient,
1234 please reply to $admin using a different off-network email,
1235 including the body of this message, with a request for reinstatement.
1236 log_dir /var/log
1237 verbose 0
1238  
1239 =head1 DESCRIPTION
1240  
1241 Mail::SpamAssassin::Contrib::Plugin::IPFilter blacklists unsolicited bulk email senders using IPTables. It will blacklist the sender IP using the smallest network possible, up to /24, when UCE originates from multiple hosts on the same network. Depending on the diversity and frequency of spam received on a server, it may take a couple of days to become effective. Thereafter, the cache state will decay to prevent spammers from burning IP blocks.
1242  
1243 Responsible, well-known email hosts (common_hosts) are given special treatment to avoid blacklisting their networks and the score is increased for external filtering of UCE originating from those hosts. The plugin may be configured to email the blacklisted sender a warning for remediation.
1244  
1245 A crontab entry is created for maintenance. IPV6 support is experimental. Future versions may include a collaborative blacklist.
1246  
1247 =head1 NAME
1248  
1249 Mail::SpamAssassin::Contrib::Plugin::IPFilter - Blocks bad MTA behavior using IPTables.
1250  
1251 =begin html
1252  
1253 <p>The following options may be used in site-wide (local.cf) configuration files to customize operation, and must be prefixed by ipfilter_:</p>
1254  
1255 <b>filter_name</b><br>
1256 The name of the chain that Mail::SpamAssassin::Contrib::Plugin::IPFilter will create to block spammers. [a-zA-Z0-9_.]
1257  
1258 <br><br><b>iptables_support</b><br>
1259 iptables support. 0 = disable iptables. 4 = support ipv4 only. 6 = support ipv4 and ipv6.
1260  
1261 <br><br><b>iptables_bin</b><br>
1262 The path to the iptables binary on your system.
1263  
1264 <br><br><b>ip6tables_bin</b><br>
1265 The path to the ip6tables binary on your system.
1266  
1267 <br><br><b>db_type</b><br>
1268 The type of storage to use (mysql/redis).
1269  
1270 <br><br><b>db_host</b><br>
1271 The IPv4 address of your database server.
1272  
1273 <br><br><b>db_port</b><br>
1274 The port that the database server is listening on.
1275  
1276 <br><br><b>db_user</b><br>
1277 The database user, if applicable.
1278  
1279 <br><br><b>db_auth</b><br>
1280 The database password, if applicable.
1281  
1282 <br><br><b>db_name</b><br>
1283 The database name (mysql) or the prefix for keys (redis) created and used by Mail::SpamAssassin::Contrib::Plugin::IPFilter. ^[a-zA-Z0-9_.]$
1284  
1285 <br><br><b>log_dir</b><br>
1286 The directory to use for apache style logs reflecting spam messages for export to analytics. Informational messages are still logged via SpamAssassin.
1287  
1288 <br><br><b>average_score_for_rule</b><br>
1289 The average spam score for a host required to trigger a rule after trigger_messages.
1290  
1291 <br><br><b>seconds_between_messages</b><br>
1292 After how long should messages with the same envelope to/from be considered.
1293  
1294 <br><br><b>cache_decay_days</b><br>
1295 After how long will entries in the cache decay, assuming no spam messages are seen. Note that the cache will decay according to: cumulative_spam_score_for_host * exp(-3*lastspam_delta/cache_decay_secs)
1296  
1297 <br><br><b>expire_rule_seconds</b><br>
1298 After how long will a block rule expire.
1299  
1300 <br><br><b>expires_multiplier_penalty</b><br>
1301 A factor used to penalize hosts with longer rule expiration based on the spam of score of the message resulting in a rule, relative to the average spam score required to set the rule.
1302  
1303 <br><br><b>seconds_to_decay_penalty</b><br>
1304 A frequency indicator used to tune penalization for a given host based on how many spam messages were seen for that host over a time period.
1305  
1306 <br><br><b>trigger_score</b><br>
1307 The score for which Mail::SpamAssassin::Contrib::Plugin::IPFilter will process a spam message. This should be greater than the SpamAssassin required_score.
1308  
1309 <br><br><b>trigger_messages</b><br>
1310 The minimum number of spam messages from a given host before a rule is triggered.
1311  
1312 <br><br><b>trigger_sensitivity</b><br>
1313 A quantity used to tune penalization for a given host based on how many spam messages were seen for that host.
1314  
1315 <br><br><b>common_hosts</b><br>
1316 Hosts which should not be blacklisted via IPTables rule, and fall back to SpamAssassin blacklist.
1317  
1318 <br><br><b>blacklist_score</b><br>
1319 A score to add to message headers of blacklisted senders originating from common_hosts.
1320  
1321 <br><br><b>admin_email</b><br>
1322 The email address to send blacklist warnings from. If left unconfigured, no warnings will be sent.
1323  
1324 <br><br><b>admin_message</b><br>
1325 The warning message that will be sent. Parameters $user, $domain, $ip, $email, $recipient and $admin may be used for templatization.
1326  
1327 <br><br><b>whitelist</b><br>
1328 Any email address or ip address to whitelist. Email addresses may be specified as foo@example.com or just @example.com to match the whole domain, and IPs may be specified as 1.2.3.4 or just 1.2.3. to match the class C address space.
1329  
1330 <br><br><b>verbose</b><br>
1331 Log additional information via Mail::SpamAssassin::Logger
1332  
1333 =end html
1334  
1335 =head1 COPYRIGHT
1336  
1337 I<Copyright E<copy> 2016 - Tamer Rizk, Inficron Inc.>
1338  
1339 This is free, open source software, licensed under the L<Revised BSD License|http://opensource.org/licenses/BSD-3-Clause>. Please feel free to use and distribute it accordingly.
1340  
1341 =head1 AUTHOR
1342  
1343 Tamer Rizk <foss@inficron.com>
1344  
1345 =head1 COPYRIGHT AND LICENSE
1346  
1347 This software is Copyright (c) 2016 by Tamer Rizk.
1348  
1349 This is free software, licensed under:
1350  
1351 The (three-clause) BSD License
1352  
1353 =cut