Iptables – Redirecting masqueraded traffic through TOR

iptablesmasqueradetor

I am trying to configure AP with redirection incoming traffic through TOR. My AP now has 2 network interfaces:

  1. eth0 – have internet access (192.168.1.92/24)
  2. wlan0 – intranet, without internet (10.0.0.1/24)

For accessing internet from wlan0 I did usual stuff: enabled forwarding and masquerading. For traffic redirection(to tor) I did iptables redirection. So, entire iptables looks like:

NON_TOR="192.168.1.0/24 192.168.0.0/24 10.0.0.1/24"
TOR_UID=$(id -ur debian-tor)
TRANS_PORT="9040"

# masqaerade for wlan0
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

iptables -t nat -A OUTPUT -m owner --uid-owner $TOR_UID -j RETURN
iptables -t nat -A OUTPUT -p udp --dport 53 -j REDIRECT --to-ports 53

for NET in $NON_TOR 127.0.0.0/9 127.128.0.0/10; do
    iptables -t nat -A OUTPUT -d $NET -j RETURN
done

iptables -t nat -A OUTPUT -p tcp -j DNAT --to-destination 10.0.0.1:9040
# iptables -t nat -A OUTPUT -p tcp --syn -j REDIRECT --to-ports $TRANS_PORT
iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT   

Tor config:

VirtualAddrNetwork 192.168.100.0/10
AutomapHostsOnResolve 1
TransPort 192.168.1.92:9040
TransPort 10.0.0.1:9040
DNSPort 53
ControlPort 9051

But for AP clients this does not work. For all conenctions originated from AP redirection to tor works perfectly. Here is a fragment of captured traffic from AP client (mobile phone) which consists the request to ident.me :

enter image description here

You can notice, that redirection rules which was described in iptables was ignored for masqueraded traffic. Why does this happen and how can it be fixed?

This is how the same request initiated by AP looks like:

enter image description here

Best Answer

Your firewall rules seem correct. However, redirection of packets that enters the AP should be configured in the PREROUTING chain. Rules added into the OUTPUT chain affect locally-generated packets only.

So, the following rule should be added:

iptables -t nat -A PREROUTING -i wlan0 -p tcp -j DNAT --to-destination 10.0.0.1:9040

Depending on the policy set at the FORWARD chain in filter table, the following rule may be needed too:

iptables -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT   
Related Topic