Load your Iptables Rules Automatically After Reboot as a Systemd Service
Iptables rules are not persistent. After reboot, they are flushed. So that you don't suddenly find yourself without a firewall, the rules can be automatically reloaded with a system service.
To do this, you create a Systemd Unit that automatically loads the iptables filter rules. This way your own firewall rules are permanently applied without you having to worry about them every time.
First you created some iptables rules with a text editor. The text file is then saved to /etc/my-iptables.rules.
# example *filter -P OUTPUT ACCEPT -P INPUT DROP -A INPUT -i lo -j ACCEPT -A OUTPUT -o lo -j ACCEPT -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT #...
(This is only an example, not a complete firewall - a guide for a firewall with iptables can be found in the Arch Wiki)
Next, create a simple Systemd Unit with a text editor that loads the iptables rules:
[Unit] Description = Apply my IPv4 Iptables Rules
ExecStart=/bin/sh -c "/sbin/iptables-restore < /etc/my-iptables.rules"
Save the file to /etc/systemd/system/my-iptables-rules.service.
The service must now be activated:
sudo systemctl start my-iptables-rules.service
sudo systemctl enable my-iptables-rules.service
To deactivate the service, enter the following into the command line and restart the computer.
sudo systemctl disable my-iptables-rules.service
systemctl status my-iptables-rules.service
In case you have made a mistake, it is helpful that the line in which the error appears is indicated in the status query.
After a correction to the rules my-iptables.rules the service has to be reloaded.
sudo systemctl daemon-reload
sudo systemctl restart my-iptables-rules.service
To see the rules, type:
sudo iptables -L -v
The same applies to IPv6. Here ip6tables are used. The rules are stored in a text file at /etc/my-ip6tables.rules.
The Systemd Service in this case is:
Description = Apply my IPv6 Iptables Rules
ExecStart=/bin/sh -c "/sbin/ip6tables-restore < /etc/my-ip6tables.rules"