#!/usr/bin/perl -w
#
# Look for specific SpamAssassin rules in maillog and add IP of sender
# to blacklist with full logs for that queueId. Works only with
# sendmail logs.
use strict;
use Getopt::Long;
use Data::Dumper;
my %opts;
GetOptions( \%opts,
'startline:i',
'stopline:i',
'infile:s',
'logfile:s',
'rule:s',
'verbose',
);
$opts{infile} = $opts{infile} || '/disk1/log/maillog';
$opts{logfile} = $opts{logfile} || '/tmp/spamScoredLogfile.log';
$opts{startline} = $opts{startline} || 0;
$opts{endline} = $opts{startline} || 999999999;
if ( ! $opts{rule} ) {
print "Usage requires you to pass '--rule=RULENAME'\n";
exit 3;
}
if ( $opts{verbose} ) {
print "Start reading in queueId's\n";
}
my $count=0;
my $queueIds;
if ( -f $opts{infile} ) {
open INFILE, "<$opts{infile}";
while (<INFILE>) {
$count++;
next if ( $count <= $opts{startline} );
last if ( $count > $opts{stopline} );
if ( m/(sm-mta|sendmail)\[\d+\]: (\w+): Milter add: header: X-Spam-Status: Yes, hits=.*$opts{rule}/ ) {
my $match = $2;
push @{$queueIds}, $match;
#$queueIds->{$match}++;
}
undef $_;
}
close INFILE;
}
if ( $opts{verbose} ) {
print "Finished reading in queueId's\n";
print "Start reading in loglines\n";
}
$count=0;
my $spams;
if ( -f $opts{infile} ) {
open INFILE, "<$opts{infile}";
while ( <INFILE>) {
$count++;
# Add lines to be searched because a log entry might cross the boundary.
# The number 100 is arbitrary.
next if ( $count <= $opts{startline}-100 );
last if ( $count > $opts{stopline}+100 );
my $line = $_;
foreach my $queueId ( @{$queueIds} ) {
if ( $line =~ m/$queueId/ ) {
$line =~ s/\'/\\'/g;
$spams->{$queueId}->{maillog} .= $line;
if ( $line =~ m/(sm-mta|sendmail)\[\d+\]: $queueId:.*relay=([\w\-.]+ )?\[([\d.]+)\]/ ) {
my $ip = $3;
$spams->{$queueId}->{ipaddr} = $ip;
$spams->{ip}->{$ip}++;
}
}
}
}
close INFILE;
}
if ( $opts{verbose} ) {
print "Finished reading in loglines\n";
}
open LOGFILE, ">>$opts{logfile}";
foreach my $queueId ( @{$queueIds} ) {
chomp $spams->{$queueId}->{maillog};
print LOGFILE '"' . $spams->{$queueId}->{ipaddr} . '","source","' .
"Spam count: " . $spams->{ip}->{$spams->{$queueId}->{ipaddr}} . "\n" .
$spams->{$queueId}->{maillog} . '"' . "\n";
}
close LOGFILE;