How to save IPtables rules in Debian

Thanks to http://jesin.tk/how-to-save-iptables-rules-in-debian/

This article explains how to make IPtables firewall rules sustain a boot in Debian. But this can also be applied on other Debian based OSes like Ubuntu and Knoppix. You show execute all these commands as the root user or use the sudo command to do it.

First view the list of rules in IPtables

iptables -L

If its a new installation there will be no rules. So add some firewall rules, the following rules will allow HTTP, HTTPS, FTP, SMTP, SSH incoming connections and rejects all other incoming connections including ICMP ping packets.

iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -m state --state NEW -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -m state --state NEW -p tcp --dport 443 -j ACCEPT
iptables -A INPUT -m state --state NEW -p tcp --dport 21 -j ACCEPT
iptables -A INPUT -m state --state NEW -p tcp --dport 25 -j ACCEPT
iptables -A INPUT -m state --state NEW -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -j REJECT

View the firewall rules once more

iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED
ACCEPT     all  --  anywhere             anywhere
ACCEPT     tcp  --  anywhere             anywhere            state NEW tcp dpt:www
ACCEPT     tcp  --  anywhere             anywhere            state NEW tcp dpt:https
ACCEPT     tcp  --  anywhere             anywhere            state NEW tcp dpt:ftp
ACCEPT     tcp  --  anywhere             anywhere            state NEW tcp dpt:smtp
ACCEPT     tcp  --  anywhere             anywhere            state NEW tcp dpt:ssh
REJECT     all  --  anywhere             anywhere            reject-with icmp-port-unreachable
Chain FORWARD (policy ACCEPT)
target     prot opt source               destination
Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Write these rules to a file using the following command.

iptables-save > /etc/iptables.rules

Now each time Debian boots iptables-restore command has to be called with these rules, so create and edit a new file as shown below. This file does NOT exist and you have to create it. I’m using VI editor to edit it

vi /etc/network/if-pre-up.d/firewall

Add the following text to that file

#!/bin/bash
/sbin/iptables-restore < /etc/iptables.rules

Save the file and grant executable permissions on that file.

chmod +x /etc/network/if-pre-up.d/firewall

Reboot the system and list the iptables rules to check if it has been applied.

reboot

After reboot

iptables -L

IMPORTANT: Whenever you add or delete rules you should overwrite the changes to the iptables.rules file using the following command

iptables-save > /etc/iptables.rules