Skip to content

Instantly share code, notes, and snippets.

@prologic
Last active September 7, 2022 02:50
Show Gist options
  • Save prologic/e3570752da7942983719acfdd14df7e1 to your computer and use it in GitHub Desktop.
Save prologic/e3570752da7942983719acfdd14df7e1 to your computer and use it in GitHub Desktop.
NFTables Port Mapping Example
  1. Create a table named nat with the ip address family:
nft add table ip nat
  1. Add the prerouting and postrouting chains to the table:
nft -- add chain ip nat prerouting { type nat hook prerouting priority -100 \; }
nft add chain ip nat postrouting { type nat hook postrouting priority 100 \; }
  1. Add a rule to the prerouting chain that redirects incoming packets on port 443 to the same port on 192.0.2.1:
nft add rule ip nat prerouting tcp dport 443 dnat to 192.0.2.1
  1. Add a rule to the postrouting chain to masquerade outgoing traffic:
nft add rule ip nat postrouting masquerade
  1. Enable packet forwarding:
echo 1 > /proc/sys/net/ipv4/ip_forward
@prologic
Copy link
Author

prologic commented Sep 7, 2022

Using freeze to relocate a Debian-installed nft binary to GoNix:

#!/bin/sh

cd nft
LD_LIBRARY_PATH=$PWD ./ld-linux-x86-64.so.2 ./nft add table ip nat
LD_LIBRARY_PATH=$PWD ./ld-linux-x86-64.so.2 ./nft add chain ip nat prerouting { type nat hook prerouting priority -100 \; }
LD_LIBRARY_PATH=$PWD ./ld-linux-x86-64.so.2 ./nft add chain ip nat postrouting { type nat hook postrouting priority 100 \; }
LD_LIBRARY_PATH=$PWD ./ld-linux-x86-64.so.2 ./nft add rule ip nat postrouting masquerade
LD_LIBRARY_PATH=$PWD ./ld-linux-x86-64.so.2 ./nft add rule ip nat prerouting tcp dport 8000 dnat to 172.29.0.150
echo 1 > /proc/sys/net/ipv4/ip_forward

@prologic
Copy link
Author

prologic commented Sep 7, 2022

This results in the following simple ruleset:

table ip nat {
	chain prerouting {
		type nat hook prerouting priority dstnat; policy accept;
		tcp dport 8000 dnat to 172.29.0.150
	}

	chain postrouting {
		type nat hook postrouting priority srcnat; policy accept;
		masquerade
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment