I tried many times to save the iptables configuration to have it start up automatically when I reboot my Raspberry Pi (Ubuntu 22.04.1 LTS) but when I look with this command:
$ sudo iptables -L
my chain rules are gone after a reboot.
I followed this documentation:
https://help.ubuntu.com/community/IptablesHowTo
Here's the rules with the commands I used in that specific order:
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
sudo iptables -A INPUT -p tcp --dport ssh -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -j DROP
sudo iptables -I INPUT 1 -i lo -j ACCEPT
Then from the same documentation, they recommend Solution #1 or Solution #2 to save and restore iptables on reboot. I tried both without success.
Here's what I have done for the Solution #2:
I saved my firewall rules to the file iptables.rules like this:
sudo sh -c "iptables-save > /etc/iptables.rules"
I created this new file for a script at /etc/network/if-pre-up.d/iptablesload. Here's the content of the script which I edited with Vim:
#!/bin/sh
iptables-restore < /etc/iptables.rules
exit 0
I saved the file on Vim with :wq
Then I created this new file for a script at /etc/network/if-post-down.d/iptablessave. It contains:
#!/bin/sh
iptables-save -c > /etc/iptables.rules
if [ -f /etc/iptables.downrules ]; then
iptables-restore < /etc/iptables.downrules
fi
exit 0
I saved the file on Vim with :wq
And finally I gave both scripts execute permissions like this:
sudo chmod +x /etc/network/if-post-down.d/iptablessave
sudo chmod +x /etc/network/if-pre-up.d/iptablesload
After doing all that, when I reboot my Raspberry Pi and type the command
sudo iptables -L
all my chain rules are gone.
I am a beginner with Ubuntu, thank you for your help.