SpamDetector/BlockList.pm untested

filter: Statementstmt 0.0% 0 / 178 Branchbran 0.0% 0 / 70 Conditioncond 0.0% 0 / 51 MC/DCmcdc 0.0% 0 / 21 Subroutinesub 0.0% 0 / 19 Podpod 0.0% 0 / 10 totaltotal 0.0% 0 / 349 CC 36 SCAR 60.5
CC
36
Cov
0%
spam_found
812.0
periodic
30.0
dbh
20.0
CRAP 426.1
1  
2  
3 package SyslogScan::Daemon::SpamDetector::BlockList;
4  
5 use strict;
6 use warnings;
7 use SyslogScan::Daemon::SpamDetector::Plugin;
8 use Plugins::SimpleConfig;
9 use Time::CTime;
10 use Time::ParseDate;
11 use Hash::Util qw(lock_keys);
12 use DBI;
13 require POSIX;
14 our(@ISA) = qw(SyslogScan::Daemon::SpamDetector::Plugin);
15  
16 my $timefmt = "%Y-%m-%d %T";
17  
18 my %defaults = (
19 debug => 1,
20 minblock => 0.04, # days
21 maxblock => 1.0, # days
22 blockmult => 1.2,
23 growtime => 0.04, # < days
24 shrinktime => 0.25, # > days
25 firstblock => 10,
26 dbi_dsn => 'DBI:mysql:database=xxxxxxx;host=localhost', # both
27 dbi_user => 'user',
28 dbi_pass => 'password',
29 block_dbi_dsn => 'DBI:mysql:database=xxxxxxx;host=localhost', # small table
30 block_dbi_user => 'user',
31 block_dbi_pass => 'password',
32 track_dbi_dsn => 'DBI:mysql:database=xxxxxxx;host=localhost', # big table
33 track_dbi_user => 'user',
34 track_dbi_pass => 'password',
35 cleanup => 86400/2,
36 blockmemory => 4, # days
37 spammemory => 10, # days
38 blockcommand => '',
39 recipweight => .333333333333333333,
40 repeatblocks => 20,
41 repeatoffender => 250,
42 rpmult => 4,
43 fastspammer => 10,
44 fastspammermult => 2,
45 cleanupfirst => 1,
46 );
47  
48 sub config_prefix { 'sdblocklist_' }
49  
50 sub parse_config_line { simple_config_line(\%defaults, @_); }
51  
52 sub new
53 {
54 my $self = simple_new(\%defaults, @_);
55 $self->block_dbh;
56 $self->track_dbh;
57 $self->{lastclean} = 0;
58 $self->{plugins} = undef;
59 $self->{block_dbh} ||= undef;
60 $self->{track_dbh} ||= undef;
61 $self->{lastclean} = time
62 unless $self->{cleanupfirst};
63 lock_keys(%$self);
64 return $self;
65 }
66  
67 sub block_dbh
68 {
69 my $self = shift;
70 $self->dbh('block');
71 }
72 sub track_dbh
73 {
74 my $self = shift;
75 $self->dbh('track', AutoCommit => 1);
76 }
77  
78 sub dbh
79 {
80 my ($self, $type, %xtra) = @_;
81 my $key = $type . "_dbh";
82 eval {
83 my $old = $self->{$key};
84 delete $self->{$key};
85 $old->disconnect() if $old;
86 $self->{$key} = DBI->connect(
87 $self->{"${type}_dbi_dsn"} || $self->{dbi_dsn},
88 $self->{"${type}_dbi_user"} || $self->{dbi_user},
89 $self->{"${type}_dbi_pass"} || $self->{dbi_pass},
90 { RaiseError => 1, PrintError => 1, %xtra });
91 };
92 if ($self->{$key}) {
93 print "# opened $type database connection\n" if $self->{debug};
94 } else {
95 print STDERR "Could not open $type database: $@";
96 }
97 return $self->{$key};
98 }
99  
100 sub reconfig
101 {
102 my $self = shift;
103 $self->block_dbh;
104 $self->track_dbh;
105 }
106  
107 sub mktime
108 {
109 my ($time) = @_;
110 return strftime($timefmt, gmtime($time));
111 }
112  
113 sub periodic
114 {
115 my $self = shift;
116 my $time = time;
117 my $oldblock = $time - 86400 * $self->{blockmemory};
118 if ($self->{lastclean} + $self->{cleanup} < time) {
119 eval {
120 my $block_dbh = $self->{block_dbh};
121 $block_dbh->disconnect();
122 $self->track_dbh;
123 my $track_dbh = $self->{track_dbh};
124 $track_dbh->disconnect();
125 my $pid = fork();
126 if (defined $pid and $pid == 0) {
127 eval {
128 my $dbh = $self->block_dbh;
129 $dbh->begin_work;
130 my $c3 = $dbh->do(<<END, undef, mktime($oldblock));
131 DELETE FROM block_history
132 WHERE blockend < ?;
133 END
134 $dbh->commit();
135 print "# CLEARED $c3 OLD BLOCK HISTORIES\n";
136 };
137 print STDERR $@ if $@;
138  
139 eval {
140 print "# Attempting to clear old spam reports\n";
141 my $dbh = $self->track_dbh;
142 $dbh->begin_work;
143 my $oldspam = $time - 86400 * $self->{spammemory};
144 my $c4 = $dbh->do(<<END, undef, mktime($oldspam));
145 DELETE FROM spam_received
146 WHERE spamtime < ?;
147 END
148 $dbh->commit();
149 print "# CLEARED $c4 OLD SPAM REPORTS\n";
150 };
151 print STDERR $@ if $@;
152 POSIX::_exit(0);
153 }
154 };
155 $self->block_dbh;
156 $self->track_dbh;
157 $self->{lastclean} = time;
158 }
159 }
160  
161 sub spam_found
162 {
163 my ($self, %info) = @_;
164 my $ip = $info{ip};
165 my $msgid = $info{hideid}
166 ? "redacted"
167 : ($info{id}
168 ? $info{id}
169 : "?");
170  
171 eval {
172 my $time = time;
173 my $track_dbh = $self->{track_dbh};
174 if ($info{id}) {
175 my $idthereq = $track_dbh->prepare_cached(<<END);
176 SELECT COUNT(*)
177 FROM spam_received
178 WHERE ip = ?
179 AND messageid = ?
180 END
181 $idthereq->execute($ip, $info{id});
182 my $crr = $idthereq->fetchall_arrayref();
183 $idthereq->finish();
184 my $count = $crr->[0][0];
185 if ($count) {
186 my $morespamq = $track_dbh->prepare_cached(<<END);
187 UPDATE spam_received
188 SET recipients = recipients + 1,
189 spamtime = ?,
190 score = ?,
191 matched = ?
192 WHERE ip = ?
193 AND messageid = ?
194 END
195 $morespamq->execute(mktime($time), $info{score} || "?", $info{match} || "?", $ip, $info{id});
196 $morespamq->finish();
197 } else {
198 my $spamtimeq = $track_dbh->prepare_cached(<<END);
199 INSERT INTO spam_received
200 VALUES (?, ?, ?, ?, ?, ?, ?)
201 END
202 $spamtimeq->execute($ip, mktime($time), $info{id}, 1, $info{host} || "?", $info{score} || "?", $info{match} || "?") or die $track_dbh->errstr;
203 $spamtimeq->finish();
204 }
205 } else {
206 my $spamtimeq = $track_dbh->prepare_cached(<<END);
207 INSERT INTO spam_received
208 VALUES (?, ?, ?, ?, ?, ?, ?)
209 END
210 $spamtimeq->execute($ip, mktime($time), $info{match} || "?", 1, $info{host} || "?", $info{score} || "?", $info{match} || "?") or die $track_dbh->errstr;
211 $spamtimeq->finish();
212 }
213 my $spamcountq = $track_dbh->prepare_cached(<<END);
214 SELECT COUNT(*), SUM(recipients), MIN(spamtime)
215 FROM spam_received
216 WHERE ip = ?
217 AND spamtime > ?
218 END
219 $spamcountq->execute($ip, mktime($time - 86400 * $self->{spammemory}));
220 my $crr = $spamcountq->fetchall_arrayref();
221 $spamcountq->finish();
222 my $rows = $crr->[0][0];
223 my $count = $crr->[0][1];
224 my $mintime = parsedate($crr->[0][2], GMT => 1);
225 my $days = int(($time - $mintime)/86400) + 1;
226 my $weighted = ($count - $rows) * $self->{recipweight} + $rows;
227 print STDERR "This is spam # $rows for $ip (recipients = $count, weighted = $weighted)\n" if $self->{debug};
228 my $docommand = 0;
229 if ($weighted >= $self->{firstblock}) {
230 my $block_dbh = $self->{block_dbh};
231 print "Blocking $ip due to excessive ($count) spams....\n" if $self->{debug};
232
233 $block_dbh->begin_work;
234 my $blockstateq = $block_dbh->prepare_cached(<<END);
235 SELECT blockstart, blockend, spamcount, blockcount
236 FROM block_history
237 WHERE ip = ?
238 END
239 $blockstateq->execute($ip);
240 my $bsrr = $blockstateq->fetchall_arrayref();
241 $blockstateq->finish();
242 if (@$bsrr) {
243 my ($starts, $ends, $oldspamcount, $blockcount) = @{$bsrr->[0]};
244 my $end = parsedate($ends, GMT => 1);
245 my $start = parsedate($starts, GMT => 1);
246 print "START=$start/$starts END=$end/$ends (".mktime($end)."/".strftime("%c", localtime($end)).")\n" if $self->{debug} > 3;
247 if ($end > $time) {
248 print "... Already blocking $ip\n" if $self->{debug};
249 } else {
250 my $rpmult = 1;
251 if ($self->{repeatoffender} && $weighted > $self->{repeatoffender}) {
252 print "Repeat offender penealty (too many spams)\n" if $self->{debug} > 2;
253 $rpmult = $self->{rpmult};
254 } elsif ($self->{repeatblocks} && $blockcount > $self->{repeatblocks}) {
255 print "Repeat offender penealty (blocked too often)\n" if $self->{debug} > 2;
256 $rpmult = $self->{rpmult};
257 }
258 my $oldsize = $end - $start;
259 print "OLD BLOCKSIZE = $oldsize\n" if $self->{debug} > 3;
260 my $now = time;
261 my $newsize = $oldsize;
262 if ($now - $end < $self->{growtime} * 86400 * $rpmult) {
263 $newsize = $oldsize * $self->{blockmult};
264 } elsif ($now - $end > $self->{shrinktime} * 86400 * $rpmult) {
265 $newsize = $oldsize / $self->{blockmult};
266 }
267 if ($weighted - $oldspamcount > $self->{fastspammer}) {
268 printf "spamming while blocked penealty (%d)\n", $weighted - $oldspamcount if $self->{debug} > 2;
269 $newsize *= $self->{fastspammermult};
270 }
271 $newsize = $self->{minblock} * 86400
272 if $newsize < $self->{minblock} * 86400;
273 $newsize = $self->{maxblock} * 86400
274 if $newsize > $self->{maxblock} * 86400;
275 $block_dbh->do(<<END, undef, mktime($time), mktime($time + $newsize), int($weighted), $msgid, $days, $ip) or die $block_dbh->errstr;
276 UPDATE block_history
277 SET blockstart = ?,
278 blockend = ?,
279 blockcount = blockcount + 1,
280 spamcount = ?,
281 messageid = ?,
282 countdays = ?
283 WHERE ip = ?;
284 END
285 print "... Reactivating block on $ip... now $newsize seconds long\n" if $self->{debug};
286 $docommand = 1;
287 }
288 } else {
289 $docommand = 1;
290 my $blocktime = $self->{minblock} * 86400;
291 $block_dbh->do(<<END, undef, $ip, mktime($time), mktime($time + $blocktime), int($weighted), $msgid, $days) or die $block_dbh->errstr;
292 INSERT INTO block_history
293 VALUES (?, ?, ?, 1, ?, ?, ?);
294 END
295 printf "Adding a first block for $ip for %.2f hours\n", $blocktime/3600 if $self->{debug};
296 }
297 $block_dbh->commit();
298 if ($docommand && $self->{blockcommand}) {
299 my $cmd = SyslogScan::Daemon::SpamDetector::substitute($self->{blockcommand}, %info);
300 print "+ $cmd\n" if $self->{debug};
301 system($cmd);
302 }
303 }
304 };
305 if ($@) {
306 print STDERR $@;
307 $self->block_dbh;
308 $self->block_dbh;
309 }
310 }
311  
312  
313 1;
314  
315 =head1 NAME
316  
317 SyslogScan::Daemon::SpamDetector::BlockList - maintain an IP-based blocklist of spam sources
318  
319 =head1 SYNOPSIS
320  
321 plugin SyslogScan::Daemon::SpamDetector as sd_
322  
323 sd_plugin SyslogScan::Daemon::SpamDetector::BlockList
324 debug 3
325 track_dbi_dsn 'DBI:mysql:database=mailstats;host=localhost'
326 track_dbi_user 'username'
327 track_dbi_pass 'passwd'
328 block_dbi_dsn 'DBI:mysql:database=iimaildb;host=blockhost'
329 block_dbi_user 'username'
330 block_dbi_pass 'passwd'
331 minblock 0.0416666666666667 # minimum block length (days)
332 maxblock 1.0 # maximum block length (days)
333 blockmult 1.2 # amount to grow/shrink the block
334 shrinktime 0.25 # grow the block length if spammed again in less than this (days)
335 growtime 0.04 # amount of times w/o a spam to shrink block length (days)
336 firstblock 10 # number of spams required to trigger first blocking
337 cleanup 86400 # clean up tables, remove blocks (seconds)
338 blockmemory 8 # keep history of previous blocks (days)
339 spammemory 8 # keep history of spams sent (days)
340 recipweight .33333333333333 # how much does an extra recipient count towards being enough spam to block
341 blockcommand ''
342 repeatblocks 50 # times blocked to get worse treatment
343 repeatoffender 250 # count of spams to get worse treatment
344 rpmult 4 # how much more/less time repeat offenders get to grow shrink their block time
345 fastspammer 20 # number of spams sent while blocked to get penealty
346 fastspammermult 1.5 # blocktime multipe for fastspammers
347  
348 =head1 DESCRIPTION
349  
350 Track and react to the spam noticed by L<SyslogScan::Daemon::SpamDetector>.
351  
352 Track the spam in an SQL database. Build a blocklist.
353  
354 Block hosts for a bit. If they keep spamming, block them for longer periods.
355  
356 We reccomend that this module I<not> be combined with
357 L<SyslogScan::Daemon::SpamDetector::SpamAssassin> becuase it will end
358 up blocking forwarded mail.
359  
360 =head1 CONFIGURATION PARAMETERS
361  
362 The following configuration parameters are supported:
363  
364 =over 4
365  
366 =item debug
367  
368 Debugging 0 (off) to 5 (verbose).
369  
370 =item minblock
371  
372 The minimum amount of time to block an IP address in days. (Default: about an hour)
373  
374 =item maxblock
375  
376 The maximum amount of time to block an IP address in days. (Default: 1)
377  
378 =item blockmult
379  
380 If a site is being re-blocked within the C<growtime> window, multiply the block
381 time by this amount. If a site is being re-blocked outside of the C<shrinktime>
382 window then divide the block time by this amount. (Default: 1.2)
383  
384 =item growtime
385  
386 If a site sends more spam and thus needs re-blocking, punish with a longer block
387 if it's needing re-blocking before this amount of time has passed. In days.
388 (Default: about one hour)
389  
390 =item shrinktime
391  
392 If a site sends more spam and thus needs re-blocking but it has been longer
393 than this amount of time since it was last blocked, then give it a shorter
394 block than it had before. In days. (Default: .25)
395  
396 =item firstblock
397  
398 Don't block a site until this many spam have been recevied. (Default: 10)
399  
400 =item block_dbi_dsn
401 =item block_dbi_user
402 =item block_dbi_pass
403  
404 Use this database for the IP block list. The table is small.
405  
406 =item track_dbi_dsn
407 =item track_dbi_user
408 =item track_dbi_pass
409  
410 Use this database for tracking incoming spam. The table is large.
411  
412 =item cleanup
413  
414 Perform cleanup of old on the database this often. Seconds. (Default: 43200 - 12 hours)
415  
416 =item blockmemory
417  
418 Remember inactive blocks for this long. Days. (Default: 4).
419  
420 =item spammemory
421  
422 Remember incoming spam for this long. Days. (Default: 10).
423  
424 =item blockcommand
425  
426 Run this command when a block is created. (No default)
427  
428 =item recipweight
429  
430 When the same message is sent to multiple recipients, count the subsequent
431 deliveries as this much of a spam. (Default: .333333333333)
432  
433 =item repeatblocks
434  
435 When an IP address has been been blocked this man times treat it specially:
436 instead of multiplying block times by C<blockmult>, multiply them by C<rpmult>.
437  
438 =item repeatoffender
439  
440 When an IP address has sent this many spams, treat it specially:
441 instead of multiplying block times by C<blockmult>, multiply them by C<rpmult>.
442  
443 =item rpmult
444  
445 For espeically bad sources,
446 instead of multiplying block times by C<blockmult>, multiply them by C<rpmult>.
447 (Default: 4)
448  
449 =item fastspammer
450  
451 If this many spams are sent while being blocked (presumably because the block
452 doesn't cover the entire network), then multiply the block time by
453 C<fastspammermult>.
454  
455 =item fastspammermult
456  
457 Block multiplier penealty for fast spammers. (Default: 1.5)
458  
459 =item cleanupfirst
460  
461 Clean out old entries from the database tables at startup? (Default: 1)
462  
463 =back
464  
465 =head1 TABLE CREATION
466  
467 SQL tables are not automatically created. Here are examples for Mysql5:
468  
469 CREATE TABLE spam_received (
470 ip VARCHAR(16),
471 spamtime DATETIME,
472 messageid TEXT,
473 recipients INT,
474 host TEXT,
475 score TEXT,
476 matched TEXT,
477 INDEX ip_index(ip)
478 ) TYPE=MyISAM;
479  
480 CREATE TABLE block_history (
481 ip VARCHAR(16),
482 blockstart DATETIME,
483 blockend DATETIME,
484 blockcount INT,
485 spamcount INT,
486 messageid TEXT,
487 countdays INT,
488 PRIMARY KEY (ip),
489 INDEX done(blockend)
490 ) TYPE=MyISAM;
491  
492 Replace "Los Angeles" with a city in your time zone.
493  
494 drop view blocking;
495 CREATE VIEW blocking AS
496 SELECT ip,
497 CONCAT("450 blocked for ",
498 SUBTIME(TIMEDIFF(blockend,blockstart),
499 SEC_TO_TIME(SECOND(TIMEDIFF(blockend,blockstart)))),
500 " until ", ADDTIME(blockend, timediff(now(), utc_timestamp())),
501 "-Los Angeles time due to ", spamcount, " spams in ", countdays,
502 " days, for example <", messageid, ">") AS message,
503 SUBTIME(TIMEDIFF(blockend,blockstart),
504 SEC_TO_TIME(SECOND(TIMEDIFF(blockend,blockstart)))) AS blocktime,
505 case when blockend > utc_timestamp() then 1 else 0 end AS active,
506 ADDTIME(blockend, timediff(now(), utc_timestamp())) as blockend_local,
507 spamcount
508 FROM block_history;
509  
510 =head1 USEFUL QUERIES
511  
512 To watch what's going on with the block list, the following queries are
513 helpful.
514  
515 select ip, COUNT(*), SUM(recipients) from spam_received
516 group by ip order by COUNT(*) desc limit 25;
517  
518 select COUNT(*), SUM(recipients) from spam_received;
519  
520 select active, count(*), AVG(blocktime), AVG(spamcount), MAX(spamcount)
521 from blocking group by active;
522  
523 select ip, message from blocking where active = 1 order by spamcount;
524  
525 select spamcount, COUNT(*), AVG(blocktime), AVG(spamcount)
526 from blocking where active = 1 group by spamcount order by spamcount;
527  
528 select blocktime, count(*), MIN(spamcount), AVG(spamcount), MAX(spamcount)
529 from blocking where active = 1 group by blocktime order by blocktime;
530  
531 select ip, blocktime, spamcount, active
532 from blocking
533 order by spamcount desc
534 limit 25;
535  
536 select count(*), SUM(active) from blocking where spamcount > 250;
537  
538 select truncate(spamcount,-1), COUNT(*), AVG(blocktime), AVG(spamcount)
539 from blocking where active = 1 group by truncate(spamcount,-1) order by truncate(spamcount,-1);
540  
541 =head1 POSTFIX CONFIG
542  
543 To configure Postfix to block using this block list, include a line like:
544  
545 smtpd_client_restrictions = check_client_access mysql:/etc/postfix/mysql_spam_senders.cf
546  
547 Then include a query in the referenced file:
548  
549 hosts = localhost maildb
550 dbname = spamdb
551 user = dbuser
552 password = dbpass
553 query = SELECT message FROM blocking WHERE ip = '%s' AND active = 1
554  
555 If your postfix doesn't have SQL support or you're using a less capable mailer,
556 you can dump the block list into a file:
557  
558 mysql -N -B --host=mx --database=spamdb --user=dbuser \
559 -e 'select ip, message from blocking where active = 1' \
560 > file
561  
562 =head1 DNS BLOCKLIST
563  
564 One way to turn this blocklist into a DNS-based blocklist that
565 can be used like other blocklists is to use L<rbldnsd(8)>.
566  
567 Set up a L<SyslogScan::Daemon::Periodic> job to rebuild the
568 blocklist:
569  
570 plugin SyslogScan::Daemon::Periodic
571 debug 1
572 period 120
573 command '/usr/local/bin/update_blocklist'
574  
575 The C<update_blocklist> script I use is:
576  
577 #!/bin/sh -e
578  
579 SUB=1171308796
580 SECONDS=`date +%s`
581 SEQN=`expr $SECONDS - $SUB`
582 DIR="/var/lib/rbldns"
583 ZONE="blocked"
584  
585 sed "s/SERIAL/$SEQN/" < $DIR/$ZONE.head > $DIR/$ZONE.new
586  
587 mysql -N -B --host=MYDBHOST --database=MYDB --user=MYDBUSER \
588 -e 'select ip, concat(":1:",message) \
589 from blocking where active = 1' \
590 | sed 's/:450 /:/' \
591 >> $DIR/$ZONE.new
592  
593 mv $DIR/$ZONE.new $DIR/$ZONE
594  
595 The C</var/lib/rbldns/blocked.head> file I use:
596  
597 $SOA 1800 ns.idiom.com. muir.idiom.com. SERIAL 300 60 3600 300
598 $NS 1800 MYHOSTNAME
599 $TTL 120
600  
601 I start L<rbldnsd(8)> with:
602  
603 /usr/sbin/rbldnsd -p /var/run/rbldnsd.pid \
604 -r/var/lib/rbldns -4 -bMYIPADDRESS/53 \
605 spammers.MYDOMAIN:ip4set:blocked
606  
607 Then, to use it with L<postfix(1)>, I set up a rbl_reply_maps so that
608 I can give a temporary failure.
609  
610 smtpd_client_restrictions =
611 permit_mynetworks,
612 reject_unauth_pipelining,
613 reject_rbl_client cbl.abuseat.org,
614 reject_rbl_client spammers.MYDOMAIN
615  
616 rbl_reply_maps = hash:/etc/postfix/rbl_reply_maps
617  
618 My rbl_rply_maps file:
619  
620 cbl.abuseat.org $rbl_code Service unavailable; $rbl_class [$rbl_what] blocked using $rbl_domain${rbl_reason?; $rbl_reason}
621 spammers.MYDOMAIN 450 4.7.1 Service unavailable; $rbl_class [$rbl_what] $rbl_reason
622  
623 =head1 SEE ALSO
624  
625 L<SyslogScan::Daemon::SpamDetector>
626  
627 =head1 THANK THE AUTHOR
628  
629 Hire the author to do some perl programming on your behalf!
630  
631 =head1 LICENSE
632  
633 Copyright(C) 2006 David Muir Sharnoff <muir@idiom.com>.
634 This module may be used and distributed on the same terms
635 as Perl itself.
636