Is it possible to write custom rules to the NixOS firewall?

Out of the box there is support to allow ports but that’s that. What about allowing IP ranges etc?

I am happy to write my own firewall rules in nftables (thankfully netwokring.nftables.enable exists).

But how?

https://search.nixos.org/options?channel=22.11&show=networking.firewall.extraCommands&from=0&size=50&sort=relevance&type=packages&query=firewall.extra

networking.firewall.extraCommands = ''
  iptables -A INPUT -p icmp -j ACCEPT"
'';

It seems a bit hacky. From what I gather[1][2] networking.firewall.extraCommands will keep adding the rules on every “deployment”. Does that mean every time I run nixos-rebuild switch? If so is there a better way to do it?

[1]

[2]

I use nftables for my firewall on NixOS. I disable the built-in one and write the rules directly. You have to set everything up yourself, but it gives you more control that way.

You can see how I do it in my configs. I define a default input chain here that sets up some things then gotos the actual input chain I add to in other modules. Here are some examples:

1 Like

I use nftables for my firewall on NixOS. I disable the built-in one and write the rules directly.

I have a different take on this. I also use nftables directly, but also take into consideration whatever is defined though networking.firewall.allowedTCPPorts and friends and build nftables config for that plus some custom stuff.

1 Like

That’s not a bad idea. It would let me clean up some of the rote firewall rules while leaving me the flexibility to define really specific ones as needed.

It seems nftables will take into account networking.firewall, in a while.

2 Likes

The PR has been merged!

2 Likes