Building Firewalls with iptables, Part 1 - Page 3
This example rule blocks traffic from a specific IP range because it belongs to a notoriously noxious spammer, and we don't want the spammer's spew polluting our nice systems:
# iptables -t filter -A INPUT -s 123.456.789.0/24 -j DROP
See how it follows the syntax described above. (See man iptables for definitions of the various switches and commands.) Now let's say your users are becoming increasingly vindictive and resentful towards spammers, which is understandable, but certain retaliatory tactics are simply not permissible, at least not from your network. We can also block all outgoing packets directed to the spammer's IPs easily enough with this slightly different syntax:
# iptables -t filter -A OUTPUT -d 123.456.789.0/24 -j DROP
Notice the -A switch. Use this to append rules to existing chains.
Spammers are shifty, experts at playing whack-a-mole (in the role of the mole) by continually changing IPs and DNS. Suppose our ignominious spammer moves to a new IP range, and the old IP address is then reassigned to some saintly nuns, whose bits are worthy to traverse your network. Simply delete the rule with the -D switch:
# iptables -t filter -D OUTPUT -d 123.456.789.0/24 -j DROP
Crafting rules to cover every contingency is a nice way to consume mass quantities of time. For those who would rather not, the basic principle is "deny all, allow only as needed." Let's set up the default rules for each chain:
# iptables -P INPUT DROP
# iptables -P FORWARD DROP
# iptables -P OUTPUT ACCEPT
-P sets the policy for the chain. Only the three built-in chains can have policies. These policies permit unfettered outgoing traffic, but no incoming traffic. At the very least, we want to hear from the nuns:
# iptables -t filter -A INPUT -s 123.456.789.0/24 -j ACCEPT
Stay tuned for Part 2, which will offer more sample rules and scripts.