#!/usr/bin/perl use warnings; use strict; ####################################################################################### ####################################################################################### # This is how far back to check in minutes. There should also be the # same amount of time between when the script is run. my $CHECK_TIME = 600; # This is the maximum number of failed attempts before adding a block rule. # this must be bigger than or equal to 2. my $MAX_FAILURES = 5; # This is the amount of time an IP will be blocked in minutes. my $BLOCK_TIME = 120; # If this is set to "on" it will only print what it would do, not actually add the rule. my $DEBUG = "on"; ####################################################################################### ####################################################################################### my $logfile = shift || die "I need a log file to analyze.\n"; my $currenttime = `date`; my $curmonth = ''; my $curday = ''; my $curhour = ''; my $curmin = ''; my $curtotalmin = ''; my %IPhash = (); if ($currenttime =~ /... (...) (\d\d) (\d\d):(\d\d):\d\d/gi) { $curmonth = $1; $curday = $2; $curhour = $3; $curmin = $4; $curtotalmin = ($curhour * 60) + $curmin; print "Current Time: $curmonth $curday $curhour:$curmin\n"; } else { die "Couldn't get the current time\n"; } open(FIN,$logfile); my @logdata = ; close(FIN); foreach my $line (@logdata) { if ($line =~ /(...) (\d\d) (\d\d):(\d\d):\d\d [\s\S]+ Failed password for([\S\s.]*) user (.*) from (\d+\.\d+\.\d+\.\d+)/gi) { my $month = $1; my $day = $2; my $hour = $3; my $minute = $4; my $username = $6; my $ipaddr = $7; my $totalminutes = ($hour * 60) + $minute; if (($month eq $curmonth) && ($day eq $curday) && (($curtotalmin - $totalminutes) < $CHECK_TIME)) { #print "$month $day $hour:$minute User: $username, IP: $ipaddr\n"; if (defined $IPhash{$ipaddr}) { #print "Incrementing $ipaddr\n"; $IPhash{$ipaddr}++; if ($IPhash{$ipaddr} == $MAX_FAILURES) { addIPBlock($ipaddr); } } else { print "Adding initial $ipaddr to hash\n"; $IPhash{$ipaddr} = 1; } } } else { next; } } while ( my ($key, $value) = each(%IPhash) ) { print "$key => $value\n"; } sub addIPBlock { my $address = shift; print "Adding block rule for $address\n"; if ($DEBUG ne "on") { system("iptables -I INPUT -s $address -j DROP"); system("echo \"iptables -D INPUT -s $address -j DROP\" > /tmp/rem$address.tmp"); system("at -f /tmp/rem$address.tmp + $BLOCK_TIME minutes"); } else { print "iptables -I INPUT -s $address -j DROP\n"; print "echo \"iptables -D INPUT -s $address -j DROP\" > /tmp/rem$address.tmp\n"; print "at -f /tmp/rem$address.tmp + $BLOCK_TIME minutes\n"; } }