iptables firewall Crash Course

by Marion Bates <mbates at whoopis.com>

Last modified: December 31 1969 16:00:00


A very simple iptables firewall rule script:

#!/bin/bash
# Flush all old rules
iptables -F INPUT
iptables -F OUTPUT
iptables -F FORWARD

# Loop through each entry 
# in a space-delimited list 
# of known-bad IP addresses/nets
for ONEADDR in 1.2.3.4/32 2.3.4.5/24 3.4.5.6/32; do
        iptables -A INPUT -s $ONEADDR -p tcp -j DROP
done

# Define default policy for all chains
iptables -P INPUT ACCEPT 
iptables -P OUTPUT ACCEPT
iptables -P FORWARD ACCEPT

# List the current ruleset, without name lookups
iptables -L -n

Save as "fwrules.sh" and run

chmod 755 fwrules.sh

to make it executable.

When you find an IP you want to block, simple add it to the ONEADDR block (don't forget the netmask).

If you already have a current set of rules in place, and you don't want to lose them, first do

iptables-save > currentrules

The resulting file will look something like this:

# Generated by iptables-save v1.2.7a on Tue Feb  8 15:17:06 2005
*nat
:PREROUTING ACCEPT [607904:34887371]
:POSTROUTING ACCEPT [247339:18276910]
:OUTPUT ACCEPT [0:0]
COMMIT
# Completed on Tue Feb  8 15:17:06 2005
# Generated by iptables-save v1.2.7a on Tue Feb  8 15:17:06 2005
*mangle
:PREROUTING ACCEPT [43497348:2682004698]
:INPUT ACCEPT [43497257:2681986573]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [71836541:99121019195]
:POSTROUTING ACCEPT [71836547:99121020539]
COMMIT
# Completed on Tue Feb  8 15:17:06 2005
# Generated by iptables-save v1.2.7a on Tue Feb  8 15:17:06 2005
*filter
:INPUT ACCEPT [158458:9004066]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [229653:282193394]
-A INPUT -s 9.8.7.6 -p tcp -j DROP 
-A INPUT -s 1.2.3.4 -p tcp -j DROP 
-A INPUT -s 6.7.8.9 -p tcp -j DROP 
COMMIT
# Completed on Tue Feb  8 15:17:06 2005

Or it'll be even less detailed if you have no rules. Anyway, copy the lines you care about and merge them into your script above.


Get Euro-style oval stickers for Geeks!

NEW -- the "magic/more magic" light switch cover!
Click here for the story.

References: