Use snat rule instead if masquerade for wireguard nat

This commit is contained in:
yuri 2023-09-19 15:58:42 +02:00
parent 74d5abdfe2
commit 6c6cfb6da8
3 changed files with 7 additions and 16 deletions

View file

@ -8,7 +8,7 @@
firewall = {
enable = true;
allowedTCPPorts = [ 80 443 ];
allowedUDPPorts = [ 51820 51821 51822 51827 51828 ];
allowedUDPPorts = [ 51820 51821 51822 51824 51827 51828 51829 51830 ];
};
wireguard = {
enable = true;

View file

@ -3,6 +3,7 @@ let
wireguard-nat-nftables = import ../../../pkgs/wireguard-nat-nftables pkgs;
config = pkgs.writeText "wireguard-nat-nftables-config" (builtins.toJSON {
interface = "ens3";
interface_address = "172.16.4.180";
wg_interface = "wg0";
pubkey_port_mapping = {
"SJ8xCRb4hWm5EnXoV4FnwgbiaxmY2wI+xzfk+3HXERg=" = [ 51827 51829 ];

View file

@ -12,6 +12,7 @@ def main():
f.close()
interface = config["interface"]
interface_address = config["interface_address"]
wg_interface = config["wg_interface"]
pubkey_port_mapping = config["pubkey_port_mapping"]
@ -19,30 +20,19 @@ def main():
nft.set_json_output(True)
nft.set_handle_output(True)
# add nat table rules for dnat and snat masquerade
# add nat table rules for dnat and snat
nft.cmd("add table wireguard-nat")
nft.cmd("flush table wireguard-nat")
nft.cmd("add chain wireguard-nat prerouting { type nat hook prerouting priority -100; }")
nft.cmd("add chain wireguard-nat postrouting { type nat hook postrouting priority 100; }")
nft.cmd("add rule wireguard-nat postrouting oifname {} snat to {}".format(interface, interface_address))
# load current nftables rules
rc, output, error = nft.cmd("list ruleset")
if error:
print(error, file=sys.stderr)
nftables_output = json.loads(output)
add_masquerade = True
for item in nftables_output["nftables"]:
if ("rule" in item
and item["rule"]["family"] == "ip"
and item["rule"]["table"] == "wireguard-nat"
and item["rule"]["chain"] == "postrouting"
and "masquerade" in item["rule"]["expr"][0]
):
add_masquerade = False
break
if add_masquerade:
nft.cmd("add rule wireguard-nat postrouting masquerade")
while True:
# list WireGuard peer endpoint addresses of WireGuard VPN connection
process = subprocess.Popen(["wg", "show", wg_interface, "endpoints"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)