#!/usr/bin/perl -w # # This script grabs ip addresses from my firewall log file # and adds them to a blacklist for my iptables ruleset. # ## NOTE - This script must be run as root use strict; # Check to make sure root is running this if ($< != 0) { print "You must run this program as root!\n"; exit } my $log = "/var/log/iptables.log"; my $blacklist = "/var/log/blacklist"; my @list; my %seen; my @sorted; # Open log file, retrieve list of ip addresses and write them # to the blacklist open(IN, "<", $log) || die "Can not open $log $!"; open(BL, ">>", $blacklist) || die "Can not open $blacklist $!"; while () { s/.*(SRC)/$1/; s/(DST).*/$1/; s/ DST//; s/SRC=//; print BL ; } close IN; close BL; # Read blacklist into an array while eliminating blank lines, # IP's from my network and duplicates open(BL, "<", $blacklist) || die "can not open $blacklist $!"; while () { next if /\A\s*\z/ ; # skip blank lines next if /192.168*/; $seen{$_}++; next if $seen{$_} > 1; push(@list, $_); } close BL; # Sort my list of IP addresses @sorted = sort { pack('C4' => $a =~ /(\d+)\.(\d+)\.(\d+)\.(\d+)/) cmp pack('C4' => $b =~ /(\d+)\.(\d+)\.(\d+)\.(\d+)/) } @list; # Create clean blacklist file and append iptables rules open(BL, ">", $blacklist) || die "Cannot open $blacklist $!"; foreach my $ip(@sorted) { print BL "$ip"; chomp($ip); system("/sbin/iptables -A BLACKLIST -p all -s $ip -d 0/0 -j LOG --log-prefix \"IPTABLES:Blacklist: \""); system("/sbin/iptables -A BLACKLIST -p all -s $ip -d 0/0 -j DROP"); } close BL; chmod 0600, "$blacklist";