使用 nftables 进行端口转发和 NAT

Dav*_* M. 3 firewall nat nftables

我有一个 OpenWRT 网关(自建 19.07,内核 4.14.156),它位于我的专用网络前面的公共 IP 地址上。我正在使用 nftables(不是iptables)。

我想在公共地址上公开一个非标准端口,并将其转发到网关后面机器上的标准端口。我认为这曾经被称为端口转发:看起来您的网关机器正在提供,例如,http 服务,但它实际上是位于私有地址的网关后面的机器。

这是我的 nftables 配置。出于这些目的,我的“标准服务”在端口 1234 上,我希望允许公众在网关:4321 上访问它。

#!/usr/sbin/nft -ef
# 
# nftables configuration for my gateway
#

flush ruleset

table raw {
        chain prerouting {
                type filter hook prerouting priority -300;
                tcp dport 4321 tcp dport set 1234 log prefix "raw " notrack;
        }
}

table ip filter {
        chain output {
                type filter hook output priority 100; policy accept;
                tcp dport { 1234, 4321 } log prefix "output ";
        }

        chain input {
                type filter hook input priority 0; policy accept;
                tcp dport { 1234, 4321 } log prefix "input " accept;
        }

        chain forward {
                type filter hook forward priority 0; policy accept;
                tcp dport { 1234, 4321 } log prefix "forward " accept;
        }
}

table ip nat {
        chain prerouting {
                type nat hook prerouting priority 0; policy accept;
                tcp dport { 1234, 4321 } log prefix "nat-pre " dnat 172.23.32.200;
        }

        chain postrouting {
                type nat hook postrouting priority 100; policy accept;
                tcp dport { 1234, 4321 } log prefix "nat-post ";
                oifname "eth0" masquerade;
        }
}
Run Code Online (Sandbox Code Playgroud)

使用此设置,外部机器可以访问位于 的私有机器gateway:1234。日志显示nat-preSYN 数据包从外部到网关 IP,然后forward从外部到内部 IP,然后nat-post从外部到内部,并且“现有连接”负责处理其余的数据包。

外部机器连接到gateway:4321log as raw,其中 4321 更改为 1234。然后 SYN 数据包被转发到内部服务器,回复 SYN 数据包返回,然后......什么都没有!

我认为,问题在于我没有进行 nftables 配置,该配置会将远程机器期望的internal:1234返回更改gateway:4321为 。即使masquerade更改internal:1234gateway:1234,远程机器也不会期望,并且可能会转储它。

对这个配置有什么想法吗?

小智 5

您没有翻译端口号。当外部连接到1234端口时,这不是问题。但是到4321时,dnat会通过内部服务器的4321端口,而不是1234端口。试试

tcp dport { 1234, 4321 } log prefix "nat-pre " dnat 172.23.32.200:1234;
Run Code Online (Sandbox Code Playgroud)

您不需要翻译从内部服务器返回的回复数据包。这是使用在第一个 Syn 数据包上创建的连接跟踪表中的条目自动完成的。