Manage your iptables rules. Properly.
I regularly see sysadmins saving their iptables rules in an init script. It works, but it’s not the most elegant way to do it. I prefer personally to save the existing rules with the iptables-save command. This command sends the result on the standard output, so let’s redirect it to a file.
# iptables-save > /etc/iptables
Interesting option: -c displays how many times the rule has been applied (on bytes and on packets).
In order to load the rules, simply use the iptables-restore command with the previously saved file in the standard input:
# iptables-restore < /etc/iptables
Add -c to take the counters in account (if you saved them, bien sur). If any rules are already loaded, you don’t even have to flush them, the command does it for you by default (-n to keep them).
To automatically restore the rules on startup, we could create an init script. I prefer to launch the restore directly from the network interface, as a pre-up command. It allows to avoid any forgetting when you flush your rules, then bring your interface up. Moreover, you gain the ability to create dedicated rules for each interfaces. If your rules are independent from your interfaces, you can still launch the restore as a pre-up command for the local loop.
iface eth0 inet static pre-up iptables-restore < /etc/iptables address 543.454.233.42 netmask 255.255.255.0 gateway 543.454.233.254 auto eth0
For those who have seen: yes, I’ve invented a new class of IP addresses.
Red Hat based
Same principle, but the way to do it is slightly different. To save the rules, you can use the iptables service:
# service iptables save
The rules are saved in the /etc/sysconfig/iptables file by default. This file is read when the iptables service is launched.
Avoid locking out (Debian only)
Be honest. Who has never been locked out when modifying firewall policies or rules. I must say that it happened to me. The failure in all its splendour.
In order to avoid this, there is a simple tool: iptables-apply. This command will apply the rules file given as a parameter, then ask for the user confirmation. If the user doesn’t answer before the timeout, iptables-apply undoes the change.
# iptables-apply /etc/iptables [ ok ] Stopping authentication failure monitor: fail2ban. Applying new ruleset... done. Can you establish NEW connections to the machine? (y/N) apparently not... Timeout. Something happened (or did not). Better play it safe... Reverting to old ruleset... done.
Convenient, isn’t it?
If you do know others good practices concerning the managenent of iptables rules, feel free to share them in the comments.
2013-11-25 23:53 +0800