Skip to content

Instantly share code, notes, and snippets.

@drmalex07
Last active October 26, 2026 12:12
Show Gist options
  • Select an option

  • Save drmalex07/c0f9304deea566842490 to your computer and use it in GitHub Desktop.

Select an option

Save drmalex07/c0f9304deea566842490 to your computer and use it in GitHub Desktop.
Setup a secure (SSH) tunnel as a systemd service. #systemd #ssh #ssh-tunnel #ssh-forward

README

Create a template service file at /etc/systemd/system/secure-tunnel@.service. The template parameter will correspond to the name of target host:

[Unit]
Description=Setup a secure tunnel to %I
After=network.target

[Service]
Environment="LOCAL_ADDR=localhost"
EnvironmentFile=/etc/default/secure-tunnel@%i
ExecStart=/usr/bin/ssh -NT -o ServerAliveInterval=60 -o ExitOnForwardFailure=yes -L ${LOCAL_ADDR}:${LOCAL_PORT}:localhost:${REMOTE_PORT} ${TARGET}

# Restart every >2 seconds to avoid StartLimitInterval failure
RestartSec=5
Restart=always

[Install]
WantedBy=multi-user.target

We need a configuration file (inside /etc/default) for each target host we will be creating tunnels for. For example, let's assume we want to tunnel to a host named jupiter (probably aliased in /etc/hosts). Create the file at /etc/default/secure-tunnel@jupiter:

TARGET=jupiter
LOCAL_ADDR=0.0.0.0
LOCAL_PORT=20022
REMOTE_PORT=22

Note that for the above to work we need to have allready setup a password-less SSH login to target (e.g. by giving access to a non-protected private key).

Now we can start the service instance:

systemctl start secure-tunnel@jupiter.service
systemctl status secure-tunnel@jupiter.service

Or enable it, so it get's started at boot time:

systemctl enable secure-tunnel@jupiter.service
@Blaimi

Blaimi commented Oct 9, 2026

Copy link
Copy Markdown

Because I stumbled on this for a fresh setup:

I use this concept sometimes as well for --user services. I want to have a tunnel to a bastion-server whenever I login, so I use this:

/etc/systemd/user/secure-tunnel@.service

[Unit]
Description=Setup a secure tunnel to %I
After=network-online.target

[Service]
ExecStart=/usr/bin/ssh -NT %i

# Restart every >2 seconds to avoid StartLimitInterval failure
RestartSec=5
Restart=always

[Install]
WantedBy=default.target

While the service defined in https://gist.github.com/drmalex07/c0f9304deea566842490?permalink_comment_id=3145418#gistcomment-3145418 is a host service, this one is a user service and uses the users default ssh config. I can be enabled with systemtctl --user enable --now secure-tunnel@foobar.service

Note: You should not use the same ssh host-config for the service as you use for your daily ssh foobar routine to open a shell on the remote because the DynamicForward will conflict.

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