使用 iptables 重定向

Redirection using iptables

我在云端有一台服务器,上面有 iptables。

iptables -A INPUT   -i  lo -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -j ACCEPT 
iptables -A INPUT -p tcp --dport 443 -j ACCEPT 
iptables -A INPUT  -j DROP

iptables -A OUTPUT -o lo -j ACCEPT 
iptables -A OUTPUT -p tcp --sport 80 -m state --state RELATED,ESTABLISHED -j ACCEPT 
iptables -A OUTPUT -p tcp --sport 443 -m state --state RELATED,ESTABLISHED -j ACCEPT 
iptables -A OUTPUT -p tcp --sport 9200 -m state --state New,RELATED,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -j DROP

iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 2900 -j DNAT --to-destination 127.0.0.1:9200

我必须在其他链中添加什么,以便我可以在 2900 端口上访问我的服务。

规则自上而下适用。

6.2 Destination NAT

This is done in the PREROUTING chain, just as the packet comes in; this means that anything else on the Linux box itself (routing, packet filtering) will see the packet going to its `real' destination

因此您希望 PREROUTING 行位于顶部,因此 NAT 首先发生。

然后是一个 INPUT 条目,允许在 NAT 之后在您的目标端口上进行传入连接。

除了,您的 INPUT 规则不接受 RELATED 和 ESTABLISHED 以及您的输出规则设置特定源端口是怎么回事?出站流量通常来自随机高位端口。

https://serverfault.com/a/578781/57144 and https://serverfault.com/a/578787/57144 开始,您想为传入端口明确说明新连接,并且应该更喜欢更少的性能规则(如果适用)。

iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 2900 -j DNAT --to-destination 127.0.0.1:9200

iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT 
iptables -A INPUT -i  lo -j ACCEPT
iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT 
iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 443 -j ACCEPT 
iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 9200 -j ACCEPT 

# or
# iptables -A INPUT -p tcp -m state --state NEW -m tcp -m multiport --dports 80,443,9200 -j ACCEPT

iptables -A INPUT  -j DROP