Iptables: redirect tcp connections to ssh tunnel

iptablesPROXYssh-tunnel

I have seen this used in many android based projects like "ProxyDroid" & "SSHTunnel"

Where you establish a connection to a proxy or ssh tunnel then using iptables it will redirect all tcp requests through the tunnel you have created.

It should be something like "-I OUTPUT -p tcp –destination-not xxx.xxx.xx.xx –redirect-to xx.xxx.xx.xx:port" but I couldn't find any examples on this and I don't know if it should be inserted to nat or something else + I have no idea if I should have more than 1 rule for e.g: one more for incoming connections.

EDIT:

Appears to be it's not possible to use the tunnel directly Or I haven't find out how to do it without using an agent, I had to install a program called redsocks to act as a local server to make this work.

As for the iptables commands used here it is:

# do not redirect connection sent to localhost so redirected connections can reach
# its destination, otherwise we'll stuck in a loop.
iptables -t nat -A OUTPUT -d 127.0.0.0/8 -j ACCEPT
# Redirect all tcp connections except ones that are going to my tunnel server 
# to the local redsocks port
iptables -t nat -A OUTPUT -p tcp ! -d tunnel.ip.goes.here -j REDIRECT --to-ports 31338

RedSocks Repo: https://github.com/darkk/redsocks


Now everything works great, but I still need to know if this can be accomplished without the redsocks (connecting to tunnel directly).

Best Answer

Do you mean to set up a poor man's VPN over SSH? If so, there's some Ubuntu documentation for this:

https://help.ubuntu.com/community/SSH_VPN

Basically, you would use the "-w" option to set up a new tun0 interface, and start routing through it. iptables is not involved, though you will need to set up routes.

Note that doing TCP over TCP may be a bad idea. A better option might be a simple VPN, like with OpenVPN, but that will be more complicated than a quick-and-dirty ssh tunnel.