You ever had to access a server/computer behind a firewall / closed network? your office computer or perhaps one of your servers behind a closed network/firewall.
For one of my contract projects I had to have a full control over a server in a remote location inside a closed network. In order to do that I had to setup a reverse ssh tunnel.
(This post is written for Ubuntu and OpenSSH)
A Server behind closed network, lets call it “remote server”.
A proxy server. A server you can access easily which you’ll use in order to SSH into the remote server.
Step 1: Configure OpenSSH
$ vi /etc/ssh/sshd_config
Find GatewayPorts and make sure it says ‘yes’. If it doesn’t exists, add it:
Save & close.
$ service ssh restart
Repeat the same process on OpenSSH of the remote server as well.
Step 2: Open the Tunnel & Connect
In your remote server, run:
$ ssh -t -t -R <tunnel_port>:localhost:22 proxy_server_user@proxy_server_ip
tunnel_port – can be any available port.
proxy_server_user – root or any other user you’ll have for that purpose.
Now the tunnel is open in our remote destination server, let’s connect to it through the proxy server.
First you need to ssh into the proxy server, then:
$ ssh user_on_remote_server@localhost -p <tunnel_port>
This is it.
If the remote server is an office computer or something you can access daily, you’ll probably open this tunnel before you leave the office. Otherwise, you need to figure out a way to do it remotely, when you don’t have physical access to that machine (read the Automating Tunnel Management below).
Every time you’ll create the tunnel, it’ll ask you for password/passphrase and etc. In my case, the tunnel is created by me for the first time, but afterwards I need to create it remotely by scripts, and I couldn’t have password/passphrase in the process. So this is what I did:
1. Create a tunnel user on proxy server.
2. Create an SSH Key on remote server (empty passphrase, so it won’t ask for it), add this key to /home/tunnel/.ssh/authorized_keys file.
Automating Tunnel Management
In my case, the server sits in a corner of a room, without any monitor or keyboard. No one can easily access it without a laptop connected to the same network this server is connected to.
Whenever I need to create a tunnel, I want to be able to click on a button on my machine and make the remote server create the tunnel on a port I define. For this reason I’ve created a cron job that runs every minute, it pings my server and asks “Hey, I’m server 163, do you need me to do anything?”
In this point I send back a JSON describing what I need this script to do. It can be anything: update the code, run OS update or open an ssh tunnel on port X and proxy server Y.
Hope it helps. I’m not a sysadmin guru, but I’ll be glad to help if you have any questions.