Setting up port forwarding
In the previous section, we configured iptables
to accept connections to port 22 in order to allow people to SSH into the host. Sometimes, you want to forward a port to a system behind the firewall instead of having the service run on the firewall itself. For example, you may have a web server running on port 8080 on an internal box that you want to expose to the Internet via port 80 on the firewall.
How to do it…
- Rewrite packets addressed to port 80 to instead go to port 8080:
# iptables -t nat -A PREROUTING -p tcp -i eth2 --dport 80 \ -j DNAT --to-destination 192.168.0.200:8080
- Accept any packets addressed to 192.168.0.200 port 8080:
# iptables -A FORWARD -p tcp -d 192.168.0.200 \ --dport 8080 -m state --state NEW,ESTABLISHED,RELATED \ -j ACCEPT
How it works…
This example is a lot simpler since it builds upon concepts we've already learned. We just have two simple commands:
- First we set up a PREROUTING rule which will be processed once the packet is received, prior to any routing rules being applied. If the packet is TCP and came in on the Internet interface (
eth2
) with a destination port, then the packet is added to the destination NAT (DNAT) chain with a final destination of 192.168.0.200 port 8080. - Next, any packet destined for 192.168.0.200 port 8080 is either a new connection or an established connection; the packet is then accepted for forwarding to the destination.