Saving and Restoring Firewall Configurations
To ensure your firewall configurations are not lost when the system powers down, you must explicitly save the active ruleset and cofnigure the OS to reload it upon startup.
Defining and Persisting Rules
First, implement the desired network restrictions. For instance, to block MySQL access (port 3306) from specific hosts:
iptables -A INPUT -s 10.0.0.5/32 -p tcp -m tcp --dport 3306 -j DROP
iptables -A INPUT -s 10.0.0.6/32 -p tcp -m tcp --dport 3306 -j DROP
iptables -A INPUT -s 10.0.0.7/32 -p tcp -m tcp --dport 3306 -j DROP
iptables -A INPUT -s 10.0.0.8/32 -p tcp -m tcp --dport 3306 -j DROP
Export the currently active rules to a persistent storage file:
iptables-save > /etc/sysconfig/iptables.rules
To guarantee these configurations are reinstated during the boot sqeuence, append the restore command to the local startup script:
echo "iptables-restore < /etc/sysconfig/iptables.rules" >> /etc/rc.d/rc.local
Ensure the startup script is executable:
chmod +x /etc/rc.d/rc.local
Auto-Saving Rules During Shutdown
To prevent the loss of any dynamicaly added rules during a session, you can configure the system to automatically dump the active ruleset to disk before halting or rebooting.
Begin by clearing the existing runtime rules to simulate a fresh state:
iptables -F
Overwrite the storage file with this blank state:
iptables-save > /etc/sysconfig/iptables.rules
Introduce a new set of filtering rules, such as rejecting HTTP traffic from particular subnets:
iptables -A INPUT -s 192.168.1.10/32 -p tcp -m tcp --dport 80 -j REJECT
iptables -A INPUT -s 192.168.1.11/32 -p tcp -m tcp --dport 80 -j REJECT
iptables -A INPUT -s 192.168.1.12/32 -p tcp -m tcp --dport 80 -j REJECT
iptables -A INPUT -s 192.168.1.13/32 -p tcp -m tcp --dport 80 -j REJECT
Confirm the active policy has been updated successfully:
iptables -nvL INPUT
Create a shutdown initialization script responsible for capturing the live rules:
cat << 'EOF' > /etc/init.d/preserve-fw
#!/bin/bash
/sbin/iptables-save > /etc/sysconfig/iptables.rules
EOF
Assign executable permissions to this newly created script:
chmod +x /etc/init.d/preserve-fw
Finally, create symbolic links in the runlevel directories for halt (runlevel 0) and reboot (runlevel 6). The system executes scripts prefixed with 'K' during shutdown, ensuring the preservation logic triggers at the right moment. A lock file must also be created in the subsystem directory:
ln -s /etc/init.d/preserve-fw /etc/rc0.d/K01preserve-fw
ln -s /etc/init.d/preserve-fw /etc/rc6.d/K01preserve-fw
ln -s /etc/init.d/preserve-fw /var/lock/subsys/preserve-fw