Skip to content

Instantly share code, notes, and snippets.

@RafaelPalomar
Created April 1, 2020 19:37
Show Gist options
  • Save RafaelPalomar/b54e420d84903d99fb75ef484853c8f8 to your computer and use it in GitHub Desktop.
Save RafaelPalomar/b54e420d84903d99fb75ef484853c8f8 to your computer and use it in GitHub Desktop.
Autotunnel with autossh #ssh #systemd #reverse #tunnel

SSH Reverse tunnels

Here we are interested to solve the following scenario:

actor User
node Proxy
node Server

User -> Proxy : SSH to Tunnel Port
Proxy -> Server : Forward SSH traffic

A user User wants to connet to Server (which is behind a firewall) through a Proxy server that will forward (using reverse tunnel) the traffic transparently to Server.

node Server
node Proxy
node Client

Server - Proxy
Proxy - Client

In order to achieve this, we will first create a user autotunnel, which will generate the tunnel. The tunnel will be valid for all the users in the Server system.

Create the autotunnel user in all the systems (Server and Proxy)

useradd -m -s /sbin/nologin autotunnel

https://hobo.house/2016/06/20/fun-and-profit-with-reverse-ssh-tunnels-and-autossh/ https://raymii.org/s/tutorials/Autossh_persistent_tunnels.html https://serverfault.com/questions/909026/ssh-into-remote-host-using-jump-box

Create a passwordless key for autotunnel in the server

ssh-keygen -t rsa -b 4096 #DONT GIVE ANY PASSWORD!!!

Copy the ssh key over to the Proxy

ssh-copy-id -i <path-to-key> <user>@<proxy-ip>

Install autossh

Configure sshd in Server (GatewayPorts yes) and in Proxy (AllowTcpForwarding yes)

Test autossh

autossh -M 20001 -i <path-to-passwordless-key> -R *.:<proxy_port>:localhost:22 <user>@<proxy_address> -N
  • Then try to connect to Proxy from Client
  • Remember to open the firewall in Proxy

Create a systemd service

[Unit]
Description=Keep a tunnel to 'Proxy' open
After=network-online.target

[Service]
Type=forking
User=autotunnel
ExecStart=/usr/bin/autossh -f -M 20001 -i /home/autotunnel/.ssh/nopasswd_id_rsa autotunnel@<proxy_address> -R *.:<proxy_port>:localhost:22 -N
ExecStop=/usr/bin/pkill -9 -u autotunnel
Restart=always

[Install]
WantedBy=multi-user.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment