in DevOps, linux

How To: Reverse SSH Tunneling

In order to SSH into a machine behind a firewall, or access a service running on that system, you will need to use Reverse SSH Port Forwarding. The machine in question needs to open an SSH connection to the outside world and include a -R tunnel whose entry point is the remote side (from server in our example) to connect to your machine, allocate a port there and make certain that any connection request on that port is then forwarded to the SSH port of the remote side (server).

ssh –f –N –T -R 1333:localhost:22 user@your.server

Flag:

  • -f: tells the SSH to background itself after it authenticates, saving you time by not having to run something on the remote server for the tunnel to remain alive.
  • -N: if all you need is to create a tunnel without running any remote commands then include this option to save resources.
  • -T: useful to disable pseudo-tty allocation, which is fitting if you are not trying to create an interactive shell.

That will open the port 1333 on your.server .

All packets arriving at this port are transferred through the SSH tunnel to your home PC.

Now you need to do an SSH connection request from your machine to your own machine at port 1333:

ssh -p 1333 username@localhost

 

Note:

  • By default the opened port is just bound to 127.0.0.1 (the servers loopback interface), so you can only send packets from the server itself (or need some more network hacking). To have this hack listening to 0.0.0.0 (all interfaces) add the following to your /etc/ssh/sshd_config on your.server and restart the daemon :
GatewayPorts yes

 

  • Run something like screen or top on the server to always transfer packets (otherwise the connection will be closed after some time), with -o ServerAliveInterval=XXX you can adjust the threshold for closing the SSH connection. Surround it with a while loop and you’ll reestablish closed connections (network errors or something like that):
    while [ 1 ]; do ssh -o ServerAliveInterval=60 -R 1333:localhost:22 user@your.server; done

 

  • Related Content by Tag