nftables NAT with maps

01.12.2023 13:37
by bitstacker

Well, this was hard to figure out... What i wanted is a NAT rule to select source address, protocol and port and map it to the destination address and port. All examples i found missed the source address or the protocol.

To make things easier for the next person, here is how i did it:

DNAT:

table ip nat {
  map IPV4-DNAT {
    # daddr . protocol . port -> daddr . port
    type ipv4_addr . inet_proto . inet_service : ipv4_addr . inet_service
    elements = {
        192.0.2.1 . tcp . 80 : 192.168.0.1 . 80,
        192.0.2.2 . udp . 53 : 192.168.0.2 . 53,
        192.0.2.3 . tcp . 8080 : 192.168.0.3 . 80,
        192.0.2.4 . udp . 27015 : 192.168.0.4 . 27015,
    }
  }

  # dNAT for ipv4
  chain prerouting {
      type nat hook prerouting priority -100;
      dnat to ip daddr . ip protocol . th dport map @IPV4-DNAT
  }
}

SNAT was easy:

table ip nat {
  map IPV4-SNAT {
    type ipv4_addr : ipv4_addr;
    elements = {
        192.168.0.1 : 192.0.2.1
    }
  }
    # NAT for ipv4
  chain postrouting {
      type nat hook postrouting priority 100; policy accept;
      oif wan snat to ip saddr map @IPV4-SNAT
  }
}

I'll probably upload my finished gateway config once i finished it.