Learn how to setup a reverse SSH tunnel with an easy to understand example. A reverse SSH tunnel allows a local service to be securely accessible by a remote connection.
Understanding Reverse SSH Tunnels
Let’s say you have a service on your local computer that is running on port 80. You want to access this service from a remote computer, but a firewall is in the way.
To bypass the firewall restrictions, you can send the local service over the SSH port via a tunnel.
Let’s take a look at a specific example.
Reverse SSH Tunnel Example
The command for establishing a reverse SSH tunnel looks like this.
ssh -N -R -p 22 localhost:8888:192.168.1.6:80 firstname.lastname@example.org
- -N is a flag to just forward ports and not execute remote commands
- -R is the reverse SSH tunnel flag that forwards remote connections to the local side
- -p 22 is the SSH port of the remote server. This can be a different port, but needs to be open
- localhost is the host on the remote server that will bind to the local service
- 8888 is the port that the remote server will listen on
- 192.168.1.6 is the internal IP address of the local service
- 80 is the port of the local service
- root is the SSH user of the remote server
- 126.96.36.199 is the public IP address of the remote server
After executing the reverse SSH tunnel command, the local service at 192.168.1.6:80 will be accessible on the remote machine at localhost:8888.
The above example is quite explicit. Here are some ways to shorten it.
- You don’t need to include localhost because that is the default
- The default SSH port is 22, so you don’t need to specify that either
- The -N flag is optional. Functionality will be the same whether or not you include it
- If the local service is running on localhost (or another hostname), you can use that instead of the internal IP address. Not to be confused with the localhost on the remote side
ssh -R 8888:localhost:80 email@example.com
Other SSH Tunnel Types
A few different flavors of SSH tunnels exist. In addition to reverse SSH tunnels, there are also normal SSH tunnels and SSH proxy tunnels. Depending on your use case, these other types of SSH tunnels may suit your needs.