基于 DROP 策略的端口转发

基于 DROP 策略的端口转发

我正在尝试将端口 80 转发到虚拟机。如果我将输入、输出和转发链上的默认策略设置为 ACCEPT,则转发可以正常工作。但是,如果我将策略设置为 DROP 并打开相关端口,则无法使其正常工作。我遗漏了什么?

#!/bin/bash
IPT="/sbin/iptables"

echo "Starting IPv4 Wall..."
$IPT -F
$IPT -X
$IPT -t nat -F
$IPT -t nat -X
$IPT -t filter -F
$IPT -t filter -X
$IPT -t mangle -F
$IPT -t mangle -X
$IPT -t nat  -F PREROUTING
$IPT -t nat  -F POSTROUTING
$IPT -t nat  -F OUTPUT
#modprobe ip_conntrack


# DROP all incomming traffic
$IPT -P INPUT DROP
$IPT -P OUTPUT DROP
$IPT -P FORWARD ACCEPT

# Unlimited Access to localhost
$IPT -A INPUT -i lo -j ACCEPT
$IPT -A OUTPUT -o lo -j ACCEPT

#Allow ESTABLISHED,RELATED

$IPT -A INPUT -i em4 -m state --state ESTABLISHED,RELATED -j ACCEPT
$IPT -A OUTPUT -o em4 -m state --state ESTABLISHED,RELATED -j ACCEPT

#Allow outbound SYN requests
$IPT -A OUTPUT -o em4 -m state --state NEW -j ACCEPT


#Allow SSH (Port 22)
$IPT -A INPUT -i em4 -p tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
$IPT -A OUTPUT -o em4 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT

### Allow HTTP port 80
###$IPT -A INPUT -i em4 -p tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT
###$IPT -A OUTPUT -o em4 -p tcp --sport 80 -m state --state NEW,ESTABLISHED -j ACCEPT

# allow HTTP & HTTPS
$IPT -A OUTPUT -p tcp -m multiport --dports 80,443 -j ACCEPT
$IPT -A INPUT -p tcp  -m multiport --sports 80,443 -j ACCEPT

# allow DNS
$IPT -A OUTPUT -p udp --dport 53 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT
$IPT -A INPUT -p udp --sport 53 -m state  --state ESTABLISHED,RELATED -j ACCEPT

# Allow Ports 2222:2226
$IPT -A INPUT -i em4 -p tcp --dport 2222:2226 -m state --state NEW,ESTABLISHED -j ACCEPT
$IPT -A OUTPUT -o em4 -p tcp --sport 2222:2226 -m state --state NEW,ESTABLISHED -j ACCEPT


##funciona
$IPT -t nat -A PREROUTING -p tcp --dst $EXTERNALIP --dport 80 -j DNAT --to-destination 192.168.122.1:8080
$IPT -t nat -A POSTROUTING -p tcp --dst 192.168.122.1 --dport 8080 -j SNAT --to-source $EXTERNALIP
$IPT -t nat -A OUTPUT --dst $EXTERNALIP -p tcp --dport 80 -j DNAT --to-destination 192.168.122.1:8080

$IPT -I FORWARD -j LOG --log-prefix "iptables denied"



echo "Done, exiting"
exit 0

答案1

官方 netfilter 文档指出在 INPUT 链之前检查 PREROUTING。

https://superuser.com/a/674103/21439

换句话说,新数据包首先经过 PREROUTING,当您的 INPUT 或 FORWARD 检查新数据包时,它已经包含目标端口 8080。并且它会被您自己的规则丢弃。

相关内容