Iptables – Difference beetween DNAT and REDIRECT in IPTABLES

iptablesPROXYrouting

Okay, it may be because I am dense or maybe just not finding the right source, but I can't understand why one of these IPTABLES setups would be better than the other.

Here is my setup:

I have a box that is serving as a transparent proxy and a router or sorts. It has two interfaces on it, ETH0 and ETH1, and the following address scheme:

ETH0 = DHCP
ETH1 = 192.168.5.1/24 serving up DHCP for the 192.168.5.0/24 network to clients behind it in the LAN

I have privoxy installed and listening on port 8080 as a transparent proxy. What I am accomplishing with this setup is to be able to drop this box into an existing network with minimal configuration and attached clients to the proxy.

Here is my original IPTABLES file

*nat
-A PREROUTING -i eth1 -p tcp -m tcp --dport 80 -j REDIRECT --to-port 8080
-A POSTROUTING -o eth0 -j MASQUERADE
COMMIT
*filter
COMMIT

This configuration works fine and traffic is flowing back and forth without issue. I get the originating clients IP address in the privoxy logfiles, and life is good.

My confusion comes in when I start looking at other people's configurations and see that they are using DNAT instead of REDIRECT, and I am trying to understand the real beneift of one over the other. Here is a sample config:

*nat
-A PREROUTING -i eth1 -p tcp -m tcp --dport 80 -j DNAT --to 192.168.5.1:8080
-A POSTROUTING -o eth0 -j MASQUERADE
COMMIT
*filter
COMMIT

Again, this configuration works too, and gives me all I need from a logging perspective…

Which is is right, or maybe MORE right, than the other one?

Thanks for taking time to read this far…

Best Answer

REDIRECT alters the destination IP address to send to the machine itself. In other words, locally generated packets are mapped to the 127.0.0.1 address. It's for redirecting local packets. If you only want to redirect the traffic between services on the local machine, it will be a good choice.

DNAT is actual Network Address Translation. If you want packets destinated outside of the local system to have the destination altered, it's the better choice of the two, as REDIRECT will not work.

Related Topic