some blag

June 17, 2008

Dynamic port forwarding with SSH (ssh -D)

Filed under: tips — andrew @ 8:59 am

The usual way to forward ports with SSH is to do something like:
ssh -L 3128:127.0.0.1:3128 user@remote
This, of course, forwards localhost:3128 on the local machine to localhost:3128 on phoenix. Coupled with a HTTP proxy running on phoenix and bound to localhost:3128, this can be used to tunnel traffic on the local machine through ssh in order to bypass restrictive firewalls. Squid is one such proxy, which works great, but a proxy is no longer necessary with SSH’s dynamic port forwarding. I’ll explain why in a bit.

Without a HTTP proxy running on phoenix, the only way to connect to accomplish this would be to do something like:
ssh -L 80:www.google.com:80 user@remote
which would forward localhost:80 on the current machine to google.com. The problems with this are obvious: you have to manually choose the websites you will access when you setup the connection, and it won’t work if the website checks to make sure that the HTTP Host your browser sends matches it (www.google.com is expected, not localhost).

Enter -D.
ssh -D creates a SOCKS proxy on the specified port that can be used to tunnel traffic. For example, running:

ssh -D 1234 user@remote

creates a SOCKS proxy on localhost:1234 of the machine running the command. Applications can then be configured to use localhost:1234 as their SOCKS proxy and all their traffic will be tunneled through the SSH connection, bypassing any firewalls in place. This is all that is needed to replace the earlier http proxy/ssh -L scenario.

If the application doesn’t support SOCKS, simply run it with tsocks. For example, tsocks irssi will make irssi use the SOCKS proxy. You will need to edit /etc/tsocks.conf to set the appropriate port and server. It would look something like this:

server = 127.0.0.1
server_port = 1234

# don’t use SOCKS for connections to these IPs
local = 127.0.0.0/255.0.0.0

tsocks will replace any connect/socket/etc calls with appropriate equivalents that use the SOCKS proxy.

Powered by WordPress