Thanks for a great question. I had a systemd service running with autossh -M 0. And just realized that using autossh along with systemd is redundant.
Here is my new service without autossh. It is running fine and restarting even if I kill the ssh process myself.
[Unit]
Description=autossh
Wants=network-online.target
After=network-online.target
[Service]
Type=simple
ExecStart=
ExecStart=/usr/bin/ssh -o "ServerAliveInterval 30" -o "ServerAliveCountMax 3" -o ExitOnForwardFailure=yes -R8023:localhost:22 sshtunnel@[address of my server] -N -p 22 -i /root/.ssh/id_rsa_insecure
Restart=always
RestartSec=60
[Install]
WantedBy=multi-user.target
HOW TO START THE SERVICE:
- Create sshtunnel user on the server (don't give root permissions)
- Put the unencrypted RSA key "id_rsa_insecure" here /root/.ssh/. The public part you should put on the server in /home/sshtunnel/.ssh/authorized_keys
- Make a file "autossh.service" with the code above and put it here /etc/systemd/system
- Run following commands
sudo systemctl daemon-reload
sudo systemctl start autossh
sudo systemctl enable autossh
A few explanatory notes:
ExitOnForwardFailure
this is what I missed first time. Without this option if port forwarding fails for some reason (and it happens, believe me) the SSH tunnel will exists but it would be useless. So it needs to be killed and restarted.
/root/.ssh/id_rsa_insecure
As you can see from the name the key is not encrypted so it has to be a special key, and you have to restrict the user with this key from doing anything on the server side but creating a reverse channel. The straightforward way to do it is to restrict the behavior in the authorized_keys file on the server side.
# /home/sshtunnel/.ssh/authorized_keys
command="/bin/true" ssh-rsa [the public key]
This prevents the "sshtunnel" user from launching the shell and performing any commands.
Additional security:
What I tried and it did not work: 1) on server side: change the shell in /etc/passwd to /bin/false for "sshtunnel" user 2) on server side: add permitopen=host:port in the authorized_keys file for sshtunnel id_rsa_insecure key
What I did not try but I think it should work: you can restrict the "sshtunnel" user further (allowing only specific port forwarding) by configuring SELinux user profiles - but I don't have a code handy for that. Please let me know if anyone would have a code.
I would love to hear any security faults in my current solution. Thanks