iptables:静态临时端口映射

iptables:静态临时端口映射

我的 Linux 服务器上有一个可执行 IPv4 NAT 的 VPN,例如:

iptables -A FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -s 10.8.0.0/24 -j ACCEPT
iptables -t nat -A POSTROUTING  -s 10.8.0.0/24 -o venet0 -j SNAT --to-source 1.2.3.4

但是我想为每个内部 10.8.0.0/24 IP 设置静态临时端口范围,以便更轻松地记录哪个客户端连接到了哪个,使用 iptables 可以实现吗?

例如,端口 1000-2500 将是 10.8.0.10 使用的临时端口,端口 10000-20000 将是 10.8.0.20 使用的临时端口,等等。

我已经用 Google 搜索过,但什么也没找到。

答案1

检查 MASQUERADE 目标而不是 SNAT:它支持以下选项:

--to-ports port[-port]
              This specifies a range of source ports to  use,  overriding  the
              default SNAT source port-selection heuristics (see above).  This
              is only valid if the rule also specifies one  of  the  following
              protocols: tcp, udp, dccp or sctp.

我从未使用过它,但测试过!但它只适用于 tcp、udp。对于其他协议,如 ICMP,运气不好,没有端口……

答案2

我认为您无法控制哪些端口用于哪些 NAT 的 IP。但是,如果您在公共空间中有任何额外的 IP,您可以通过映射要跟踪的 IP 来利用这一点:

iptables -t nat -A POSTROUTING  -s 10.8.0.10/32 -o venet0 -j SNAT --to-source 1.2.3.1
iptables -t nat -A POSTROUTING  -s 10.8.0.20/32 -o venet0 -j SNAT --to-source 1.2.3.2
iptables -t nat -A POSTROUTING  -s 10.8.0.0/24 -o venet0 -j SNAT --to-source 1.2.3.4

答案3

我知道这个问题很老了,所以我将分享我的发现:根据 iptables 手册页https://linux.die.net/man/8/iptables

SNAT

This target is only valid in the nat table, in the POSTROUTING chain. It specifies that the source address of the packet should be modified (and all future packets in this connection will also be mangled), and rules should cease being examined. It takes one type of option:
--to-source ipaddr[-ipaddr][:port-port]
which can specify a single new source IP address, an inclusive range of IP addresses, and optionally, a port range (which is only valid if the rule also specifies -p tcp or -p udp). If no port range is specified, then source ports below 512 will be mapped to other ports below 512: those between 512 and 1023 inclusive will be mapped to ports below 1024, and other ports will be mapped to 1024 or above. Where possible, no port alteration will occur.
In Kernels up to 2.6.10, you can add several --to-source options. For those kernels, if you specify more than one source address, either via an address range or multiple --to-source options, a simple round-robin (one after another in cycle) takes place between these addresses. Later Kernels (>= 2.6.11-rc1) don't have the ability to NAT to multiple ranges anymore.

--to-source ipaddr[-ipaddr][:port-port]选项允许您指定端口。虽然我还没有测试过,如果有人能纠正我,我会很高兴,但我认为现在您可以使用类似于@chicks 答案的东西,但带有端口。

iptables -t nat -A POSTROUTING  -s 10.8.0.10/32 -o venet0 -j SNAT --to-source 1.2.3.4:1000-1500
iptables -t nat -A POSTROUTING  -s 10.8.0.20/32 -o venet0 -j SNAT --to-source 1.2.3.4:10000-20000

ETC。

当然,这只有当规则还指定-p tcp或时才有效-p udp

相关内容