Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexproca/6470069817aa7571d6792dec4fe9e8ca to your computer and use it in GitHub Desktop.
Save alexproca/6470069817aa7571d6792dec4fe9e8ca 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 -R ${REMOTE_ADDR}:${REMOTE_PORT}:${LOCAL_ADDR}:${LOCAL_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 bastion (probably aliased in /etc/hosts). Create the file at /etc/default/secure-tunnel@bastion:

TARGET=bastion
REMOTE_ADDR=0.0.0.0
LOCAL_ADDR=0.0.0.0
LOCAL_PORT=22
REMOTE_PORT=2022

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@bastion.service
systemctl status secure-tunnel@bastion.service

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

systemctl enable secure-tunnel@bastion.service
@gpongelli
Copy link

some changes to be done at HIL side:

  1. create an ssh config file with content
Host bastion
    HostName <bastion_ip>
    User bastion
    IdentityFile ~/.ssh/bastion
    Port 22022
    RemoteForward 127.0.0.1:2022 127.0.0.1:22

with this change, command ssh -v bastion should succeed.

  1. change file at /etc/default/secure-tunnel@bastion:
TARGET=bastion
REMOTE_ADDR=127.0.0.1
LOCAL_ADDR=127.0.0.1
LOCAL_PORT=22
REMOTE_PORT=2022
  1. change service file at /etc/systemd/system/secure-tunnel@.service to
[Unit]
Description=Setup a secure tunnel to %I
After=network.target

[Service]
Environment="LOCAL_ADDR=127.0.0.1"
EnvironmentFile=/etc/default/secure-tunnel@%i
User=<HIL user that has SSH config at point 1>
ExecStart=/usr/bin/ssh -NT -o ServerAliveInterval=60 -o ExitOnForwardFailure=yes -R ${REMOTE_ADDR}:${REMOTE_PORT}:${LOCAL_ADDR}:${LOCAL_PORT} ${TARGET}

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

[Install]
WantedBy=multi-user.target

service instance should work at this point.

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