#!/usr/bin/perl # Developted by Antonis Sidiropoulos for securing Delab :-) # # use IO::Handle; STDERR->autoflush(1); STDOUT->autoflush(1); $0='watching'; $log_file = '/var/log/secure'; $string = 'Failed password for'; $unblock = '/usr/local/admin/bin/unblock_ip'; $me = '/usr/local/admin/bin/watching'; print "Starting Watching $$\n"; $host=`hostname`; chomp $host; $SIG{ALRM} = reset_c; alarm(60*60); #alarm(60); if(!open(FF,"tail -f $log_file|")) { print STDERR "cannot open $log_file\n"; exit 1; } print "$$: Starting watching ($$)\n"; while(my $l=) { chomp $l; chomp $l; if($l=~/$string/i) { block_ip($l); } } sub reset_c { print "$$: reseting counts\n"; %counter=(); exec($me); alarm(24*60*60); #alarm(60); } sub block_ip{ local($line)= @_; my ($ip,$user)=(); if($line=~/[^0-9]([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)[^0-9]/) { $ip = $1; } print "$$: $line\n"; if($line=~/for[\s\t]+([^\s\t]*)[\s\t]+from/i || $line=~/user[\s\t]+([^\s\t]*)[\s\t]+from/i) { $user = $1; } $counter{"$ip"}++; print "$$: Attempt ($counter{$ip}) from ip $ip by user $user\n"; if($counter{"$ip"}>=2) { $time = ($counter{"$ip"} -2)**2; if($time==0) { $time=1;} print "$$: Will block for $time minutes\n"; system "iptables -I RH-Firewall-1-INPUT 1 --source $ip -j REJECT"; system "iptables -I RH-Firewall-1-INPUT 1 --destination $ip -j REJECT"; system "echo $unblock $ip| at now +$time minutes 2>&1 > /tmp/.watching.$$"; open(FO,"|Mail -s 'Bad password @ '$host root "); print FO "Bad user $user from $ip\nattempts=".$counter{"$ip"}."\nBlocking for $time minutes\n"; close FO; } else { print "$$: Will not block $ip yet\n"; } }