Always-on Reverse SSH Tunnel

Auto re-establish SSH tunnel when disconnected.


3 min read

What Is SSH Tunnel

There are many articles providing better and detailed explanation. I will provide a brief explanation here. Readers are expected to know what SSH Tunnel in order to benefit from this blog post.

SSH Tunnel works by establishing a SSH connection from local host to remote host. It allows forwarding traffic from any local port to a any remote port (port forwarding). Let's say due to (firewall) restriction, incoming traffic to port 80 (HTTP) is blocked on remote host, but port 22 (SSH) is allowed. You want to access the web application that is hosted on remote host. SSH Tunnel allows you to forward traffic from local port 80 to remote port 80. After establishing a SSH tunnel, you load "localhost" in local host's browser, the website from remote host will be served. It as-if the web application is hosted locally.

Reverse SSH Tunnel

Let's say you are in a closed network, outgoing traffic is allowed but incoming traffic is blocked. It might be a server in corporate's private network, and you want to be able to access the local server from remote location. Applications like TeamViewer/VNC will not work since incoming traffic is blocked by corporate firewall.

From local server, you establish a SSH connection to a remote host, and listens to port 2022 in remote host. Traffic to port 2022 on remote host will be forwarded to port 22 on local server. You execute ssh -p 2022 someone@localhost on remote host, and get connected to local server.

Normally SSH Tunnel forwards traffic from local host to remote host. Reverse SSH Tunnel forwards traffic from remote host to local host.


How To Setup Reverse SSH Tunnel

I have a home server, but it is not accessible from public due to ISP's restriction. Sometime I like to access my home server while I am outside. Fortunately I have a server on DigitalOcean, and I use it as a "jump server". From the home server, I establish a Reverse SSH Tunnel with my cloud server. Once I logged in to my cloud server, I can connect to my home server anytime. The SSH Tunnel tends to get disconnected from time to time due to variety of reasons (e.g. inactivity timeout, network glitch, home router daily restart). I need my home server to automatically reestablish the tunnel when it breaks. I achieve it with a shell script and cronjob.

Explanation of the SSH command used:

I create a executable script (in ~/.local/bin/) and named it "". Then I create a cronjob:

* * * * * /home/hong/.local/bin/ > /dev/null 2>&1

The script is executed once every minute. It checks if there is an active SSH Tunnel. If there isn't, it will establish a new SSH Tunnel.

Once the remote server, I connect to my home server using the following command: ssh -p 2022 someone@localhost

Did you find this article valuable?

Support Hong by becoming a sponsor. Any amount is appreciated!