Iptables fails to redirect traffic to transparent proxy

iptablessockstransparent-proxy

My goal was to use ubuntu as a router, with Redsocks serving as a transparent SOCKS proxy redirector. Each machine on my network would have its TCP/UDP traffic redirected to a different port where Redsocks was listening. Example: Machine 1 would have traffic sent to port 12345, and Redsocks would hand that off to external proxy 1. Machine 2 would have traffic sent to port 12346, and Redsocks would send that to proxy 2.

I figured that iptables could handle the initial redirecting to the specific Redsocks port location. I found a case similar to mine where SNAT was employed (iptables for transparent NAT) but cannot get it to work with the following:

iptables -t nat -N REDSOCKS
iptables -t nat -A REDSOCKS -d 0.0.0.0/8 -j RETURN
iptables -t nat -A REDSOCKS -d 10.0.0.0/8 -j RETURN
iptables -t nat -A REDSOCKS -d 127.0.0.0/8 -j RETURN
iptables -t nat -A REDSOCKS -d 169.254.0.0/16 -j RETURN
iptables -t nat -A REDSOCKS -d 172.16.0.0/12 -j RETURN
iptables -t nat -A REDSOCKS -d 192.168.0.0/16 -j RETURN
iptables -t nat -A REDSOCKS -d 224.0.0.0/4 -j RETURN
iptables -t nat -A REDSOCKS -d 240.0.0.0/4 -j RETURN
iptables -t nat -A POSTROUTING -s 192.168.50.2 -p tcp --dport 80 -j SNAT --to-source 192.168.1.50:12345
iptables -t nat -A POSTROUTING -s 192.168.50.2 -j MASQUERADE

Not sure where I'm going wrong with this.

My setup: Router has 2 NICs. Eth0 faces the WAN. Eth1 faces the LAN and has a static IP.

/proc/sys/net/ipv4/ip_forward = 1

eth0=192.168.1.50

eth1=192.168.50.1

All router clients have one NIC, static IP facing the LAN.
eth1=192.168.50.2

Why I want to do this: I can run Redsocks successfully on the individual machines and transmit via their respective proxies, but I wanted to keep all the routing in one place for the sake of convenience.

Best Answer

For this to work you need a DNAT rule in the PREROUTING chain and a SNAT rule in the POSTROUTING chain.

Take another look at the previous serverfault answer that you linked:

iptables -t nat -I PREROUTING -d 192.168.250.3 -j DNAT --to-destination 192.168.250.4 
iptables -t nat -I POSTROUTING -s 192.168.250.4 -j SNAT --to-source 192.168.250.3

Additionally, you do not want to set the port on the --to-source for the SNAT rule.

You will want to read up on the differences between DNAT and SNAT, which you can do here.

This document on TLDP may be able to help with this specific scenario.