I'm trying to do a port forwarding on port 80 to a virtualmachine. If I set default policy to ACCEPT on input, output and forward chains the forwarding works. However, if I put the policy on DROP and open the relevant ports I cannot make it work. What am I missing?

#!/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
up vote 2 down vote accepted

The official netfilter doc states that the PREROUTING is checked before the INPUT chain.

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

In other words the NEW packet first goes through PREROUTING and when your INPUT or your FORWARD examines the NEW packet, it already contains destination port 8080. And it gets dropped by your own rules.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.