Building Firewalls with iptables, Part 2 - Page 3
Scripting
So far, all the examples have been run from the command line. This is a good way to test new rules. Once they are working to your satisfaction, preserve them in a script. This sample is not a complete script, though, as it only illustrates using variables and provides additional sample rules.
#!/bin/sh
#Assign variables
#Any kernel modules that need to be loaded go here
#IP forwarding is usually disabled in the kernel, by default. To enable it:
#Sers with dynamically assigned IPs need this
###Every time this script is restarted, it is a good idea to flush all rules and start over
###Random useful rule examples
#Must enable loopback!
###Foil source IP spoofing; drop incoming packets that claim to be from us,
###Some outgoing traffic must be restricted, to
###Other good ports to block include 31335, 27444, 27665, 20034 NetBus, 9704, 137-139 (smb)
IPTABLES=/sbin/iptables
LAN_NET="192.168.1.0/24"
IFACE= "eth0"
LO_IFACE="lo"
LO_IP="127.0.0.1"
/sbin/modprobe ip_conntrack
/sbin/modprobe iptable_nat
echo "1" > /proc/sys/net/ipv4/ip_forward
echo "1" > /proc/sys/net/ipv4/ip_dynaddr
#Many tutorials recommend setting OUTPUT to DROP. This is very restrictive, so
#do what suits your needs
$IPTABLES -P INPUT DROP
$IPTABLES -F INPUT
$IPTABLES -P OUTPUT ACCEPT
$IPTABLES -F OUTPUT
$IPTABLES -P FORWARD DROP
$IPTABLES -F FORWARD
$IPTABLES -F -t nat
#Allow ssh connections inside the LAN only
$IPTABLES -A INPUT -s LAN_NET -p tcp --destination-port ssh -j ACCEPT
$IPTABLES -A INPUT -i lo -p all -j ACCEPT
$IPTABLES -A OUTPUT -o lo -p all -j ACCEPT
#and drop outgoing packets that are not from us
$IPTABLES -A INPUT -i $IFACE -s $LAN_NET -j DROP
$IPTABLES -A OUTPUT -o $IFACE -s ! $LAN_NET -j DROP
#foil spyware and trojans from phoning home
$IPTABLES -A OUTPUT -o eth0 -p tcp -dport 31337 -j DROP
$IPTABLES -A OUTPUT -o eth0 -p tcp -sport 31337 -j DROP
#...etc.... it may be easier to OUTPUT DROP and then define what is allowed!
Big Fat Warning
We have used only tcp in our examples to this point, but don't forget there are UDP and ICMP packets to contend with as well. In other words, by no means is this a complete firewall tutorial! Hopefully, you now understand the basic concepts and terminology. If you are new to iptables, I recommend starting with some serious TCP/IP study, followed by a review of Oskar Andreasson's wonderful iptables tutorial.
Resources
iptables Tutorial 1.1.19 by Oskar Andreasson
Netfilter/iptables home page - includes downloads, documentation, and mail lists
LinuxGuruz - offers a mondo collection of iptables scripts
Building Secure Servers with Linux by Michael D. Bauer
»
See All Articles by Columnist Carla Schroder