Skip to content

Instantly share code, notes, and snippets.

@beledouxdenis
Last active April 17, 2019 14:08
Show Gist options
  • Save beledouxdenis/3706baf36d25b2b21f379c73740eccd7 to your computer and use it in GitHub Desktop.
Save beledouxdenis/3706baf36d25b2b21f379c73740eccd7 to your computer and use it in GitHub Desktop.
Auto-starting self hosted Ngrok (requires a server with Nginx and a registered domain)

On the remote server

vim /etc/nginx/sites-enabled/tunnel_yourdomain_com
server {
    server_name tunnel.yourdomain.com;

    access_log /var/log/nginx/$host;

    location / {
            proxy_pass http://localhost:3333/;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto https;
            proxy_redirect off;
    }

    error_page 502 /50x.html;
    location = /50x.html {
            root /usr/share/nginx/html;
    }
}
useradd -m tunnel /bin/false
mkdir /home/tunnel/.ssh
touch /home/tunnel/.ssh/authorized_keys

On the local computer

vim /etc/systemd/system/secure-tunnel@.service
[Unit]
Description=Setup a secure tunnel to %I
After=network.target

[Service]
Environment="LOCAL_ADDR=localhost"
EnvironmentFile=/etc/default/secure-tunnel@%i
ExecStart=/usr/bin/ssh -NT -o ServerAliveInterval=60 -o ExitOnForwardFailure=yes -i ${SSH_KEY} -R ${TUNNEL_PORT}:${LOCAL_ADDRESS}:${LOCAL_PORT} ${TARGET}

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

[Install]
WantedBy=multi-user.target
vim /etc/default/secure-tunnel@tunnel_yourdomain_com
TARGET=tunnel@tunnel.yourdomain.com
LOCAL_ADDRESS=127.0.0.1
LOCAL_PORT=8069
TUNNEL_PORT=3333
SSH_KEY=/home/user/.ssh/id_rsa_tunnel_yourdomain_com
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

Do not set a password. This key will only use to connect to your tunnel without password required.

When asked, save the key in /home/[your_user]/.ssh/id_rsa_tunnel_yourdomain_com.

Then, add the ssh key you just created in the authorized keys of the remote tunnel user:

cat /home/[your_user]/.ssh/id_rsa_tunnel_yourdomain_com.pub | ssh root@tunnel.yourdomain.com "cat >> /home/tunnel/.ssh/authorized_keys"

Sources

SSH Tunnel using systemctl: https://gist.github.com/drmalex07/c0f9304deea566842490

Roll your own ngrok with Nginx and SSH reverse: https://jerrington.me/posts/2019-01-29-self-hosted-ngrok.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment