Sometimes you need to get SSH access into a host that is inside a network behind a Firewall/NAT and only outbound connections are allowed.

AutoSSH can be installed on the client and will establish and persist an SSH tunnel into an external server allowing reverse connections into the client.

Install and manually test the connection

sudo apt install autossh
autossh -N -R 2022:localhost:22 [email protected]

Note: [email protected] is the server exposed to the internet ready to receive SSH connections, 2022 is the port that the server will start to listen and forward to the client on port 22. If the server firewall exposes port 2022 to the internet, anyone will be able to log into the client through the server at that port.

On the host that will receive the connection

ssh user@localhost -p 2022

AutoSSH will not type the password to connect to the server, so it requires an SSH-Key [Link].

It was tested and works fine. Now create a service on the client to enable the AutoSSH on the boot.

Configuring AutoSSH to run as a service

sudo nano /etc/systemd/system/autossh-tunnel.service

Add the content:

[Unit]
Description=AutoSSH Tunnel Service - Remote Port 2022

[Service]
#User=userName
Restart=always
RestartSec=10
ExecStart=/usr/bin/autossh -N -R 2022:localhost:22 [email protected]

[Install]
WantedBy=multi-user.target

The service will be executed as root, so the root user has to have the private key to be able to authenticate the connection.

sudo cp ~/.ssh/id_rsa /root/.ssh/
sudo cp ~/.ssh/id_rsa.pub /root/.ssh/

Use the systemctl to manage the AutoSSH service:

sudo systemctl daemon-reload
sudo systemctl enable autossh-tunnel.service
sudo systemctl start autossh-tunnel.service
sudo systemctl stop autossh-tunnel.service

The SSH Tunnel can be used to allow connection to different ports client’s localhost.

autossh -N -R 8080:localhost:80 [email protected]

The example above maps the port 8080 on the server that will be tunneled and get access to the HTTP (port 80) on the client.

The websites LocalHost.Run [Link] and Ngrok [Link] offers a service that uses the same ssh tunneling but connecting to their server instead of yours.


SSHd Configuration

Possibly the following configuration will have to be enabled on the SSH server:

...
AllowTCPForwarding yes
GatewayPorts yes
...

SSH is a versatile protocol that allows many other functionalities such as mount a remote directory locally and even set up a temporary VPN.

Mounting a Remote File System over SSH with SSHFS (client-side only):

sudo apt install sshfs
sshfs [email protected]:/shared sshfs

Setting a VPN over SSH with SSHuttle (client-site only):

sudo apt-get install sshuttle -y
sshuttle --dns -vvr user@host 0/0

Read also the post about Setting Up and Copying SSH Keys [Link]