Save your firewall rules to a file:
sudo sh -c "iptables-save > /etc/iptables.rules"At this point you have several options. You can make changes to /etc/network/interfaces or add scripts to /etc/network/if-pre-up.d/ and /etc/network/if-post-down.d/ to achieve similar ends. The script solution allows for slightly more flexibility.
Solution #1 - /etc/network/interfaces
Modify the /etc/network/interfaces configuration file to apply the rules automatically.
Open your /etc/network/interfaces file:
sudo vi /etc/network/interfacesAdd a single line (shown below) just after ‘iface lo inet loopback’:
pre-up iptables-restore < /etc/iptables.rulesYou can also prepare a set of down rules, save them into second file /etc/iptables.downrules and apply it automatically using the above steps:
post-down iptables-restore < /etc/iptables.downrulesA fully working example using both from above:
auto eth0You may also want to keep information from byte and packet counters.
iface eth0 inet dhcp
pre-up iptables-restore < /etc/iptables.rules
post-down iptables-restore < /etc/iptables.downrules
sudo sh -c "iptables-save -c > /etc/iptables.rules"The above command will save the whole rule-set to a file called /etc/iptables.rules with byte and packet counters still intact.
Solution #2 /etc/network/if-pre-up.d and ../if-post-down.d
NOTE: This solution uses iptables-save -c to save the counters. Just remove the -c to only save the rules.
Alternatively you could add the iptables-restore and iptables-save to the if-pre-up.d and if-post-down.d directories in the /etc/network directory instead of modifying /etc/network/interface directly.
The script /etc/network/if-pre-up.d/iptablesload will contain:
#!/bin/shThen be sure to give both scripts execute permissions:
iptables-restore < /etc/iptables.rules
exit 0
and /etc/network/if-post-down.d/iptablessave will contain:
#!/bin/sh
iptables-save -c > /etc/iptables.rules
if [ -f /etc/iptables.downrules ]; then
iptables-restore < /etc/iptables.downrules
fi
exit 0
sudo chmod +x /etc/network/if-post-down.d/iptablessaveSolution #3 iptables-persistent
sudo chmod +x /etc/network/if-pre-up.d/iptablesload
Install and use the iptables-persistent package.
Tips
If you manually edit iptables on a regular basis
The above steps go over how to setup your firewall rules and presume they will be relatively static (and for most people they should be). But if you do a lot of development work, you may want to have your iptables saved everytime you reboot. You could add a line like this one in /etc/network/interfaces:
pre-up iptables-restore < /etc/iptables.rules
post-down iptables-save > /etc/iptables.rules
The line "post-down iptables-save > /etc/iptables.rules" will save the rules to be used on the next boot.
No comments:
Post a Comment