IPtables DNATs on NixOS?

Hello, does anyone have a working nix config for running IP tables DNATS? I’m trying to expose a port on another device masqueraded to my NixOS so that it’s open and accessible via my NixOS server’s IP

This is what chat jippity gave me as a start (It doesn’t work, but does compile)

{ config, pkgs, ... }:

{
  networking = {
    firewall = {
      enable = true;
      allowedTCPPorts = [ 80 443 1514 1515 ];
      allowedUDPPorts = [ 1514 1515 ];
      extraForwardRules = ''
        # Enable IP forwarding
        iptables -A FORWARD -i ens5 -o ztc25frxue -m state --state RELATED,ESTABLISHED -j ACCEPT
        iptables -A FORWARD -i ztc25frxue -o ens5 -j ACCEPT

        # DNAT rules for TCP
        iptables -t nat -A PREROUTING -i ens5 -p tcp --dport 1514 -j DNAT --to-destination 192.168.192.157:1514
        iptables -t nat -A PREROUTING -i ens5 -p tcp --dport 1515 -j DNAT --to-destination 192.168.192.157:1515

        # DNAT rules for UDP
        iptables -t nat -A PREROUTING -i ens5 -p udp --dport 1514 -j DNAT --to-destination 192.168.192.157:1514
        iptables -t nat -A PREROUTING -i ens5 -p udp --dport 1515 -j DNAT --to-destination 192.168.192.157:1515

        # Masquerade rule
        iptables -t nat -A POSTROUTING -o ztc25frxue -j MASQUERADE
      '';
    };
  };
}

Since it’s not strictly Nix/NixOS you are having an issue with here, if you don’t receive help, you might have better luck in some Linux networking related forums.

You could try using the networking.nat module instead. The iptables CLI is pretty confusing and error prone.

I am not sure if this is the BEST way, but i found using extraCommands for IPtables seem to do the trick. Here is the full config that appears to be working just fine with zero issues so far

{ config, pkgs, ... }:

{
  networking = {
    firewall = {
      enable = true;
      allowedTCPPorts = [ 80 443 1514 1515 ];
      allowedUDPPorts = [ 1514 1515 ];
      extraCommands = ''
        # Enable IP forwarding
        iptables -A FORWARD -i ens5 -o ztc25frxue -m state --state RELATED,ESTABLISHED -j ACCEPT
        iptables -A FORWARD -i ztc25frxue -o ens5 -j ACCEPT

        # DNAT rules for TCP
        iptables -t nat -A PREROUTING -i ens5 -p tcp --dport 1514 -j DNAT --to-destination 192.168.192.157:1514
        iptables -t nat -A PREROUTING -i ens5 -p tcp --dport 1515 -j DNAT --to-destination 192.168.192.157:1515

        # DNAT rules for UDP
        iptables -t nat -A PREROUTING -i ens5 -p udp --dport 1514 -j DNAT --to-destination 192.168.192.157:1514
        iptables -t nat -A PREROUTING -i ens5 -p udp --dport 1515 -j DNAT --to-destination 192.168.192.157:1515

        # Masquerade rule
        iptables -t nat -A POSTROUTING -o ztc25frxue -j MASQUERADE
      '';
    };
  };
}