Preserve Firewall Rules Across Server Reboots (iptables edition)
Premium Challenge
Upgrade your membership to unlock this and all other premium materials.
Firewall rules added with the iptables command exist only in the kernel's memory.
When the server reboots, the rules disappear, and the ports they protect become exposed again.
This server runs an HTTP service on port 8080 that should be accessible only from the server itself.
A colleague has blocked access to the port from the network with the following commands,
as in the Protect an Unintentionally Exposed Server Port with Firewall Rules challenge:
sudo iptables -A INPUT -i lo -p tcp --dport 8080 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 8080 -j DROP
The rules work now, but the next reboot of the server will remove them.
Your task is to make the iptables rules persistent, so that port 8080 stays protected after the server reboots.
When the rules are persistent, reboot the server with sudo reboot.
Don't stop or reconfigure the http-server service. Only the firewall configuration should change.
The port must stay protected at all times, including while you change the firewall configuration and while the server reboots.
Hint 1
The iptables-save command prints the current rules in a format that the iptables-restore command can load back:
sudo iptables-save
Saving the rules to a file is only half of the job. Something also has to load the file every time the server boots, before the services start accepting connections.
Hint 2
You don't have to write the boot-time part yourself.
On Debian and Ubuntu, the iptables-persistent package installs a service that restores the rules saved in the /etc/iptables/ directory at boot.
RHEL-based distributions have the iptables-services package for the same purpose.
Hint 3
If the port is still exposed after the reboot, check which rules the kernel has now:
sudo iptables -S INPUT
Then look at the log of the service that should have restored them during the boot with journalctl -b -u <service-name>.