Ubuntu 18.04 doesn't load iptables rules after reboot
We provision servers with chef so we have same configuration for Ubuntu 16.04 and 18.04 versions.
And there is same rule for restoring iptables rules
cat /etc/network/if-pre-up.d/iptables_load
/sbin/iptables-restore < /etc/iptables/general
but it doesn't work for Ubuntu 18.04.
If I run it manually it works. Does it mean this script isn't running at startup?
UPDATE
I created systemd service as it is described here and it works fine.
[Unit]
Description = Apply iptables rules
[Service]
Type=oneshot
ExecStart=/etc/network/if-pre-up.d/iptables_load
[Install]
WantedBy=network-pre.target
Solution 1:
Here's what I did:
- Drop your iptables.rules into /etc/iptables.rules
-
Create service template like so:
sudo nano /etc/systemd/system/restore-iptables-rules.service
Copy-paste this:
[Unit] Description = Apply iptables rules [Service] Type=oneshot ExecStart=/bin/sh -c 'iptables-restore < /etc/iptables.rules' [Install] WantedBy=network-pre.target
-
Enable service like so:
sudo systemctl enable restore-iptables-rules.service
-
Reboot and check that the rules have been applied:
sudo iptables -L
Solution 2:
I ran into a variety of problems with iptables triggered in if-up locations. As my iptables script grew more complicated, the fact that it may run (depending on exact location of the script) for each interface became a problem as did the need for the correct network interface to be up if things like hostname resolution are to work. These factors were causing slow booting and failures. You could consider the alternative, which is to run the iptables script as a systemd service.
This can be done by creating a file called, for example, real_iptables.service in /etc/systemd/system/ with contents like:
[Unit]
Description=Set up the firewall
After=network.target
[Service]
Type=oneshot
ExecStart=/root/iptables
[Install]
WantedBy=multi-user.target
The actual iptables script is, as you can see, at /root/iptables. Install the service with:
systemctl enable real_iptables
systemctl start real_iptables
With the service enabled, it will be started at boot time, but will run only once. If you want to be completely secure, it's possible to put a script in /etc/network/if-up.d/ that uses iptables to block all network communications. This means nothing can happen until the service starts.