[ Team LiB ] Previous Section Next Section

Recipe 2.20 Loading a Firewall Configuration

2.20.1 Problem

You want to load your firewall rules, e.g., at boot time.

2.20.2 Solution

Use ipchains-restore or iptables-restore. Assuming you've saved your firewall configuration in /etc/sysconfig: [Recipe 2.19]

For iptables:

#!/bin/sh
echo 1 > /proc/sys/net/ipv4/ip_forward       (optional)
iptables-restore < /etc/sysconfig/iptables

For ipchains:

#!/bin/sh
echo 1 > /proc/sys/net/ipv4/ip_forward       (optional)
ipchains-restore < /etc/sysconfig/ipchains

To tell Red Hat Linux that firewall rules should be loaded at boot time:

# chkconfig iptables on

# chkconfig ipchains on

2.20.3 Discussion

Place the load commands in one of your system rc files. Red Hat Linux already has rc files "iptables" and "ipchains" in /etc/init.d that you can simply enable using chkconfig. SuSE Linux, in contrast, has a script /sbin/SuSEpersonal-firewall that invokes iptables or ipchains rules, and it's optionally started by /etc/init.d/personal-firewall.initial and /etc/init.d/personal-firewall.final at boot time.

To roll your own solution, you can write a script like the following and invoke it from an rc file of your choice:

#!/bin/sh
# Uncomment either iptables or ipchains
PROGRAM=/usr/sbin/iptables
#PROGRAM=/sbin/ipchains

FIREWALL=`/bin/basename $PROGRAM`
RULES_FILE=/etc/sysconfig/${FIREWALL}
LOADER=${PROGRAM}-restore
FORWARD_BIT=/proc/sys/net/ipv4/ip_forward

if [ ! -f ${RULES_FILE} ]
then
        echo "$0: Cannot find ${RULES_FILE}" 1>&2
        exit 1
fi

case "$1" in
        start)
                echo 1 > ${FORWARD_BIT}
                ${LOADER} < ${RULES_FILE} || exit 1
                ;;
        stop)
                ${PROGRAM} -F                   # Flush all rules
                ${PROGRAM} -X                   # Delete user-defined chains
                echo 0 > ${FORWARD_BIT}
                ;;
        *)
                echo "Usage: $0 start|stop" 1>&2
                exit 1
                ;;
esac

Make sure you load your firewall rules for all appropriate runlevels where networking is enabled. On most systems this includes runlevels 2 (multiuser without NFS), 3 (full multiuser), and 5 (X11). Check /etc/inittab to confirm this, and use chkconfig to list the status of the networking service at each runlevel:

$ chkconfig --list network
network         0:off   1:off   2:on    3:on    4:on    5:on    6:off

2.20.4 See Also

iptables-load(8), ipchains-load(8), iptables(8), ipchains(8).

    [ Team LiB ] Previous Section Next Section