Reverse tunnel
Open SSH connections to servers under NAT without needing to redirect ports on the router.
Consider the following scenario: you are about to deploy a server on-premisse and you cannot deal with router ports redirection and firewall rules.
The solution is open a reverse tunnel, so you have a secure backdoor open to SSH connections:
Setup the tunnel server
This server (which can be on the cloud) will handle all connections from on-premisse servers.
Install SSH server
Add an user called tunnel
tunnel
Setup the RSA key
Login as tunnel
user.
Create an RSA key.
Accept all defaults (do not input a password)
Now authorize tunnel's user RSA public key in its authorized_keys.
Remember we are creating a reverse tunnel. So the on-premisse server will use the same private RSA key, so the compatible public key must be authorized.
Copy the RSA public key.
Now edit /home/tunnel/.ssh/authorized_keys
Add the following content.
It will look like this.
command="",restrict,port-forwarding
will restrict the access. If someone get physical access to the on-premisse server it will not be possible to allocate a TTY using the RSA key.
Copy the content of the following files (we will use them to set up the on-premisse server).
Setup the on-premisse server
This server will open the reverse tunnel to the tunnel server.
Install SSH server
Setup the RSA key
Let's suppose you want the user ubuntu to be able to open the tunnel.
Create the RSA key.
Paste the content from /home/tunnel/.ssh/id_rsa
you copied from the tunnel server.
Fix permissions.
Add tunnel server's public RSA to authorized keys.
Paste the content from /home/tunnel/.ssh/id_rsa.pub
you copied from the tunnel server.
Test connection
From your on-premisse server
Open a tunnel to test the connection.
Replace PUT-YOUR-TUNNEL-SERVER-HOST-HERE
with your tunnel server host or IP.
You can change the port 1822 to any port you want (just keep me same port for the rest of the tutorial)
This command will open a the tunnel using the port 1822 on the tunnel server. All connections on port 1822 on the tunnel server will be redirected to port 22 on the on-premisse server.
If everything is OK the command above will hang the tunnel. Leave it running.
From your tunnel server
Login as tunnel user and check if the tunnel port is open.
You should see something like.
Now test the tunnel.
You should be able to SSH to your on-premisse server.
Configure the tunnel as a service on the on-premisse server
Go back to your on-premisse server. You can cancel/stop the test tunnel we opened before.
Create the following file.
With the following content.
Replace PUT-YOUR-TUNNEL-SERVER-HOST-HERE
with your tunnel server host or IP.
You can change the port 1822 to any port you want
Then start and enable the service to start on boot.
Last updated