Sometimes you need SSH access to a host inside a network behind a Firewall/NAT where only outbound connections are allowed.

AutoSSH can be installed on the client to establish and maintain an SSH tunnel to an external server, enabling reverse connections back 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 internet-facing server that will receive SSH connections. Port 2022 is the port the server listens on and forwards to the client on port 22. If the server firewall exposes port 2022 publicly, anyone can log into the client through the server on that port.

On the host that will receive the connection

ssh user@localhost -p 2022

AutoSSH does not enter a password to connect to the server, so an SSH key is required [Link].

Once tested and confirmed working, create a service on the client to start AutoSSH automatically on boot.

Configuring AutoSSH to run as a service

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

Add the following 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 runs as root, so the root user must have the private key to authenticate the connection.

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

Use 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 also forward other ports on the client’s localhost. For example:

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

This maps port 8080 on the server to port 80 (HTTP) on the client.

The services LocalHost.Run [Link] and Ngrok [Link] offer hosted versions of this same SSH tunneling approach, connecting to their servers instead of your own.


SSHd Configuration

You may need to enable the following settings on the SSH server:

...
AllowTCPForwarding yes
GatewayPorts yes
...

SSH is a versatile protocol that supports many other features, including mounting a remote directory locally and setting 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 up a VPN over SSH with SSHuttle (client-side only):

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

BONUS

Check out Pinggy [Link], a service that provides TCP-based connectivity to any local port (similar to NGROK) with a single command. Works for SSH, HTTP, and more.

ssh -p 443 -R0:localhost:22 [email protected]

READ ALSO

Setting Up and Copying SSH Keys [Link].