Blocking bogons with iptables

iptables Linux

ipsets is a fairly recent addition to the netfilter family.

It is possible to define networks / addresses and then use them in iptables.

ipset --create bogons nethash
ipset --add bogons 10.0.0.0/8
ipset --add bogons 192.168.0.0/16
ipset --add bogons 0.0.0.0/8
ipset --add bogons 169.254.0.0/16
ipset --add bogons 172.16.0.0/12
ipset --add bogons 192.0.2.0/24
ipset --add bogons 192.42.172.0/24

For example, on one of my Debian boxes I have created /etc/ipset.bogons.up

create bogons hash:net family inet hashsize 1024 maxelem 65536
add bogons 192.0.2.0/24
add bogons 169.254.0.0/16
add bogons 192.42.172.0/24
add bogons 10.0.0.0/8
add bogons 0.0.0.0/8
add bogons 172.16.0.0/12
add bogons 192.168.0.0/16

And in /etc/network/if-pre-up.d/ I have: (this in on Debian)

#!/bin/sh
/usr/sbin/ipset restore < /etc/ipset.bogons.up
/sbin/iptables-restore < /etc/iptables.up.rules
#

Which restores both the ipsets and iptables rules at boot time.
In my iptables ruleset I reference the ipsets:

-A INPUT -m set --match-set bogons src -j DROP
-A INPUT -m set --match-set bogons dst -j DROP
-A FORWARD -m set --match-set bogons src -j DROP
-A FORWARD -m set --match-set bogons dst -j DROP