Secure port forwarding with ssh & systemd

I wanted an easy way to forward ports from my VPS to a host on my local network. Firewalld and iptables were giving me grief, so I settled on using ssh port forwarding instead. I came across this gist which was super helpful. Now instead of dealing with firewall and iptables, I simply have an ssh session spun up as a systemd service. If the connection gets dropped or killed it auto connects again. The port forwards come through nice and clean. Brilliant.

I had to configure ssh keys to allow for passwordless connection. Here’s my systemd file (I went the lazy route and didn’t configure environment variables in /etc/system/default like the gist suggests)

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

[Service]
Environment="LOCAL_ADDR=<REMOTE_IP_OF_VPS>"
ExecStart=/usr/bin/ssh -i /home/ssh_user/.ssh/id_rsa -NT -o ServerAliveInterval=60 -o ExitOnForwardFailure=yes -L ${LOCAL_ADDR}:VPS_PORT:localhost:LAN_PORT -L ${LOCAL_ADDR}:VPS_PORT_2:localhost:LAN_PORT_2 ssh_user@LAN_HOST

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

[Install]
WantedBy=multi-user.target
 

Put that in /etc/systemd/system and do a systemctl daemon-reload. Ensure your firewall has those ports open (including firewall-reload.) Then enable & start it. Profit.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.