Self-hosted HTTP tunnels with SSH and nginx

Vincent Bernat

A friend wants to proof­read your work-in-progress blog post, but its pre­view only runs on localhost:​8080. Sev­eral tools can help. Some run as a com­mer­cial ser­vice, like ngrok or Cloud­flare Quick Tun­nels. Some are self-hostable but re­quire a spe­cific client, like frp or lo­cal­tun­nel. Some only re­quire a plain SSH client but rely on a spe­cific SSH server, like sish. Let’s im­ple­ment a self-hosted so­lu­tion with only OpenSSH and nginx!

$ ssh -R 0:localhost:8080 http-over-ssh
Allocated port 41535 for remote forward to localhost:8080
https://6J3jK1WmB15c6WmjW_X-Wg--1789928654@p41535.ssh.luffy.cx/

Basic setup#

First, we for­ward con­nec­tions from a port on a re­mote server to your lo­cal service:

$ ssh -N -R 0:localhost:8080 web02.luffy.cx
Allocated port 41535 for remote forward to localhost:8080

When you spec­ify 0 as the re­mote port, the server al­lo­cates a free port. Then, we con­fig­ure ng­inx to proxy re­quests from https://​p41535.​ssh.​luffy.cx to http://​127.0.0.1:41535:

server {
  listen 0.0.0.0:443 ssl ;
  listen [::0]:443 ssl ;
  server_name ~^p(?<port>\d\d\d\d\d)\.ssh\.luffy\.cx$;
  location / {
    proxy_pass http://127.0.0.1:$port;
  }
}

We also need to add DNS records for *.ssh.​luffy.cx and get a wild­card cer­tifi­cate through Let’s Encrypt:

*.ssh.luffy.cx.               CNAME web02.luffy.cx.
ssh.luffy.cx.                 CAA   0 issuewild "letsencrypt.org"
_acme-challenge.ssh.luffy.cx  CNAME ssh.luffy.cx.acme.luffy.cx.

acme.​luffy.cx is a zone hosted on Route 53. I use it for ACME DNS-01 chal­lenges, both for wild­card cer­tifi­cates and for do­mains served by sev­eral web servers. In my case, NixOS gets the cer­tifi­cates au­to­matically.

Access control#

The port is the only “se­cret”1 keep­ing the con­tent con­fi­den­tial. Other for­ward­ing so­lu­tions add a ran­dom string to the do­main name to pre­vent an in­truder from enu­mer­at­ing the pos­si­ble values.

Thanks to ngx_​http_​secure_​link_​module, we can se­cure this setup a bit. This mod­ule com­putes a hash2 over a set of val­ues, in­clud­ing a se­cret, and com­pares it with the hash from the re­quest. The hash is base64-en­coded, so we can­not put it in the do­main name, which is case-in­sen­si­tive. In­stead, we put it in the URL as a user­name, along with its ex­pi­ra­tion timestamp:3

https://6J3jK1WmB15c6WmjW_X-Wg--1789928654@p41535.ssh.luffy.cx/en/blog
        ╰─────────┬──────────╯  ╰───┬────╯  ╰─┬─╯             ╰──┬───╯
                hash             expires    port               path

The client sends the user­name to the server with HTTP ba­sic au­then­ti­ca­tion. This works with most HTTP clients, in­clud­ing curl. Ng­inx ex­poses the user­name in the $remote_​user vari­able. The mod­ule ex­pects the hash and the ex­pi­ra­tion time­stamp sep­a­rated by a comma. We use a map di­rec­tive to ex­tract the two parts from $remote_​user and join them with a comma.4 We also give the mod­ule the string to hash. It con­tains the ex­pi­ra­tion time­stamp, the port, and a secret:

map $remote_user $httpssh_link {
  "~^([-_A-Za-z0-9]{22})--([0-9]+)$" "$1,$2";
}
server {
  # […]
  location / {
    secure_link $httpssh_link;
    secure_link_md5 "$secure_link_expires $port ZuPerS3cr3!";
  }
}

The mod­ule re­turns the sta­tus of the check in the $secure_​link variable:

  • empty if the hashes do not match,
  • "0" if they match but the link has ex­pired, or
  • "1" otherwise.

If the hash is in­cor­rect or miss­ing, we re­turn a 401 er­ror with a WWW-Authenticate header to ask for cre­den­tials. If the link has ex­pired, we re­turn a 410 er­ror. We re­move the Authorization header be­fore for­ward­ing the re­quest and add a few di­rec­tives to proxy WebSocket con­nec­tions. Here is the com­plete con­fig­u­ration:5

map $remote_user $httpssh_link {
  "~^([-_A-Za-z0-9]{22})--([0-9]+)$" "$1,$2";
}
server {
  listen 0.0.0.0:443 ssl ;
  listen [::0]:443 ssl ;
  server_name ~^p(?<port>\d\d\d\d\d)\.ssh\.luffy\.cx$;
  location / {
    secure_link $httpssh_link;
    secure_link_md5 "$secure_link_expires $port ZuPerS3cr3!";
    if ($secure_link = "") {
      add_header WWW-Authenticate 'Basic realm="tunnel"' always;
      return 401;
    }
    if ($secure_link = "0") {
      return 410;
    }
    proxy_pass http://127.0.0.1:$port;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Authorization "";
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_buffering off;
    proxy_read_timeout 30m;
  }
}

I think you are now ask­ing your­self the ob­vi­ous ques­tion: “How should I gen­er­ate the hash?” Easy peasy!

$ expires=$(( $(date +%s) + 86400 ))
$ port=41535
$ secret='ZuPerS3cr3!'
$ printf '%s %s %s' "$expires" "$port" "$secret" \
>   | openssl md5 -binary \
>   | openssl base64 \
>   | tr +/ -_ | tr -d =
6J3jK1WmB15c6WmjW_X-Wg

Well, I sup­pose you are now say­ing: “Vin­cent, this is not very con­ve­nient! I’ll stick with ngrok if you don’t mind.” Okay, I hear you. Let’s write a helper script.

Helper script#

The main dif­fi­culty is find­ing the ephemeral port that OpenSSH al­lo­cates, as it does not ap­pear in any en­vi­ron­ment vari­able.6 To work around this ob­sta­cle, we look for the an­ces­tor sshd-session pro­cesses:7

pids=$(
  pid=$$
  while [ "$pid" -gt 1 ]; do
    line=$(ps -o comm=,pid=,ppid= -p "$pid")
    echo "$line"
    pid=${line##* }
  done | awk '$1 == "sshd-session" { printf "pid=%s,\n", $2 }'
)
if [ -z "$pids" ]; then
  echo "not an ssh session" >&2
  exit 1
fi

Then, we get the lis­ten­ing ports as­so­ci­ated with these sshd-session pro­cesses:8

ports=$(sudo -n ss --listening --numeric --tcp --processes --no-header \
  | grep -F "$pids" \
  | awk '{ print $4 }' | awk -F: '{ print $NF }' \
  | sort -un)
if [ -z "$ports" ]; then
  echo "no forwarded port, use ssh -R 0:localhost:PORT" >&2
  exit 1
fi

Fi­nally, we dis­play the URLs and keep the ses­sion open:

lifetime=86400
secret='ZuPerS3cr3!'
expires=$(( $(date +%s) + lifetime ))
for port in $ports; do
  token=$(printf '%s %s %s' "$expires" "$port" "$secret" \
            | openssl md5 -binary \
            | openssl base64 \
            | tr +/ -_ | tr -d =)
  echo "https://$token--$expires@p$port.ssh.luffy.cx/"
done
sleep infinity

I in­stall this script as http-over-ssh on the server and add this en­try to my ~/.​ssh/config:

Host http-over-ssh
  Hostname web02.luffy.cx
  RemoteCommand http-over-ssh
  ControlPath none

With this so­lu­tion, I only rely on OpenSSH and ng­inx, two pieces of soft­ware al­ready run­ning on this server. One short com­mand gives me a self-hosted tun­nel and a URL to share. To try it, grab the com­plete helper script, which in­cludes a few mi­nor im­prove­ments. If you run NixOS, as any per­son of taste would, have a look at my http-over-ssh.​nix instead. ❄️

Up­date (2026-10)

This post was widely dis­cussed on Hacker News and Lobsters.

Up­date (2026-10)

I have since switched to Caddy, which does not in­clude a mod­ule to check the va­lid­ity of a URL. In­stead, Caddy queries a lo­cal HTTP ser­vice writ­ten in Go through the forward_​auth di­rec­tive. As a bonus, this lets me put the to­ken in the do­main name.