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
apt update
apt install openssh-serverAdd an user called tunnel
tunneluseradd -m -s /bin/bash tunnelSetup the RSA key
Login as tunnel user.
su - tunnelCreate an RSA key.
ssh-keygen -t rsa -b 4096Now authorize tunnel's user RSA public key in its authorized_keys.
Copy the RSA public key.
Now edit /home/tunnel/.ssh/authorized_keys
Add the following content.
It will look like this.
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.
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.
Then start and enable the service to start on boot.
Last updated
Was this helpful?