Reverse SSH Tunnel – when you cannot SSH to your host

Sometimes you need a workaround for SSH to an host. On my case, i cannot SSH to a ppp connected Raspberry Pi, but he can SSH to every other host. Solution is simple: ppp-Pi will SSH to a remote SSH server leaving a door open. Then i can SSH to my host, and login to my Pi. Confused? I know.

There’s a pretty good explanation on StackExchange.

You need to install autossh.

For this howto, please remember:

  • ppp-Pi listens to port 1324,
  • server-Pi listens on 2200.
  • Forwarded session on the server is 19998.

Copy your keys from the ppp-Pi to your server:

root@ppp-Pi:~# ssh-keygen
root@ppp-Pi:~# ssh-copy-id -i .ssh/id_rsa.pub -p 2200 pi@server-pi
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
pi@server-pi's password:

Connect from the ppp-Pi to the server and test keys.

root@ppp-Pi:~# ssh -p '2200' 'pi@server-pi'

Test the reverse tunnel. On ppp-Pi establish the reverse tunnel:

ssh -N -T -R 19998:localhost:1324 pi@server-pi -p 2200

On the server ssh back to the ppp-Pi:

ssh -p 19998 pi@localhost

Configure systemd/ for autossh autostart:

root@ppp-Pi:~# cat /etc/systemd/system/autossh-tunnel.service
[Unit]
Description=AutoSSH tunnel service for remote access
After=network.target

[Service]
Environment="AUTOSSH_GATETIME=0"
ExecStart=/usr/bin/autossh -M 0 -o "ServerAliveInterval 30" -o "ServerAliveCountMax 3" -N -T -R 19998:localhost:1324 pi@server-pi -p 2200

[Install]
WantedBy=multi-user.target

You can use a tool like the amazing MobaXterm to autostart these tunnels when you open the tool. And you can create a tunnel within a tunnel (for instance, forward rpi-monitor’s port 8888 via SSH reverse tunnel!).

Leave a Reply

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