systemd: Start your Firewall before network interfaces coming up
linux debian, ubuntu, systemd, networking, uptables
There are a serveral “tutorials” and code snippets out there but they wont work on modern systemd versions and may cause fatal errors! In case you want to start your firewall before the network interfaces will be initialized, you have to hook into the special systemd target network-pre.target. It is a passive target which is invoked before any network services has been started.
Additionally, you have to explicit set the
DefaultDependencies=no option – otherwise systemd automatically adds dependency of the type
After=basic.target to your service and your firewall is invoked AFTER networking has been started!
Systemd Service File#
The following service file assumes that your firewall script is located in /usr/sbin/myfirewall.sh
[Unit] Description=MyFirewall # Start before Network Interfaces coming up Before=network-pre.target Wants=network-pre.target After=local-fs.target # Do not start after basic.target! DefaultDependencies=no [Service] ExecStart=/usr/sbin/myfirewall start ExecStop=/usr/sbin/myfirewall stop # Just Execute the shell script Type=oneshot RemainAfterExit=yes
Debugging Service Startup#
The systemd-analyze utility provides a really cool way to show the system startup. Finally you should verify that your firewall is executed before networking has started!
# dump the service startup systemd-analyze plot > /root/systemd_startup.svg
Startup of the Firewall and Networking