Zero-Key Browser SSH to a Mac mini via Cloudflare Tunnel
Following up on
reaching a home lab with pure OpenSSH
: a
reverse SSH tunnel via a VPS jump box gives you end-to-end encryption and full
OpenSSH features, but it still requires a VPS, outbound SSH from corp-laptop,
and an encrypted personal SSH private key sitting on corp-laptop.
When you want zero personal SSH keys on corp-laptop (or pi), or only
HTTPS/443 is allowed out, Cloudflare Tunnel (cloudflared) running on pi can
route a Cloudflare Zero Trust Access application straight over the home LAN to a
Mac mini (mini:22)—rendered directly in a browser terminal and authenticated
with hardware Passkeys and Short-lived SSH Certificates.
Reverse SSH Tunnel vs. Cloudflare Tunnel
| Dimension | Reverse SSH Tunnel (VPS) | Cloudflare Tunnel (Browser SSH) |
|---|---|---|
| Infrastructure | VPS + stock OpenSSH / systemd |
Free tier + domain on CF DNS + cloudflared |
| Client setup | Native ssh + encrypted personal key |
Browser only (HTTPS/443); zero keys on client |
| Capabilities | Full ssh, scp, rsync, -L/-D |
Interactive xterm.js shell only |
| Trust boundary | End-to-end SSH; no third party | CF Edge decrypts browser I/O & signs certs |
| Reconnect / uptime | Single VPS (~90s stale-port window) | 4 redundant QUIC/HTTP2 conns across 2 PoPs |
Trade-offs of the Cloudflare Tunnel path:
- Pros: zero SSH private keys on
corp-laptoporpi, works over plain HTTPS/443 without installingcloudflaredon the client, hardware Passkey auth via Cloudflare Access, and shares the samepitunnel with other home services (e.g., a family webcam). - Cons: Cloudflare sits in the auth boundary (mitigated by scoping the CA to a
non-admin user
cfuserfrompi’s IP) and decrypts terminal I/O at its edge to render the browser UI (every hop on the wire is still encrypted—HTTPS/WSS to the browser, QUIC/TLS + SSH topi, and SSH on the LAN tomini—just not end-to-end encrypted through Cloudflare); browserxterm.jslacksscp,rsync, and port forwarding.
Architecture
browser (Passkey) --> Cloudflare Edge (Access + SSH CA)
| (cloudflared tunnel)
v
pi (10.0.0.6) --(LAN :22)--> mini (10.0.0.7, user: cfuser)
- Direct LAN routing from
cloudflared(pi→mini:22): avoids usingpias an SSH jump hop and eliminates any SSH private key onpi. - Passkeys + Short-lived SSH Certificates: authentication requires a hardware
security key / Passkey at Cloudflare Access, which mints an ephemeral SSH
certificate so zero personal SSH keys live on
corp-laptop. - Least-privilege blast-radius isolation:
TrustedUserCAKeysis scoped strictly to a dedicated Standard (non-admin) macOS user (cfuser) and connections frompi’s LAN IP (10.0.0.6), keeping the macOS admin account unreachable by Cloudflare’s CA.
1. Router, cloudflared on pi, and Cloudflare Zero Trust
- Home router: reserve static DHCP IPs for
pi(e.g.,10.0.0.6) andmini(e.g.,10.0.0.7) so the tunnel target andsshdAddressmatch never drift. - Mac mini power: disable automatic sleep so
pican always reach port22. - On
pi: installcloudflaredfrom Cloudflare’s APT repo and register itssystemdservice (sudo cloudflared service install <TUNNEL_TOKEN>). - Cloudflare Zero Trust: follow Cloudflare’s
Browser-rendered SSH terminal
guide to wire up the Access application, Short-lived SSH Certificate, and
tunnel route, watching out for a few pitfalls:
- Create the Self-hosted Access Application before adding the tunnel route
(leaving Path blank) so
mini:22is never exposed unauthenticated. - Restrict the application to Passkeys only (uncheck One-time PIN) so login requires a hardware key or Passkey instead of email OTP.
- The allowed email prefix must match the non-admin macOS username
(
[email protected]→cfuser): browser SSH always logs in as the prefix before@and cannot remap viaAuthorizedPrincipalsFile(use an alternate email alias if needed). - Point the tunnel’s
SSHroute atmini’s static LAN IP (10.0.0.7:22), notlocalhost:22, sincecloudflaredruns onpi.
- Create the Self-hosted Access Application before adding the tunnel route
(leaving Path blank) so
2. Non-Admin User & Remote Login on Mac mini
- Create a Standard (non-admin) macOS user matching the Access email prefix
(
cfuser) so Cloudflare’s CA can never access the admin user orsudo. - Enable Remote Login (
System Settings -> General -> Sharing -> Remote Login) and addcfuserto thecom.apple.access_sshallowlist. Without this, macOS PAM (pam_sacl) accepts the key or certificate and immediately drops the connection withConnection closed:
sudo dseditgroup -o edit -a cfuser -t user com.apple.access_ssh
3. Mac mini sshd Hardening & Scoped Cloudflare CA
macOS upgrades can overwrite /etc/ssh/sshd_config, so keep all custom rules in
/etc/ssh/sshd_config.d/ (included at the top of /etc/ssh/sshd_config).
- Base hardening (
/etc/ssh/sshd_config.d/00-hardening.conf): enforce key/certificate-only auth and restrict SSH logins to home LAN + loopback:
sudo tee /etc/ssh/sshd_config.d/00-hardening.conf >/dev/null <<'EOF'
PermitRootLogin no
PubkeyAuthentication yes
AuthenticationMethods publickey
PasswordAuthentication no
KbdInteractiveAuthentication no
AllowUsers *@10.0.0.0/24 *@127.0.0.1 *@::1
EOF
sudo chmod 644 /etc/ssh/sshd_config.d/00-hardening.conf
- Save Cloudflare’s SSH CA public key (
/etc/ssh/cloudflare-ca.pub):
sudo tee /etc/ssh/cloudflare-ca.pub >/dev/null <<'EOF'
<CLOUDFLARE_SSH_CA_PUBLIC_KEY>
EOF
sudo chown root:wheel /etc/ssh/cloudflare-ca.pub
sudo chmod 400 /etc/ssh/cloudflare-ca.pub
- Scope CA trust strictly to
cfuserfrompi’s LAN IP (/etc/ssh/sshd_config.d/99-cf-access.conf):
sudo tee /etc/ssh/sshd_config.d/99-cf-access.conf >/dev/null <<'EOF'
Match User cfuser Address 10.0.0.6
PubkeyAuthentication yes
TrustedUserCAKeys /etc/ssh/cloudflare-ca.pub
EOF
sudo chmod 644 /etc/ssh/sshd_config.d/99-cf-access.conf
4. Verification & Troubleshooting
Validate syntax and confirm TrustedUserCAKeys only applies to cfuser from
pi’s LAN IP:
sudo /usr/sbin/sshd -t
# Expected: trustedusercakeys /etc/ssh/cloudflare-ca.pub
sudo /usr/sbin/sshd -T -C "user=cfuser,addr=10.0.0.6" | grep trustedusercakeys
# Expected: trustedusercakeys none (admin user must never trust the CA)
sudo /usr/sbin/sshd -T -C "user=<ADMIN_USER>,addr=10.0.0.6" | grep trustedusercakeys
# Expected: trustedusercakeys none (other LAN IPs must not trust the CA)
sudo /usr/sbin/sshd -T -C "user=cfuser,addr=10.0.0.1" | grep trustedusercakeys
If login closes immediately after authentication, inspect macOS sshd logs:
log show --predicate 'process == "sshd" OR process == "sshd-session"' --last 5m
Dual-Stack Xray: Cloudflare CDN vs. Direct REALITY
Following up on
dropping Caddy for direct Xray
:
after a quick detour evaluating kernel WireGuard (where macOS gVisor and iOS
NetworkExtension userspace netstacks capped out around ~370 Mbps against a
fast European VM vs. ~1 Gbps over CDN + VLESS), I stayed on Xray and added a
direct VLESS + REALITY + XTLS-Vision inbound alongside the existing
Cloudflare CDN + VLESS + XHTTP (H2) + TLS 1.3 stack in the same xray
process.
The question I wanted to answer with real measurements: does REALITY + Vision’s
zero-copy Linux splice(2) path beat Cloudflare’s split-TCP + private backbone
on European links, and how much CPU and RAM does each stack actually cost? The
dual-stack setup lives on the
reality branch
while my VPS setup scripts
on main stay on single-stack Cloudflare
CDN.
Dual-Stack Architecture
Direct REALITY: Client → Xray (:443, REALITY + Vision) → Internet
Cloudflare CDN: Client → Cloudflare (:443) → Origin Rule → Xray (:8443, XHTTP/H2) → Internet
- Single
xrayprocess: adding a second inbound shares the Go runtime and adds ~1–5 MiB at idle. - Zero cert churn: Cloudflare Origin CA certs are bound to hostnames, not
ports, so the same 15-year wildcard cert moves straight to
:8443. A free Cloudflare Origin Rule rewrites:443 → :8443so clients still hit:443on Cloudflare, while UFW restricts:8443to Cloudflare IP ranges and opens:443globally for REALITY.
Benchmark: NetCup 2c/4G VM (Vienna, 2.5 Gbps NIC)
Tested from a Mac mini in Switzerland through two local Xray SOCKS clients
against a NetCup VM in Vienna (AMD EPYC-Genoa, 2 vCPUs, 4 GB RAM, Debian 13, 2.5
Gbps NIC, GOMEMLIMIT=2112MiB), capping the test conservatively at 45% of
2-core host CPU (= 90% of 1 core) and <504 MiB RSS. Downloads used CacheFly EU
(TLSv1.3 + h2, 1,360 MB total proxied). Here TTFB (Time to First Byte,
curl %{time_starttransfer}) measures end-to-end startup latency until the
first HTTP response byte arrives, HostPk is % of the full 2-core VM, and Xr*
is 1-core Irix % (100% = 1 full core).
| Test | Stack | Mbps | TTFB | HostPk | XrUsr | XrSys | XrAvg | XrPk | RSS | CgMem | MacCPU |
|---|---|---|---|---|---|---|---|---|---|---|---|
| Google 204 (p50) | CDN | — | 164ms | — | — | — | — | — | — | — | — |
| Google 204 (p50) | REALITY | — | 160ms | — | — | — | — | — | — | — | — |
| DL 1×50 MB | CDN | 580.5 | 167ms | 31.5% | 12.6% | 27.3% | 40.0% | 43.0% | 51.6M | 25.1M | 33.4% |
| DL 1×50 MB | REALITY | 194.2 | 165ms | 9.1% | 1.8% | 1.9% | 3.7% | 3.7% | 51.1M | 31.7M | 6.3% |
| DL 2×75 MB | CDN | 734.3 | 220ms | 35.7% | 13.7% | 27.3% | 41.0% | 53.5% | 51.1M | 28.3M | 42.8% |
| DL 2×75 MB | REALITY | 497.1 | 158ms | 14.5% | 1.2% | 3.7% | 4.9% | 7.4% | 51.1M | 39.3M | 17.4% |
| DL 4×50 MB | CDN | 767.3 | 215ms | 37.7% | 11.0% | 23.3% | 34.3% | 53.1% | 51.2M | 30.5M | 50.4% |
| DL 4×50 MB | REALITY | 368.0 | 168ms | 14.3% | 0.7% | 4.0% | 4.7% | 7.4% | 51.6M | 54.0M | 21.6% |
| DL 8×35 MB | CDN | 811.5 | 241ms | 43.4% | 14.0% | 19.5% | 33.4% | 65.9% | 51.6M | 35.0M | 60.1% |
| DL 8×35 MB | REALITY | 371.6 | 179ms | 24.1% | 1.6% | 3.6% | 5.3% | 11.1% | 51.6M | 86.3M | 19.2% |
Three things stood out:
- CDN won decisively on throughput (1.5–3× faster across every tier): CDN
scaled cleanly to 811.5 Mbps (and 580.5 Mbps on a single 50 MB
stream), while REALITY peaked at 497.1 Mbps (
2×75 MB) and settled around ~370 Mbps at 4–8 streams. Server CPU was clearly not the bottleneck (REALITY averaged ~5% of 1 core with 0% steal). Instead, Cloudflare’s local Zurich POP keeps a warm persistent HTTP/2 congestion window on a short RTT leg and rides Cloudflare’s private backbone to Vienna, whereas every new REALITY stream pays cold TCP slow-start over the public ISP-to-Netcup peering path. - REALITY + Vision is ~5× more CPU-efficient per Mbps: normalized per 100
Mbps on this VM, CDN spent ~4.5–5.6% of 1 core (
~1.8%user +~3.2%sys) vs. REALITY’s ~1.0% of 1 core (~0.24%user +~0.74%sys) — and roughly half the Mac client CPU per Mbps. Even so, the server had plenty of headroom for CDN: 811.5 Mbps averaged only 33.4% of 1 core (43.4% peak across both cores). - Loaded TTFB and memory: fresh TTFB to Vienna was a wash (~160 ms on
both), but under 2–8 concurrent streams REALITY stayed 50–60 ms snappier
(
158–179 msvs.215–241 ms) because independent TCP sockets avoid head-of-line queueing inside a shared HTTP/2 tunnel. Xray RSS stayed pinned at ~51 MiB on both; cgroup memory peaked at 86 MiB on 8-stream REALITY from kernel socket/pipe buffers used bysplice(2)(vs. 35 MiB on CDN).
Takeaway
The common advice to “always use direct REALITY for maximum speed” didn’t hold
on Zurich ↔ Vienna — network path and warm split-TCP mattered more than kernel
splice(2):
- Pick CDN (
:8443) for highest sustained throughput on cross-border links (580–811 Mbps here) and whenever origin IP hiding matters (e.g., China mainland). - Pick REALITY (
:443) for CPU-constrained servers, mobile battery savings (~5× lower server CPU/Mbps, ~2× lower client CPU/Mbps), and snappier TTFB under concurrent browsing.
Your 1 GB VPS Is Enough for a Proxy
Following up on tuning a 1 GB proxy VPS : Caddy was originally in the stack for automatic TLS certificate management and the flexibility to host a real website alongside the proxy. Since I don’t actually need to host a website on a proxy VPS — and under load Caddy was burning ~55–60% of both proxy CPU and RAM just to sit between Cloudflare and Xray — I dropped it altogether and let Xray terminate TLS 1.3 + HTTP/2 + XHTTP directly, along with a few remaining OS and runtime tweaks. Everything below is backported into my VPS setup scripts .
Architecture Change
Before: Client → Cloudflare → Caddy (:443) → h2c (@xray) → Xray → Internet
After: Client → Cloudflare → Xray (:443) → Internet
Dropping Caddy removes a second Go runtime/GC, internal h2c re-framing, and
the @xray Unix-socket IPC copy:
- 15-year ECC Cloudflare Origin CA cert (
/opt/xray/{cert,key}.pem, SSL modeFull (Strict)): a one-time wildcard cert reusable across all subdomains, eliminating ACME renewal and Let’s Encrypt CT-log subdomain leakage. - Non-root
:443with full systemd hardening: settingnet.ipv4.ip_unprivileged_port_start = 443letsUser=xraybind:443with zero capabilities andPrivateUsers=yesintact. - Tighter UFW rules:
:443/tcponly accepts Cloudflare’s published IPv4/IPv6 ranges, so direct IP scans are silently dropped.
Other Optimization Points
- Go runtime & scheduling: dynamic
GOMEMLIMITcomputed from actualMemTotal(reservingmax(448 MiB, 20%)for OS/kernel and an extra1 GiBfor Docker on ≥ 4 GB VMs),GOGC=200on ≥ 2 GB VMs, plusOOMScoreAdjust=-500,Nice=-5, andCPUWeight=200onxray.service. - Kernel, swap & I/O hygiene: persisted
nf_conntrackinmodules-load.d(fixing a boot-order skip ofnf_conntrack_max), cappedip_local_port_rangebelow60000, switchedzramfromzstdtolz4(lower CPU on burstable vCPUs) with tuned VM watermarks/dirty ratios, enablednoatimeon/, disabled UFW drop logging, removedlocate, and disabledman-db/e2scrub_all/multipathd. - Tested and left at default:
mode=stream-upandstream-onefail behind Cloudflare (which buffers POST bodies at the edge), and tuningxmux(maxConnections=4vs. default) showed only marginal tail-latency gains — somode=autoand defaultxmuxstayed untouched.
Results
Verified with A/B benchmarks on both identical OCI free-tier 1 GB VMs (1/8 OCPU,
50 Mbps NIC) and a NetCup 2c/4G VM constrained to 1 GB-equivalent conditions
(2,730 MiB mlock RAM ballast + 1 GB GOMEMLIMIT + 16 MB TCP caps) up to 500
Mbps:
| Metric (Caddy + Xray → Direct Xray) | Before | After | Delta |
|---|---|---|---|
| Proxy CPU at ~485 Mbps (1-core, NetCup) | 44.5% |
22.0% |
−51% (~2× CPU eff.) |
| Proxy CPU at ~48 Mbps cap (1-core, OCI) | 25.5% |
10.8% |
−58% |
| Peak RPS on 1/8 OCPU (OCI) | 78.4 rps |
118.0 rps |
+51% (at lower CPU) |
| Proxy RSS / private RAM at 485 Mbps | 123 / 67 MiB |
39 / 13 MiB |
−68% / −81% |
| Proxy RSS / private RAM under mixed load | 169 / 113 MiB |
48 / 21 MiB |
−72% / −81% (+107M free) |
| Unloaded / loaded p50 latency (NetCup) | 41 / 50 ms |
32 / 41 ms |
−21% / −19% |
Removing Caddy cut proxy CPU roughly in half and private RAM by 70–80% while simplifying the stack to a single hardened binary — leaving plenty of headroom even on a 1 GB VPS.
Reaching a Home Lab from a Locked-Down Work Laptop with Pure OpenSSH
The default answers for reaching a home server behind ISP NAT are Tailscale or
Cloudflare Tunnel (cloudflared). Both are great—until you hit a common set of
constraints:
- Home LAN (behind NAT): An always-on Raspberry Pi (
pi) and a Mac mini (mini). - Tiny public VPS (
vps): Too small for extra VPN daemons, and also a personal dev box that pushes to personal GitHub repos. - Locked-down work laptop (
corp-laptop): Cannot install VPN clients, outbound SSH is allowed, corporate keys live dynamically in$SSH_AUTH_SOCK, and corporate keys must never be offered or forwarded to the VPS or the internet.
Plain OpenSSH solves all of it with a few megabytes of RAM, end-to-end encryption, zero third-party control planes, and strict separation between corporate and personal keys. Both server setup scripts—setup-tunnel.sh and persist-tunnel.sh —are hosted right alongside this note; for a zero-key browser-only alternative that needs no VPS and no outbound SSH, see the companion Cloudflare Tunnel browser SSH setup.
Why Pure OpenSSH?
| Criterion | Pure OpenSSH (Reverse Tunnel + ProxyJump) |
Tailscale | Cloudflare Tunnel (Browser SSH) |
|---|---|---|---|
| Corp laptop | Outbound SSH + encrypted personal key | Blocked (VPN client) | Browser only (HTTPS/443); zero keys |
| Extra software | None (sshd + systemd) |
Daemon on every node | cloudflared + domain + Zero Trust |
| Trust boundary | End-to-end (corp-laptop → target) |
End-to-end WireGuard | CF Edge decrypts browser I/O & signs CA |
| VPS RAM footprint | ~few MB | ~30–60+ MB | N/A (runs on pi) |
| Capabilities | Full ssh, scp, rsync, -L/-D |
Built-in (full L3) | Interactive xterm.js shell only |
Tailscale is still great for mobile devices (e.g., viewing a Pi webcam from a
phone), and Cloudflare Tunnel is a strong fallback when you want zero personal
keys on corp-laptop. Keeping OpenSSH for daily laptop access gives you native
terminal ergonomics and full port forwarding without ever putting the VPS on
your tailnet.
Architecture
corp-laptop --(SSH #1)--> vps <--(reverse tunnel :2222)-- pi --(LAN :22)--> mini
| ^ ^
+----------------(SSH #2, end-to-end)----------------+ |
+----------------(SSH #3, end-to-end)-----------------------------------+
- Persistent reverse tunnel (
pi→vps):pidials out tovpsand binds its SSH port strictly to loopback (127.0.0.1:2222) under a locked-down/bin/falseuser—nothing new is exposed publicly. - Chained
ProxyJump(corp-laptop→vps→pi→mini): Every hop authenticates end-to-end fromcorp-laptop. No personal private keys live onvpsorpi, andForwardAgentstays off for both. - Isolated personal
ssh-agent(~/.ssh/agent.sock): OpenSSH cannot filter dynamically loaded corporate keys per host inside a shared agent. A dedicated, unexported personal socket leaves$SSH_AUTH_SOCKuntouched while safely enablingForwardAgent ~/.ssh/agent.socktovpsfor personal GitHub pushes.
1. Reverse Tunnel (pi → vps)
Both scripts assume Debian 12+ or Ubuntu 22.04+. First, generate a dedicated
passphrase-free ed25519 key on pi solely for unattended tunnel reconnects:
ssh-keygen -t ed25519 -N "" -C "pi-reverse-tunnel" -f ~/.ssh/id_ed25519_vps_tunnel
On vps, fetch and run setup-tunnel.sh
with the Pi’s public
key (either as a file argument or piped on stdin):
curl -fLO https://joyus.org/2026/lightweight-ssh-homelab/setup-tunnel.sh
chmod +x setup-tunnel.sh
cat id_ed25519_vps_tunnel.pub | sudo ./setup-tunnel.sh
It creates a /bin/false tunnel user, installs a scoped Match User tunnel
drop-in at /etc/ssh/sshd_config.d/99-reverse-tunnel-tunnel.conf, validates
with sshd -t (rolling back on error), reloads sshd, and verifies the
effective config via sshd -T -C user=tunnel. A few details matter:
AllowTcpForwarding remote,GatewayPorts no, andPermitListen localhost:* 127.0.0.1:* [::1]:*restrict forwards strictly to loopback.localhost:*is required because OpenSSH sendslocalhoston the wire for-R 2222:127.0.0.1:22; allowing only127.0.0.1:*rejects it.ClientAliveInterval 30/ClientAliveCountMax 3scoped insideMatch User tunnelclears stale tunnels within ~90s after ISP drops without affecting normal sessions.- Keep
AllowTcpForwarding yes(the default) for your normal users onvpsandpisoProxyJump(ssh -W) works.
On pi, skip autossh and let systemd + OpenSSH handle reconnects via
persist-tunnel.sh
, which auto-detects pi’s local sshd
port and installs reverse-ssh-tunnel.service:
curl -fLO https://joyus.org/2026/lightweight-ssh-homelab/persist-tunnel.sh
chmod +x persist-tunnel.sh
sudo ./persist-tunnel.sh <VPS_IP> 2222
Verify on vps that port 2222 is listening on loopback only:
ss -tln | grep ':2222\b'
# Expected: LISTEN ... 127.0.0.1:2222 0.0.0.0:*
The critical unit options in reverse-ssh-tunnel.service:
-F /dev/null+IdentitiesOnly=yes+IdentityFile=...isolate the daemon from your personal~/.ssh/config.ExitOnForwardFailure=yesforces an immediate exit (and 10ssystemdretry) ifvpsbriefly still holds port2222from a dead connection.StartLimitIntervalSec=0preventssystemdfrom giving up during multi-hour ISP outages, andBatchMode=yes+StrictHostKeyChecking=accept-newavoids interactive hangs while pinning the VPS host key on first connect.
2. Isolated ssh-agent and ~/.ssh/config
On corp-laptop, never overwrite global $SSH_AUTH_SOCK. Instead, start a
dedicated personal agent at ~/.ssh/agent.sock in your shell rc without
exporting it (see __setup_ssh_agent in
zsh/zshrc
and
bash/bashrc
).
There is no passphrase prompt on terminal startup—OpenSSH unlocks the key lazily
on first use via AddKeysToAgent, and modern ed25519 private keys embed their
public key unencrypted so no sibling .pub file is needed.
Then adapt
config.sample
into ~/.ssh/config (chmod 600 ~/.ssh/config): Host vps sets
ForwardAgent ~/.ssh/agent.sock; Host pi targets 127.0.0.1:2222 via
ProxyJump vps with HostKeyAlias pi; Host mini sets ProxyJump pi; a
shared Host vps pi mini github.com block pins
IdentityAgent ~/.ssh/agent.sock, IdentityFile ~/.ssh/%u.key,
IdentitiesOnly yes, and AddKeysToAgent 10h; and corporate hosts sit above
Host *.
Three Subtle OpenSSH Gotchas
- Never pass
-A(ssh -A vps): CLI flags override~/.ssh/config.-AsetsForwardAgent yes, dropping~/.ssh/agent.sockand silently forwarding your corporate$SSH_AUTH_SOCK. - Use
HostKeyAlias pifor tunneled targets: Avoids[127.0.0.1]:2222collisions in~/.ssh/known_hostswith other port forwards. - Never put corporate
IdentityFilelines inHost *: UnlikeIdentityAgentorForwardAgent(first-match-wins),IdentityFileaccumulates across every matching block.
3. Day-to-Day Usage
Once wired up, every host and tunnel is one command from corp-laptop:
ssh vps # Dev session (personal GitHub via isolated agent)
ssh pi # corp-laptop -> vps -> pi
ssh mini # corp-laptop -> vps -> pi -> mini
ssh -N -L 5900:localhost:5900 mini # Mac mini Screen Sharing -> vnc://localhost:5900
ssh -D 1080 pi # Ad-hoc SOCKS5 proxy into home LAN
Sometimes the boring tool sitting in /usr/bin/ssh for 25 years is still the
cleanest one for the job.
Tuning a 1 GB Proxy VPS: 5× Throughput, Half the Latency, Half the RAM
I run my personal proxy stack (VLESS + TLS (Caddy) + Cloudflare CDN) on a
cheap GCP e2-micro VM — 2 shared vCPUs (0.25 vCPU sustained baseline), 964 MiB
RAM, zero swap, Debian 13, sitting in Taiwan (asia-east1-b). Connecting from
Switzerland gives ~8 ms to Cloudflare’s Zurich edge and ~250 ms across the long
transcontinental leg to Taiwan.
It worked fine, but I had never actually measured or tuned it. So I spun up two
identical e2-micro VMs in the same zone — keeping tw1 untouched as the
baseline and tuning tw2 one layer at a time with interleaved A/B benchmarks.
An initial A/A run confirmed both unmodified servers behaved identically: ~31
Mbps single-stream download, ~17 Mbps upload, ~21–28 Mbps across 6 parallel
downloads, ~1,800 ms median cold TTFB, and 478 MiB idle available RAM.
Everything below ended up backported into my VPS setup scripts .
Layer 1: Linux Kernel & TCP Stack (BBR + fq)
With ~250 ms RTT between Cloudflare’s edge and GCP Taiwan, default cubic
congestion control, 208 KB socket caps, tcp_slow_start_after_idle = 1, and an
8,192-entry conntrack table left massive bandwidth on the table.
We switched to BBR
(Bottleneck
Bandwidth and Round-trip propagation time) — Google’s model-based TCP congestion
control algorithm that estimates the path’s bandwidth and minimum RTT to pace
sending instead of filling router queues until packets drop like cubic —
paired with fq
(Fair
Queueing), the Linux packet scheduler that provides the per-flow packet pacing
BBR relies on to avoid micro-bursts.
In /etc/sysctl.d/99-proxy-tuning.conf (with tcp_bbr persisted in
/etc/modules-load.d/bbr.conf and tc qdisc replace dev <iface> root fq so
pacing takes effect without a reboot):
- Congestion control & pacing:
net.core.default_qdisc = fqandnet.ipv4.tcp_congestion_control = bbr. - RAM-scaled buffers & conntrack: 16 MB max TCP/UDP buffers and 65,536 conntrack entries on 1 GB VMs, scaling to 32 MB / 131k on 2 GB and 64 MB / 262k on 4 GB+.
- Persistent proxy tuning:
tcp_slow_start_after_idle = 0,tcp_fastopen = 3,tcp_mtu_probing = 1,tcp_notsent_lowat = 131072,somaxconn = 8192,netdev_max_backlog = 8192. (In Linux,net.ipv4.tcp_*applies to both IPv4 and IPv6 TCP sockets.)
Result vs. baseline: single-stream DL +23% (29.5 → 36.4 Mbps), upload +9%,
6-stream DL +93% (23.5 → 45.5 Mbps), and TCP retransmits dropped -75%
(0.28% → 0.07%).
Layer 2: Eliminating the Local Proxy Hop (unix/@xray)
Previously, every packet between Caddy and Xray traversed:
Caddy → 127.0.0.1:60066 → docker-proxy (userland copy) → docker0 veth → iptables NAT → Xray
Switching Xray to an abstract Unix domain socket (listen: "@xray",
reverse_proxy unix/@xray) removed docker-proxy, bridge NAT, loopback TCP,
and ephemeral port churn in one move. Stripping X-Forwarded-For on the reverse
proxy also stopped Xray from writing a warning to disk on every connection.
Result: 6-stream download jumped from 28.1 → 95.4 Mbps (+239%, peaking at 102 Mbps) while using ~50% fewer conntrack entries, ~30% fewer TCP segments, and slightly lower CPU than the baseline.
Layer 3: Migrating WebSocket to XHTTP (H2)
Even at 95 Mbps, cold HTTPS latency stayed stubbornly stuck at ~1,800 ms and connection churn capped at ~9 rps. Why? Because HTTP/1.1 WebSocket cannot be multiplexed over a single origin connection behind Cloudflare — every new proxied flow pays origin TCP+TLS setup plus a WebSocket Upgrade round-trip across 250 ms RTT.
- Quick test — WebSocket Early Data (
?ed=2048): piggybacking the VLESS header on the WS upgrade request (client-only change) immediately cut 365 ms off median latency (1,801 → 1,436 ms, -20%) and boosted churn by +26%. - Full upgrade — VLESS + XHTTP over HTTP/2 (
h2c): with XHTTP (route /$route*andtransport http { versions h2c 2 }in Caddy,alpn: ["h2"]on the client), bothClient ↔ CloudflareandCloudflare ↔ Caddymultiplex streams over warm HTTP/2 connections.
| Metric | Baseline (WS) | Tuned WS | WS + ?ed=2048 |
XHTTP (H2) |
|---|---|---|---|---|
| Latency p50 | 1,793 ms | 1,818 ms | 1,436 ms | 764 ms (-57%) |
| Latency p95 | 1,945 ms | 1,929 ms | 1,517 ms | 1,033 ms (-47%) |
| Churn (16 conc) | 9.1 rps | 9.2 rps | 11.2 rps | 18.4 rps (2.0×) |
| 6-stream DL | 28.5 Mbps | 86.8 Mbps | 74.3 Mbps | 155.0 Mbps (5.4×) |
| 1-stream DL | 32.4 Mbps | 37.6 Mbps | 39.3 Mbps | 42.1 Mbps (peak 96.6) |
| TCP Retransmits | 0.10% | 0.00% | 0.02% | 0.00% |
Cold TTFB dropped by over a full second, and Xray’s WebSocket deprecation
warning disappeared. We also replaced the hardcoded URL path with the first
segment of the generated UUID (${uuid%%-*}) and appended &tfo=1 to the
Shadowrocket QR URI so TCP Fast Open enables automatically on scan.
Layer 4: Putting a 1 GB VM on a Memory Diet
Next, I simulated 3 heavy concurrent devices (continuous downloads, 4K video
chunks, uploads, and 12 browser request loops plus an active tmux session)
with 1-second server telemetry — then pushed it to 60 concurrent streams to see
where a 964 MiB e2-micro actually breaks.
The biggest surprise wasn’t Xray or Caddy — it was the OS itself. Nearly half the VM (~470 MiB) was already gone before proxy traffic even started:
- 6 GCP guest/telemetry agents:
~145 MiBRSS (google-osconfig-agent,google-guest-compat-manager,google-guest-agent-managerplus its workload identity and telemetry plugins). - Docker runtime:
~140–160 MiBRSS (dockerd+containerd+ shim) just to wrap a single static Go binary running with--network=host. - Redundant daemons:
haveged(obsolete on Linux 6.12),networkd-dispatcher, andrsyslog(redundant withsystemd-journald).
Here is what actually moved the needle:
- Disabled unused background services (keeping
unattended-upgradesfor kernel security patches, and stoppinggoogle-guest-agent-managerafter a 15-second background delay so GCE first-boot startup scripts still complete cleanly). Verified across a full reboot that SSH andsystemd-networkdDHCP come straight back up. - Replaced Docker with a hardened native
systemdservice: Docker andsystemduse the same Linux kernel isolation primitives. Running Xray directly under a dedicatedxraysystem user withNoExecPaths=/,ExecPaths=/opt/xray/xray,MemoryDenyWriteExecute=yes,CapabilityBoundingSet=(zero caps),PrivateUsers=yes,ProtectSystem=strict,ProtectProc=invisible,SystemCallFilter=@system-service, and read-onlyconfig.jsonscored1.1 OK :-)onsystemd-analyze security xray.service— matching or beatingdocker --network=hostwhile reclaiming ~150 MiB and removing a root daemon. (One subtle catch:ProcSubset=pidhid/proc/sys/net/core/somaxconnfrom Go, silently dropping the@xraylisten backlog from 8,192 to 128 — droppingProcSubset=pidwhile keepingProtectProc=invisiblerestored 8,192 with the same1.1 OKscore.) - Trimmed Caddy: Disabled Caddy’s unused HTTP/3 UDP
:443listener (servers { protocols h1 h2 }— Cloudflare never uses H3 to origins), set globallog { level ERROR }, dropped Debian’s default:80file server, and shrunk theh2cupstream pool (32 KBbuffers,30skeepalive,16idle conns). - Added 512 MB
zstdzramswap (systemd-zram-generator,vm.page-cluster = 0,vm.swappiness = 100, plusjournaldcapped at 32 MB). Under pressure, cold pages compressed at 11:1–15:1 (28 MiBinto2.5 MiBof RAM) with zero disk I/O.
Memory Metric (e2-micro, 964 MiB) |
Before (Docker + GCP agents + 0 swap) | After (Native systemd + trimmed + zram) |
|---|---|---|
Idle MemAvailable |
478 MiB | 704 MiB (+226 MiB) |
| OS + Kernel peak (3 heavy devices) | 469–511 MiB | 249 MiB (-50%) |
Min MemAvailable (3 heavy devices) |
273 MiB | 509 MiB (+86%) |
Min MemAvailable (60 streams) |
48.5 MiB (near OOM) | 213.5 MiB (4.4×) |
| Memory PSI (60 streams) | 6.8–10.1 | 0.36 (~25× lower) |
We also measured GOMEMLIMIT (finding a consistent 60% Caddy / 40% Xray usage
split across every load level), but with ~670–700 MiB free and 512 MB of zram
on a 1 GB VM, OOM is no longer a realistic risk — so we kept GOMEMLIMIT on a
side branch rather than adding complexity prematurely.
Final Numbers (and One Bonus Lesson)
From start to finish on the exact same ~$7/month e2-micro:
- Cold latency (p50):
1,793 ms → 764 ms(-57%) - 6-stream burst throughput:
28.5 Mbps → 155–167 Mbps(5.4×; peaked at 248 Mbps DL + 38 Mbps UL in 60-second multi-device stress while CPU burst credits lasted, before settling to ~35–60 Mbps at the 0.25 vCPU sustained baseline) - TCP retransmits:
0.10–0.28% → 0.00%in standard benchmarks (0.04–0.21%under heavy multi-device saturation) - Available RAM (idle):
478 MiB → ~670–704 MiB(Caddy37 MiB+ Xray34 MiBfresh)
And one unexpected takeaway: pushing 60 concurrent HTTPS streams (~295 Mbps
outbound burst) through an e2-micro to public speed-test endpoints was
effective enough to trigger a Google Cloud Trust & Safety DoS alert twenty
minutes later. Measure your changes, keep your load tests realistic, and don’t
accidentally DDoS-alert yourself.