Saturday, March 26, 2011

perl script to Block IP addresses - IPTABLES - Centos 5

#!/usr/bin/perl

# To run through cron - run every 10-15 minutes or so
# Scan /var/log/secure and then add those ip's to IPTABLES.

use strict;

my $user;
my $block_ip;
my $valid_user = "user1|oracle";
my @valid_ip   = ("146.21.0.0",);
my %distinct_ip = ();

open(IP,"tail -50 /var/log/secure | grep 'Failed password'|") || die "cannot open file for reading $!\n";


while(my $line = <IP>) {
 if ($line =~ /for (invalid user )*?(\w{1,}) from (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/) {
  $user = $2;
  $block_ip = $3;
  if ($user !~ /($valid_user)/) {
   #print "$line\n";
   $distinct_ip{$block_ip} = $user;
  }
 }
}


foreach my $ip (keys %distinct_ip) {
  my $already_blocked = `/sbin/iptables -L -n | grep DROP | grep $ip`;
  if (! $already_blocked) {
   if (&block_ip_yn($ip) ) {
      #print "Will block $ip for user $distinct_ip{$ip}\n";
      system("/sbin/iptables -I INPUT 1 -s $ip -j DROP");
   }
   else {
     #print "Will ALLOW $ip\n";
   }
  }
  else {
    #print "Will IGNORE - Already Blocked\n";
  }
}


sub block_ip_yn {
 my $ip_to_block = shift;
 my ($vip_1,$vip_2,$vip_3,$vip_4);
 my ($bip_1,$bip_2,$bip_3,$bip_4) = split("\\.",$ip_to_block);
 my $to_block = 1;

 foreach my $vip (@valid_ip) {
   ($vip_1,$vip_2,$vip_3,$vip_4) = split("\\.",$vip);
    if ( &sub_part($vip_1,$bip_1) + &sub_part($vip_2,$bip_2) + &sub_part($vip_3,$bip_3) + &sub_part($vip_4,$bip_4)  == 0) {
    $to_block = 0;
    last;
   }
 }
 return $to_block;
}

sub sub_part {
 my ($a,$b) = @_;

 if ( ($a == $b) || ($a == 0) ) {
  return 0;
 }
  return 1;
# return 0 if subpart matches else return 1;
}

No comments:

Post a Comment

Followers

About Me

Torrance, CA, United States