#!/usr/bin/perl -w
#                      /usr/local/bin/block
# http://crystalfaeries.net/posix/bin/block
# A simple script to go through a VSFTPD log and block people who have unsuccessfully attempted to log in.
# destuxor (wjholden@gmail.com) - 4/26/2006
# TauRush (snakesandarrows@gmail.com) - 3/17/2007
# celeste:crystalfaery (kahealani@inbox.com) 2014-12-06 15:02:45+00:00

#configuration options:
$logfilename = '/var/log/vsftpd.log'; # location of your 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/vsftpd.ban';  # 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

$command = 'grep \'FAIL LOGIN\' '.$logfilename.' | sed -r \'s/^.{0,}Client .//\' | sed -r \'s/\"//\' | uniq -c';

@connected_ips = `$command`;


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("/sbin/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;
    }
}

