#!/usr/bin/perl -w
##########################################################################
# $Id: smtpd,v 0.1 2002/12/16 11:00:00 aries $
##########################################################################
# $Log: smtpd,v $
#
# Revision 0.1  2002/12/16 11:00:00 aries
# 'smtpd' module started.
#
##########################################################################

########################################################
# This was written and is maintained by:
#    Andrea Gelpi <security@gelpi.it>
#
# Please send all comments, suggestions, bug reports,
#    etc, to security@gelpi.it.
#
########################################################

$Debug = $ENV{'LOGWATCH_DEBUG'};
$Detail = $ENV{'LOGWATCH_DETAIL_LEVEL'};

sub LookupIP {
   my ($name, $a1, $a2,$a3,$a4,$PackedAddr,$Addr);
   $Addr = $_[0];
   ($a1,$a2,$a3,$a4) = split /\./,$Addr;
   $PackedAddr = pack('C4',$a1,$a2,$a3,$a4);
   if ($name = gethostbyaddr ($PackedAddr,2)) {
#     return ($name . " (" . $Addr . ")");
      return ($Addr . " (" . $name . ")");
   } else {
      return ($Addr);
   }
}

sub byip {
    my($a1,$a2,$a3,$a4) = split /\./,$a,4;
    my($b1,$b2,$b3,$b4) = split /\./,$b,4;
    $a1 <=> $b1 ||
    $a2 <=> $b2 ||
    $a3 <=> $b3 ||
    $a4 <=> $b4
}

# No sense in running if 'smtpd' doesn't even exist on this system...
unless (( -f "/usr/local/bin/rblsmtpd" )) {
   exit (0);
}

if ( $Debug >= 5 ) {
   print STDERR "\n\nDEBUG: Inside SMTPD Filter \n\n";
   $DebugCounter = 1;
}

while (defined($ThisLine = <STDIN>)) {
   if ( $Debug >= 5 ) {
      print STDERR "DEBUG($DebugCounter): $ThisLine";
      $DebugCounter++;
   }
   chomp($ThisLine);
   if ($ThisLine =~ /rblsmtpd: ([\d\.]+)/) {
     $mailer = LookupIP($1);
     $Mailfrom{"$mailer"}++;
#    push @Mailfrom, LookupIP($1);
   }
   if ( $Detail >= 10 ) {
      push @OtherList,$ThisLine."\n";
   } else {
#      if ($ThisLine =~ /([\d\.]+) rblsmtpd: ([\d\.]+) pid ([\d]):/) {
     if ($ThisLine =~ /rblsmtpd: ([\d\.]+) pid ([\d]+): ([\S+\s]+)/) {
        $ThisLine = "$1 : $3";
        $OtherList{"$ThisLine"}++;
     }
   }
}

print "\n\n -------------------- SMTPD Begin ------------------------ \n";

if (keys %Mailfrom) {
   $Counter = 0;
   print "\nPossible SPAM from IPs:\n\n";
   for (sort byip (keys %Mailfrom)) {
       print "$_: $Mailfrom{$_} time(s)\n";
       $Counter = $Counter + $Mailfrom{$_};
   }
   print "\nTotals events: $Counter\n";
}
#      if ($#Mailfrom >= 0) {
#         print "\nPossible SPAM from IPs:\n";
#         foreach $ThisOne (@Mailfrom) {
#            print "   " . $ThisOne . "\n";
#         }
#      }

if ( $Detail >= 10 ) {
   if ($#OtherList >= 0) {
      print "\n**RBLSMTPD Entries**\n\n";
      print @OtherList;
   }
} else {
   if (keys %OtherList) {
      print "\n**RBLSMTPD Entries**\n\n";
      for (sort byip (keys %OtherList)) {
          print "$_\n";
      }
   }
}

print "\n\n --------------------- SMTPD End ------------------------- \n\n";

exit(0);
