#!/usr/bin/perl -w
# destuxor (wjholden@gmail.com) - 4/26/2006
# TauRush (snakesandarrows@gmail.com) - 3/17/2007
# jeffrehley (jeffrehley@hotmail.com) - 5/21/2010 - look for failed attempts in auth.log as well
# A simple script to go through a VSFTPD log and block people who have
# unsuccessfully attempted to log in.

#configuration options:
$logfilename1 = '/var/log/vsftpd.log'; # location of ftp logfile.
$logfilename2 = '/var/log/auth.log '; # location of auth logfile.

$allow_exceptions = 1; # if you wish to specify a file to put exceptions into,
# say 1 here, otherwise put 0.

$exception_file = '/var/log/banned.log'; # if you said 1 above, put your filename here.


$max_failures = 5; # maximum number of failures someone can have before
# getting blocked.
#end of configuration options

$command1 = 'grep \'FAIL LOGIN\' '.$logfilename1.' | sed -r \'s/^.{0,}Client .//\' | sed -r \'s/\"//\' | uniq -c';
$command2 = 'grep \'Failed password for invalid user\' '.$logfilename2.' | cut -f 4 -d: | awk \'{print $8}\' | uniq -c';
$command3 = 'grep \'Failed password for root\' '.$logfilename2.' | cut -f 4 -d: | awk \'{print $6}\' | uniq -c';

@connected_ips1 = `$command1`;
@connected_ips2 = `$command2`;
@connected_ips3 = `$command3`;

push (@connected_ips,@connected_ips1);
push (@connected_ips,@connected_ips2);
push (@connected_ips,@connected_ips3);

#print @connected_ips;

undef %noblock;
if ($allow_exceptions == 1) {
open (FH, $exception_file) or die "$!\n";
@exceptions = <FH>;
close (FH);
}

foreach $ip (@exceptions) {
# Added by TauRush to chop LF character
chop ($ip);
$noblock{"$ip"} = 1;
}

foreach $host (@connected_ips)
{
@info = split(/\s+/, $host);

if (($info[1] > $max_failures) and !$noblock{$info[2]}) {
system("iptables -I INPUT 1 -s $info[2] -j DROP");
# 3 lines added by TauRush to create banned.log file
open FILE,">>$exception_file" or die "Unable to open file!\n";
print FILE "$info[2]\n";
close FILE;
}
}
