#!/usr/bin/perl -w
# Date:2009-03-12
# Author:HyphenWang
# Version:1.1
use strict;
my $IPTABLES_CMD="/sbin/iptables -v -n -x -L FORWARD";
my $BANIP_CMD="/root/banip.sh";
my $SEC="3";
my $ZERO="0";
my $BANIP="1";
my $BANSEC="60";
my $limit_input_rate=150;
my $limit_output_rate=20;
my @exclude_ip=qw(30 153 155 200 221);
my (%first_input,%first_output);
my (%second_input,%second_output);
my (%ban_ip,$input_rate,$output_rate);

sub get_ipflow {
  my ($ip_input,$ip_output)=@_;
  for my $line (`$IPTABLES_CMD`) {
    my @columns = split(/\s+/,$line);
    $ip_input->{$columns[-1]}=$columns[2] if ($columns[3] eq "ACCEPT" and $columns[-1] =~ m/192\.168\.228\.\d+/);
    $ip_output->{$columns[-2]}=$columns[2] if ($columns[3] eq "ACCEPT" and $columns[-2] =~ m/192\.168\.228\.\d+/);
    $ban_ip{$columns[-1]}=1 if ($columns[3] eq "DROP" and $columns[-1] =~ m/192\.168\.228\.\d+/);
    $ban_ip{$columns[-2]}=1 if ($columns[3] eq "DROP" and $columns[-2] =~ m/192\.168\.228\.\d+/);
  }
}
get_ipflow(\%first_input,\%first_output);
sleep $SEC;
get_ipflow(\%second_input,\%second_output);
print "Now is ".localtime()."\n";
print "-"x53,"\n";
print "IP Address\t\tIn Flow Rate\tOut Flow Rate\n";
for my $ip (keys %first_input) {
  if ($ZERO != 1) {
  	if (defined $second_input{$ip} and defined $second_output{$ip} and int(($second_input{$ip}-$first_input{$ip})/1024/$SEC) == 0) {
      next;
    }
  }
  if (defined $second_input{$ip} and defined $second_output{$ip}) {
    $input_rate = ($second_input{$ip}-$first_input{$ip})/1024/$SEC;
    $output_rate = ($second_output{$ip}-$first_output{$ip})/1024/$SEC;
    printf ("%s\t\t%.f KByte/s\t%.f KByte/s\n",$ip,$input_rate,$output_rate);
    if ($BANIP == 1 and $input_rate >= $limit_input_rate and ! grep ("192.168.228.$_" eq $ip,@exclude_ip)) {
      system ("$BANIP_CMD INPUT $ip $BANSEC &");
      $ban_ip{$ip}=1;
    }
    if ($BANIP == 1 and $output_rate >= $limit_output_rate and ! grep ("192.168.228.$_" eq $ip,@exclude_ip)) {
      system ("$BANIP_CMD OUTPUT $ip $BANSEC &");
      $ban_ip{$ip}=1;
    }
  }
}
print "-"x53,"\n";
print "Banned IP Address:\n";
for (keys %ban_ip) {
  print "$_\n";
}
