The Personal Blog of a Geek in Arizona

Menu

Search

Reverse SSH tunnels for fun and profit

Ever needed to access, or maintain access, to a computer that’s behind a firewall? Just run one of these commands on that computer (in Linux or maybe Mac) and you’ll get a tunnel to that computer’s port 22 (SSH) over whatever port you type for the PORTNUM in the examples below.

First example: ssh -R PORTNUM:localhost:22 USERNAME@SERVERNAME

So if you ran the command ssh -R 5001:localhost:22 user@example.com you’d be able to login to example.com and then run ssh user@localhost.com -p 5001 to connect back to that computer.
Second example: autossh -R PORTNUM:localhost:22 USERNAME@SERVERNAME

Same as the last one, but autossh is a nice program that attempts to reconnect if the connection is dropped. This doesn’t protect against the session you’re running autossh in being logged out, but it does protect against internet connectivity issues and the remote session being logged out.

Screen protects against session logout, so this is one of the most robust options. The only thing it doesn’t do at this point is try to prevent remote logout or autoconnect upon boot. Also, we’ve added the -i option which points to a public/private keypair. Look up how to connect to an ssh server with an RSA key for how to set this up on your ssh server. This lets you connect without needing to type a password each time.

Here we add the full home path of the user whose SSH key you’re using, plus KeepAlive details. This *might* be good enough to use in a CRON job though I’ve had poor luck with it.

And there you go! I’m not quite sure how to make this work reliably in CRON yet, but at least you’re initiating and maintaining a secure reverse tunnel despite firewalls. By changing the 22 in the command, you can actually tunnel to almost any service on the computer, not just SSH.

By the way, if this isn’t quite what you wanted, you can also do a port forwarding tunnel which instructs the remote machine to forward your traffic elsewhere instead of being restricted to ports local to that machine. For port forwarding, try:

ssh -L LOCALPORT:REMOTESERVER:REMOTEPORT USERNAME@SERVERNAME

For example to connect to yahoo.com via an SSH tunnel to your server, you’d run: ssh -L 9001:yahoo.com:80 USERNAME@SERVERNAME and then point your web browser to http://localhost:9001 .