Skip to content

Instantly share code, notes, and snippets.

@sjmf
Created August 5, 2025 19:18
Show Gist options
  • Save sjmf/6ad576684fd12f59a6f8e969cfedb9cc to your computer and use it in GitHub Desktop.
Save sjmf/6ad576684fd12f59a6f8e969cfedb9cc to your computer and use it in GitHub Desktop.
Systemd configuration for persistent ssh reverse tunnel
[Unit]
Description=SSH tunnel service SSH on local port 22 to 22000 on remote host
Wants=network-online.target
After=network-online.target
StartLimitIntervalSec=0
[Service]
User=tunnel
Group=tunnel
Type=simple
Restart=always
RestartSec=60
ExecStart=/usr/bin/ssh -o UserKnownHostsFile=/home/tunnel/.ssh/known_hosts -o ExitOnForwardFailure=yes -o "ServerAliveInterval 30" -o "ServerAliveCountMax 3" -NTR 22000:localhost:22 [email protected] -i /home/tunnel/.ssh/id_rsa
[Install]
WantedBy=multi-user.target
@sjmf
Copy link
Author

sjmf commented Aug 5, 2025

To set up the user (as root, or prefix sudo):

useradd -s /usr/sbin/nologin tunnel
mkdir -p /home/tunnel/.ssh
touch /home/tunnel/.ssh/authorized_keys
chown -R tunnel:tunnel /home/tunnel
chmod 750 /home/tunnel /home/tunnel/.ssh
chmod 600 /home/tunnel/.ssh/authorized_keys

Create passwordless ssh keys and copy to the remote:

ssh-keygen -t rsa  -C "reverse tunnel key" -f /home/tunnel/.ssh/id_rsa
ssh-copy-id -i /home/tunnel/.ssh/id_rsa.pub -o "IdentityFile hostkey.rsa" [email protected]

Bring up systemd service:

sudo systemctl enable ssh.remote.service
sudo systemctl start ssh.remote.service

The command sudo journalctl -exu ssh.remote.service will show logs. Add -v to the command to view verbose.

Ideally, remove the password for the remote tunnel user: passwd --delete tunnel

@sjmf
Copy link
Author

sjmf commented Aug 5, 2025

The remote address can be bound publicly using the bind: -R *:22000:localhost:22, but this increases attack surface.

Instead, one can use an SSH config (.ssh/config) to bounce off localhost on the remote:

Host dm-iarc-01
    Hostname localhost
    Port 22000
    User change_me

    # Connect via remote host
    ProxyCommand ssh [email protected] nc -w 5 $(echo %h|cut -d%% -f1) %p

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment