#!/usr/bin/perl -w
#
# waix.ipac version 0.5
#
# Copyright 2003-2009 Martin Pot
# http://martybugs.net/waix.ipac/
#
# fetchwaix.pl

# builds ipac-ng accounting rules to track incoming/outgoing traffic from WAIX
# using a list of WAIX network addresses


use NetAddr::IP;
use Net::CIDR;

# define internet-connected interface
my $iface="eth1";

# define working directory (without trailing /)
my $dir="/usr/local/waix.ipac";

# define location of ipac rules working file
my $rules=$dir."/rules.conf";


print "\nfetching waix subnet lists...\n";

# get the WAIX list
`wget -N -r -nd -q -O $dir/waix.txt http://users.spin.net.au/~boostlinux/pipefilter/ipfilter.dat.wa.txt`;

print "\nbuilding array of subnets...\n";


# compress and merge network lists
# thanks to Stygen's info at http://ii.net/~stygen/waixfwl.html and code cleanup by zombie
open (FILE, "$dir/waix.txt");
foreach $line (<FILE>)
{
	$line =~ s/\n//;
	$line =~ s/\r//;
	
	# convert range to list of cidr blocks
	my @cidrlist = Net::CIDR::range2cidr($line);
	
#print "line: $line \n";
	# loop through each element in the list of cidr blocks
	foreach $cidr (@cidrlist)
	{

		# add it to array
		push @addresses, NetAddr::IP->new($cidr);
#print "cidr: $cidr\n";
	}
}
close (FILE);

print "found ".scalar(@addresses)." cidr blocks\n";


# manually add some additional subnets
push @addresses, NetAddr::IP->new("172.22.0.0/16");

print "\ncompressing subnet list...\n";

# compact subnets
@subnets=NetAddr::IP::compact(@addresses);


print "\nbuilding ipac rules...\n";

# start with any custom ipac rules
`cp $dir/rules.head $rules`;

# append rules to ipac config file
if (!open(FILE, ">>$rules")) 
{
	die "Unable to append $rules";
}

print FILE "# rules below are generated by waix.ipac\n";
print FILE "# http://martybugs.net/waix.ipac/\n\n";

# build rule for incoming traffic from internet to home network
print FILE "incoming from internet|ipac~fi|$iface|all||||\n";
# build rule for incoming traffic from internet to linux router
print FILE "incoming from internet|ipac~o|$iface|all||||\n\n";

# build rule for outgoing traffic to internet from home network
print FILE "outgoing to internet|ipac~fo|$iface|all||||\n";
# build rule for outgoing traffic to internet from linux router
print FILE "outgoing to internet|ipac~i|$iface|all||||\n\n";

# also write subnet addresses to a temp file (makes debugging much easier)
open(FILE2, ">$dir/waixsub.txt");
foreach $subnet (@subnets)
{
        print FILE2 "$subnet\n";
	# build rules for incoming traffic from WAIX to home network
	print FILE "incoming from WAIX|ipac~fi|$iface|all|$subnet|||\n";
	# build rules for incoming traffic from WAIX to linux router
	print FILE "incoming from WAIX|ipac~o|$iface|all|$subnet|||\n";

}
close FILE;
close FILE2;


# copy the new rules file into the ipac config directory
`cp $rules /etc/ipac-ng/`;

print "\nre-initialising ipac...\n";

# re-initialise ipac
`/usr/local/sbin/fetchipac -Sv`;

print "\ndone!\n";
