Wednesday, September 24, 2008

Perl Script to Update Recommended IP Block Ranges

Yesterday, I started down the road of learning to develop in Perl. Came up with the idea of updating my OpenBSD firewall badhosts table with the DShields recommended IP block range list.

In order to get it to run I had to install the p5-LWP-UserAgent-Determined-1.03.tgz package on the OpenBSD system.

Configured Cron to run the script:
sudo crontab -e
* 23 * * * /usr/bin/perl /etc/bhupdate.pl >/dev/null 2>&1

----Part of pf.conf-------------

table <badhosts> persist file "/etc/badhosts"

block in log quick on $ext_if from <badhosts> \
label "Badhosts in"
block out log quick on $ext_if to <badhosts> \
label "Badhosts out"

--------------------------------------------------

Here is the Perl script:

#!/usr/local/bin/perl -w
use LWP::Simple;

#open the badhosts file and load it to an array
open(BH,"/etc/badhosts");
@badhosts = ;
close BH;

#create arrays and get recommended block data from site
@badips = ();
@dshield = split("\n",get('http://feeds.dshield.org/block.txt'));

foreach $newrange(@dshield)
{
#check to see if line starts with an ip. if so then
#pull only the first ip

if($newrange =~ m/^\d/i)
{
@ipinfo = split("\t",$newrange);
$ip = "$ipinfo[0]/24\n";

$counter = 0;

#check to see if ip range is already listed in badhosts file
#if not then load in into badips array

foreach $badrange(@badhosts)
{
if($badrange eq $ip)
{
$counter++;
}
}

if($counter == 0)
{
push(@badips,$ip);
}

}

}

#append badhosts file with newly recommended block ranges
open(BH,">>/etc/badhosts");
print BH @badips;
close BH;

system("pfctl -f /etc/pf.conf")

No comments: