What does iptables -j REDIRECT *actually* do to packet headers?

7,497

Take a look at this answer: How does a transparent SOCKS proxy know which destination IP to use?

Quotation:

iptables overrites the original destination address but it remembers the old one. The application code can then fetch it by asking for a special socket option, SO_ORIGINAL_DST.

Share:
7,497
Lapsio
Author by

Lapsio

Updated on September 18, 2022

Comments

  • Lapsio
    Lapsio over 1 year

    Out of curiosity I'm reading some tutorials about transparent TOR proxies as it's quite interesting topic from a networking standpoint. As opposed to VPN gateways which just use tun/tap interfaces and are totally clear to me, TOR proxy uses a single port. All tutorials repeat the magic line:

    iptables -t nat -A PREROUTING -i eth0 -p tcp --syn -j REDIRECT --to-ports 9040
    

    where eth0 is the input (LAN) interface and 9040 is some TOR port. The thing is, I completely don't get why such a thing makes sense at all from networking standpoint.

    According to my understanding of redirect / dst-nat chains and how it seems to work in physical routers, dst-nat chain takes dst-port and dst-addr BEFORE routing decision is taken and changes them to something else. So for example:

    • before dst-nat: 192.168.1.2:46364 -> 88.88.88.88:80
    • after dst-nat: 192.168.1.2:46364 -> 99.99.99.99:8080

    And 99.99.99.99:8080 is what further chains in IP packet flow lane see (for example filter table) and this is how the packet looks from now on after leaving device for example.

    Now many people around the internet (including on this stackexchange) claimed that redirect is basically the same as dst-nat with dst-addr set to local address of interface. In such light, this rule:

    iptables -t nat -A PREROUTING -i eth0 -p tcp --syn -j REDIRECT --to-ports 9040
    

    clearly doesn't make sense. If that would be how it works, then TOR would get all packets with destination 127.0.0.1:9040. For typical applications where app takes packet and responds to it somehow (for example web servers) it totally makes sense because after all, such a server process is the final destination of the packet anyways so it's okay that the destination address is localhost. But TOR router is well... a router so it has to know original destination of packet. Am I missing something? Does DNAT not affect what local applications receive? Or is it specific behavior of REDIRECT directive?

    • Admin
      Admin over 6 years
      I installed demo and it does work. What's more - I've set up nodejs server in place of tor and it really does show 192.168.1.1:9040 as destination in connection details so I have no idea how Tor proxy knows what is actual destination of packet... It's complete... magic