#!/usr/bin/perl # spam kill program # killspam 9/9/2007 kurt theis # scan /usr/spool/mail/spam for messages, get the line # that has an IP message in format [xxx.xxx.xxx.xxx] # and block the ip, and add it to a list in /var/log/spamMail # run from crontab # to use this, have it running in cron every minute (or 5 minutes if # you want). When the user get's an e-mail he considers spam, he # forwards the header to spam@your_local_box.com # this program looks at the messages in the user spam's mail # file to extract the IP address. The IP address is then blocked # by the IPCHAINS/IPTABLES (you need some varient of this) commands. # read the mail file sent to spam if (-s "/usr/spool/mail/spam") { # file must not be empty open(INFILE,"/usr/spool/mail/spam") || die "Cannot open mail file $!\n"; # read in mail file while() { chop; push(@templist,$_); } close(INFILE); } else { # empty file - stop exit; } # now parse the data open(OUTFILE,">>/var/log/spamMail") || die "Cannot write to /var/log/spamMail\n"; foreach(@templist) { if ( /\[[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\]/ ) { # line has an IP address in it $ipline = $_; @words = split (/ /, $ipline); foreach (@words) { $len = length($_); for ($a=0; $a<=$len; $a++) { if (substr($_,$a,1) eq '[') { $start = $a; } if (substr($_,$a,1) eq ']') { $end = $a; } } $len = $end - $start; $ip = substr($_,$start,(($end - $start)+1)); if ($ip =~ /\[[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\]/) { # print "$_ -> "; $_ = $ip; s/\[//; s/\]//; s/\)//; s/\(//; $ip = $_; # print "ip is $ip\n"; # ignore anything from our network if ($ip eq "64.175.56.187") { last; } if ($ip eq "64.175.56.185") { last; } if ($ip eq "64.175.56.186") { last; } if ($ip eq "64.175.56.188") { last; } if ($ip eq "64.175.56.189") { last; } if (length($ip) > 15) { last; } push(@badip,$ip); } } } } # if @badip has entries do stuff below $bipcount = @badip; if ($bipcount > 0) { # remove duplicate entries # print "bipcount is $bipcount\n"; %seen = (); foreach $item (@badip) { push(@uniq, $item) unless $seen{$item}++; } foreach(@uniq) { $cmd = "iptables -A INPUT -s $_ -j DROP"; system($cmd); # print $cmd . "\n"; print OUTFILE "$_\n"; } # now delete the mail file $cmd = "> /usr/spool/mail/spam"; system($cmd); } # done exit;