Table of Contents

Automatic load of iptables rules on Ubuntu

The fact that iptables is empty on each boot is both beautiful and iritating! You can mess everything up, and just reboot the PC to get a clean start (or just empty the rules - to be faster). But what if you want the rules to apply even after reboot? Here are a few ways to d othis:

  1. Create a save/restore script in the if-up/if-down folder
  2. Create a save/restore script that runs on boot/shutdown
  3. Use iptables-persistent

The if-up.d and if-down.d method

The simplest way is to add a script called iptables in the /etc/network/if-up.d directory

#!/bin/sh
iptables-restore < /etc/firewall.conf

And another script called iptables in the /etc/network/if-down.d directory

#!/bin/sh
iptables-save > /etc/firewall.conf

Make them both executable (chmod +x iptables) and every time an interface goes up - it will restore all the rules, and when an interface goes down - it will save the rules. Note that /etc/firewall.conf must allready be populated with rules, so make sure to run iptables-save once you configure all the rules.

The startup and shutdown method

This can be done eather through /etc/rc.local or crontab

A⇒ Place the iptables-restore command before the exit 0 line
B⇒ run crontab -e and create this entry: @reboot /path/to/script (the restore script ofcourse)

To save the iptables rules, place the iptables-save script inside the /etc/rc6.d directory, and make sure thet the name starts with K99. For example executable file /etc/rc6.d/K99iptables

The iptables-persistent method

Simply install iptables-persistent by issuing this command

sudo apt-get install iptables-persistent

and follow the prompts. When asked, hit 'Yes' to save the current rules (on both prompts). Now - upon reboot, iptables will be populated with current rules.

If you for any reason want to change the rules - you can do so, but you have to issue theese commends afterwards:

sudo su -c 'iptables-save > /etc/iptables/rules.v4'
sudo su -c 'ip6tables-save > /etc/iptables/rules.v6'

The first one to save the v4 rules, and the second one to save the v6 rules (if used).

If you don't do this - the modifications will be lost after reboot (wich could be useful)