#!/usr/bin/perl
# USAGE
#       EDIT THE SCRIPT TO SPECIFY the log pipe and threshold of login attempts
#	perl ssh-anti-brute-1.1.pl&
#       And leave it running
# SEE ALSO
#
#   perldoc ssh-anti-brute-1.1.pl

#Automatically block ips attempting ssh brute force

#Pipe configured in syslog
my $pipe = "/var/log/auth.info.pipe";
#Numper of attemtps to block
my $threshold = 3;

#Nothing configureable next
my %ips;   
open(FIFO,"<$pipe");
while(my $line = <FIFO>)
   {
       if($line =~ /Failed password/)
         {
             my ($a) = ( $line =~ m/ffff:(.*?)\s/ );
             getit($a);
         }elsif($line =~ /Accepted password/)
         {
             my ($a) = ( $line =~ m/ffff:(.*?)\s/ );
             releaseit($a)
         }
    }
close(FIFO);

sub getit
{
   my($ip) = @_;
    if($ips{$ip} > 0)
     {
        $ips{$ip} = $ips{$ip} + 1;
     }else
     {
        $ips{$ip} = 1;
     }
     if($ips{$ip} > $threshold)
      {
        `iptables -A INPUT -p tcp -s $ip --dport 22 -j DROP`;
         releaseit($ip);
      }
}

sub releaseit
{
   my($ip) = @_;
   delete($ips{$ip});
}

__END__

=head1 NAME

ssh-anti-brute-1.1.pl - Automatically block ips attempting ssh brute force

=head1 SCRIPT CATEGORIES

Networking

=head1 README

This script read a named pipe which is configured in syslog for auth.info and block the ips trying to bruteforce ssh.


=head1 OSNAMES

All

=head1 PREREQUISITES
   A named pipe must be configured in syslog to receive auth.info

=head1 COREQUISITES

=head1 SYNOPSIS

=head1 AUTHOR

Jamshaid Faisal

 { 
   domain   => "gmail", 
   tld      => "com", 
   username => "j.faisal" 
 }

=cut
