#!/usr/bin/perl
use Date::Manip qw(UnixDate);
use Time::HiRes qw(gettimeofday);
use POSIX qw(strftime);
$log = "/var/log/iptables/iptables.log";
$undenytime = 300;
$exiretime = 600;
$finelogtime = 600;
sub add_ip {
@array = `tail -n 2000 /var/log/secure|grep "Failed"|grep "ffff:"`;
foreach (@array){
if(/^(\w+\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}).*::ffff:(.*)port/){
print "$1 $2\n";
$timeold = UnixDate("$1","%s") - 14*3600;
chomp ( $ip = $2);
$time = time;
$timenow = strftime ("%Y-%m-%d %H:%M:%S",localtime($time)); #strftime( "%Y-%m-%d %H:%M:%S",localtime(time))
($timenew,$temenewsec)= gettimeofday;
if ($time - $timeold < $finelogtime ){
# print "$1 $timenow $ip\n";
$p = $time - $timeold;
$badlist{$ip}{$timeold} = 1;
}}}}
sub refresh_ip {
# print "refresh_ip\n";
foreach $ipnew (keys %badlist){
foreach $misec (keys %{$badlist{$ipnew}}){
if ( time - $misec > $exiretime ){
delete $badlist{$ipnew}{$misec};
# print "$badlist{$ipnew}{$misec}\n";
}
$num = keys %{$badlist{$ipnew}};
if ( $num == 0 ){
# print "delete $badlist{$ipnew}\n";
delete $badlist{$ipnew};
}
}}}
sub check_bad_ip {
# print "check_bad_ip\n";
foreach $ipnew (keys %badlist){
$num = keys (%{$badlist{$ipnew}});
if ( $num > 0 ) {
print "check_bad_ip $ipnew -- $num\n";
deny_bad_ip($ipnew);
delete $badlist{$ipnew};
}
}}
sub deny_bad_ip{
local $ip;
$ip = $_[0];
chomp $ip;
# print "deny_bad_ip() $ip\n";
foreach ( keys %deny_ip ){
return if (/^$ip$/)
}
# print "if ( $ip =~ /\./){\n";
if ( $ip =~ /\./){
$cmd = "iptables -A INPUT -p tcp -s $ip -j REJECT --reject-with tcp-reset";
system ( $cmd );
# print "$cmd\n";
$deny_ip{$ip} = time;
$time = strftime ("%Y-%m-%d %H:%M:%S",localtime(time));
open(LOG,">>$log") or die "$!";
print LOG "$time $ip deny login with ssh $undenytime \n";
close(LOG);
}}
sub undeny_bad_ip {
local $time;
local $ip;
# print "undeny_bad_ip\n";
foreach $ip ( keys %deny_ip){
if (time - $deny_ip{$ip} > $undenytime){
delete $deny_ip{$ip};
$time = strftime ("%Y-%m-%d %H:%M:%S",localtime(time));
open(LOG,">>$log") or die "$!";
print LOG "$time $ip Undeny login with ssh $undenytime \n";
close(LOG);
chomp $ip;
$ipline = `iptables -L -n --line-number |grep $ip `;
# print "$ipline\n";
$ipline =~ /^(.*)\s+REJECT/ ;
$iplin = $1;
# print "$iplin = iptables -L -n --line-number |grep $ip\n";
chomp $iplin;
$cmd = "iptables -D INPUT $iplin ";
# print "iptables -D INPUT $iplin\n";
system( $cmd );
}}}
sub init_iptables {
$cmd1 = "iptables -F > /dev/null 2>&1";
$cmd2 = "iptables -X > /dev/null 2>&1";
$cmd3 = "iptables -N > /dev/null 2>&1";
system ($cmd1);
system ($cmd2);
system ($cmd3);
}
init_iptables ();
while (1){
# init_iptables ();
add_ip ();
refresh_ip ();
check_bad_ip ();
deny_bad_ip ();
undeny_bad_ip();
#print "sleep 60 now \n";
sleep 60;
}
阅读(4076) | 评论(0) | 转发(0) |