#!/usr/bin/perl ############################################################################## # By BumbleBeeWare.com 2006 # SSH Log Checker # sshlogcheck.cgi # reads ssh log and blocks hacking attempts using ip tables ############################################################################## # CONFIGURE ############################################################################## # location of complete log of banned ips for reference $banned = "bannedips.txt"; # set path or default will be the same dir as this script ############################################################################## # MAIN PROGRAM ############################################################################## # open the baned ips list and ignore existing banned ips open (BASE, "<$banned"); while () { $bannedip = $_; chomp $bannedip; $BANNEDIP{$bannedip} = $bannedip; } close BASE; open(SECURELOG,"/usr/bin/tail -n -3000 /var/log/secure |"); while ($line=){ chomp $line; if ($line =~ /Failed password/i){ # if day in log is same ad today count failed attempts at each ip if (substr($line,0,6) eq substr(localtime,4,6)){ ($messafe, $ip) = split(/from /, $line); ($ip, $port) = split(/ /, $ip); $ip =~ s/\:\:ffff\://g; # remove the ::ffff: in some logs $FAILEDIP{$ip}++; } } } close(SECURELOG); # for each ip with more than 20 fails in one day block the ip foreach $ip (sort keys(%FAILEDIP)) { if ($FAILEDIP{$ip} > 20){ # make sure the ip is not previously banned if ($ip eq $BANNEDIP{$ip}){} else { #print "$FAILEDIP{$ip} $ip\n"; # ban the ip from any input to this server $banip = `iptables -I INPUT -s $ip -j DROP`; # log to banned list open (FILE, ">>$banned"); print FILE "$ip\n"; close (FILE); } } }