How to set-up reliable autossh tunnel in Ubuntu 20.10
Client
The idea is that a machine hosted anywhere - i.e. behind the NAT, with no public IP - will establish SSH tunnel to publicly available server. The only required connectivity is access to the server IP & port.
First install autossh and generate public/private keys.
apt install autossh
ssh-keygen
Let’s say that:
- The public server that runs SSH client is available at server.muras.eu.
- It has SSH available externally on port 10001
- Internally SSH is running on standard port 22
- There is a user tunnel that we will use to authenticate SSH session
Create /etc/systemd/system/autossh.service with the content below.
[Unit]
Description=AutoSSH to My Server
After=network.target
[Service]
Environment="AUTOSSH_GATETIME=0"
ExecStart=/usr/bin/autossh -N -M 0 -o "ExitOnForwardFailure=yes" -o "ServerAliveInterval=180" -o "ServerAliveCountMax=3" -o "PubkeyAuthentication=yes" -o "PasswordAuthentication=no" -i /root/.ssh/id_rsa -R 6668:localhost:22 tunnel@server.muras.eu -p 10001
Restart=always
[Install]
WantedBy=multi-user.target
Then enable the service and reboot to make sure it works automatically.
systemctl enable autossh
reboot
Server
Create user tunnel that has no interactive shell session (-s /bin/false) but create its home directory (-m).
useradd -d /home/tunnel -s /bin/false -m tunnel
Add to /home/tunnel/.ssh/authorized_keys the public key of the root user from our client (/root/.ssh/id_rsa.pub )
no-pty,no-X11-forwarding,permitopen="localhost:6668",command="/bin/echo do-not-send-commands" ssh-rsa abcdef....
Connection
To access client machine, login to server and run:
ssh -p 6668 tunnel@127.0.0.1