SSH Tunnel Service with Systemd

Reading time: 4m

The purpose of this is to have a secure way back into the office or home or wherever you need to get to, and keep your NAT / firewall exceptions empty so you needn’t whitelist anything.

You’ll need a small VPS with a public IP that can be secured, though you can use a Colo / Dedicated for this for better security.

Create a tunnel user on the gateway server:

gateway# adduser tunnel
gateway# chsh -s /bin/bash tunnel
gateway# su - tunnel
gateway$ ssh-keygen -t rsa -b 4096 -N ''
gateway$ echo 'YOUR_SSH_PUBLIC_KEY' >> ~/.ssh/authorized_keys

On your target network, SSH to the gateway as the tunnel user to record the fingerprint in ~user/.ssh/known_hosts

We then create a systemd service on the machine that’s on the network you want to access, called tunnel.service:

local# vim /etc/systemd/system/tunnel.service
Description=Tunnel Service

ExecStart=/usr/bin/ssh -tt -N -i /home/user/.ssh/id_rsa -R REMOTE_PORT:LAN_SSHD_IP:LAN_SSHD_PORT -l tunnel SSH_GATEWAY


Edit the parts above to reflect your desired forwarded SSH port on the SSH Gateway.  Preferably both servers only accept SSH key authentication (PasswordAuthentication no) and root disabled (PermitRootLogin no).

Enable the service on the target network:

local# systemctl start tunnel.service
local# systemctl enable tunnel.service

Now go back to the tunnel user and get the public key:

gateway$ cat ~/.ssh/

Put the tunnel user’s key in ~/.ssh/authorized_keys on your local machine, check the systemd tunnel.service for the user.

SSH from the tunnel user on the gateway to record the fingerprint from the tunnel user to your SSH user on your network.

gateway# ssh -p REMOTE_PORT -l user

You should now be in, and no firewall rules have been added!  All you need is SSH access to the gateway server via your own key to ~tunnel/.ssh/authorized_keys

Leave a Reply

Your email address will not be published. Required fields are marked *