Tuesday, April 28, 2015

SSH tunneling trick: using localhost subdomains

Here's a little trick I just discovered which is useful if you do a lot of tunneling over ssh.

You can actually bind your local port tunnels to their own local address, instead of just using the default of localhost.

The first step is to define a localhost subdomain in /etc/hosts. (On Windows, this file is located at %windir%\System32\drivers\etc\hosts). Bind it to a local IP address other than 127.0.0.1 (you have free reign over the last three numbers, as long as the IP starts with 127).

127.0.0.100 nytimes.com.localhost

Next, create your ssh tunnel.

ssh -L 127.0.0.100:80:nytimes.com:80 user@example.com 1

Now try opening http://nytimes.com.localhost in a browser on your local machine. The entire page will not load, because nytimes.com loads images and other assets from domains other than nytimes.com, but enough should load to let you know that the tunnel is working.

This technique is useful for remembering your ssh tunnels if you have a lot of them (like me). It's a lot easier to remember http://nytimes.com.localhost than it is to remember http://localhost:6103. It's also useful if you need to tunnel a program that is finicky about which port it connects to.

If you're having trouble getting this to work, make sure you're not running a local web server that has bound itself to port 80 on all of your 127.* addresses. If you are, either disable your web server, or try this experiment using a different service, such as RDP (port 3389) or SQL Server (port 1433).

1I'm actually using PuTTY, but have translated it to the regular SSH command for wider applicability. The same forwarding will work in PuTTY, even though it looks like it wouldn't because of the narrow local port text field in the settings.

No comments:

Post a Comment