Open firewall ports only towards local network?

Another thing to note is that if you add rules via networking.firewall.extraStopCommands, you might want to remove them with have networking.firewall.extraCommands - and you want to do that idempotently.

There are cases in which the rules removed by extraStopCommands don’t match the ones added by extraCommands (for example, if the systemd unit failed to reach the point where the rules are added).
If that happens, the teardown will fail to happen cleanly.

So it’s a good idea to make the extraStopCommands idempotent by appending || true:

networking.firewall.extraStopCommands = ''
  iptables -D nixos-fw -p tcp --source 192.0.2.0/24 --dport 1714:1764 -j nixos-fw-accept || true
  iptables -D nixos-fw -p udp --source 192.0.2.0/24 --dport 1714:1764 -j nixos-fw-accept || true
'';

You can see this in many places across nixpkgs.

5 Likes