Skip to content

Instantly share code, notes, and snippets.

@EdJoPaTo
Last active March 9, 2022 10:56
Show Gist options
  • Save EdJoPaTo/a9039ebb7b8a9ce573123e71512fe161 to your computer and use it in GitHub Desktop.
Save EdJoPaTo/a9039ebb7b8a9ce573123e71512fe161 to your computer and use it in GitHub Desktop.

Reverse SSH Tunnel

When a device is not reachable you can install the reverse-ssh-tunnel.service to it. Activate it and it will connect by itself to an accessible sshd. Then you can connect (directly or via ProxyJump) to the device.

(Generate and) copy the ssh key over to the reversessh server:

ssh-keygen -t ed25519 && ssh-copy-id reversessh@reversessh.3t0.de

IMPORTANT

connect once to the remote manually: ssh reversessh@reversessh.3t0.de

Once everything is done use ssh -p 43022 localuser@reversessh.3t0.de from your client

Expose the Port

You can expose the port so you can connect to it directly. This is simpler to setup but allows everyone to connect to your device.

ssh -p 43022 reversessh.3t0.de

This required GatewayPorts clientspecified to be set on the server sshd_config to bind to all interfaces.

ProxyJump

With ProxyJump (see man ssh_config -> ProxyJump) you can connect via the server. Use localhost:43022:localhost:22 instead of *:43022… in the service file.

Adapt your ~/.ssh/config:

Host my-device
  HostName localhost
  ProxyJump reversessh.3t0.de
  Port  43022

For more convenience adapt the /etc/hosts and set the device name as ::1 to be used instead of localhost in the ssh config.

::1 my-device

now you can connect with ssh my-device

[Unit]
Description=Handles a reverse tunnel
Wants=network-online.target
After=network-online.target
StartLimitIntervalSec=0
[Service]
Type=simple
Restart=always
RestartSec=20
ExecStart=/usr/bin/ssh -N -n -R *:43022:localhost:22 -o "ServerAliveInterval 10" -o "ExitOnForwardFailure yes" reversessh@reversessh.3t0.de
User=localuser
[Install]
WantedBy=multi-user.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment