Thursday, July 11, 2013

How to make iptables rules permanent

Linux distributions come with a pretty good firewall, called iptables. However one drawback with iptables is that changes made to the iptables are temporary i.e., they will be lost in the next reboot unless you save them.

There are couple of commands iptables-save and iptables-restore to save and restore the iptables. It is simple to use once you are done making your changes to the iptables, you can use the command iptables-save > [your file] to save your firewall rules to a file and later on restore the iptables rules by using the command iptables-restore < [your file].

However the restore command has to be executed by someone when the machine reboots. There are two approaches to handle this:
  • You execute the iptables-restore command manually every-time you reboot your linux OS, or
  • Make changes in your OS so that the iptables-restore command is executed automatically.
In this blog post I will list out the various mechanisms you can use to run the iptables-restore command. Note: This assumes that you do not install any other packages for managing the iptables.
  1. Add the iptables-restore command to your /etc/rc.local file. The /etc/rc.local file is a quick and easy way to restore your iptables, but be advised this is not the best place to put the iptables-restore command. Check this link on why not to use /etc/rc.local file. Anyways if you want to use it, simply add this to your /etc/rc.local file: /sbin/iptables-restore < /etc/iptables.rules, assuming you had saved your iptables rules in the /etc/iptables.rules file.
  2. The approach I recommend is to add a script in one of the following directories as per your need:
    • /etc/network/if-pre-up.d/: Scripts placed in this directory are executed just before the network is brought up.
    • /etc/network/if-up.d/: Scripts placed in this directory are executed just after the network has been brought up. I recommend using this directory for firewall rules. Create a file called iptables and give it execute permissions and add the following line in it
                  /sbin/iptables-restore < /etc/iptables.rules

There are other software packages for various linux distributions which also can be used to manage your firewalls. On ubuntu based distros, you can even use iptables-persistent application, which can help you manager your iptables based firewall. Some other firewall applications are ufw (Uncomplicated Fire Wall).



 

No comments: