Wednesday, January 28, 2009

Filtering bogons with iptables

There are a bunch of IP addresses that cannot be used (routed) across the internet. The private IP address ranges typically use for NAT are an example. I wrote a script to grab the unallocated ranges and create iptable rules for each. I thought i would be clever (-: i never learn, do i? :-) and integrate these with system-config-firewall, which appears to be a frontend to lokkit. Going to "Custom Rules", "Add", "ipv4", "filter", and choosing the file makes lokkit crap out with an error AND drop all the other rules. Bad form. I tracked the error down to the apparent fact the lokkit doesn't allow more the nine custom rules, no matter how many files the rules are broken in to. More bad form. So i just add them by hand. I should get around to using ipset for all this... Anyway, here's that script
#! /bin/bash

TEMP=/tmp/bogons

wget --quiet -O - http://www.iana.org/assignments/ipv4-address-space | \
grep UNALLOCATED | \
cut -d ' ' -f 1 > /tmp/unallocated

sed -e '/^$/d' \
-e 's/^00*//' \
-e 's/^/iptables -D INPUT -s /' \
-e 's/$/ -j DROP/' < /tmp/unallocated > $TEMP

sed -e '/^$/d' \
-e 's/^00*//' \
-e 's/^/iptables -I INPUT -s /' \
-e 's/$/ -j DROP/' < /tmp/unallocated >> $TEMP

echo 'iptables -D INPUT -s 10/24 -j DROP' >> $TEMP
echo 'iptables -I INPUT -s 10/24 -j DROP' >> $TEMP
echo 'iptables -D INPUT -s 172.16/12 -j DROP' >> $TEMP
echo 'iptables -I INPUT -s 172.16/12 -j DROP' >> $TEMP
echo 'iptables -D INPUT -s 192.168/16 -j DROP' >> $TEMP
echo 'iptables -I INPUT -s 192.168/16 -j DROP' >> $TEMP

sh $TEMP
rm /tmp/unallocated $TEMP
ci -m "" -l /etc/sysconfig/iptables
iptables-save > /etc/sysconfig/iptables

No comments: