I deal with headless linux boxes a lot, and one of the first things you always want to do is configure your firewall. The general rule of thumb says to deny all traffic and only poke holes where you need them. It’s an awful pain to configure iptables one rule at a time from the command line. It’s also a pain if you need to open one more port before that deny-all at the end of a chain, because that involves running through the whole chain again.
Now there’s probably some clever “iptables ninja” way to do it, but I prefer simplicity, so I use the iptables-save and iptables-restore commands. The first will dump your current firewall rules to standard out. The second will read rules from standard in into the firewall table.
For reference, my distro of choice is Fedora, so these commands are Red-Hat-centric.
Using iptables-save to dump your rules to a file is simple enough. Just redirect standard out to a file. Don’t forget to run it as root.
# sudo iptables-save > ./firewall.rules
Open up that file in vim (or a less worthy text editor… take that emacs!) and you’ll see it’s just a list of iptables commands. Perfect. Just drop in the new rule where you wanted it.
Reloading the firewall table from this file is a little more tricky, though. Specifically, iptables-restore takes input from standard input, but mysteriously doesn’t work when you redirect standard in from a file with the < redirector.
The solution? Call the plumber! Using the piped output from cat works just fine. Don’t forget to flush the firewall rules before you read them in again, and run both the iptables commands as root.
# sudo iptables -F # cat ./firewall.rules | sudo iptables-restore
Now double check to make sure that the firewall configuration is really what you think it is.
# sudo iptables -L
Lastly, save the firewall configuration so that it persists after a reboot. If you skip this step, your old configuration will come back when the iptables service starts next time.
# sudo service iptables save
For good measure, I always like to restart the iptables service to verify that it will come back up using the config that I expect.
# sudo service iptables restart # sudo iptables -L
All done! Not to painful, right? This is also a great way to backup your firewall config. If anything bad happens, you need to reinstall iptables, or you’re provisioning a duplicate server, just run the back half of this process with iptables-restore and your backed up firewall.rules file.
Thanks!! I was struggling with why I could not get iptables-restore to work and your instructions solved my problem – I was not flushing the tables properly.