Tag System Administration

Block An IP Range Using IPTables

One of the great things about hosting a website on a Virtual Private Server (VPS) is root access. This gives a website administrator the power to do a lot of interesting things. For example, one can easily block internet traffic from blog spammers using the built-in Linux packet filter iptables.

By way of example, let’s say a lot of comment spam begins to appear from an IP address like 194.8.74.0.

First, look up the owner of that address (and the associated address range) using the whois databases at ARIN or RIPE. Their entire address range — ie, every IP address they are ever likely to use — will be shown.

In this example, the entire address range is 194.8.74.0 – 194.8.75.255.

Under Ubuntu, blocking a port range is pretty simple. Start by backing up your current iptables rules and create a test rule set.

[root@agrajag]$ iptables-save > /etc/iptables.up.rules
[root@agrajag]$ iptables-save > /etc/iptables.test.rules
[root@agrajag]$ vim /etc/iptables.test.rules

In vim, add this line to the top of the test rule set to block the address range in question:

-A INPUT -m iprange --src-range 194.8.74.0-194.8.75.255 -j DROP

Then, save the new rules to the running iptables:

[root@agrajag]$ iptables-restore < /etc/iptables.test.rules

Last, list the running iptables rules and verify:

[root@agrajag]$ iptables -L

You should see something like this:

DROP       all  --  anywhere             anywhere            source IP range 194.8.74.0-194.8.75.255

That's all it takes to enjoy a spam-free existence.

(Obviously, I could use the Akismet plugin to accomplish the same thing. However, this has the advantage of dropping bad traffic before it's even processed by the web server. Thus saving server resources for more important things.)