How to create a reverse SSH tunnel
Sometimes that we need to connect via SSH into another computer, we come across the issue that the computer's IP is not known, or it is behind a NAT (Network Address Translation) and therefore it doesn't have a public IP address that we could use to connect to it, or it may be behind a firewall that won't allow access from the outside.
If the computer that we want to access can successfully establish a SSH connection to another computer that is accessible from both end points, we can utilize this computer as a bridge towards "destiny" to establish a SSH connection, this is known as a "Reverse SSH tunnel".
A reverse SSH tunnel works by connecting "destiny" to "bridge" and then utilizing this connection to SSH into "destiny" from any computer that can connect to "bridge". This reverse SSH tunnel should work in most Linux systems without any problem.
So, lets assume that we have this two computers:
"Bridge" IP: aaa.bbb.ccc.ddd
"Destiny" IP: unknown or unavailable
First of all, we establish the SSH connection from "destiny" to "bridge", enabling the reverse SSH functionality with the parameter -R:
ssh -R 61999:localhost:22 firstname.lastname@example.org
The first number (61999) indicates which port are we going to use in "bridge" to log into "destiny", localhost is the domain name that we will be using for this as well, and the last number (22) indicates which port is "destiny" listening for SSH.
Once this connection is live, we connect to "bridge" (it doesn't matter if we are logged in locally or remotely), and then we can establish the connection to "destiny" using:
ssh -p 61999 destiny_user@localhost
Effectively, we can use a computer with permanent SSH access as a bridge between computers that are not otherwise accessible via SSH. Any computer that is connected to "bridge" can then log into other computers with reverse SSH tunneling enabled.