Reverse SSH

In this article, I will demonstrate how to bypass firewall to access the server behind the firewall and NAT

How does it work?

Reverse SSH provides you a method to access the server behind NAT and Firewall. Its theory is very simple, server make a connection to client, and client use the connection to establish SSH connection. That's it.

Given a scenario in which we have a host behind NAT and firewall, how can we access to in from internet?

Assume Client is the host machine behind the firewall and Server is a machine in the internet.

In this circumstance, the Client can make a reverse ssh call to Server and then setup a tunnel to let Server to make a callback ssh to Client via a reverse port.

First Step: Generate the Key

We need to generate a key for ssh access so that when Client access Server to establish the tunnel in the background, there is no password input is required.

Note, if you are using the private key to access the cloud Server, you do not need to take this step.

Client generate private key, public key (ssh-keygen -t rsa) and add its public key to Server ~/.ssh/authorized_key

You can use scp to transfer the file between them. DO NOT transfer private key and please keep it secret.

Reference

Second Step: Set-up Server Environment

We can now test if reverse ssh can be establish by entering the following command

Try to make a ssh call to Server from Client

Once the reverse tunnel is established, you can now make a ssh call in Server to connect Client

Next, we need to install autossh , it helps to monitor the ssh connection and resume it to normal if there is any accident on it. Use this command:

Last Step: Work as daemon

The previous step is perfect to implement but we need it to run in the background and even the server is auto-restart. To make this happen, we have to create a background services for it.

  1. Create a systemd file using nano or vim or appropriate editor of choice

2. Add the following contents

3. Reload systemd

4. Start the autossh service

5. Enable at boot

6. check status with

There is however an important thing to note about systemd and AutoSSH: -f (background usage) already implies AUTOSSH_GATETIME=0, however -f is not supported by systemd. So in the case of systemd you need to make use of AUTOSSH_GATETIME

Reference

Troubleshoot

  • A : Select all processes

  • u : Select all processes on a terminal, including those of other users

  • x : Select processes without controlling ttys

Kill Process

Check network status (Port is listening)

Issues

As mentioned before, do not apply -f in .services file, otherwise you will trigger this exception:

Last updated