Skip to content

VPNs & Tunnels: SSH Port Forwarding, Bastions, WireGuard, Site-to-Site vs Client VPN, Zero-Trust Access ​

"WireGuard is a secure network tunnel, operating at layer 3, implemented as a kernel virtual network interface for Linux, which aims to replace both IPsec for most use cases, as well as popular user space and/or TLS-based solutions like OpenVPN, while being more secure, more performant, and easier to use." — Jason A. Donenfeld, WireGuard: Next Generation Kernel Network Tunnel (whitepaper abstract)

Summary: A tunnel carries one protocol inside another so traffic can cross a network that would not carry it directly; SSH forwards, WireGuard, mesh VPNs, cloud VPN gateways and identity-aware proxies are the same idea at different layers and with different trust models. Focus: SSH -L, -R, -D, -J, -W, ControlMaster and agent forwarding, bastion hosts and short-lived certificates, WireGuard internals (cryptokey routing, AllowedIPs, handshake, roaming, keepalive, MTU), Tailscale-style meshes, OpenVPN and IPsec/IKEv2, site-to-site vs client VPN, cloud VPN vs peering vs PrivateLink, split tunneling and DNS, overlapping subnets, reverse tunnels (cloudflared, ngrok, ssh -R), kubectl port-forward, and zero-trust access. Learning goal: Pick the right tunnel for a job (reach a private database, expose a dev server, join two networks, give a contractor access to one app), build it with real commands, read wg show and ssh -v, and diagnose the six classic failures from the symptom alone.

This chapter is the complete reference for how a developer meets tunnels: ssh -L to a database that has no public address, a bastion in front of production, a WireGuard link between a laptop and a home server, a corporate VPN client, an AWS Site-to-Site connection, a Tailscale tailnet, a cloudflared tunnel for webhook testing, and kubectl port-forward to a pod. It builds on IP addressing, private ranges and CIDR (what overlaps and why), NAT, PAT and port forwarding (why a tunnel dials out, hole punching, keepalive), and network models (encapsulation). Sockets, ports and ss live in ports, sockets and connections; DNS and split DNS in DNS resolution for developers; packet filtering and security groups in firewalls; container networks in Docker networking and Kubernetes networking; the cipher and key primitives in cryptography fundamentals; certificates in TLS in practice; a symptom-first view in the troubleshooting playbook. Zero-trust as an architecture, mTLS between services and DDoS design stay in system design: authorization and zero trust, mTLS, PKI and secrets, proxies, network security. Database access rules are in database security and connection pooling.

Page map ​

If you are looking forGo to
The tables to memoriseEverything in one minute
What a tunnel is, TUN vs TAP, overhead and MTUWhat a tunnel is
Why not just open the database portWhy tunnels and VPNs exist
Origins: SSH 1995, IPsec, OpenVPN, WireGuard, BeyondCorpWhere it comes from
ssh -L to a private databaseLocal forward
ssh -R to expose a dev server, GatewayPortsRemote forward
ssh -D and SOCKS, DNS leaksDynamic forward
-J, ProxyJump, ProxyCommand, -WJump hosts
ControlMaster, keepalive, autosshMultiplexing and keeping tunnels alive
Agent forwarding and why it is riskyAgent forwarding
Hardening a bastion, certificates, auditBastion hosts
WireGuard config, handshake, keysWireGuard in depth
AllowedIPs, roaming, PersistentKeepaliveAllowedIPs, Roaming and keepalive
Tailscale, Headscale, Netbird, DERP, MagicDNS, ACLsMesh VPNs
OpenVPN, IPsec, IKEv2, NAT-TOpenVPN and IPsec
Site-to-site vs client VPN, split tunnelTopologies
AWS Site-to-Site, Client VPN, GCP Cloud VPN, peering, PrivateLink, TGWCloud VPN and private links
Overlapping subnetsOverlapping subnets
Split tunneling, split DNS, DNS leaksSplit tunnel and DNS
VPN vs zero-trust, BeyondCorp, Teleport, Boundary, Cloudflare AccessZero-trust access
ngrok, cloudflared, webhooksReverse tunnels
kubectl port-forward, subnet router into a clusterKubernetes access
MTU clamping, keepalive vs conntrackTunnels and observability
Keys, rotation, exposed -R portsSecurity considerations
Real commands and outputsMechanics, Lab
Go and Laravel codeSolving the classic problems, Laravel
Symptom to causeCommon failures

Everything in one minute ​

The picture. Every row is unpacked later.

ThingIn plain wordsTiny exampleTrust model
TunnelOne protocol carried inside anotherIP packets inside UDP; TCP streams inside SSHNone by itself: encryption is a separate feature
SSH local forward -LOpen a port on my machine that leads to a host the bastion can reachssh -L 5433:db:5432 bastion, then psql -h 127.0.0.1 -p 5433SSH key or certificate for one server
SSH remote forward -ROpen a port on the server that leads back to my machinessh -R 9000:localhost:8080 demoSSH login; the exposed port is as public as the server's bind address
SSH dynamic forward -DA SOCKS proxy that sends everything through the serverssh -D 1080 bastion, browser uses SOCKS5 127.0.0.1:1080SSH login
Jump host -JReach host B by SSH through host A without a shell on Assh -J bastion app-1SSH login to both; keys stay on the laptop
BastionThe one hardened SSH entry point into a private networkPublic IP, port 22, forwarding only, loggedShort-lived certificates, MFA
WireGuardA fast, small, kernel VPN built on public keyswg-quick up wg0; peers identified by 32-byte keysKey pair per peer, AllowedIPs per key
Mesh VPNWireGuard between every pair of devices, coordinated centrallyTailscale, Netbird, HeadscaleIdentity provider plus ACL policy
OpenVPN / IPsecThe older, widely deployed VPNsAWS Client VPN (OpenVPN-based), AWS Site-to-Site (IPsec, IKEv2)Certificates, SSO, pre-shared keys
Site-to-site VPNJoin two networks; hosts need no clientOffice router to a VPC gatewayGateway keys; the whole subnet is trusted
Client VPNJoin one device to a networkLaptop to the officeUser and device credentials
Zero-trust accessNo network at all: each request is authenticated and authorized for one appCloudflare Access, Teleport, Boundary, BeyondCorpIdentity, device posture, policy per request
Reverse tunnelThe private side dials out; the public side forwards incloudflared, ngrok, ssh -RVendor edge or your server

The three forwards, in one sentence each.

FlagListener is onDial is made fromTypical use
-L [bind:]port:host:hostportThe ssh client machineThe ssh serverReach a private database, cache or admin UI
-R [bind:]port:host:hostportThe ssh serverThe ssh client machineShow a local dev server to a colleague or a webhook sender
-D [bind:]portThe ssh client machine (SOCKS5)The ssh server, to whatever the SOCKS client asks forBrowse a private network through a bastion

Six symptoms and where to look first.

SymptomFirst suspect
WireGuard handshake never completes (latest handshake missing)UDP blocked, wrong Endpoint, wrong public key
Handshake fine, no trafficAllowedIPs, routes, IP forwarding, MTU
Works, then dies after minutes of idleNAT/conntrack timeout, no keepalive
Internal names do not resolveSplit DNS not configured
Tunnel is up but the database refusesBind address, security group, AllowTcpForwarding, wrong target
ssh -L listener exists but connections resetThe far end is wrong; the tunnel only reports it per connection

What a tunnel is ​

Encapsulation, TUN and TAP Must-know ​

In plain words: A tunnel puts a whole packet (or a whole byte stream) into the payload of another one, ships it across a network that only understands the outer one, and takes it out at the other end. A VPN is a tunnel plus encryption plus a way to decide who may use it.

Common misunderstanding: "A VPN makes my traffic anonymous and my laptop safe." It moves where your traffic enters the internet and encrypts the part between your device and the VPN endpoint. Everything after the endpoint is as exposed as before, and a laptop that joins a flat network brings its malware along.

Definition: Encapsulation is the step from network models applied recursively: the inner packet (with its own IP header) becomes the data of an outer protocol. WireGuard wraps IP packets in UDP; IPsec ESP wraps them in IP protocol 50 (or in UDP port 4500 for NAT traversal, RFC 3948); OpenVPN wraps them in TLS-protected UDP or TCP; SSH forwarding does not wrap packets at all, it relays TCP byte streams inside encrypted channels. On Linux a VPN presents itself to applications as a virtual network interface:

Device typeLayerWhat the application seesUsed by
TUN (tun0, wg0)3An IP interface; only IP packets, routedWireGuard, OpenVPN (dev tun), IPsec VTIs, ssh -w point-to-point, Tailscale
TAP (tap0)2An Ethernet interface; frames, ARP, broadcastOpenVPN (dev tap), ssh -w in ethernet mode (PermitTunnel ethernet), bridges between sites

Layer 3 is what you want almost always: routed, no broadcast storms, easy to firewall. Layer 2 is for the rare case of bridging a legacy protocol across a site link.

1  app writes to 10.200.0.2:5432           -> kernel looks up the route: dev wg0
2  wg0 receives the IP packet (84 bytes for a ping)
3  WireGuard encrypts it for the peer owning 10.200.0.2   -> 96 B padded + 16 B tag
4  prepends its 16-byte header, sends as UDP to the peer's endpoint
5  outer IP + UDP + WireGuard + encrypted inner = 156 bytes on eth0
6  peer decrypts, checks the source against AllowedIPs, hands the inner packet to ITS wg0
One ping through wg0 as it appears on eth0 (captured with tcpdump, 84-byte inner packet)Outer IPv420 B (UDP)UDP8 B 51820WireGuard header 16 Btype | receiver | counterEncrypted inner packet84 B padded to 96 (multiple of 16)Poly1305 tag16 BUDP payload = 16 + 96 + 16 = 128 bytes (tcpdump: "UDP, length 128")on the wire = 20 + 8 + 128 = 156 bytes for an 84-byte pingOverhead rule for the tunnel MTUIPv4 underlay: 20 + 8 + 16 + 16 = 60 bytes, so wg0 MTU = underlay MTU - 60 (1500 gives 1440).IPv6 underlay: 40 + 8 + 16 + 16 = 80 bytes, so 1500 gives 1420: the default wg-quick picks to be safe for both.Any other link in the path (PPPoE 1492, a second tunnel, a cloud overlay at 1450) lowers the number again.

Real scenarios: a laptop reaching a private subnet; two offices sharing an address plan; a server exposing a port from behind CGNAT by dialling out; a Kubernetes node reaching a database in another cloud.

ProductTunnel it createsDevice
WireGuardUDP, one port, layer 3wg0 (kernel module since Linux 5.6; wireguard-go elsewhere)
OpenVPNUDP or TCP, TLS control channeltun0 or tap0
IPsec (strongSwan, AWS, Cisco)ESP (protocol 50) or UDP 4500Kernel XFRM policy or a VTI interface
Tailscale / Netbird / HeadscaleWireGuard plus coordinationtailscale0 / wt0
OpenSSH -L/-R/-DChannels in one TCP connectionNone: a userspace listener
OpenSSH -wA real tun/tap pair (needs PermitTunnel)tun0 on both ends

Overhead and MTU Must-know ​

In plain words: The wrapping costs bytes. A 1500-byte Ethernet frame has only 1440 bytes left for the inner packet once WireGuard adds its 60. If the inner packet is bigger than the tunnel's MTU, something has to split it or drop it.

Common misunderstanding: "The VPN is slow, it must be bandwidth." A wrong MTU makes small requests work and large ones hang forever: logins succeed, git push or a big API response stalls. That is a black hole, not slowness.

Definition: The tunnel interface's MTU must be at most the physical path's MTU minus the encapsulation overhead. WireGuard adds an outer IP header (20 bytes IPv4, 40 IPv6), UDP (8), its own header (16) and an authentication tag (16): 60 bytes over IPv4, 80 over IPv6. wg-quick uses 1420, which is safe even over IPv6 on a 1500 link. When a packet is larger than the path allows and the Don't Fragment bit is set (TCP does this), a router must answer ICMP "fragmentation needed"; if a firewall eats that ICMP, the sender never learns and retransmits the same oversized packet forever (Path MTU Discovery black hole). AWS says so for its own VPN: "An Site-to-Site VPN connection does not support Path MTU Discovery."

Underlay MTU            1500   1492 (PPPoE)   1450 (some cloud overlays)   1280 (IPv6 minimum)
WireGuard over IPv4     1440   1432           1390                         1220
WireGuard over IPv6     1420   1412           1370                         1200
wg-quick default        1420 (safe everywhere that starts at 1500)

Real measurement from the lab (below): with the underlay squeezed to 1280 and the tunnel left at 1420, a middlebox that drops IP fragments made ping -s 56 work and ping -s 1300 lose 100 percent; setting ip link set dev wg0 mtu 1220 on both ends fixed it, and the largest ping with the DF bit that still passed was 1192 payload bytes (1220 on the wire); one byte more gave ping: local error: message too long, mtu=1220.

FixHowWhere
Lower the tunnel MTUMTU = 1380 in wg0.conf, ip link set dev wg0 mtu 1380Both ends
Clamp TCP MSSiptables -t mangle -A FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtuThe gateway that forwards tunnel traffic
Allow ICMP type 3 code 4Security groups and firewalls must pass "fragmentation needed"Every device on the path
Avoid tunnels in tunnelsDo not run a VPN inside another VPN without subtracting both overheadsDesign

Why tunnels and VPNs exist ​

Private networks (see IP addressing) are not reachable from the internet, and that is a feature: a database on 10.0.2.30 cannot be scanned. But people and programs still need to reach it. Three answers exist, and the rest of the chapter is their trade-offs.

AnswerWhat you exposeWhat it costs
Open the port to the internetThe service itself, to every scannerConstant attack surface; credentials are the only defence
Put a door in front: bastion, VPN gatewayOne hardened door (SSH 22 or UDP 51820)The door must be run, patched, audited; after it, the network is flat
Dial out from the inside: reverse tunnel, zero-trust connectorNothing inbound at allA relay or vendor in the path; policy lives in their plane
Weaker, simplerStronger, more work
ssh -L from a laptop, no infrastructureMesh VPN with ACLs and an identity provider
One flat VPN: if you are in, you can reach everythingPer-app access with device posture and per-request policy
Long-lived SSH keys on laptopsCertificates valid for an hour, issued after SSO and MFA
Static AllowedIPs and hand-edited configsCoordination server that distributes keys and routes

An everyday picture. A gated community. The internet is the public road; the private subnet is the houses. A bastion is the single guarded gate with a visitor log. A VPN gives you a resident's badge: once through, you can try every door. Zero-trust access is a concierge who checks who you are for each apartment you ask about. A reverse tunnel is a resident who stays on the phone with the front desk so the desk can forward your call without ever opening the gate.

Three common misunderstandings, up front.

  1. "A tunnel is a VPN." A tunnel only encapsulates. ssh -L is a tunnel for one TCP port; a VPN gives you a whole network interface with routes.
  2. "WireGuard is a connection." It has no connection state the application can see. It is a table of keys and allowed addresses; the handshake happens on demand and wg show only prints the latest one.
  3. "Zero trust replaces the VPN." Zero-trust access changes what is exposed (an app, not a network); many deployments still use WireGuard or a tunnel underneath it.

Where it comes from ​

YearEventWhy it matters
1995SSH is created by Tatu Ylönen after a password-sniffing incident (secondary source, not fetched; the OpenSSH manuals below are the primary reference for behaviour)Encrypted logins replaced telnet and rlogin; TCP port forwarding became a standard SSH feature (RFC 4254 section 7 defines the channel types)
Nov 1998RFC 2401, "Security Architecture for the Internet Protocol"The first IPsec architecture; IKE for key exchange came alongside
Jan 2005RFC 3948, UDP Encapsulation of IPsec ESP PacketsNAT traversal for IPsec: ESP inside UDP port 4500
Oct 2014RFC 7296, IKEv2, an Internet StandardSimpler, faster re-keying, mobility; what AWS Site-to-Site VPN speaks
Dec 2014Ward and Beyer, "BeyondCorp: A New Approach to Enterprise Security" (USENIX ;login:): "We are removing the requirement for a privileged intranet and moving our corporate applications to the Internet."The start of zero-trust access as an architecture
2017WireGuard whitepaper (appeared at NDSS 2017): Noise IK, Curve25519, ChaCha20-Poly1305, BLAKE2sA small, kernel-resident VPN whose design goal is "more secure, more performant, and easier to use" than IPsec and OpenVPN
Linux 5.6WireGuard in the mainline kernel (wireguard.com: "Users of kernels < 5.6 may also choose wireguard-lts or wireguard-dkms")ip link add wg0 type wireguard works out of the box
2020sTailscale, Netbird, Headscale: WireGuard meshes with a coordination plane and relays (DERP)VPNs stop being gateways and become overlays

OpenSSH ships the manual pages that define everything in the SSH half of this chapter; the quotes below come from ssh(1), ssh_config(5) and sshd_config(5) as published at man.openbsd.org. The WireGuard half rests on the whitepaper, the protocol page and wg(8)/wg-quick(8). Both are cited under References with the saved text.

The concept catalogue ​

SSH first, because every developer already has it. Everything in this half was run against a bastion container (OpenSSH 9.7 on Alpine, reached through 127.0.0.1:2222) in front of a Postgres container and an nginx container on an internal Docker network with no route to the internet; the client was the macOS OpenSSH 10.3. The outputs are real.

-L local forward: the listener is on YOUR side, the dial happens on the bastionLaptoppsql -h 127.0.0.1 -p 5433listens on 127.0.0.1:5433Bastionsshd opens a direct-tcpipchannel, dials the targetPostgres10.0.2.30:5432private, no public IPone SSH TCPplain TCP-R remote forward: the listener is on the BASTION, the dial happens on your laptopLaptopGo dev server127.0.0.1:8080Bastionlistens on :9000loopback by defaultViewer / sendercolleague, webhook,demo audienceGET :9000forwarded-tcpip-D dynamic forward: a SOCKS5 proxy on your side, the bastion dials whatever the client asks forBrowser / curlSOCKS5 127.0.0.1:1080(ssh is the proxy)Bastiondials host:port from theSOCKS request + DNSAnything privategrafana.internal:300010.0.2.40:80, 10.0.2.30one SSH TCPany dest.What to rememberThe thick arrow is ONE encrypted TCP connection to port 22; every forwarded connection is a channel inside it.The host in -L host:port is looked up and dialled BY THE BASTION, so "localhost" there means the bastion itself.-J and -W reuse the same channel type: the next ssh connection simply runs inside it.

SSH local forward (-L) Must-know ​

In plain words: "Open a port on my laptop; whatever connects to it, the server connects onward to this other address for me." The laptop gets a door that leads to a private database.

Common misunderstanding: "-L 5433:db.internal:5432 means db.internal is resolved on my laptop." The host part is resolved and dialled by the SSH server. If you write localhost there, you mean the bastion itself, not your laptop; and the name db.internal does not have to exist on your machine at all.

Definition: ssh -L [bind_address:]port:host:hostport makes ssh listen on bind_address:port locally (loopback by default) and, for every accepted connection, open a direct-tcpip channel to the server asking it to connect to host:hostport (RFC 4254 section 7.2). The man page says: "Specifies that connections to the given TCP port or Unix socket on the local (client) host are to be forwarded to the given host and port, or Unix socket, on the remote side." A Unix socket form exists too (-L 5433:/var/run/postgresql/.s.PGSQL.5432).

1  laptop: ssh -fN -L 127.0.0.1:5433:10.141.0.30:5432 bastion      -> ssh listens on 127.0.0.1:5433
2  psql connects to 127.0.0.1:5433                                  -> TCP accept inside ssh
3  ssh sends "direct-tcpip 10.141.0.30:5432" over the SSH connection
4  bastion sshd connects to 10.141.0.30:5432                        -> the DATABASE sees the bastion's address
5  bytes flow both ways inside one encrypted TCP connection (port 22)

Real run (-f backgrounds ssh after authentication, -N means no remote command):

$ nc -zv -w 2 127.0.0.1 5433            # before the tunnel
nc: connectx to 127.0.0.1 port 5433 (tcp) failed: Connection refused
$ ssh -F ssh_config_lab -fN -L 127.0.0.1:5433:10.141.0.30:5432 bastion
$ lsof -nP -iTCP:5433 -sTCP:LISTEN
COMMAND  PID  NODE NAME
ssh     30710  TCP 127.0.0.1:5433 (LISTEN)
$ # PostgreSQL SSLRequest: 00 00 00 08 | 04 d2 16 2f  (length 8, code 80877103)
SSLRequest 00 00 00 08 04 d2 16 2f -> reply byte: b'N'

The byte N is PostgreSQL saying "no TLS here" (S would mean TLS is available): a Postgres server answered through the tunnel. Note what the database sees: connections come from the bastion's address, not yours, so pg_hba.conf and security groups must allow the bastion, and per-user audit must happen on the bastion.

Real scenarios: psql/DBeaver/Laravel against a private RDS or Cloud SQL; Redis or Grafana admin UIs; Elasticsearch on a private subnet; reaching a Kubernetes API server that has no public endpoint.

OptionMeaning
-NDo not run a remote command; just forward
-fGo to the background after authentication (but forwards fail silently without ExitOnForwardFailure)
-o ExitOnForwardFailure=yesExit if the local port is taken instead of "connecting" without a forward
-L 0.0.0.0:5433:... or GatewayPorts yes (client)Listen on all interfaces: anyone on your LAN now has the database. Almost always a mistake
LocalForward in ~/.ssh/configSame, written once per host
-L 5433:/path/to/.s.PGSQL.5432Forward to a Unix-domain socket on the server

The first failure everyone meets is not in the client at all. On the Alpine image sshd_config ships AllowTcpForwarding no on line 90 (first match wins, so a later yes is ignored). ssh connects, the local port listens, and every connection dies:

$ nc -v 127.0.0.1 5433 < /dev/null
Connection to 127.0.0.1 port 5433 [tcp/pyrrho] succeeded!        # the LOCAL listener accepts
--- ssh client stderr:
channel 1: open failed: administratively prohibited: open failed   # the SERVER refuses the channel
$ sshd -T | grep -i allowtcp            # on the bastion
allowtcpforwarding no

sshd_config(5), on AllowTcpForwarding: "Specifies whether TCP forwarding is permitted. The available options are yes (the default) or all to allow TCP forwarding, no to prevent all TCP forwarding, local to allow local (from the perspective of ssh(1)) forwarding only or remote to allow remote forwarding only."

SSH remote forward (-R) Must-know ​

In plain words: "Open a port on the server; whatever connects to it gets carried back to a service on my laptop." The reverse of -L: you publish something that lives on your machine.

Common misunderstanding: "-R 0.0.0.0:9000:localhost:8080 makes my dev server public." Only if the server allows it. The server forces loopback unless GatewayPorts is set, and silently downgrades your request when it is not. The man page: "By default, TCP listening sockets on the server will be bound to the loopback interface only. This may be overridden by specifying a bind_address. ... Specifying a remote bind_address will only succeed if the server's GatewayPorts option is enabled."

Definition: ssh -R [bind_address:]port:host:hostport sends a tcpip-forward global request; the server listens, and for every connection opens a forwarded-tcpip channel back to the client, which dials host:hostport from the laptop. With -R port only (no destination) the client acts as a SOCKS proxy for the remote side. sshd_config(5): "GatewayPorts ... By default, sshd(8) binds remote port forwardings to the loopback address. This prevents other remote hosts from connecting to forwarded ports." Values: no (default), yes (always wildcard), clientspecified (the client's bind_address decides).

1  laptop: ssh -fN -R 9000:127.0.0.1:8080 bastion          -> bastion listens on 9000
2  colleague: curl http://bastion:9000/                    (only works if bound to 0.0.0.0)
3  sshd opens "forwarded-tcpip" back to the laptop         -> over the SAME SSH connection
4  laptop ssh dials 127.0.0.1:8080, relays the bytes

Real run, with python3 -m http.server 8080 on the laptop and a second container on the same Docker network standing in for the colleague:

$ ssh -F ssh_config_lab -fN -R 9000:127.0.0.1:8080 bastion
$ netstat -ltn | grep :9000                  # on the bastion, GatewayPorts no
tcp   0   0 127.0.0.1:9000   0.0.0.0:*   LISTEN
tcp   0   0 ::1:9000         :::*        LISTEN
$ curl -s http://127.0.0.1:9000/             # on the bastion
hello from the laptop dev server
$ curl -s --max-time 3 http://10.140.0.2:9000/    # from the other container
curl exit=7 (refused)

$ ssh -fN -R 0.0.0.0:9000:127.0.0.1:8080 bastion     # still GatewayPorts no: request silently downgraded
tcp   0   0 127.0.0.1:9000   0.0.0.0:*   LISTEN

# GatewayPorts clientspecified + the same -R 0.0.0.0:9000
tcp   0   0 0.0.0.0:9000     0.0.0.0:*   LISTEN
$ curl -s http://10.140.0.2:9000/            # from the other container
hello from the laptop dev server

If the remote port is already taken, plain ssh warns and carries on with no forward at all; ExitOnForwardFailure turns that into a failure you can supervise:

$ ssh -o LogLevel=INFO -N -R 9000:127.0.0.1:8080 bastion
Warning: remote port forwarding failed for listen port 9000          # ssh keeps running, useless
$ ssh -o LogLevel=INFO -o ExitOnForwardFailure=yes -N -R 9000:127.0.0.1:8080 bastion
Error: remote port forwarding failed for listen port 9000
exit=255

Real scenarios: showing a half-finished feature to a customer; receiving a webhook on a laptop (see reverse tunnels); letting a machine behind CGNAT be reached through a small VPS; a support engineer reverse-tunnelling a customer's device back to the office.

Exposure riskWhyMitigation
Port open to the worldGatewayPorts yes or clientspecified plus a wildcard bindKeep no; put a TLS reverse proxy with auth in front
Anyone can open any remote portDefault AllowTcpForwarding yesAllowTcpForwarding local for most users; PermitListen to pin allowed -R ports
A forgotten -RLong-lived ssh -fN processesTime-box with ControlPersist, timeout, or supervise; audit ss -ltn on the server

SSH dynamic forward (-D) Important ​

In plain words: ssh turns into a SOCKS proxy on your laptop. Point a browser or curl at it and every connection is made from the bastion, so you can open any private address without writing one -L per service.

Common misunderstanding: "A SOCKS proxy is a VPN." It proxies TCP connections from applications that speak SOCKS. Anything that does not (ping, UDP, many CLI tools, DNS lookups made before the proxy) bypasses it, and local DNS leaks the names you look up.

Definition: -D [bind_address:]port is "a local dynamic application-level port forwarding" speaking SOCKS4 and SOCKS5. Each SOCKS CONNECT becomes a direct-tcpip channel. The difference between socks5 and socks5h is who resolves the name: with curl --socks5-hostname the name travels to the bastion and is resolved there (so Docker's or the VPC's private DNS works); with curl --socks5 your laptop resolves it first.

$ ssh -F ssh_config_lab -fN -D 127.0.0.1:1080 bastion
$ curl -s --socks5-hostname 127.0.0.1:1080 -o /dev/null -w "%{http_code} via SOCKS5\n" http://10.141.0.40/
200 via SOCKS5
$ curl -s --max-time 3 -o /dev/null -w "%{http_code}\n" http://10.141.0.40/      # no proxy
000
$ curl -s --socks5-hostname 127.0.0.1:1080 -o /dev/null -w "%{http_code}\n" http://vpnlab-web/
200                                           # name resolved BY the bastion's Docker DNS
$ curl -s --max-time 5 --socks5 127.0.0.1:1080 -o /dev/null -w "%{http_code}\n" http://vpnlab-web/
000   (exit 28)                               # name looked up locally: not found, nothing proxied
ClientHow to use the SOCKS proxyDNS through the proxy?
curl--socks5-hostname host:portYes (--socks5 does not)
FirefoxNetwork settings: SOCKS v5, tick "Proxy DNS when using SOCKS v5"Only with that box ticked
Chrome--proxy-server="socks5://127.0.0.1:1080"Yes, remote DNS
ssh itself-o ProxyCommand="nc -X 5 -x 127.0.0.1:1080 %h %p"Remote
Gogolang.org/x/net/proxy SOCKS5 dialerRemote (proxy.SOCKS5 passes the name)

Jump hosts: -J, ProxyJump, ProxyCommand and -W Must-know ​

In plain words: To reach a server that only the bastion can see, ask ssh to hop through the bastion without ever logging in to it. Your key stays on your laptop and the bastion only relays encrypted bytes.

Common misunderstanding: "ssh bastion then ssh app is the same thing." It is not: that logs into the bastion (a shell, files, a place for an attacker to look) and typically needs agent forwarding to authenticate the second hop. -J makes the second SSH connection run inside a channel of the first, end to end, so the bastion never sees plaintext or your keys.

Definition: ssh(1): "Connect to the target host by first making an ssh connection to the jump host described by destination and then establishing a TCP forwarding to the ultimate destination from there. Multiple jump hops may be specified separated by comma characters." -J is shorthand for the ProxyJump directive, which is shorthand for ProxyCommand ssh -W %h:%p jump. -W host:port "requests that standard input and output on the client be forwarded to host on port over the secure channel": a netcat that runs over SSH.

$ ssh -F ssh_config_lab app hostname          # Host app / ProxyJump bastion in the config
bda52f481327
$ ssh -o ProxyCommand="ssh -F ssh_config_lab -W %h:%p bastion" dev@10.141.0.50 hostname
bda52f481327
$ printf 'GET / HTTP/1.0\r\nHost: x\r\n\r\n' | ssh -F ssh_config_lab -W 10.141.0.40:80 bastion | head -3
HTTP/1.1 200 OK
Server: nginx/1.31.10
Date: Wed, 25 Nov 2026 18:04:49 GMT

A trap straight from the manual: "configuration directives supplied on the command-line generally apply to the destination host and not any specified jump hosts. Use ~/.ssh/config to specify configuration for jump hosts." In the lab ssh -o StrictHostKeyChecking=no -J dev@127.0.0.1:2222 dev@10.141.0.50 failed with Host key verification failed. because the option reached only the destination; the same hop through ProxyCommand or a config Host block worked. Put jump-host settings (identity, certificate, known_hosts policy) in ~/.ssh/config.

FormWhen
ssh -J bastion appOne-off
Host app + ProxyJump bastionDaily use; also scp, rsync -e ssh, git over SSH, IDE remote
ProxyJump b1,b2Chained bastions (office, then cloud)
ProxyCommand ssh -W %h:%p bastionOld clients, or when the hop needs a special command (aws ssm start-session, cloudflared access ssh)
ssh -W host:port bastionRaw stdin/stdout pipe to one port (used inside ProxyCommand, or to test a port)

Multiplexing and keeping tunnels alive Important ​

In plain words: Opening an SSH connection costs a TCP handshake, key exchange and authentication. ControlMaster keeps one connection open and lets later ssh commands reuse it. Idle tunnels die when a NAT or firewall forgets them, so ask the other side something every few seconds.

Common misunderstanding: "-f keeps the tunnel up." -f only backgrounds ssh. If the network drops, ssh exits (or hangs half-dead for a long time) and nothing restarts it.

Definition: In ssh_config(5): ControlMaster auto opens a master or becomes a client of an existing one; ControlPath names the socket (%C is a hash of host, port and user); ControlPersist 10m keeps the master after the last client exits. Control commands: ssh -O check|forward|cancel|exit host. On loopback the effect is small and still visible:

ssh #1 (multiplexed) real 0.10          # master created
ssh #2 (multiplexed) real 0.00
ssh #3 (multiplexed) real 0.00
$ ssh -O check bastion
Master running (pid=39040)
ssh #1 (fresh)       real 0.09          # no master: full handshake every time
$ ssh -O forward -L 127.0.0.1:5435:10.141.0.30:5432 bastion      # add a forward to the RUNNING master
Connection to 127.0.0.1 port 5435 [tcp/dttl] succeeded!

Across an ocean the 0.09 s becomes 0.5 to 1 s per command, which is why git, rsync and Ansible love ControlMaster.

Keepalives, from ssh_config(5) on ServerAliveInterval: "Sets a timeout interval in seconds after which if no data has been received from the server, ssh(1) will send a message through the encrypted channel to request a response from the server. The default is 0, indicating that these messages will not be sent to the server." With ServerAliveInterval 15 and the default ServerAliveCountMax 3, a dead server is detected "after approximately 45 seconds". The server-side twin is ClientAliveInterval / ClientAliveCountMax in sshd_config. TCP keepalive (TCPKeepAlive) is the kernel's, much slower, and is not encrypted.

ToolWhat it does
autossh -M 0 -f -N -L ... hostRuns ssh, restarts it when it exits; -M 0 relies on ServerAliveInterval instead of a monitor port
systemd unit with Restart=always and ExitOnForwardFailure=yesThe modern supervisor; no extra tool
ssh -O exitClose a ControlMaster cleanly
Go forwarder belowThe same loop in code, with reconnect and backoff

Agent forwarding and its risks Important ​

In plain words: ssh -A lets the server use your laptop's ssh-agent to log in to the next machine, so you do not copy your private key to the bastion. The key never leaves the laptop, but the server gets a live line to it.

Common misunderstanding: "The key cannot be stolen, so agent forwarding is safe." ssh_config(5): "Agent forwarding should be enabled with caution. Users with the ability to bypass file permissions on the remote host (for the agent's Unix-domain socket) can access the local agent through the forwarded connection. An attacker cannot obtain key material from the agent, however they can perform operations on the keys that enable them to authenticate using the identities loaded into the agent." Root on the bastion can log in as you everywhere your key works, while your session is open.

Real run: the laptop agent holds the lab key; connect with -A, then act as root on the bastion:

$ ssh -F ssh_config_lab -A bastion 'echo "SSH_AUTH_SOCK=$SSH_AUTH_SOCK"; ssh-add -l'
SSH_AUTH_SOCK=/tmp/ssh-XXXXEimbLi/agent.384
256 SHA256:nSRtserPgcpEXKruDZCDUxobGdVLxWODBn+zgo5BiyM vpnlab (ED25519)
# while that session is open, ROOT on the bastion:
socket: /tmp/ssh-XXXXBboIPl/agent.391
256 SHA256:nSRtserPgcpEXKruDZCDUxobGdVLxWODBn+zgo5BiyM vpnlab (ED25519)
$ ssh -o StrictHostKeyChecking=no dev@10.141.0.50 id -un      # root signs a login with YOUR key
dev
# the alternative needs no agent on the bastion at all:
$ ssh -F ssh_config_lab app 'echo "SSH_AUTH_SOCK=[$SSH_AUTH_SOCK]"; id -un'
SSH_AUTH_SOCK=[]
dev
NeedUse instead of -A
Reach a host behind the bastionProxyJump (the key stays local)
Clone from GitHub on a serverDeploy keys, or a short-lived token
Must forward an agentssh-add -c (confirm each use), a hardware key (ed25519-sk), a dedicated agent with only that key, and ForwardAgent only for named hosts, never Host *
Server-side defenceAllowAgentForwarding no on the bastion

Bastion hosts Must-know ​

In plain words: A bastion (jump host) is one small, hardened server with a public address whose only job is to let authorised people reach the private network. Everything else has no public address.

Common misunderstanding: "A bastion is a firewall." It is a door, not a wall. If it is breached, the attacker is inside; so it should run nothing else, give nobody a shell, log everything and be easy to rebuild.

Definition: The pattern: a public subnet host with SSH (or WireGuard, or a zero-trust connector), security groups that allow it to reach private subnets on specific ports and private hosts to accept SSH only from it. Why not SSH straight to production? A public SSH port on every server is the largest and noisiest attack surface; credentials are scattered; there is no single place to log, rate-limit, or revoke.

ControlSettingWhy
AuthPublic keys or certificates only: PasswordAuthentication noPasswords are guessable
Short-lived certificatesTrustedUserCAKeys + AuthorizedPrincipalsFile; certificates valid for minutes to hoursA stolen laptop key expires on its own; no authorized_keys sprawl
No shellPermitTTY no, ForceCommand /bin/false for tunnel-only usersForwarding without a foothold
Narrow forwardingAllowTcpForwarding local, PermitOpen host:port ...A user can reach the database, not the whole VPC; no -R
No agentAllowAgentForwarding noSee above
LoggingLogLevel VERBOSE (key fingerprint or certificate ID per login) plus shipped logs; or session recording with Teleport or BoundaryYou can answer "who connected to what"
KeepaliveClientAliveInterval 30, ClientAliveCountMax 3Dead sessions are reaped
NetworkSecurity group: 22 only from known egress ranges; private hosts accept 22 only from the bastion's groupDefence in depth

Real run of the certificate path: a key that is not in authorized_keys, signed by a CA the bastion trusts, valid for a few minutes:

$ ssh-keygen -s ca -I morteza@laptop -n dev -V +5m id_cert.pub
$ ssh-keygen -L -f id_cert-cert.pub
        Type: ssh-ed25519-cert-v01@openssh.com user certificate
        Signing CA: ED25519 SHA256:NIPAqJIXkl7kh6h9jFe03U7MW8QrHwCcN7AoZFscL0o (using ssh-ed25519)
        Key ID: "morteza@laptop"
        Valid: from 2026-11-25T21:35:00 to 2026-11-25T21:41:42
        Principals: dev
$ ssh -i id_cert dev@127.0.0.1 'id -un'                            # certificate present
dev
$ ssh -i id_cert -o CertificateFile=/dev/null dev@127.0.0.1 id -un # same key, no certificate
dev@127.0.0.1: Permission denied (publickey,keyboard-interactive).
$ ssh-keygen -s ca -I morteza@laptop -n dev -V -10m:-5m id_cert.pub   # an expired certificate
dev@127.0.0.1: Permission denied (publickey,keyboard-interactive).

A hardened server configuration and a client configuration (ProxyJump, ControlMaster, ServerAliveInterval, certificates). The lab bastion was a stock Alpine sshd with forwarding enabled, so these two files were not used there; both were parsed instead (sshd -t -f ... -h hostkey exits 0 and ssh -G -F ... db.internal resolves proxyjump bastion, user deploy). Trailing comments are placed on their own lines because older OpenSSH versions do not accept them after a directive:

ini
# /etc/ssh/sshd_config.d/10-bastion.conf : a hardened jump host.
# Keys are CA-signed and short-lived; nobody gets a shell, only forwarding to what they need.

PasswordAuthentication no
KbdInteractiveAuthentication no
PermitRootLogin no
PubkeyAuthentication yes
# accept certificates signed by our CA
TrustedUserCAKeys /etc/ssh/user_ca.pub
# which certificate principals may log in as %u
AuthorizedPrincipalsFile /etc/ssh/principals/%u
MaxAuthTries 3
LoginGraceTime 20

# ProxyJump does not need it
AllowAgentForwarding no
X11Forwarding no
# no tun/tap devices over SSH
PermitTunnel no
# -R binds loopback only
GatewayPorts no
# no interactive shell on the bastion at all
PermitTTY no
ClientAliveInterval 30
ClientAliveCountMax 3

# logs the key fingerprint / certificate ID per login
LogLevel VERBOSE

Match Group tunnelusers
  # -L, -D and -J only; no -R
  AllowTcpForwarding local
  # host:port only, no CIDR
  PermitOpen db.internal:5432 cache.internal:6379 app-1.internal:22 app-2.internal:22
  ForceCommand /bin/false
ini
# ~/.ssh/config : one place for everything the command line would otherwise repeat.

Host *
  # ask the server every 30 s; counts as traffic for NAT and firewalls
  ServerAliveInterval 30
  # give up after 3 unanswered asks (~90 s)
  ServerAliveCountMax 3
  # share one TCP+auth handshake between sessions
  ControlMaster auto
  # %C = hash of host, port, user: short and unique
  ControlPath ~/.ssh/cm-%C
  # keep the master alive 10 minutes after the last session
  ControlPersist 10m
  # offer only the key named below, not every key in the agent
  IdentitiesOnly yes
  # the default, written down so nobody "just turns it on"
  ForwardAgent no

Host bastion
  HostName bastion.example.com
  User morteza
  IdentityFile ~/.ssh/id_ed25519
  # short-lived, from your CA / identity provider
  CertificateFile ~/.ssh/id_ed25519-cert.pub
  # Always-on forwards for development; they exist only while the master is alive.
  LocalForward 127.0.0.1:5433 db.internal:5432
  LocalForward 127.0.0.1:6380 cache.internal:6379
  ExitOnForwardFailure yes

# Every host in 10.0.0.0/8 is reached THROUGH the bastion: no agent forwarding, the key stays on the laptop.
Host 10.*.*.* *.internal
  ProxyJump bastion
  User deploy
  IdentityFile ~/.ssh/id_ed25519
  CertificateFile ~/.ssh/id_ed25519-cert.pub

# Browser profile that goes through the bastion:   ssh -D 1080 -N bastion   then SOCKS5 127.0.0.1:1080
Product / approachWhat it adds over a plain bastion
OpenSSH + CA (ssh-keygen -s)Short-lived certificates, principals, no key distribution
TeleportCertificate authority, SSO, recorded sessions, RBAC, access requests; proxies SSH, databases, Kubernetes, web apps
HashiCorp Boundary"identity-based access management ... without requiring users to access the underlying network directly"; session recording; dynamic credentials from Vault
Cloudflare Tunnel + Access for SSHNo inbound port at all; identity check at the edge
AWS SSM Session Manager / EC2 Instance ConnectCloud-native alternatives (vendor docs, not fetched for this chapter)

WireGuard in depth Must-know ​

In plain words: Each machine has a key pair and a short list of other machines' public keys. For each peer you say which IP addresses live behind it. WireGuard then behaves like a network cable that is plugged in whenever there is traffic.

Common misunderstanding: "WireGuard has client and server modes." It has none. Every device is a peer; "server" only means "the peer with a stable Endpoint that others dial". Either side can send first once the other's public key and address are known.

Definition: WireGuard is a layer 3 tunnel. The protocol page lists the primitives: one per line ("ChaCha20 for symmetric encryption, authenticated with Poly1305, using RFC7539's AEAD construction", "Curve25519 for ECDH", "BLAKE2s for hashing and keyed hashing", "SipHash24 for hashtable keys", "HKDF for key derivation"), and says "WireGuard uses the Noise_IK handshake from Noise ... All packets are sent over UDP." There is no cipher negotiation: no downgrade attacks, no TLS-style cipher-suite zoo (see cryptography fundamentals for ChaCha20-Poly1305 and X25519). A peer is identified by its 32-byte Curve25519 public key, which is also its identity: no certificates, no CA, in the style of authorized_keys.

1  a: wg genkey | tee priv | wg pubkey > pub          (32 random bytes, clamped; base64)
2  a and b exchange PUBLIC keys out of band (and optionally a preshared key)
3  first packet for 10.200.0.2: initiator sends handshake initiation (type 1, 148 B)
4  responder answers handshake response (type 2, 92 B)         -> 1 round trip, both authenticated
5  keys derived; data flows as transport messages (type 4); an empty one is a keepalive (32 B)
6  after 120 s or 2^60 messages the initiator re-handshakes; sessions are dropped after 180 s of nothing

The message sizes from a real capture on the lab link (tcpdump -ni eth0 udp port 51820, wg-quick down; up on one side, then one ping):

+078ms 10.140.0.10 > 10.140.0.20: UDP, length 148     # handshake initiation  (type 1)
+079ms 10.140.0.20 > 10.140.0.10: UDP, length 92      # handshake response    (type 2)
+079ms 10.140.0.10 > 10.140.0.20: UDP, length 32      # first transport message: empty = keepalive
+079ms 10.140.0.10 > 10.140.0.20: UDP, length 128     # the ping (84 B inner + padding + tag)
+080ms 10.140.0.20 > 10.140.0.10: UDP, length 128     # the reply

The first 16 bytes of the 128-byte ping packet, from the hex dump of that capture (tcpdump -X), start right after the UDP header:

04 00 00 00          message type 4 (transport data) + 3 reserved zero bytes
36 b5 11 05          receiver index (which session this belongs to)
04 00 00 00 00 00 00 00    64-bit little-endian counter = 4 (nonce and replay protection)
e4 b1 9c ef c4 72 ...      ChaCha20-Poly1305 ciphertext of the inner IP packet, then a 16-byte tag

Timers (whitepaper section 6): Rekey-After-Time 120 s, Reject-After-Time 180 s, Rekey-Timeout 5 s, Keepalive-Timeout 10 s, Rekey-After-Messages 2^60, Reject-After-Messages 2^64 minus 2^13. Session keys rotate every two minutes of use, which is what gives forward secrecy without any state the user manages. A peer that does not know your key does not answer at all: the whitepaper's design goal is "allocating no resources in response to received packets", so a port scan of a WireGuard host sees silence.

CommandWhat it does
wg genkey, wg pubkey, wg genpskMake a private key, derive the public key, make a preshared key (post-quantum hedge, "mixed into the already existing public-key cryptography")
wg-quick up wg0 / downReads /etc/wireguard/wg0.conf, creates the interface, assigns addresses, sets MTU, installs routes from AllowedIPs, runs PostUp/PostDown
wg show, wg show wg0 dumpInterface and per-peer state: endpoint, allowed ips, latest handshake, transfer counters
wg set wg0 peer KEY allowed-ips ...Change a running interface; does NOT touch routes (only wg-quick does)
wg syncconf wg0 <(wg-quick strip wg0)Apply a changed config without taking the interface down
ip link add wg0 type wireguardWhat wg-quick does first; works because the module is in the kernel

The configuration used in the lab (two containers, kernel 7.0.14-linuxkit, wireguard-tools v1.0.20210914), with the keys generated by wg genkey and the config files shaped as wg-quick expects:

[Interface]
Address = 10.200.0.1/24
ListenPort = 51820
PrivateKey = <a's private key>

[Peer]
PublicKey = sLsnQYYG7siO70O4BVxUXD57AMR2Wqy0rxXiWz4Gqm4=
AllowedIPs = 10.200.0.2/32
Endpoint = 10.140.0.20:51820
PersistentKeepalive = 25
$ wg-quick up wg0
[#] ip link add wg0 type wireguard
[#] wg setconf wg0 /dev/fd/63
[#] ip -4 address add 10.200.0.1/24 dev wg0
[#] ip link set mtu 1420 up dev wg0
$ wg show
interface: wg0
  public key: 1aZklq+fWY8bbSyp0Iu249VYNFSUdU+ns2ResGy3qxc=
  private key: (hidden)
  listening port: 51820

peer: sLsnQYYG7siO70O4BVxUXD57AMR2Wqy0rxXiWz4Gqm4=
  endpoint: 10.140.0.20:51820
  allowed ips: 10.200.0.2/32
  latest handshake: 7 seconds ago
  transfer: 476 B received, 712 B sent
  persistent keepalive: every 25 seconds
$ ip route
10.140.0.0/24 dev eth0 proto kernel scope link src 10.140.0.10
10.200.0.0/24 dev wg0 proto kernel scope link src 10.200.0.1
$ ping -c 3 10.200.0.2
64 bytes from 10.200.0.2: icmp_seq=1 ttl=64 time=0.254 ms

How to read wg show: no latest handshake line means no valid handshake has ever completed (keys, endpoint, UDP path); transfer: X received, Y sent where received is zero and sent grows means packets leave but nothing authenticated comes back; both growing means healthy. A handshake older than about three minutes while traffic is flowing is abnormal; with no traffic it is normal (WireGuard is silent when idle, except for keepalives).

Kernel vs userspace. On Linux the data path runs in the kernel (ip -d link show wg0 prints wireguard); that is why it reaches line rate with little CPU. Elsewhere (wg-quick on macOS, Windows, BSD) a userspace implementation, wireguard-go, does the same job through a TUN device ("Non-Linux users will instead write wireguard-go wg0", from the quick start). OpenVPN is userspace on every platform: each packet crosses the kernel/user boundary twice. The WireGuard project's own performance page warns "these benchmarks are old, crusty, and not super well conducted" while noting that WireGuard still edges out IPsec in some cases because of multi-threading and "OpenVPN remains extremely slow"; treat any single throughput number as a hint, and measure with iperf3 on your own hardware.

AspectWireGuardOpenVPNIPsec (IKEv2)
TransportUDP onlyUDP or TCP (443 to pass strict firewalls)ESP (protocol 50) or UDP 500/4500
Crypto agilityNone (fixed suite)TLS cipher suitesMany proposals, large configuration surface
IdentityPublic keyX.509 certificates, user/password, SSO pluginsCertificates, PSK, EAP
State the admin seesPeer table, last handshakeSessionsSecurity associations (SAs)
RoamingNative (endpoint follows the latest packet)ReconnectsMOBIKE (RFC 4555) in IKEv2 (not fetched here)
Typical useNew deployments, meshesLegacy and corporate clients, AWS Client VPNSite-to-site, built-in OS clients, AWS Site-to-Site

AllowedIPs: routing, access control and identity in one list Must-know ​

In plain words: AllowedIPs for a peer says: "packets for these addresses go to this peer, and this peer may only send me packets whose source address is in this list." One list, both directions.

Common misunderstanding: "AllowedIPs = 0.0.0.0/0 means allow everything through the firewall" or "it is a firewall allow-list of destinations I may visit". It is a routing table and a source-address filter keyed by public key. 0.0.0.0/0 means "send ALL traffic to this peer", which is a full tunnel.

Definition: The whitepaper calls it cryptokey routing: "The fundamental principle of a secure VPN is an association between peers and the IP addresses each is allowed to use as source IPs." Outgoing: "this table is consulted to determine which public key to use for encryption" (longest prefix match on the destination). Incoming: "after decrypting and authenticating it, it will only accept it if its source IP resolves in the table to the public key used in the secure session for decrypting it ... otherwise it is dropped." wg(8): "AllowedIPs — a comma-separated list of IP (v4 or v6) addresses with CIDR masks from which incoming traffic for this peer is allowed and to which outgoing traffic for this peer is directed." Two peers must not claim the same range; the most specific prefix wins, and a later assignment of the same prefix moves it to the new peer.

wg0 on the hub (10.200.0.1/24)cryptokey routing tablepeer A key aaaa...AllowedIPs 10.200.0.2/32peer B key bbbb... endpoint learnedAllowedIPs 10.200.0.3/32, 192.168.10.0/24peer C key cccc...AllowedIPs 10.200.0.4/32Peer A (laptop)roams between networksPeer B (office)owns 192.168.10.0/24Peer C (server)behind NAT, keepalive 25UDPSend pathpacket to 192.168.10.7longest AllowedIPs match= peer B: use B's key,send to B's endpointReceive pathdecrypts with B's key,inner source 10.200.0.9?not in B's AllowedIPs= dropped silently(no ICMP, no log)The same list does three jobs1. Routing: which peer gets a packet for this destination (wg-quick also turns the list into kernel routes).2. Access control: which source addresses a peer may use; a stolen key can only impersonate its own addresses.3. Identity: the public key IS the peer; its address, port and network may change at any packet (roaming).No connection, no session state to the application: "wg show" only reports the latest handshake and counters.

Real breakage in the lab, three ways. First the sender side: AllowedIPs for peer b changed to 10.200.0.99/32, so nothing is configured for 10.200.0.2:

$ wg set wg0 peer sLsn... allowed-ips 10.200.0.99/32
$ ip route get 10.200.0.2
10.200.0.2 dev wg0 src 10.200.0.1            # the kernel route (from Address /24) still points at wg0
$ ping -c 2 -W 1 10.200.0.2
ping: sendmsg: Required key not available    # no peer owns this destination: ENOKEY
From 10.200.0.1 icmp_seq=1 Destination Host Unreachable

Now the receiver side: b's entry for peer a is changed to 10.200.0.77/32, so a's packets (source 10.200.0.1) decrypt fine and are then dropped for a source mismatch. Nothing is logged and nothing comes back:

$ wg set wg0 peer 1aZk... allowed-ips 10.200.0.77/32      # on b
$ ping -c 2 -W 1 10.200.0.2                               # on a
2 packets transmitted, 0 received, 100% packet loss
$ wg show wg0 transfer                                    # on b
1aZklq+fWY8bbSyp0Iu249VYNFSUdU+ns2ResGy3qxc=    852    732   # received 852 and still growing: packets ARRIVE, then are dropped

Third: the setting a config generator should be careful with. Full tunnel: wg-quick up with AllowedIPs = 0.0.0.0/0 does not simply replace the default route. It marks WireGuard's own UDP packets with a firewall mark and uses policy routing, so the tunnel's outer packets do not loop into the tunnel (real output from the lab):

[#] wg set full fwmark 51820
[#] ip -4 route add 0.0.0.0/0 dev full table 51820
[#] ip -4 rule add not fwmark 51820 table 51820
[#] ip -4 rule add table main suppress_prefixlength 0
[#] sysctl -q net.ipv4.conf.all.src_valid_mark=1
sysctl: error setting key 'net.ipv4.conf.all.src_valid_mark': Read-only file system

The last line is the Docker trap: inside a container that sysctl is read-only and wg-quick rolls everything back. Start the container with --sysctl net.ipv4.conf.all.src_valid_mark=1.

PatternHub AllowedIPs for the spokeSpoke AllowedIPs for the hubResult
Hub and spoke (VPN to a private network)spoke's /32the tunnel subnet and the private subnetsSplit tunnel
Full tunnel (exit through the hub)spoke's /320.0.0.0/0, ::/0All traffic through the hub; hub must NAT
Site-to-sitethe site's /32 plus its LAN /24the other site's LANTwo networks joined
Mesh (each pair direct)other peer's /32other peer's /32Peer to peer, no transit
Hub relays spoke to spokespoke's /32the whole tunnel subnet /24Spokes reach each other through the hub (needs forwarding)

Sample hub and spoke files in the shape the Go generator below produces. The samples add PostUp forwarding rules and a DNS line, which the generator leaves to you, and the generator also writes MTU and a PresharedKey:

ini
# /etc/wireguard/wg0.conf on the hub (public IP 203.0.113.10). Generated by wgconf; keys shortened.
[Interface]
Address = 10.200.0.1/24
ListenPort = 51820
PrivateKey = <hub private key>
MTU = 1420
# Let spokes reach each other and the office LAN through the hub:
PostUp = sysctl -w net.ipv4.ip_forward=1; iptables -A FORWARD -i wg0 -j ACCEPT; iptables -A FORWARD -o wg0 -j ACCEPT
PostDown = iptables -D FORWARD -i wg0 -j ACCEPT; iptables -D FORWARD -o wg0 -j ACCEPT

[Peer]
# alice-laptop
PublicKey = <alice public key>
AllowedIPs = 10.200.0.2/32

[Peer]
# office-router: a SITE, so it owns a whole subnet (this is what makes it site-to-site)
PublicKey = <office public key>
AllowedIPs = 10.200.0.3/32, 192.168.10.0/24
ini
# /etc/wireguard/wg0.conf on a laptop. Split tunnel: only the tunnel subnet and the office LAN use the VPN.
[Interface]
Address = 10.200.0.2/32
PrivateKey = <alice private key>
DNS = 10.200.0.1            # wg-quick runs resolvconf; this makes ALL DNS go to the hub unless you scope it (see split DNS)
MTU = 1420

[Peer]
PublicKey = <hub public key>
PresharedKey = <optional psk>
Endpoint = 203.0.113.10:51820
AllowedIPs = 10.200.0.0/24, 192.168.10.0/24     # routes AND the source filter for packets coming back
# AllowedIPs = 0.0.0.0/0, ::/0                  # full tunnel: everything leaves through the hub
PersistentKeepalive = 25                        # keep the NAT mapping of THIS side alive

Roaming, NAT and PersistentKeepalive Important ​

In plain words: WireGuard does not care where a peer is. Whatever address a valid packet came from becomes that peer's address. And because NAT forgets idle mappings, a peer that wants to be reachable while quiet must send a small packet every so often.

Common misunderstanding: "I need PersistentKeepalive on every peer." Only on a peer that is behind NAT (or a stateful firewall) and must be reachable from the outside while it is not sending. A server with a public IP does not need it; a hub that spokes dial does not need it; the laptop behind a home router does.

Definition: wg(8): "Endpoint — an endpoint IP or hostname, followed by a colon, and then a port number. This endpoint will be updated automatically to the most recent source IP address and port of correctly authenticated packets from the peer." The whitepaper: "Since a public key uniquely identifies a peer, the outer external source IP of an encrypted WireGuard packet is used to identify the remote endpoint of a peer, enabling peers to roam freely between different external IPs." And on NAT: "Note that the listen port of peers and the source port of packets sent are always the same, adding much simplicity, while also ensuring reliable traversal behind NAT." The quick start on keepalives: "Because NAT and stateful firewalls keep track of 'connections', if a peer behind NAT or a firewall wishes to receive incoming packets, he must keep the NAT/firewall mapping valid, by periodically sending keepalive packets... A sensible interval that works with a wide variety of firewalls is 25 seconds. Setting it to 0 turns the feature off, which is the default."

1  a (a has Endpoint = 10.140.0.20:51820 configured) and b are connected
2  b moves networks: new address 10.140.0.21; a still believes 10.140.0.20
3  b sends ANY packet (a ping, or a keepalive)         -> arrives at a from 10.140.0.21:51820
4  a authenticates it, updates the peer's endpoint to 10.140.0.21:51820
5  replies and a's own traffic now go to the new address; nothing was reconfigured

Real output of exactly that:

$ wg show wg0 endpoints              # on a, before b sends anything
sLsn...  10.140.0.20:51820
$ ping -c 2 10.200.0.1               # on b (now 10.140.0.21)
2 packets transmitted, 2 received, 0% packet loss
$ wg show wg0 endpoints              # on a, after
sLsn...  10.140.0.21:51820

If BOTH peers sit behind NAT with unknown endpoints, neither can start the conversation: that is the NAT traversal problem of NAT, PAT and port forwarding (STUN, hole punching), solved by a mesh coordination server or by routing through a public hub.

NAT / firewall idle timeout (typical)Keepalive needed
UDP mappings on home routers: tens of seconds to a few minutes25 s is the recommended interval
AWS NAT gateway: 350 seconds idle for TCP (AWS NAT gateway troubleshooting page, see References)TCP keepalive or SSH ServerAliveInterval below 350 s
Linux conntrack, established TCP: 5 days; UDP: 30 s (single packet) / 120 s (stream)WireGuard keepalive below 30 s on a path with a Linux NAT; see tunnels and observability

Mesh VPNs ​

Tailscale, Headscale and Netbird Important ​

In plain words: A mesh VPN is WireGuard with the tedious parts automated: a service hands out keys and addresses, every device gets one stable private address, devices talk directly when they can and through a relay when they cannot, and a policy file says who may reach whom.

Common misunderstanding: "Tailscale sends my traffic through Tailscale's servers." Most traffic goes directly between your devices. The Tailscale docs: "Most connections between tailnet devices only use DERP servers to establish a direct connection to another tailnet device. But as a last resort, when other connection types aren't possible due to hard NAT, firewalls, or another reason, devices can communicate using a DERP server as a relay." And the relay cannot read the data: "A DERP server blindly forwards already-encrypted traffic from one device to another."

Definition: A control plane (coordination server) distributes public keys, addresses, routes, DNS settings and ACLs; the data plane is WireGuard between devices. The relay protocol is DERP, "Designated Encrypted Relay for Packets". The Tailscale NAT traversal article describes the first step in its own words: STUN is "your machine sends a 'what's my endpoint from your point of view?' request to a STUN" server; then both sides try the discovered endpoints at the same time (hole punching, see NAT traversal).

1  device starts: logs in with the identity provider, reports its public key and candidate endpoints
2  control plane returns the peers it may see, their keys, addresses, the DERP map and the ACL result
3  it first sends through its home DERP relay, so the first packets are delivered immediately
4  in parallel, both sides probe each other's candidate endpoints (STUN-learned, LAN, IPv6)
5  a probe succeeds: traffic switches to the direct WireGuard path; DERP stays as the fallback
6  hard NAT on both sides (e.g. symmetric): stays on DERP; the relay is 'last resort', not the default
FeatureWhat it doesTypical command or setting
MagicDNSRegisters a DNS name per device and adds search domains, so ssh laptop works. Docs: "MagicDNS automatically registers DNS names for devices in your network"Enabled in the admin console; names like laptop or laptop.tailnet-name.ts.net
ACL policyWho may reach which device and port; docs: "Using a default deny policy prevents communication between devices without explicit access to each other. However, in the absence of an acls section in the tailnet policy file, Tailscale applies the default allow all policy."acls / grants in the tailnet policy file
Subnet routerA device that advertises a physical subnet so others reach machines that do not run the clienttailscale set --advertise-routes=192.0.2.0/24 plus IP forwarding (net.ipv4.ip_forward = 1), approve in the admin console
Exit nodeSends ALL internet traffic through one device (default routes 0.0.0.0/0, ::/0)tailscale set --advertise-exit-node, clients choose it
Peer relay / DERPLast-resort pathRun your own DERP or peer relays for data residency
HeadscaleOpen-source, self-hosted control server for one tailnet: "an open source, self-hosted implementation of the Tailscale control server"headscale binary, official clients pointed at it
NetbirdOpen-source WireGuard mesh with Management, Signal and Relay services ("NetBird relies on four components - Client application, Management, Signal and Relay services")NetBird client

The subnet router is also how you get into a Kubernetes pod network or a VPC without installing a client everywhere: run one router pod or instance with --advertise-routes=10.0.0.0/16, approve the route, and every authorised tailnet device reaches private addresses, subject to ACLs. Overlapping prefixes advertised by several routers are resolved by longest prefix match, with failover rules described in the Tailscale docs.

ProductControl planeData planeRelaySelf-hostable
TailscaleHostedWireGuard (userspace tailscaled or kernel)DERP, peer relaysNot the hosted plane; Headscale is the community option
HeadscaleYou run itTailscale clientsDERP (embedded or yours)Yes
NetbirdHosted or self-hosted (Management and Signal services)WireGuard, with Pion ICE for NAT traversalRelay service (Coturn-based, per the Netbird docs)Yes
Plain WireGuardNone; you distribute keysWireGuardNoneAlways

OpenVPN and IPsec/IKEv2 Good to know ​

In plain words: Before WireGuard, a VPN was OpenVPN (TLS-based, one process) or IPsec (a standard every router speaks). Both are alive: corporate clients, cloud gateways and old hardware still need them.

Common misunderstanding: "OpenVPN is obsolete." AWS Client VPN is "a managed client-based VPN service ... using an OpenVPN-based VPN client". And "IPsec is just encryption": it is two layers, IKE (authenticates and negotiates keys) and ESP (carries the packets).

Definition: OpenVPN: "a full-featured SSL VPN that implements OSI layer 2 or 3 secure network extension using the industry standard SSL/TLS protocol, supports flexible client authentication methods based on certificates, smart cards, and/or username/password credentials, and allows user or group-specific access control policies using firewall rules applied to the VPN virtual interface." IKEv2 (RFC 7296): "IKE is a component of IPsec used for performing mutual authentication and establishing and maintaining Security Associations (SAs)." When a NAT sits in the path, ESP cannot carry ports, so ESP is wrapped in UDP port 4500 (RFC 3948), and the AWS Site-to-Site feature list includes "Internet Key Exchange version 2 (IKEv2)" and "NAT traversal".

IPsec (IKEv2)                                       OpenVPN
1 UDP 500: IKE_SA_INIT (DH, nonces)                 1 UDP 1194 by convention (or TCP 443): TLS handshake
2 IKE_AUTH (certs / PSK / EAP) -> first CHILD SA    2 server pushes routes, DNS, IP via the control channel
3 ESP (proto 50, or UDP 4500 with NAT-T)            3 data channel: encrypted packets over UDP/TCP
4 rekey CHILD SA every few hours, DPD for liveness  4 keepalive ping / ping-restart, tls renegotiation
Where each is still the right answerWhy
IPsec IKEv2 site-to-site to AWS/GCP/Azure, Cisco, Juniper, FortinetEvery router and cloud gateway speaks it; BGP over the tunnel
IKEv2 built-in clients on phones and laptopsNo app to install, MOBIKE for roaming
OpenVPNCorporate SSO/PKI integration, TCP 443 to pass hostile firewalls, AWS Client VPN
WireGuardEverything else new, especially servers, meshes and containers
L2TP/IPsec, PPTPLegacy only; PPTP is broken; the whitepaper notes L2TP/IPsec's layer-2 design makes clean network design harder

Topologies and cloud networks ​

1. Site-to-site: networks talk, users notice nothingOffice LANno VPN clientgatewayVGW / TGWVPC 10.0.0.0/16private subnetsIPsec / WGalways on, BGP or static routes,CIDRs must not overlap2. Client (road warrior): one device joins one networkLaptopVPN client, wg0 / tun0VPN serverPrivate networksplit or full tunnelUDP 51820 / 1194 / 4500on demand, per user, per device;whole subnet becomes reachable3. Mesh (Tailscale, Netbird, Headscale): direct peer-to-peer, control plane on the sidecoordinatorlaptopserver (NAT)phoneDERP relaykeys and addresses via the control plane (dashed),data goes straight between devices (thick),relay only when NAT traversal fails;ACL policy decides who may reach whom4. Zero-trust access: no network, only an authenticated request to one appUser + deviceSSO, postureIdentity proxyAccess, Teleportconnectordials OUT onlyOne appgrafana, ssh, dbpolicy per request,audit per session

Site-to-site vs client (road-warrior) VPN Must-know ​

In plain words: Site-to-site joins two networks: the office router and the cloud gateway hold the tunnel, and the computers behind them just see a route. A client VPN (road warrior) joins one device: the laptop runs the VPN software and gets an address inside the network.

Common misunderstanding: "I connected the VPN, so my cloud and my office are connected." A client VPN connects one device to one network. Two networks need a site-to-site link, and the routes have to be present on both sides, not only the tunnel.

Definition: The AWS documentation gives the problem and the answer in two sentences: "By default, an instance that you launch within an Amazon VPC can't communicate with a local (AWS Cloud) network and a remote device — for example, this might be a site or an on-premises device. You can enable access to your remote devices from your VPC by creating an AWS Site-to-Site VPN (Site-to-Site VPN) connection, and configuring routing to pass traffic through the connection." And for client access: "AWS Client VPN is a managed client-based VPN service that enables you to securely access your AWS resources and resources in your on-premises network."

Site-to-site                                         Client (road warrior)
1  office router + cloud VGW/TGW each have a         1  laptop installs a client (wg, OpenVPN, IKEv2)
   public IP and a shared secret / cert              2  authenticates (key, cert, SSO, MFA)
2  IKEv2 builds two IPsec tunnels (redundancy)       3  gets an address in 10.200.0.0/24 (or a pool)
3  BGP or static routes advertise 192.168.10.0/24    4  server pushes routes (split) or 0.0.0.0/0 (full)
   and 10.0.0.0/16 to the other side                 5  only THIS laptop is inside the network
4  hosts send to the gateway as next hop; no client
AspectSite-to-siteClient / road warrior
Who holds the tunnelA gateway or router per siteEach device
Hosts need softwareNoYes
Typically always onYesOn demand
AuthenticationGateway keys, certificates, PSKPer user and device: certificate, SSO, MFA
Address planningBoth sides' CIDRs must be uniqueThe VPN pool must not overlap the user's home network
Failure impactWhole site loses reachOne user
ProductsAWS Site-to-Site, GCP Cloud VPN, strongSwan, WireGuard between routers, Tailscale subnet routerAWS Client VPN, OpenVPN Access Server, WireGuard, Tailscale, Cloudflare One Client

Cloud VPN vs private links Important ​

In plain words: A cloud has several ways to connect networks and they are not interchangeable: VPNs ride the public internet in encrypted tunnels; VPC peering joins two VPCs; Transit Gateway is a hub; PrivateLink exposes one service, not a network.

Common misunderstanding: "VPC peering is transitive, so A can reach C through B." AWS: "VPC peering does not support transitive peering relationships. For example, if there are VPC peering connections between VPC A and VPC B, and between VPC A and VPC C, you can't route traffic from VPC B to VPC C through VPC A." Another: "Private link traffic goes over my VPN." PrivateLink does not use one: "You do not need to use an internet gateway, NAT device, public IP address, Direct Connect connection, or AWS Site-to-Site VPN connection."

Definition:

OptionWhat it connectsDirection and scopeOverlapping CIDRsNotes
AWS Site-to-Site VPNVPC (via a virtual private gateway "attached to a single VPC" or a transit gateway) to an on-premises networkWhole networks, both ways; IPsec, IKEv2, NAT traversal; two tunnels per connection; standard tunnel up to 1.25 Gbps, "Large Bandwidth Tunnel" up to 5 Gbps on Transit Gateway or Cloud WAN"We recommend that you use non-overlapping CIDR blocks""An Site-to-Site VPN connection does not support Path MTU Discovery"
AWS Client VPNIndividual users to VPC and on-premPer user, OpenVPN-based clientPool and VPC must not collide with the user's networkManaged server; authorisation rules per group
AWS VPC peeringTwo VPCs, private IPsWhole networks, non-transitiveNot allowed: "You cannot create a VPC peering connection between VPCs that have matching or overlapping IPv4 or IPv6 CIDR blocks."No gateway, no bandwidth bottleneck; N VPCs need N(N-1)/2 peerings
AWS Transit Gateway"a network transit hub used to interconnect virtual private clouds (VPCs) and on-premises networks"Hub and spoke; attachments for VPCs, VPN, Direct ConnectRoute tables per attachment decide; overlapping needs separate route tables or NATPer-attachment and per-GB charges
AWS PrivateLinkA specific service (endpoint to an endpoint service)One service, one direction (consumer dials provider)Overlap does not matter in practice: the consumer talks to an endpoint address inside its own VPC (design property of interface endpoints; the page fetched does not state it)"you control the specific API endpoints, sites, services, and resources that are reachable from your VPC"
GCP Cloud VPNVPC to on-prem or another cloud over IPsecWhole networks (HA VPN with BGP)Not allowed to overlapVendor documentation was not retrievable for this chapter (403); verify limits at cloud.google.com before relying on numbers
Direct Connect / InterconnectA dedicated line, no internetWhole networksAs VPNNot encrypted by default; add IPsec or MACsec
QuestionAnswer
Reach one SaaS-like service in another VPC or account without exposing the network?PrivateLink
Join two VPCs with no hub and no overlapping addresses?VPC peering
Many VPCs plus an on-prem site?Transit Gateway with a Site-to-Site attachment
One office to the cloud?Site-to-Site VPN (or WireGuard between two routers)
Remote staff into a VPC?Client VPN, or a mesh or zero-trust connector
Anything the internet-facing parts must not see?Private subnets, no public IPs, access via the options above

Overlapping subnets and how to survive them Important ​

In plain words: If both sides of a tunnel use 10.0.0.0/16, a packet for 10.0.1.5 could mean "here" or "there", so the router cannot decide. Everyone picks 10.0.0.0/16 or 192.168.1.0/24 because those are the defaults.

Common misunderstanding: "My laptop at home is 192.168.1.0/24 and so is the office. The VPN will sort it out." It cannot: the local connected route wins, so packets for the office network never enter the tunnel; the kernel delivers them to the home router. Merging companies and connecting customers hits the same wall at larger scale.

Definition: Two networks overlap when their CIDR ranges share addresses (see IP addressing). Prevention is a plan: an IP address management (IPAM) inventory, a range per environment, and RFC 1918 space carved so that no two VPCs, offices or Kubernetes pod/service networks collide.

FixHowTrade-off
RenumberChange one sideHard but permanent; the only real fix
1:1 NAT (NETMAP)Map the remote 10.0.0.0/16 to 172.20.0.0/16 as seen locally (iptables -t nat -A PREROUTING -d 172.20.0.0/16 -j NETMAP --to 10.0.0.0/16 plus the mirror on POSTROUTING)Apps must use the translated addresses; protocols that embed IPs break
Source NAT at the gatewayThe tunnel gateway masquerades one sideOne-way only; hides the real client addresses
Longest-prefix tricksAdvertise /25 halves of the local range from one router and the remote range from another (Tailscale documents overlapping routes with different prefix lengths)Fragile; only works when ranges differ in size
PrivateLink instead of peeringExpose a service, not a networkOne service per endpoint
Per-tunnel route tables (Transit Gateway)Each attachment gets its own tableComplex
Choose less common ranges10.x with random second octets, 100.64.0.0/10 for CGNAT-like space, 172.16.0.0/12 middlePlanning

In SQL, an IPAM table makes overlap a query instead of an outage. PostgreSQL's inet/cidr types have the && operator ("overlaps"):

sql
CREATE TABLE network_inventory (
  id       bigserial PRIMARY KEY,
  name     text NOT NULL UNIQUE,          -- 'aws-prod-eu-west-1', 'office-tehran', 'k8s-pods-prod'
  cidr     cidr NOT NULL,
  owner    text NOT NULL,
  tunnel   text                            -- which VPN or peering links it
);

-- Which pairs of networks overlap? Run in CI before approving a new range.
SELECT a.name AS net_a, a.cidr AS cidr_a, b.name AS net_b, b.cidr AS cidr_b
FROM network_inventory a
JOIN network_inventory b ON a.id < b.id AND a.cidr && b.cidr;

-- Is a candidate range free?
SELECT NOT EXISTS (SELECT 1 FROM network_inventory WHERE cidr && '10.42.0.0/16') AS is_free;

-- First free /24 inside 10.50.0.0/16 (naive scan; fine for a few hundred rows)
SELECT ('10.50.0.0/16'::cidr)::inet + (g * 256) AS candidate
FROM generate_series(0, 255) AS g
WHERE NOT EXISTS (
  SELECT 1 FROM network_inventory
  WHERE cidr && set_masklen((('10.50.0.0/16'::cidr)::inet + (g * 256)), 24)
)
LIMIT 1;

Split tunneling, split DNS and DNS leaks Important ​

In plain words: A full tunnel sends every packet through the VPN. Split tunneling sends only traffic for the company network and lets the rest go straight out. DNS has the same choice: ask the company resolver only for company names, or for everything.

Common misunderstanding: "Split tunnel is less secure." It trades control for performance: the VPN is not a bottleneck and not an inspection point, so you lose central filtering of the user's internet traffic. And "I use the VPN, so my DNS is private": if the OS keeps using the Wi-Fi resolver for some queries, names leak outside the tunnel (a DNS leak).

Definition: What decides the split: the routes. In WireGuard it is the peer's AllowedIPs; 0.0.0.0/0, ::/0 is a full tunnel. DNS is separate: DNS = in wg-quick sets the resolver (via resolvconf) for the interface; per-domain routing needs systemd-resolved (resolvectl domain wg0 ~internal.example.com) or the VPN product's split DNS (Tailscale MagicDNS with restricted nameservers, Cloudflare One). See DNS resolution for developers for the resolver order.

Full tunnel: AllowedIPs = 0.0.0.0/0, ::/0     all packets -> VPN; DNS -> company resolver; exit IP = company
Split:       AllowedIPs = 10.0.0.0/8, 192.168.10.0/24    only those -> VPN; everything else direct
Leak:        split routes + DNS still the Wi-Fi resolver  -> "db.internal" asked to 8.8.8.8 (NXDOMAIN, and the name is disclosed)
IPv6 leak:   AllowedIPs = 0.0.0.0/0 only                  -> IPv6 traffic bypasses the tunnel; add ::/0
SymptomCauseFix
Internal names do not resolve but IPs workResolver for the internal zone not used (split DNS missing)DNS = in the config, resolvectl domain, or MagicDNS routing
Public sites slow while on VPNFull tunnel through a small gatewaySplit tunnel, or an exit node near the user
Streaming/geo sites see the wrong countryFull tunnel exitSplit or per-app rules
"VPN on" but a site shows the home IPIPv6 or a hard-coded resolver bypasses::/0, block DNS-over-HTTPS in the browser, kill switch (firewall rule dropping non-tunnel traffic)
Docker containers bypass the VPNTheir traffic uses the bridge and the host's default route/NAT; policy routing rules differCheck ip rule, iptables -t nat, run containers with --network host or route the bridge subnet via the tunnel

Zero-trust access and reverse tunnels ​

VPN vs zero-trust access Must-know ​

In plain words: A VPN answers "are you on our network?" and then trusts you with the network. Zero-trust access answers "is this person, on this healthy device, allowed to use this one app right now?" for every request.

Common misunderstanding: "Zero trust is a product you buy." The BeyondCorp paper describes an architecture: "Virtually every company today uses firewalls to enforce perimeter security. However, this security model is problematic because, when that perimeter is breached, an attacker has relatively easy access to a company's privileged intranet." The fix: "We are removing the requirement for a privileged intranet and moving our corporate applications to the Internet." Products implement it; they do not equal it.

Definition: The BeyondCorp design has a device inventory database, a user and group database, an "Internet-Facing Access Proxy" and an access control engine that decides per request. The same pattern today: an identity-aware proxy authenticates the user (SSO, MFA), checks device posture, evaluates policy for one application, and reaches it through a connector that dials out. The user never receives a network address. Cloudflare's wording for the connector: "a lightweight daemon in your infrastructure (cloudflared) creates outbound-only connections to Cloudflare's global network" so "your origins can serve traffic through Cloudflare without being vulnerable to attacks that bypass Cloudflare". Boundary: "secure, authenticated access to servers, databases, applications, and other cloud or on-premises infrastructure without requiring users to access the underlying network directly ... creates auditable sessions while keeping sensitive credentials and network details protected." Teleport: "Secure app & SSH access with no VPNs or proxies" for "Apps, servers, databases, Kubernetes clusters, desktops".

1  user opens grafana.company.com -> hits the identity-aware proxy (public)
2  proxy redirects to the identity provider: SSO + MFA; device posture is read (managed laptop? disk encryption?)
3  policy engine: group "sre" may reach app "grafana" from managed devices between 06:00 and 22:00
4  allowed -> the proxy forwards the request to the connector (cloudflared / Teleport agent / Boundary worker)
5  the connector, which dialled OUT earlier, delivers it to grafana on the private network
6  every request and session is logged and can be revoked in seconds; nothing is exposed inbound
AspectVPN (network access)Zero-trust (per-app access)
What you getAn IP address and routes to a whole networkA session to one named app, protocol aware (SSH, DB, HTTP, K8s)
Trust decisionAt connect timeAt every request or session
Lateral movementPossible: the network is flat unless segmentedContained to the app
Inbound portsVPN endpoint exposedNone; connectors dial out
Device postureOptionalPart of the policy
AuditNetwork flowsIdentity and command/query level, session recording
Legacy appsWork unchangedNeed a connector or protocol support
Setup costLowHigher (IdP, policy)
ProductsWireGuard, OpenVPN, IPsec, AWS Client VPNCloudflare Access + Tunnel, Teleport, Boundary, Tailscale with ACLs and posture, BeyondCorp / Google IAP

Both can combine: Cloudflare says "To enable seamless and secure access for on-network employees, use Cloudflare Tunnel to connect your private network and have users connect through the Cloudflare One Client". A mesh VPN with ACL policy is a middle position: still a network, but each device is authenticated and the policy is least-privilege by default if you write it so.

Reverse tunnels for webhooks and demos Must-know ​

In plain words: When your server is behind NAT you cannot connect to it, but it can connect out. A reverse tunnel keeps an outbound connection to a public relay open, and the relay hands incoming requests down that connection.

Common misunderstanding: "The tunnel URL is private because nobody knows it." Quick tunnel URLs are random but public: anything that learns the URL (logs, referrers, scanners reading certificate transparency logs) can send you requests. Verify a signature, do not trust the source IP.

Definition: The three common tools, all outbound-initiated:

ToolCommandWhat you getNotes
cloudflared quick tunnelcloudflared tunnel --url http://localhost:8000A random trycloudflare.com URL, no accountCloudflare: "Quick Tunnels are for testing and development" (see the NAT chapter); named tunnels give stable hostnames and Access policies
cloudflared named tunnelcloudflared tunnel create, tunnel route dns, tunnel runA stable hostname you own, "a persistent object identified by a UUID", multiple connectorsProduction-capable; pairs with Cloudflare Access
ngrokngrok config add-authtoken TOKEN, ngrok http 8000A public URL, inspector UI, replayFrom the ngrok docs: brew install ngrok, ngrok config add-authtoken <token>, ngrok http <port>
ssh -R to your own VPSssh -R 9000:localhost:8000 vps + GatewayPorts clientspecified + a TLS reverse proxyA URL on a host you control, no third partyYou run, patch and secure the relay
WireGuard to a VPSPeer with a public IP forwards a port to your tunnel addressFull UDP and TCP, not only HTTPDNAT on the VPS; see NAT chapter

Webhook development flow: start the app, start the tunnel, register the printed URL in the provider's dashboard, receive. The provider signs the request (Stripe puts a timestamp in the Stripe-Signature header that is, in its words, "part of the signed payload"; other providers differ, for example GitHub signs only the body, so replay protection is yours to add: follow each provider's documented scheme), you verify with a constant-time comparison and a replay window, and answer fast with 2xx while the work goes to a queue. The Laravel implementation is in Laravel and PHP; the matching Go check is in solutions.

Kubernetes access: kubectl port-forward, VPN into the pod network, subnet routers Important ​

In plain words: kubectl port-forward opens a local port that leads to a pod, a service or a deployment, through the Kubernetes API server, with no load balancer and no node access. It is an SSH -L for Kubernetes.

Common misunderstanding: "port-forward exposes the pod to my network." It binds to the loopback by default and is a debugging tool: one pod, one process, dies with your terminal, and it is not load balanced (when pointed at a Service it picks one pod once).

Definition: The Kubernetes docs: "kubectl port-forward allows using resource name, such as a pod name, to select a matching pod to port forward to" and print Forwarding from 127.0.0.1:28015 -> 27017. Forms: kubectl port-forward pod/NAME 28015:27017, deployment/NAME, service/NAME, -n NAMESPACE, --address 0.0.0.0 (do not, unless you mean it). The docs note "kubectl port-forward does not return", so run it in a separate terminal or background it. The docs add two facts worth knowing: "Access to kubectl port-forward is controlled by Kubernetes authorization mechanisms like Role-Based Access Control (RBAC). Authorization is enforced by the Kubernetes API server, not by the kubectl client", and "kubectl port-forward is implemented for TCP ports only" (no UDP). The stream goes from kubectl to the API server and on to the kubelet of the pod's node, which connects inside the pod's network namespace; nothing is opened on the node or in the cluster network.

laptop: kubectl port-forward svc/postgres 5433:5432 -n prod
  1  kubectl connects to the API server (kubeconfig credentials, TLS), subresource pods/portforward
  2  API server upgrades the connection to a stream and talks to the kubelet on the pod's node
  3  kubelet enters the pod's network namespace and dials localhost:5432 there
  4  local 127.0.0.1:5433 <-> API server <-> kubelet <-> pod: one stream per local connection
NeedUseWhy
One-off debugging of a pod or servicekubectl port-forwardNo infrastructure, RBAC-controlled, audited by the API server
A team regularly needs private cluster IPsSubnet router (Tailscale --advertise-routes=<pod/service CIDR>, WireGuard gateway pod)Real IPs and DNS, any protocol, ACL-controlled
Access to cluster-internal DNS namesA VPN or mesh with split DNS toward CoreDNS*.svc.cluster.local resolves only inside the cluster
Publish a service to partnersIngress / Gateway API, or a connector (cloudflared in the cluster)Not a developer tool
Reach a database in a VPC from the clusterPrivateLink or Site-to-Site, NetworkPolicy and egressA tunnel from a pod is rarely right

Pod CIDR and service CIDR must not overlap with the VPN's ranges or your office network; clusters often use 10.244.0.0/16 and 10.96.0.0/12, which collide with home networks more often than you expect.

Tunnels and observability: MTU, keepalive and conntrack Important ​

In plain words: Tunnels fail in boring ways: packets too big, idle timers that fire, tables that fill. They almost never fail by "the VPN stopped working"; one specific layer stops.

Common misunderstanding: "If wg show has a recent handshake, the tunnel is fine." The handshake proves the keys and the UDP path. It says nothing about AllowedIPs, routes, MTU, forwarding or the target service.

Definition: Four numbers to watch.

WhatWhere to see itHealthyBroken looks like
Latest handshakewg show (latest handshake: 7 seconds ago)Under about 3 minutes while traffic flowsNo line at all (never completed)
Transfer counterswg show (transfer: X received, Y sent)Both grow with trafficSent grows, received stays: nothing authentic comes back
Path MTUping -M do -s 1392 host (Linux), ping -D -s 1392 host (macOS)Largest size passes, one more says message too long, mtu=1420Small works, large hangs: black hole
NAT/conntrack entriesconntrack -L -p udp --dport 51820, conntrack -SEntry refreshed by keepalivesEntry expired, inbound packets dropped until the peer sends again

The timers that matter, together: Linux conntrack keeps an established TCP flow for 432000 s (5 days) but an UDP flow for 30 s after one packet and 120 s once there is traffic both ways (kernel nf_conntrack-sysctl); AWS NAT gateways drop idle TCP after 350 s; home routers range from seconds to minutes. A PersistentKeepalive = 25 stays below all of them. SSH needs ServerAliveInterval 15 to 30 for the same reason, and Postgres connections through a tunnel need TCP keepalives (tcp_keepalives_idle or the driver option), or an idle pooled connection is killed silently and the next query hangs for minutes.

t=0     tunnel idle; conntrack on the NAT in front of the laptop has udp 10.0.0.5:51820 -> hub:51820 [UNREPLIED], timer 30 s
t=25    PersistentKeepalive sends a 32-byte packet            -> timer refreshed
t=30    without keepalive: the entry would be gone here
t=60    hub wants to send to the laptop: NAT has no entry     -> packet dropped (nothing logged)
t=61    with keepalive the entry still exists                 -> delivered

Debug recipe: (1) wg show: handshake? (2) ping the peer's tunnel address: routes and AllowedIPs; (3) ping -M do -s N: MTU; (4) tcpdump -ni eth0 udp port 51820 on both ends: does the UDP leave, does it arrive, what size; (5) tcpdump -ni wg0: inner packets; (6) conntrack -L, firewall counters. See the network troubleshooting playbook for the generic version. Metrics worth exporting: wireguard_latest_handshake_seconds (from the Prometheus WireGuard exporter, not fetched here), tunnel interface errors/drops (ip -s link show wg0), and the health probe in Go.

Security considerations Must-know ​

In plain words: A tunnel moves the trust boundary; it does not remove it. The new risks are the keys, the exposed ends, and the flat network behind the door.

Common misunderstanding: "Encrypted means safe." A tunnel with a stolen private key, a wildcard -R listener or an agent forwarded to a compromised host is an authenticated path for the attacker.

RiskHow it happensControl
WireGuard private key theftKey file in a repo, backup or imagechmod 600, never in git, generated on the device that uses it, rotate on loss; PostUp secrets via wg set ... private-key <(...)
No revocation by defaultA key is valid until someone deletes the peerInventory of keys per person/device; remove on offboarding; mesh products revoke centrally
Key rotationSame static key for yearsGenerate a new pair, add the new public key as a second peer entry, switch, remove the old; the session keys rotate every ~2 minutes on their own, only the static identity needs a human
Preshared keysA PSK adds a symmetric layer "for post-quantum resistance" (wg(8))Optional per-peer secret; useful, not a substitute for rotation
Exposed -R portsGatewayPorts yes or a wildcard bind on a public hostGatewayPorts no; PermitListen; firewall; reverse proxy with auth
Agent forwarding theftRoot on an intermediate host uses your agentProxyJump, ssh-add -c, hardware keys, AllowAgentForwarding no
Forwarding enabled for everyoneAllowTcpForwarding yes default; "disabling TCP forwarding does not improve security unless users are also denied shell access, as they can always install their own forwarders" (sshd_config)PermitTTY no, ForceCommand, PermitOpen, Match blocks
Host key trustStrictHostKeyChecking no in scriptsknown_hosts pinned; SSH CA host certificates
Flat network behind a VPNEveryone connected can reach everythingSegment, ACLs (mesh), per-app access (zero trust), security groups scoped to the VPN CIDR
Split DNS leaksQueries for internal names go to a public resolverResolver routing, kill switch, DoH policy
VPN gateway as a single targetPublic UDP/TCP port with a known protocolWireGuard stays silent to unauthenticated packets; keep OpenVPN/IPsec patched; rate limit
Logs without identityEveryone appears as the bastion's IPCertificate IDs, session recording, application-level audit

Mechanics ​

Commands and what they print ​

TaskCommandWhat to look at
Is a forward listening?lsof -nP -iTCP:5433 -sTCP:LISTEN or ss -ltnp127.0.0.1 vs 0.0.0.0; the owning ssh process
Debug an ssh connectionssh -vvv -L ... bastionLocal connections to 127.0.0.1:5433 forwarded to remote address ...; channel N: open failed: administratively prohibited; cannot listen to port: 5433
Effective server settingssshd -T | grep -i -E 'allowtcp|gatewayports|permitopen'First-match-wins surprises from included files
Effective client settingsssh -G app | grep -i -E 'proxyjump|identityfile|controlpath'What ~/.ssh/config really resolves to
Multiplexingssh -O check|forward|cancel|exit hostMaster pid
Make a WireGuard key pairumask 077; wg genkey | tee priv | wg pubkey > pub44-character base64 strings
Bring up / downwg-quick up wg0, wg-quick down wg0, wg-quick strip wg0The [#] command log it prints
Statewg show, wg show wg0 dump (tab-separated; machine readable)handshake time, endpoint, transfer
Routesip route, ip -4 rule, ip route show table 51820dev wg0 entries; fwmark 51820 rules for full tunnels
Capture outer vs innertcpdump -ni eth0 udp port 51820 / tcpdump -ni wg0Outer sizes (148, 92, 32, 128) vs inner packets
MTUip link show wg0, ping -M do -s 1392 peermtu 1420; message too long, mtu=...
Meshtailscale status, tailscale ping peer, tailscale netcheckDirect vs relay "fra" connections (output formats from the product; not fetched)
Kuberneteskubectl port-forward svc/x 8080:80 -n nsForwarding from 127.0.0.1:8080 -> 80
Cloud VPNAWS console / aws ec2 describe-vpn-connectionsTunnel state UP/DOWN, BGP status

The WireGuard handshake in one picture (from the whitepaper's protocol, the packet sizes are from the real capture above):

initiator (laptop)                                         responder (hub)
 1   [type 1, 148 B] ephemeral pubkey, encrypted static key, timestamp, MACs  ->
 2                                                       <-  [type 2, 92 B] ephemeral pubkey, empty, MACs
 3   both sides derive the same two transport keys (Noise_IK: 1 round trip)
 4   [type 4, 32 B] empty keepalive  ->   confirms the responder's keys
 5   [type 4, N B]  data packets     <->  counter in every header; replay window rejects repeats
 6   under load: if a handshake arrives from an unverified source, the responder answers with a cookie (type 3, 64 B) first

What each product does ​

ProductConfig file or interfaceDefault portKeepaliveNotes
OpenSSH~/.ssh/config, /etc/ssh/sshd_configTCP 22ServerAliveInterval (default 0 = off), ClientAliveIntervalForwarding is a channel inside one connection
WireGuard (wg-quick)/etc/wireguard/wg0.confUDP 51820 (convention, not a rule)PersistentKeepalive (default off)MTU 1420 by default; fwmark 51820 for full tunnels
OpenVPNserver.conf, client.ovpnUDP 1194 by convention (TCP 443 is common to pass firewalls)Its own ping and restart directivesdev tun or dev tap
strongSwan (IPsec)swanctl.confUDP 500 and 4500, ESPDPD (dead peer detection)IKEv2, certificates or PSK
AWS Site-to-Site VPNConsole, two tunnels per connectionIPsec to AWS endpointsTunnel monitoringIKEv2, NAT-T, BGP or static routes; no PMTUD
AWS Client VPNEndpoint plus .ovpnOpenVPN (UDP/TCP)OpenVPNAuthorisation rules and route table per endpoint
Tailscale / Headscaletailscaled, tailnet policy fileUDP direct when NAT traversal works, DERP relays otherwiseBuilt inMagicDNS, ACLs, subnet routers, exit nodes
NetbirdClient, Management, Signal and Relay servicesWireGuard + ICEBuilt inRelay via Coturn
Cloudflare Tunnelcloudflared tunnel runOutbound only (to Cloudflare)Built in"a tunnel is a persistent object identified by a UUID"; each connector goes to the nearest data center
ngrokngrok http 8000Outbound onlyBuilt inURL, inspector
Teleport / BoundaryCluster plus agents/workersOutbound from agentsBuilt inSession recording, identity, RBAC
kubectl port-forwardNoneThe API server'sEnds with the processTCP only; RBAC on pods/portforward

Solving the classic problems ​

ProblemSolutionHowCost / limitation
Developer needs the private databasessh -L through a bastion; or ProxyJump + a DB client with SSH supportLocalForward in config, ExitOnForwardFailure yesPer-developer tunnel; audit is at the bastion
Demo a local build to a customerssh -R to a demo host or cloudflared quick tunnelGatewayPorts clientspecified, TLS proxyPublic URL: authenticate
Webhooks at a laptopcloudflared / ngrok + signature verificationHMAC over timestamp + raw bodyThird-party relay; URLs change on quick tunnels
Reach all private hosts from a laptopClient VPN or mesh with subnet routerWireGuard hub, Tailscale --advertise-routesFlat network unless ACLs
Join an office and a VPCSite-to-site (IPsec with BGP, or WireGuard between routers)Non-overlapping CIDRsGateway HA, MTU
Contractor needs one app for a weekZero-trust access (Access, Teleport, Boundary)Policy + expiry, no networkSetup of IdP and connector
Tunnel dies when idleKeepalives below the shortest idle timerServerAliveInterval 15, PersistentKeepalive 25, TCP keepaliveA little traffic
Tunnel must come back by itselfSupervisor: systemd Restart=always, autossh, the Go loop belowReconnect with backoffNeeds a health check, see below
Large requests hangCorrect the MTU, clamp MSSMTU = 1380, TCPMSS --clamp-mss-to-pmtuSlightly less payload per packet
Internal names failSplit DNSDNS=, resolvectl domain, MagicDNSTwo views of DNS
Same CIDR on both sidesRenumber, or NETMAPSee overlapRenumbering is work
Kubernetes pod debuggingkubectl port-forwardRBAC pods/portforwardSingle pod, TCP

Go: a minimal SSH local forward with reconnect ​

golang.org/x/crypto/ssh (v0.39.0, the API used here: ssh.ParsePrivateKey, ssh.PublicKeys, ssh.ClientConfig, ssh.Dial, (*ssh.Client).Dial, SendRequest("keepalive@openssh.com", ...), Wait, and knownhosts.New from golang.org/x/crypto/ssh/knownhosts) turns ssh -L into 150 lines. Two decisions worth copying: it verifies the bastion's host key through known_hosts and offers no insecure mode, and it keeps the local listener open while it reconnects, so clients see "slow" instead of "refused" during a blip. The same forwarder is what ssh -L does; for goroutines, net.Listener and context see Go goroutines, context and OS signals.

go
// Command sshforward is a minimal "ssh -L" with the autossh part built in:
// it listens locally and relays every accepted connection through one SSH
// connection to a target that only the bastion can reach. When the SSH
// connection dies it reconnects with backoff while the local listener stays up.
package main

import (
	"context"
	"errors"
	"flag"
	"fmt"
	"io"
	"log/slog"
	"net"
	"os"
	"os/signal"
	"sync"
	"time"

	"golang.org/x/crypto/ssh"
	"golang.org/x/crypto/ssh/knownhosts"
)

// forwarder owns the current SSH client; the listener outlives reconnects.
type forwarder struct {
	mu     sync.RWMutex
	client *ssh.Client
	target string
}

func (f *forwarder) current() *ssh.Client {
	f.mu.RLock()
	defer f.mu.RUnlock()
	return f.client
}

func (f *forwarder) set(c *ssh.Client) {
	f.mu.Lock()
	f.client = c
	f.mu.Unlock()
}

// dial authenticates with a private key and verifies the bastion's host key
// against known_hosts. There is deliberately no "accept any host key" option:
// that would turn the tunnel into a man-in-the-middle target.
func dial(addr, user, keyPath, knownHosts string) (*ssh.Client, error) {
	pem, err := os.ReadFile(keyPath)
	if err != nil {
		return nil, fmt.Errorf("read key: %w", err)
	}
	signer, err := ssh.ParsePrivateKey(pem)
	if err != nil {
		return nil, fmt.Errorf("parse key: %w", err)
	}
	hostKey, err := knownhosts.New(knownHosts)
	if err != nil {
		return nil, fmt.Errorf("known_hosts: %w", err)
	}
	cfg := &ssh.ClientConfig{
		User:            user,
		Auth:            []ssh.AuthMethod{ssh.PublicKeys(signer)},
		HostKeyCallback: hostKey,
		Timeout:         10 * time.Second,
	}
	return ssh.Dial("tcp", addr, cfg)
}

// keepAlive is ServerAliveInterval: a request the server must answer. If it does
// not, the TCP connection is half-dead (NAT timeout, Wi-Fi switch) and we close it.
func keepAlive(client *ssh.Client, every time.Duration, misses int) {
	t := time.NewTicker(every)
	defer t.Stop()
	failed := 0
	for range t.C {
		if _, _, err := client.SendRequest("keepalive@openssh.com", true, nil); err != nil {
			failed++
			if failed >= misses {
				slog.Warn("keepalive failed, closing", "misses", failed)
				client.Close()
				return
			}
			continue
		}
		failed = 0
	}
}

// pipe copies both ways and returns when either side ends.
func pipe(a, b net.Conn) {
	done := make(chan struct{}, 2)
	cp := func(dst, src net.Conn) {
		io.Copy(dst, src)
		done <- struct{}{}
	}
	go cp(a, b)
	go cp(b, a)
	<-done
	a.Close()
	b.Close()
}

func (f *forwarder) handle(local net.Conn) {
	client := f.current()
	if client == nil {
		local.Close()
		return
	}
	// The dial happens ON the bastion: f.target is resolved from its point of view.
	remote, err := client.Dial("tcp", f.target)
	if err != nil {
		slog.Error("open channel", "target", f.target, "err", err)
		local.Close()
		return
	}
	pipe(local, remote)
}

func (f *forwarder) serve(ctx context.Context, ln net.Listener) {
	go func() { <-ctx.Done(); ln.Close() }()
	for {
		c, err := ln.Accept()
		if err != nil {
			if errors.Is(err, net.ErrClosed) {
				return
			}
			slog.Error("accept", "err", err)
			continue
		}
		go f.handle(c)
	}
}

func main() {
	bastion := flag.String("bastion", "127.0.0.1:2222", "bastion host:port")
	user := flag.String("user", "dev", "SSH user")
	key := flag.String("key", "", "private key file")
	known := flag.String("known-hosts", os.ExpandEnv("$HOME/.ssh/known_hosts"), "known_hosts file")
	listen := flag.String("listen", "127.0.0.1:5433", "local listen address (keep it on loopback)")
	target := flag.String("target", "10.141.0.30:5432", "host:port as seen FROM the bastion")
	flag.Parse()

	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	defer stop()

	ln, err := net.Listen("tcp", *listen)
	if err != nil {
		slog.Error("listen", "err", err)
		os.Exit(1)
	}
	f := &forwarder{target: *target}
	go f.serve(ctx, ln)

	backoff := time.Second
	for ctx.Err() == nil {
		client, err := dial(*bastion, *user, *key, *known)
		if err != nil {
			slog.Error("dial bastion", "err", err, "retry_in", backoff)
			select {
			case <-time.After(backoff):
			case <-ctx.Done():
			}
			backoff = min(backoff*2, 30*time.Second)
			continue
		}
		backoff = time.Second
		f.set(client)
		slog.Info("tunnel up", "listen", *listen, "via", *bastion, "target", *target)
		go keepAlive(client, 15*time.Second, 3)
		go func() { <-ctx.Done(); client.Close() }()
		client.Wait() // blocks until the SSH connection ends
		f.set(nil)
		slog.Warn("tunnel down")
	}
}

Real run against the lab bastion (the first probe is before the forwarder starts; then every SSH session on the bastion is killed to simulate a NAT timeout):

$ tunnelhealth -addr 127.0.0.1:5433
probe=1 addr=127.0.0.1:5433 verdict=FAIL rtt=456µs detail="nothing listens on the local end: tunnel process is down"
$ sshforward -bastion 127.0.0.1:2222 -user dev -key id_lab -known-hosts known_hosts_lab -listen 127.0.0.1:5433 -target 10.141.0.30:5432
INFO tunnel up listen=127.0.0.1:5433 via=127.0.0.1:2222 target=10.141.0.30:5432
$ tunnelhealth -addr 127.0.0.1:5433
probe=1 addr=127.0.0.1:5433 verdict=OK rtt=5.454ms detail="PostgreSQL answered 'N'"
# docker exec bastion pkill -f "sshd: dev"
WARN tunnel down
INFO tunnel up listen=127.0.0.1:5433 via=127.0.0.1:2222 target=10.141.0.30:5432

Go: a health checker over the tunnel ​

A TCP connect to the local port proves only that the forwarder listens. This probe sends the 8-byte PostgreSQL SSLRequest and expects one byte back, so it proves the whole path to the database, and it tells the failure layers apart (the same four layers as the Laravel command below).

go
// Command tunnelhealth probes a PostgreSQL endpoint THROUGH a tunnel and says
// which layer is broken. It sends the 8-byte SSLRequest (length 8, code
// 80877103 = 0x04D2162F) that every PostgreSQL client may send first; the
// server answers one byte, 'S' (TLS available) or 'N' (no TLS).
package main

import (
	"errors"
	"flag"
	"fmt"
	"io"
	"net"
	"os"
	"syscall"
	"time"
)

var sslRequest = []byte{0x00, 0x00, 0x00, 0x08, 0x04, 0xd2, 0x16, 0x2f}

type result struct {
	verdict string
	hint    string
	rtt     time.Duration
}

func probe(addr string, timeout time.Duration) result {
	start := time.Now()
	conn, err := net.DialTimeout("tcp", addr, timeout)
	if err != nil {
		return classify(err, time.Since(start), "dial")
	}
	defer conn.Close()
	conn.SetDeadline(time.Now().Add(timeout))
	if _, err := conn.Write(sslRequest); err != nil {
		return classify(err, time.Since(start), "write")
	}
	reply := make([]byte, 1)
	if _, err := io.ReadFull(conn, reply); err != nil {
		return classify(err, time.Since(start), "read")
	}
	rtt := time.Since(start)
	if reply[0] != 'S' && reply[0] != 'N' {
		return result{"FAIL", fmt.Sprintf("not PostgreSQL: first byte 0x%02x", reply[0]), rtt}
	}
	return result{"OK", fmt.Sprintf("PostgreSQL answered %q", reply[0]), rtt}
}

// classify maps Go errors to the layer that most likely failed.
func classify(err error, rtt time.Duration, stage string) result {
	var ne net.Error
	switch {
	case errors.Is(err, syscall.ECONNREFUSED):
		return result{"FAIL", "nothing listens on the local end: tunnel process is down", rtt}
	case errors.As(err, &ne) && ne.Timeout():
		return result{"FAIL", "timeout at " + stage + ": packets vanish (firewall, NAT mapping expired, MTU black hole)", rtt}
	case errors.Is(err, syscall.ECONNRESET), errors.Is(err, io.EOF), errors.Is(err, io.ErrUnexpectedEOF):
		return result{"FAIL", "tunnel accepted the connection but the far end refused: AllowTcpForwarding/PermitOpen, wrong target, security group", rtt}
	default:
		return result{"FAIL", err.Error(), rtt}
	}
}

func main() {
	addr := flag.String("addr", "127.0.0.1:5433", "tunnel local endpoint")
	timeout := flag.Duration("timeout", 3*time.Second, "per-probe timeout")
	every := flag.Duration("every", 5*time.Second, "interval between probes")
	count := flag.Int("count", 1, "number of probes (0 = forever)")
	flag.Parse()

	failures := 0
	for i := 1; *count == 0 || i <= *count; i++ {
		r := probe(*addr, *timeout)
		fmt.Printf("%s probe=%d addr=%s verdict=%s rtt=%s detail=%q\n",
			time.Now().Format(time.RFC3339), i, *addr, r.verdict, r.rtt.Round(time.Microsecond), r.hint)
		if r.verdict != "OK" {
			failures++
		}
		if *count == 0 || i < *count {
			time.Sleep(*every)
		}
	}
	if failures > 0 {
		os.Exit(1)
	}
}

The three verdicts, produced for real:

verdict=FAIL ... detail="nothing listens on the local end: tunnel process is down"                     # forwarder stopped
verdict=FAIL ... detail="tunnel accepted the connection but the far end refused: AllowTcpForwarding/PermitOpen, wrong target, security group"   # sshd AllowTcpForwarding no
verdict=FAIL rtt=3.002293s detail="timeout at read: packets vanish (firewall, NAT mapping expired, MTU black hole)"   # target 10.141.0.99: nothing there

Go: a WireGuard config generator ​

Generates a hub and N spokes with crypto/ecdh (X25519; the same curve and clamping as wg genkey), pre-shared keys, per-spoke /32 entries on the hub, PersistentKeepalive = 25 on spokes, and the MTU computed from the underlay (1500 gives 1440 over IPv4). Output files are mode 0600 because they contain private keys.

go
// Command wgconf generates a hub-and-spoke WireGuard setup: one hub with a public
// endpoint and N spokes behind NAT. It writes hub.conf and spokeN.conf, each
// with its own key pair, and prints the MTU it chose. Keys come from crypto/ecdh
// (X25519), the same curve "wg genkey" uses; no third-party code is involved.
package main

import (
	"crypto/ecdh"
	"crypto/rand"
	"encoding/base64"
	"flag"
	"fmt"
	"net/netip"
	"os"
	"path/filepath"
	"text/template"
)

type keyPair struct{ Private, Public string }

// newKeyPair mirrors "wg genkey | wg pubkey". The clamping is what wg genkey
// does; X25519 would clamp on use anyway, but stored keys are clamped too.
func newKeyPair() (keyPair, error) {
	raw := make([]byte, 32)
	if _, err := rand.Read(raw); err != nil {
		return keyPair{}, err
	}
	raw[0] &= 248
	raw[31] = (raw[31] & 127) | 64
	priv, err := ecdh.X25519().NewPrivateKey(raw)
	if err != nil {
		return keyPair{}, err
	}
	enc := base64.StdEncoding
	return keyPair{enc.EncodeToString(raw), enc.EncodeToString(priv.PublicKey().Bytes())}, nil
}

type peer struct {
	PublicKey, PresharedKey, AllowedIPs, Endpoint string
	Keepalive                                     int
}

type conf struct {
	Address, PrivateKey string
	ListenPort          int
	MTU                 int
	Peers               []peer
}

var tmpl = template.Must(template.New("wg").Parse(`[Interface]
Address = {{.Address}}
PrivateKey = {{.PrivateKey}}
{{- if .ListenPort}}
ListenPort = {{.ListenPort}}
{{- end}}
MTU = {{.MTU}}
{{range .Peers}}
[Peer]
PublicKey = {{.PublicKey}}
PresharedKey = {{.PresharedKey}}
AllowedIPs = {{.AllowedIPs}}
{{- if .Endpoint}}
Endpoint = {{.Endpoint}}
{{- end}}
{{- if .Keepalive}}
PersistentKeepalive = {{.Keepalive}}
{{- end}}
{{end}}`))

// tunnelMTU is the underlay MTU minus WireGuard's overhead:
// outer IP (20 for IPv4, 40 for IPv6) + UDP 8 + WireGuard data header 16 + Poly1305 tag 16.
func tunnelMTU(underlay int, v6 bool) int {
	ip := 20
	if v6 {
		ip = 40
	}
	return underlay - ip - 8 - 16 - 16
}

func write(dir, name string, c conf) error {
	f, err := os.OpenFile(filepath.Join(dir, name), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600)
	if err != nil {
		return err
	}
	defer f.Close()
	return tmpl.Execute(f, c)
}

func main() {
	subnet := flag.String("subnet", "10.200.0.0/24", "tunnel subnet; hub gets .1, spokes .2, .3, ...")
	endpoint := flag.String("endpoint", "vpn.example.com:51820", "hub public host:port")
	spokes := flag.Int("spokes", 3, "number of spokes")
	underlay := flag.Int("underlay-mtu", 1500, "MTU of the physical path")
	full := flag.Bool("full-tunnel", false, "spokes send ALL traffic (0.0.0.0/0) through the hub")
	dir := flag.String("out", "wg-out", "output directory")
	flag.Parse()

	prefix, err := netip.ParsePrefix(*subnet)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	if err := os.MkdirAll(*dir, 0o700); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	mtu := tunnelMTU(*underlay, false)

	hubKeys, _ := newKeyPair()
	hub := conf{Address: netip.PrefixFrom(prefix.Addr().Next(), prefix.Bits()).String(), PrivateKey: hubKeys.Private, ListenPort: 51820, MTU: mtu}

	addr := prefix.Addr().Next() // .1 is the hub
	for i := 1; i <= *spokes; i++ {
		addr = addr.Next()
		keys, err := newKeyPair()
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
		psk := make([]byte, 32)
		rand.Read(psk)
		pskB64 := base64.StdEncoding.EncodeToString(psk)

		// Hub side: the spoke may only use ITS OWN address as a source (/32).
		hub.Peers = append(hub.Peers, peer{PublicKey: keys.Public, PresharedKey: pskB64, AllowedIPs: addr.String() + "/32"})

		// Spoke side: everything for the tunnel subnet (or everything at all) goes to the hub.
		allowed := prefix.Masked().String()
		if *full {
			allowed = "0.0.0.0/0, ::/0"
		}
		spoke := conf{
			Address: addr.String() + "/32", PrivateKey: keys.Private, MTU: mtu,
			Peers: []peer{{PublicKey: hubKeys.Public, PresharedKey: pskB64, AllowedIPs: allowed, Endpoint: *endpoint, Keepalive: 25}},
		}
		if err := write(*dir, fmt.Sprintf("spoke%d.conf", i), spoke); err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
		fmt.Printf("spoke%d  %-15s public key %s\n", i, addr, keys.Public)
	}
	if err := write(*dir, "hub.conf", hub); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	fmt.Printf("hub     %-15s public key %s  mtu=%d (underlay %d)\n", hub.Address, hubKeys.Public, mtu, *underlay)
}
$ wgconf -spokes 2 -out out
spoke1  10.200.0.2      public key Epiy/rA6KvR03TFEUdvJ4i4HzzQ8xeLpmClz066OaiQ=
spoke2  10.200.0.3      public key XErOdL7HzO3xLyVOX+D1+v80Wf7Q6/d+RqqxFzE/OhQ=
hub     10.200.0.1/24   public key WPfKcYYogBKfISuSTzk0oA7m9+dRb4e1KYGxmlfoS1E=  mtu=1440 (underlay 1500)
$ grep PrivateKey out/spoke1.conf | cut -d' ' -f3 | wg pubkey      # does wg derive the same public key?
Epiy/rA6KvR03TFEUdvJ4i4HzzQ8xeLpmClz066OaiQ=
$ wg-quick strip out/hub.conf                                       # parses cleanly
[Peer]
PublicKey = Epiy/rA6KvR03TFEUdvJ4i4HzzQ8xeLpmClz066OaiQ=
AllowedIPs = 10.200.0.2/32

The derived public key matches wg pubkey, and wg-quick up accepted the hub file (the lab keys above were throwaway and destroyed). For a team, keep the spokes' keys on their devices and distribute only public keys; this generator is for labs, CI and bootstrap.

Verifying a webhook through a tunnel in Go ​

The receiver of a cloudflared or ngrok URL must verify the sender, because the URL is public. The check is the same in every language: parse the timestamp, compute HMAC-SHA256 over timestamp + "." + raw body, compare in constant time, reject old timestamps.

go
// Package webhookverify checks the signature of a webhook that arrived through a
// public tunnel (cloudflared, ngrok). The tunnel URL is public, so the sender is
// authenticated by an HMAC, never by its source IP.
package webhookverify

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"errors"
	"strconv"
	"strings"
	"time"
)

// Verify checks a header of the form "t=<unix seconds>,v1=<hex>" against
// HMAC-SHA256(secret, t + "." + rawBody). The timestamp is inside the signed text,
// so a captured request cannot be replayed after the tolerance window.
func Verify(header string, rawBody, secret []byte, tolerance time.Duration, now time.Time) error {
	var ts, sig string
	for _, part := range strings.Split(header, ",") {
		k, v, _ := strings.Cut(strings.TrimSpace(part), "=")
		switch k {
		case "t":
			ts = v
		case "v1":
			sig = v
		}
	}
	sec, err := strconv.ParseInt(ts, 10, 64)
	if err != nil {
		return errors.New("missing or invalid timestamp")
	}
	if d := now.Sub(time.Unix(sec, 0)); d > tolerance || d < -tolerance {
		return errors.New("timestamp outside the tolerance window")
	}
	mac := hmac.New(sha256.New, secret)
	mac.Write([]byte(ts + "."))
	mac.Write(rawBody)
	want := hex.EncodeToString(mac.Sum(nil))
	if !hmac.Equal([]byte(want), []byte(sig)) { // constant-time comparison
		return errors.New("invalid signature")
	}
	return nil
}

A table-driven test next to it (verify_test.go) covers a valid signature, a tampered body, a stale timestamp and a missing header; go test ./webhookverify passes. The HTTP handler reads the raw body with io.ReadAll(r.Body) first, calls Verify, answers 401 on error and 202 after queueing the work.

Laravel and PHP ​

Laravel code for the three jobs developers actually have: reach a private database from a laptop, develop webhooks through a public tunnel, and put a demo on a server. PHP is not installed on the authoring machine, so these files were reviewed against the Laravel 13 documentation (processes, Artisan, database, middleware), not executed.

1. A database through ssh -L in local development. The application does not know about the tunnel: DB_HOST=127.0.0.1 and DB_PORT point at the local end. Laravel's database config reads them with env('DB_HOST', ...) and env('DB_PORT', ...) (see the Laravel 13 database docs).

ini
# .env for local development against a database that lives in a private subnet.
# The application believes the database is on this machine; the SSH tunnel makes it so.
DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5433
DB_DATABASE=app
DB_USERNAME=app_readonly
DB_PASSWORD=change-me

# Start the tunnel in another terminal (or from dev-tunnel.sh):
#   ssh -N -L 127.0.0.1:5433:db.internal:5432 bastion
# 127.0.0.1:5433 is the LOCAL end; db.internal:5432 is resolved and dialled BY THE BASTION.
sh
#!/usr/bin/env bash
# Open (or reuse) an SSH local forward to the private database, then wait until it works.
set -euo pipefail

BASTION="${BASTION:-bastion}"             # Host alias from ~/.ssh/config
LOCAL_PORT="${LOCAL_PORT:-5433}"
TARGET="${TARGET:-db.internal:5432}"      # as seen FROM the bastion
CTL="${XDG_RUNTIME_DIR:-/tmp}/dbtunnel-${BASTION}.sock"

if ssh -S "$CTL" -O check "$BASTION" 2>/dev/null; then
  echo "tunnel already up"
else
  # -f: background after authentication   -N: no remote command
  # ExitOnForwardFailure: die if 5433 is taken instead of "connecting" without a forward
  # ServerAlive*: detect a half-dead connection after about 45 s and exit, so a supervisor can restart it
  ssh -f -N \
    -M -S "$CTL" \
    -o ExitOnForwardFailure=yes \
    -o ServerAliveInterval=15 -o ServerAliveCountMax=3 \
    -L "127.0.0.1:${LOCAL_PORT}:${TARGET}" \
    "$BASTION"
fi

# The listener exists as soon as ssh forks; the far end may still be wrong. Prove it.
for _ in 1 2 3 4 5; do
  if php artisan db:tunnel-check --quiet; then echo "database reachable through the tunnel"; exit 0; fi
  sleep 1
done
echo "tunnel is up but the database does not answer: see 'php artisan db:tunnel-check'" >&2
exit 1

The Artisan command below separates the four failure layers (the same ones as the Go probe), so "SQLSTATE connection refused" does not send you to the wrong place. It uses $this->components->error()/info(), self::SUCCESS/self::FAILURE and DB::connection($name)->selectOne(...):

php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Throwable;

// php artisan db:tunnel-check
// Tells the four failure layers apart, in order, instead of printing one vague
// "SQLSTATE[08006] connection refused":
//   1. nothing listens on DB_HOST:DB_PORT          -> the tunnel process is not running
//   2. it accepts but the far end hangs up         -> sshd forbids forwarding / wrong target / security group
//   3. it accepts and nothing comes back           -> black hole (NAT timeout, firewall, MTU)
//   4. TCP works but login fails                   -> credentials, pg_hba.conf, database name
class TunnelCheckCommand extends Command
{
    protected $signature = 'db:tunnel-check {--connection= : Connection name from config/database.php}';

    protected $description = 'Check a database reached through an SSH tunnel, layer by layer';

    public function handle(): int
    {
        $name = $this->option('connection') ?: config('database.default');
        $cfg = config("database.connections.{$name}");
        $host = $cfg['host'];
        $port = (int) $cfg['port'];

        // Layer 1: is anything listening on the local end?
        $sock = @stream_socket_client("tcp://{$host}:{$port}", $errno, $err, 2);
        if ($sock === false) {
            $this->components->error("Layer 1: {$host}:{$port} refuses ({$err}). The tunnel is not running.");

            return self::FAILURE;
        }

        // Layers 2 and 3: send the PostgreSQL SSLRequest (8 bytes) and read one byte back.
        stream_set_timeout($sock, 3);
        fwrite($sock, pack('NN', 8, 80877103));
        $reply = fread($sock, 1);
        $meta = stream_get_meta_data($sock);
        fclose($sock);

        if ($meta['timed_out']) {
            $this->components->error('Layer 3: accepted but no answer within 3 s (firewall, NAT timeout, MTU black hole).');

            return self::FAILURE;
        }
        if ($reply === '' || $reply === false) {
            $this->components->error('Layer 2: the tunnel accepted and then closed. Check AllowTcpForwarding, PermitOpen, the target host and security groups.');

            return self::FAILURE;
        }

        // Layer 4: a real query with real credentials.
        try {
            $row = DB::connection($name)->selectOne('select current_user as u, inet_server_addr() as s');
            $this->components->info("OK: logged in as {$row->u}; server address {$row->s}.");
        } catch (Throwable $e) {
            $this->components->error('Layer 4: TCP works, login failed: '.$e->getMessage());

            return self::FAILURE;
        }

        return self::SUCCESS;
    }
}

Production note: a developer's -L tunnel must never be what the production app uses. Applications in the VPC connect to the private address directly through connection pooling and the rules in database security; queue workers and scheduled jobs that need another network get a VPN or a PrivateLink endpoint, not an SSH process.

2. Webhook development through cloudflared or ngrok. Register the public URL with the provider, verify the signature on every request, trust forwarded headers only on a development machine, and answer fast. The middleware registered in bootstrap/app.php (Laravel 13: $middleware->alias() and $middleware->trustProxies()):

php
<?php

// bootstrap/app.php (Laravel 13) for local development behind a tunnel edge.
use App\Http\Middleware\VerifyWebhookSignature;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->alias(['webhook.signed' => VerifyWebhookSignature::class]);

        // cloudflared / ngrok are reverse proxies: they reach the app over plain HTTP from
        // 127.0.0.1 and put the public scheme and client address in X-Forwarded-*.
        // Trust them ONLY on a development machine; in production list your real proxy CIDRs.
        if (env('APP_ENV') === 'local') {
            $middleware->trustProxies(
                at: ['127.0.0.1'],
                headers: Request::HEADER_X_FORWARDED_FOR
                    | Request::HEADER_X_FORWARDED_HOST
                    | Request::HEADER_X_FORWARDED_PORT
                    | Request::HEADER_X_FORWARDED_PROTO,
            );
        }
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        //
    })
    ->create();
php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

// Local webhook development through cloudflared or ngrok:
//   cloudflared tunnel --url http://localhost:8000      (prints https://<random>.trycloudflare.com)
//   ngrok http 8000                                     (prints https://<random>.ngrok-free.app)
// The URL is PUBLIC. Anyone who learns it can POST to your laptop, so authenticate the
// SENDER with a signature (never with the source IP: it is the tunnel edge's, not the provider's).
//
// Scheme (modelled on Stripe's "t=...,v1=..." header; other providers differ, so follow
// the documented scheme of the provider you integrate):
//   signature = HMAC-SHA256(secret, "{timestamp}.{raw body}")   header: X-Signature: t=1764100000,v1=ab12...
// The timestamp is part of the signed text so a captured request cannot be replayed later.
class VerifyWebhookSignature
{
    private const TOLERANCE_SECONDS = 300;

    public function handle(Request $request, Closure $next): Response
    {
        $header = (string) $request->header('X-Signature', '');
        parse_str(str_replace(',', '&', $header), $parts);
        $timestamp = (int) ($parts['t'] ?? 0);
        $given = (string) ($parts['v1'] ?? '');

        if ($timestamp === 0 || abs(time() - $timestamp) > self::TOLERANCE_SECONDS) {
            return response('stale or missing timestamp', 401);
        }

        // getContent() is the RAW body. Re-encoding $request->all() would change the bytes.
        $expected = hash_hmac('sha256', $timestamp.'.'.$request->getContent(), config('services.provider.webhook_secret'));

        if (! hash_equals($expected, $given)) {
            return response('invalid signature', 401);
        }

        return $next($request);
    }
}
php
<?php

// routes/api.php
use App\Jobs\HandleProviderWebhook;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::post('/webhooks/provider', function (Request $request) {
    // Acknowledge fast, work in a queue: the tunnel edge and the sender both time out quickly.
    HandleProviderWebhook::dispatch($request->getContent());

    return response('', 202);
})->middleware('webhook.signed');

3. ssh -R for a demo environment. A command that keeps a reverse tunnel alive with the Process facade (Process::forever()->run([...]), $result->exitCode()), with ExitOnForwardFailure so a taken port is a visible failure:

php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Process;

// php artisan demo:expose
// Publishes the local dev server on the demo host with a reverse tunnel (ssh -R) and
// restarts the tunnel when it drops (autossh in 30 lines). People open
// http://demo.example.com:9000 and reach YOUR laptop.
//
// Server side (sshd_config on the demo host), otherwise the port binds to loopback only:
//   GatewayPorts clientspecified
// and a firewall rule that allows 9000 from where the viewers are. Put a reverse proxy
// with TLS and authentication in front for anything beyond a five-minute demo.
class DemoExposeCommand extends Command
{
    protected $signature = 'demo:expose {--host=demo-host : ssh alias} {--remote=9000} {--local=8000}';

    protected $description = 'Expose the local dev server on a demo host through ssh -R';

    public function handle(): int
    {
        $spec = sprintf('0.0.0.0:%d:127.0.0.1:%d', $this->option('remote'), $this->option('local'));

        while (true) {
            $this->components->info("ssh -R {$spec} via {$this->option('host')}");

            $result = Process::forever()->run([
                'ssh', '-N',
                '-o', 'ExitOnForwardFailure=yes',   // fail loudly if the remote port is taken
                '-o', 'ServerAliveInterval=15',
                '-o', 'ServerAliveCountMax=3',
                '-R', $spec,
                $this->option('host'),
            ]);

            $this->components->warn('tunnel ended (exit '.$result->exitCode().'), retrying in 5 s');
            sleep(5);
        }
    }
}
Laravel APIWhat it doesNote
DB_HOST, DB_PORT in .envRead by config/database.phpPoint at the tunnel's local end in development only
DB::connection($name)->selectOne($sql)One row from a named connectionUse for the health check; a real query proves login
Process::forever()->run([...])Runs a command with no timeoutArray form avoids shell quoting; returns a result with exitCode(), successful(), failed()
$middleware->alias([...])Names a middleware for route useIn bootstrap/app.php
$middleware->trustProxies(at:, headers:)Declares trusted proxies'*' or the tunnel edge only in local development
$request->getContent()The raw request bodyNeeded for signature checks; never re-encode JSON
hash_hmac() / hash_equals()HMAC and constant-time comparisonNever == for signatures
$this->components->error()Styled console outputArtisan commands

Choosing ​

SituationRecommendationExtra techniqueReason
One developer, one private database, occasionallyssh -L through the bastionLocalForward, ExitOnForwardFailure, certificatesNo new infrastructure
A team reaching many private hostsBastion with ProxyJump and short-lived certificatesTeleport or Boundary when audit and recording matterCentral logging, no key sprawl
Always-on link between two sitesSite-to-site IPsec (cloud gateways) or WireGuard between routersBGP, two tunnels, MTU clampingStandard, redundant
A few people and servers, quick private networkMesh (Tailscale/Headscale/Netbird) with ACLsSubnet router into the VPC, exit node for travelNAT traversal solved, central keys
Large company, many rolesZero-trust access in front of apps, VPN only for legacyDevice posture, per-app policySmaller blast radius
Strict firewall, only 443 openOpenVPN over TCP 443, SSH over 443, Cloudflare TunnelPass hostile networks
Webhooks and demoscloudflared / ngrok quick tunnel, or ssh -R + proxySignature verificationPublic URL without router changes
Kubernetes debuggingkubectl port-forwardRBACNo exposure
Service in another VPC/accountPrivateLinkEndpoint policiesExpose one service, not a network
Many VPCs and officesTransit GatewayRoute tables, non-overlapping CIDRsHub instead of a peering mesh
Roaming laptops with changing Wi-FiWireGuard / meshPersistentKeepaliveEndpoint follows the packets
Public-internet privacy for browsingA full tunnel to a provider you trustKill switch, IPv6 ::/0Different trust model, not company access

In architecture: from a single process to a distributed system ​

Monolith (one process, one database) ​

One Laravel or Go app on one server with one Postgres. Nothing needs a tunnel in production; the app and the database share a host or a private subnet. A tunnel appears at the edges of the developer workflow: DB_HOST=127.0.0.1 with ssh -L to run the app locally against a staging copy, ssh -R or cloudflared to receive a webhook from a payment provider while building it, and one bastion (or one WireGuard peer) so the founder can reach the server without opening 22 to the world. Example: the staging database lives in a private subnet; developers run dev-tunnel.sh, and php artisan db:tunnel-check tells them which layer broke.

Modular monolith ​

Several modules, possibly several databases (reporting replica, search index, cache). The VPC has public, application and data subnets; security groups say "the data subnet accepts 5432 only from the application subnet and the bastion". Developers keep one ~/.ssh/config with ProxyJump bastion for every private host and LocalForward lines for the replica and the cache. A WireGuard or Tailscale subnet router replaces the bastion once more than a handful of people need many ports. Example: the analytics module reads a read replica through the same tunnel on a different local port (5434), so a mistake cannot write to the primary.

Microservices ​

Services in several VPCs or accounts, a Kubernetes cluster and managed databases. Developers need private cluster IPs and DNS (*.svc.cluster.local): a Tailscale subnet router pod advertising the pod and service CIDRs with ACLs per team, or kubectl port-forward for one-offs. Services call each other through service mesh or mTLS, not VPN tunnels: a VPN authenticates networks and devices, mTLS authenticates workloads. Partner access uses PrivateLink or a zero-trust connector; the partner never receives a route into the VPC. Example flow: engineer laptop -> mesh with SSO and ACL -> subnet router in the cluster -> payments.prod.svc.cluster.local:8080; the audit shows the engineer's identity because the mesh, not the pod network, authenticated them.

Distributed data: replicas, caches, multi-region ​

A primary in one region and replicas in others: replication traffic crosses regions over IPsec or Transit Gateway inter-region peering, or a mesh between database hosts. Tunnels add latency (one more hop to a relay when NAT traversal fails: DERP is not a data-plane for replication lag), overhead (MTU 1440 or less shrinks every page of WAL) and a failure mode that looks like database trouble: a TCP session stalls silently when a NAT forgets the flow, so replication clients need TCP keepalives and short timeouts. Overlapping CIDRs between regions or acquired companies turn into NETMAP/renumbering projects. Example: a read replica in another cloud connected by WireGuard with PersistentKeepalive = 25, MTU = 1380 and a Prometheus alert on latest handshake older than three minutes.

Scaling path ​

ScaleAccess patternWhat changes
1x: one engineerssh -L, one bastionConfig in ~/.ssh/config
10x: a teamBastion with certificates, or a WireGuard hub; ACL by groupKey lifecycle, onboarding and offboarding, central logs
100x: an organisationMesh or zero-trust access per app, SSO, device posture, session recordingPolicy as code, break-glass, IPAM and non-overlapping ranges, regional relays
Multi-cloudTransit hubs, BGP, PrivateLink, a mesh over the topEgress cost, MTU, route leaks; DNS per environment

Lab ​

Steps 1 to 5 were run on the authoring machine exactly as the commands are written (bash) (Docker Desktop on macOS, kernel 7.0.14-linuxkit, alpine:3.20, wireguard-tools v1.0.20210914, OpenSSH 9.7 in the bastion, 10.3 on the client). Names are prefixed vpnlab-; clean up with the last block.

1. WireGuard between two containers ​

docker network create --subnet 10.140.0.0/24 vpnlab-net
docker run -d --name vpnlab-a --network vpnlab-net --ip 10.140.0.10 --cap-add NET_ADMIN alpine:3.20 sleep 7200
docker run -d --name vpnlab-b --network vpnlab-net --ip 10.140.0.20 --cap-add NET_ADMIN alpine:3.20 sleep 7200
for n in a b; do
  docker exec vpnlab-$n sh -c 'apk add --no-cache wireguard-tools iproute2 iputils tcpdump >/dev/null'
  docker exec vpnlab-$n sh -c 'mkdir -p /etc/wireguard && umask 077 && wg genkey | tee /etc/wireguard/priv | wg pubkey > /etc/wireguard/pub'
done
PA=$(docker exec vpnlab-a cat /etc/wireguard/pub); PB=$(docker exec vpnlab-b cat /etc/wireguard/pub)
docker exec vpnlab-a sh -c "cat > /etc/wireguard/wg0.conf <<EOF
[Interface]
Address = 10.200.0.1/24
ListenPort = 51820
PrivateKey = \$(cat /etc/wireguard/priv)

[Peer]
PublicKey = $PB
AllowedIPs = 10.200.0.2/32
Endpoint = 10.140.0.20:51820
PersistentKeepalive = 25
EOF
chmod 600 /etc/wireguard/wg0.conf"
docker exec vpnlab-b sh -c "cat > /etc/wireguard/wg0.conf <<EOF
[Interface]
Address = 10.200.0.2/24
ListenPort = 51820
PrivateKey = \$(cat /etc/wireguard/priv)

[Peer]
PublicKey = $PA
AllowedIPs = 10.200.0.1/32
EOF
chmod 600 /etc/wireguard/wg0.conf"
docker exec vpnlab-a wg-quick up wg0 ; docker exec vpnlab-b wg-quick up wg0
docker exec vpnlab-a ping -c 3 10.200.0.2            # expect 0% loss, ~0.2 ms
docker exec vpnlab-a wg show                          # expect: latest handshake: N seconds ago, transfer both directions
docker exec vpnlab-b sh -c 'tcpdump -ni eth0 -c 2 -X udp port 51820 & sleep 1; ping -c 1 10.200.0.1 >/dev/null; wait'   # UDP, length 128 (84-byte ping + padding + tag); payload starts 04 00 00 00

2. Break and fix AllowedIPs ​

docker exec vpnlab-a wg set wg0 peer $PB allowed-ips 10.200.0.99/32
docker exec vpnlab-a ping -c 2 -W 1 10.200.0.2        # expect: ping: sendmsg: Required key not available
docker exec vpnlab-a wg set wg0 peer $PB allowed-ips 10.200.0.2/32     # fixed
docker exec vpnlab-b wg set wg0 peer $PA allowed-ips 10.200.0.77/32    # now b DROPS a's source address
docker exec vpnlab-a ping -c 2 -W 1 10.200.0.2        # expect: 100% loss, no error
docker exec vpnlab-b wg show wg0 transfer             # received keeps growing: they arrive, then die at the source check
docker exec vpnlab-b wg set wg0 peer $PA allowed-ips 10.200.0.1/32     # restore before the next step

3. Roaming and MTU ​

# roaming: change b's underlay address, then ping a from b; a's endpoint for b updates by itself
docker exec vpnlab-b sh -c 'ip addr flush dev eth0; ip addr add 10.140.0.21/24 dev eth0; ip route add default via 10.140.0.1'
docker exec vpnlab-b ping -c 2 10.200.0.1 ; docker exec vpnlab-a wg show wg0 endpoints     # expect 10.140.0.21:51820

# MTU black hole: underlay 1280, tunnel 1420, a middlebox that drops IP fragments
docker exec vpnlab-b sh -c 'apk add --no-cache iproute2-tc >/dev/null; tc qdisc add dev eth0 ingress; tc filter add dev eth0 parent ffff: protocol ip u32 match u16 0x2000 0x3fff at 6 action drop'
for n in a b; do docker exec vpnlab-$n ip link set dev eth0 mtu 1280; done
docker exec vpnlab-a ping -c 2 -W 1 -s 56 10.200.0.2      # works
docker exec vpnlab-a ping -c 3 -W 1 -s 1300 10.200.0.2    # 100% loss
for n in a b; do docker exec vpnlab-$n ip link set dev wg0 mtu 1220; done
docker exec vpnlab-a ping -c 2 -W 1 -s 1192 -M do 10.200.0.2   # works
docker exec vpnlab-a ping -c 1 -W 1 -s 1193 -M do 10.200.0.2   # ping: local error: message too long, mtu=1220

4. SSH to a Postgres container through a bastion ​

Use the Compose file (bastion publishes only 127.0.0.1:2222; db and web exist only on an internal network):

yaml
# Lab: a private subnet with a database and a web server, reachable only through a bastion.
#   ssh-keygen -t ed25519 -N '' -f keys/id_lab        (creates keys/id_lab.pub)
#   docker compose -f compose.lab.yaml up -d
#   ssh -i keys/id_lab -p 2222 dev@127.0.0.1
services:
  bastion:
    image: alpine:3.20
    # Installs openssh at start (lab only; build an image for anything real).
    command: >
      sh -c "apk add --no-cache openssh-server >/dev/null &&
             adduser -D -s /bin/sh dev &&
             echo \"dev:$$(head -c12 /dev/urandom | base64)\" | chpasswd &&
             mkdir -p /home/dev/.ssh && cp /keys/id_lab.pub /home/dev/.ssh/authorized_keys &&
             chown -R dev:dev /home/dev/.ssh && chmod 700 /home/dev/.ssh && chmod 600 /home/dev/.ssh/authorized_keys &&
             ssh-keygen -A >/dev/null &&
             sed -i 's/^AllowTcpForwarding.*/AllowTcpForwarding yes/' /etc/ssh/sshd_config &&
             exec /usr/sbin/sshd -D -e"
    volumes: ["./keys:/keys:ro"]
    ports: ["127.0.0.1:${BASTION_PORT:-2222}:22"]   # the ONLY thing published to the host
    networks: [public, private]

  db:
    image: postgres:18-alpine
    environment: { POSTGRES_PASSWORD: labpass }
    networks: [private]               # no ports: only reachable from inside "private"

  web:
    image: nginx:alpine
    networks: [private]

networks:
  public: {}
  private:
    internal: true                    # no route to the internet at all
mkdir -p keys && ssh-keygen -t ed25519 -N '' -f keys/id_lab && docker compose -f compose.lab.yaml up -d
SSH="ssh -i keys/id_lab -p 2222 -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=keys/known_hosts"
until $SSH -o ConnectTimeout=3 dev@127.0.0.1 true 2>/dev/null; do sleep 3; done   # the bastion installs openssh on first start (10-60 s)
nc -zv 127.0.0.1 5432                                    # refused: the db is not published
$SSH -fN -L 127.0.0.1:5433:db:5432 dev@127.0.0.1         # "db" is resolved BY the bastion
nc -zv 127.0.0.1 5433                                    # succeeded
psql -h 127.0.0.1 -p 5433 -U postgres                    # password labpass (or the Go tunnelhealth probe)
$SSH -D 1080 -fN dev@127.0.0.1 && curl -s --socks5-hostname 127.0.0.1:1080 http://web/ | head -4   # nginx welcome page
docker compose -f compose.lab.yaml exec bastion sshd -T | grep -E 'allowtcp|gatewayports'

5. Expose a local Go server with ssh -R through the same bastion ​

cat > /tmp/serve.go <<'EOF'
package main
import ("fmt";"log";"net/http")
func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "hello from my laptop") }); log.Fatal(http.ListenAndServe("127.0.0.1:8080", nil)) }
EOF
go run /tmp/serve.go &
$SSH -fN -o ExitOnForwardFailure=yes -R 9000:127.0.0.1:8080 dev@127.0.0.1
docker compose -f compose.lab.yaml exec bastion sh -c 'apk add --no-cache curl >/dev/null; curl -s http://127.0.0.1:9000/'   # hello from my laptop
docker compose -f compose.lab.yaml exec db wget -qO- -T 3 http://bastion:9000/ || echo refused   # a different container on the private network
# refused: GatewayPorts is "no". Set "GatewayPorts clientspecified" in the bastion's sshd_config, HUP sshd, reconnect with -R 0.0.0.0:9000:..., repeat the last curl.

6. Clean up ​

docker rm -f vpnlab-a vpnlab-b ; docker network rm vpnlab-net
docker compose -f compose.lab.yaml down ; pkill -f 'ssh -i keys/id_lab' ; pkill -f serve.go

Common failures ​

SymptomLikely causeHow to confirmFix
WireGuard: wg show has no latest handshakeUDP 51820 blocked, wrong Endpoint, wrong or swapped public key, peer not configuredtcpdump -ni eth0 udp port 51820 on the hub: do 148-byte packets arrive? do 92-byte replies leave?Open UDP, fix endpoint/keys; the hub must know the client's public key
Handshake OK, ping fails, transfer shows only sentPeer's AllowedIPs too narrow or source mismatch; peer has no route/forwardingping: sendmsg: Required key not available means no peer owns the destinationFix AllowedIPs on both ends; net.ipv4.ip_forward=1 and FORWARD rules on the hub
Handshake OK, small packets work, large hangMTU/fragment black holeping -M do -s 1392; message too long or silenceLower MTU, clamp MSS, allow ICMP type 3 code 4
Works for minutes, then dies until you ping firstNAT/conntrack timeout on the idle sideconntrack -L: no entry; tcpdump: peer sends, NAT dropsPersistentKeepalive = 25 on the NATed peer
Full tunnel: wg-quick up fails on src_valid_markRead-only sysctl in a containersysctl: error setting key ... Read-only file systemdocker run --sysctl net.ipv4.conf.all.src_valid_mark=1
Internal names do not resolve through the VPNSplit DNS missingdig db.internal vs dig @10.200.0.1 db.internalDNS =, resolvectl domain wg0 ~internal, MagicDNS routes
Tunnel is up, database refusesWrong target host or port from the bastion's view; security group; pg_hba.conf does not allow the bastion's addressFrom the bastion: nc -zv db 5432Fix the -L target; allow the bastion's group; add the bastion CIDR to pg_hba.conf
ssh -L: listener exists but every connection resetsAllowTcpForwarding no or PermitOpen mismatchchannel N: open failed: administratively prohibited in ssh -v; sshd -TSet AllowTcpForwarding yes/local, add the target to PermitOpen
ssh -L: bind [127.0.0.1]:5433: Address already in use / cannot listen to portPort taken by an earlier tunnellsof -nP -iTCP:5433 -sTCP:LISTENKill the old ssh; use ExitOnForwardFailure yes
ssh -R: works on the server only, not from outsideBound to loopback because GatewayPorts nonetstat -ltn on the server: 127.0.0.1:9000GatewayPorts clientspecified + -R 0.0.0.0:9000:..., firewall
ssh -J fails with Host key verification failed although -o StrictHostKeyChecking=no was givenCommand-line options apply to the destination, not the jump hostThe manual's notePut the settings in ~/.ssh/config for the jump host
SOCKS proxy: names do not resolveClient resolves locally (socks5 vs socks5h)curl --socks5-hostname works, --socks5 does notUse remote DNS
Client VPN connected, office subnet unreachableOverlapping CIDR with the home networkip route get 192.168.1.10 stays on the LAN interfaceRenumber or NAT; choose rarely used ranges
Site-to-site up, one direction failsMissing return route or security group/NACLRoute tables on both sides; flow logsAdd routes; allow the remote CIDR
AWS Site-to-Site: large transfers stallNo Path MTU DiscoveryDocumented limitationLower MTU or clamp MSS on the customer gateway
kubectl port-forward dies after idle/pod restartIt is bound to one pod; no reconnectProcess exits or errors lost connection to podRe-run; use a Service/Ingress or a mesh for stable access
Tailscale shows relay instead of directHard NAT on both sides, UDP blockedtailscale ping peer reports DERPOpen UDP, enable IPv6, run a peer relay or own DERP

Common misconceptions ​

BeliefReality
"A VPN makes me anonymous"It moves the exit point and hides traffic from the local network; the VPN operator sees everything it forwards
"ssh -L host part is resolved on my laptop"It is resolved and dialled by the server; localhost means the server
"-R makes my server public"Only with GatewayPorts and a wildcard bind; the default is loopback
"Agent forwarding cannot leak my key"Nobody gets the key, but anyone who can read the socket can use it while you are connected
"WireGuard has a server and clients"Only peers; "server" means a stable endpoint
"AllowedIPs is a firewall for destinations"It is routing plus a source-address check per peer; 0.0.0.0/0 means "everything through this peer"
"A recent handshake means everything works"It proves keys and UDP reachability; MTU, routes and services are separate
"WireGuard needs keepalive everywhere"Only on peers behind NAT that must receive while idle
"Tailscale routes all my traffic through its servers"Direct WireGuard when possible; DERP is a last resort and cannot read the traffic
"VPC peering lets A reach C through B"Peering is not transitive; use Transit Gateway
"PrivateLink is a VPN"It exposes one service privately; no gateway, NAT or VPN is involved
"Zero trust means no VPN"It means no implicit trust in network location; tunnels may still carry the traffic
"Overlapping subnets work if the VPN is up"The connected route wins; the tunnel is never used for the shadowed range
"Disabling AllowTcpForwarding stops tunnelling"Not while users have a shell: "they can always install their own forwarders"
"A quick-tunnel URL is private"It is public and guessable by anyone who sees it; authenticate the sender

Cheat sheet ​

TopicWhat to remember
-Lssh -fN -o ExitOnForwardFailure=yes -L 127.0.0.1:LOCAL:HOST:PORT bastion; listener local, dial from the bastion
-Rssh -fN -R 9000:127.0.0.1:8080 server; loopback unless GatewayPorts
-Dssh -fN -D 1080 bastion; curl --socks5-hostname for remote DNS
-J / -WProxyJump bastion in config; jump-host options only work from ~/.ssh/config
MultiplexingControlMaster auto, ControlPath ~/.ssh/cm-%C, ControlPersist 10m, ssh -O check/exit
KeepaliveServerAliveInterval 15 (client), ClientAliveInterval 30 (server), autossh -M 0 or systemd
AgentPrefer ProxyJump; ssh-add -c; AllowAgentForwarding no
BastionCertificates, PermitOpen, PermitTTY no, LogLevel VERBOSE, no shell
WireGuard keyswg genkey | tee priv | wg pubkey; X25519; static key = identity
AllowedIPsRouting + source filter per key; /32 per client on the hub; 0.0.0.0/0, ::/0 = full tunnel
HandshakeNoise IK, 148 B + 92 B, rekey every 120 s, UDP only, silent to strangers
Keepalive (WG)PersistentKeepalive = 25 on NATed peers only
MTUUnderlay minus 60 (IPv4) or 80 (IPv6); 1420 default; ping -M do -s N
MeshControl plane + WireGuard + DERP fallback; ACLs; subnet router; exit node; MagicDNS
OpenVPN vs IPsecOpenVPN: TLS, 1194 or TCP 443, client VPN; IPsec: IKEv2, UDP 500/4500, site-to-site
TopologySite-to-site joins networks; client joins a device; non-overlapping CIDRs
CloudVPN = encrypted over internet; peering = non-transitive; TGW = hub; PrivateLink = one service
DNSSplit DNS for internal zones; watch IPv6 and DoH leaks
Zero trustPer-request identity, posture, per-app; connectors dial out
Reverse tunnelscloudflared / ngrok / ssh -R; verify HMAC signatures, never the source IP
Kuberneteskubectl port-forward is TCP only, RBAC on the API server; subnet router for teams

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — In ssh -L 5433:db.internal:5432 bastion, who resolves db.internal, and who connects to it? Must-know ​

Answer

Answer: The bastion's sshd resolves the name and opens the TCP connection (a direct-tcpip channel). The laptop only listens on 5433. The database therefore sees the bastion's address as the client.

2 — A -L listener accepts connections but every one is reset. Name two server-side causes and the client message that confirms it. Important ​

Answer

Answer: AllowTcpForwarding no or a PermitOpen that does not list the target (also a wrong target address). ssh -v shows channel N: open failed: administratively prohibited: open failed; sshd -T shows the effective setting.

3 — You run ssh -R 0.0.0.0:9000:localhost:8080 server and colleagues cannot reach port 9000. Why? Important ​

Answer

Answer: GatewayPorts is no (the default) so sshd binds the listener to loopback and silently ignores the wildcard. Use GatewayPorts clientspecified or yes, and open the firewall; better, put an authenticated TLS proxy in front.

4 — Why is ProxyJump safer than ssh -A through a bastion? Must-know ​

Answer

Answer: -J runs the second SSH connection end-to-end inside a channel; the key never leaves the laptop and no agent socket exists on the bastion. With -A, anyone who can read the agent socket on the bastion can use your identities while you are connected.

5 — What does AllowedIPs = 10.200.0.2/32 on the hub for a spoke do in each direction? Important ​

Answer

Answer: Outgoing: packets for 10.200.0.2 are encrypted to that peer's key. Incoming: after decryption only packets with source 10.200.0.2 are accepted from that key; others are dropped silently. So it is routing and a source filter.

6 — ping through WireGuard says Required key not available. What is wrong? Important ​

Answer

Answer: No peer's AllowedIPs covers the destination address, so cryptokey routing cannot choose a key (ENOKEY). Fix the AllowedIPs of the peer that owns that address.

7 — Small requests work through the tunnel and large ones hang. Name the cause and two fixes. Must-know ​

Answer

Answer: MTU/path-MTU black hole: oversized packets are fragmented or dropped and the ICMP "fragmentation needed" is blocked. Lower the tunnel MTU (underlay minus 60 or 80), clamp TCP MSS at the gateway, allow ICMP type 3 code 4.

8 — Which side of a WireGuard link needs PersistentKeepalive, and why 25? Important ​

Answer

Answer: The peer behind NAT or a stateful firewall that must receive while idle. 25 seconds is below the common UDP mapping timeouts (for example Linux conntrack's 30 s for a single-packet UDP flow), so the mapping never expires.

9 — Tailscale shows a connection as relayed through DERP. What does that mean for privacy and for latency? Good to know ​

Answer

Answer: The packets are still WireGuard-encrypted end to end, so the relay cannot read them; they take a longer path through a relay server because direct NAT traversal failed (hard NAT or blocked UDP), which adds latency and is slower.

10 — When do you choose VPC peering, Transit Gateway, PrivateLink and Site-to-Site VPN? Important ​

Answer

Answer: Peering: two VPCs, non-overlapping, non-transitive. Transit Gateway: many VPCs and on-prem, hub and spoke. PrivateLink: expose one service without exposing networks (overlap does not matter). Site-to-Site VPN: connect an on-premises network to a VPC over IPsec.

11 — How is a zero-trust access proxy different from a VPN for a contractor who needs one internal web app? Must-know ​

Answer

Answer: The contractor never gets a network address or routes. Each request is authenticated with SSO and checked against policy (identity, device) for that single app; a connector that dials out reaches the app; sessions are logged and revoked centrally. A VPN would give them a path to the whole subnet.

12 — Why can a webhook developed through cloudflared not be authenticated by source IP, and what do you verify instead? Must-know ​

Answer

Answer: Requests arrive from the tunnel edge, not the provider, and the URL is public. Verify an HMAC signature over timestamp plus raw body with a constant-time comparison and a short replay window.

Glossary ​

TermMeaning
TunnelA protocol carried as the payload of another protocol
EncapsulationWrapping a packet inside another packet's payload
TUN / TAPVirtual interfaces at layer 3 (IP packets) / layer 2 (Ethernet frames)
MTULargest packet an interface or path carries without fragmenting
PMTUDPath MTU Discovery: ICMP "fragmentation needed" tells the sender to shrink
MSS clampingRewriting the TCP maximum segment size on SYN packets to fit the tunnel MTU
SSH local forward (-L)Local listener whose connections the server dials onward
SSH remote forward (-R)Server listener whose connections the client dials onward
Dynamic forward (-D)A SOCKS proxy provided by ssh
SOCKS5 / socks5hProxy protocol; the h variant sends the host name to the proxy for remote resolution
ProxyJump / -JReach a host by SSH through another host without logging in to it
ProxyCommandRun a command that supplies the connection's stdin/stdout, e.g. ssh -W %h:%p jump
-WForward standard input and output to host:port over the SSH channel
ControlMaster / ControlPersistShare one SSH connection between sessions; keep it after the last one exits
ServerAliveIntervalClient-side keepalive request interval
GatewayPortssshd setting deciding whether remote forwards may bind non-loopback addresses
AllowTcpForwarding / PermitOpen / PermitListen / PermitTunnelsshd controls over forwarding, allowed targets, allowed remote listeners and tun devices
Agent forwarding (-A, ForwardAgent)Lets a remote host use your local ssh-agent
autosshSupervisor that restarts an ssh tunnel
Bastion / jump hostHardened entry point to a private network
SSH certificateA public key signed by a CA with principals and a validity period
WireGuardKernel layer 3 VPN: Noise IK, Curve25519, ChaCha20-Poly1305, UDP
Cryptokey routingThe table associating each public key with the source addresses it may use
AllowedIPsPer-peer list used both as routing table and as source filter
PersistentKeepalivePeriodic empty authenticated packet keeping a NAT mapping alive
Preshared key (PSK)Optional symmetric secret mixed into the handshake
wg-quickHelper that turns a config file into an interface, routes and scripts
fwmark / policy routingPacket marks and rules wg-quick uses so full tunnels do not capture their own packets
Mesh VPNPeer-to-peer WireGuard overlay with a control plane
Control plane / coordination serverService distributing keys, routes, DNS and ACLs
DERPTailscale's encrypted relay protocol, last-resort data path
MagicDNSTailscale feature registering names for devices
ACLPolicy deciding which devices/users reach which targets
Subnet routerA mesh device advertising a physical subnet to the mesh
Exit nodeA mesh device that carries all internet traffic of other devices
HeadscaleOpen-source self-hosted Tailscale control server
NetbirdOpen-source WireGuard mesh platform
OpenVPNTLS-based userspace VPN, UDP or TCP
IPsecSuite of protocols (IKE, ESP, AH) for network-layer encryption
IKEv2Internet Key Exchange v2 (RFC 7296): authentication and SAs for IPsec
NAT-TNAT traversal: ESP wrapped in UDP 4500 (RFC 3948)
SASecurity Association: negotiated keys and parameters for an IPsec direction
Site-to-site VPNPermanent tunnel joining two networks via gateways
Client / road-warrior VPNA device connecting to a network on demand
VGW / TGWAWS virtual private gateway (one VPC) / transit gateway (hub)
VPC peeringPrivate routing between two VPCs; non-transitive
PrivateLinkPrivate access to one service through an endpoint
Overlapping CIDRTwo networks sharing addresses; breaks routing across the join
NETMAPiptables target mapping one prefix 1:1 onto another
Split tunnel / full tunnelOnly some routes / all traffic through the VPN
Split DNSDifferent resolvers for different domains
DNS leakLookups that bypass the tunnel's resolver
Zero-trust accessPer-request identity and device-based authorization to one app
BeyondCorpGoogle's zero-trust access architecture
Identity-aware proxyProxy that authenticates and authorizes each request
ConnectorAgent that dials out and delivers requests inside the private network
Reverse tunnelThe private side dials out so the public side can reach it
cloudflared / ngrokReverse-tunnel clients of Cloudflare and ngrok
kubectl port-forwardTCP forward to a pod through the API server
conntrackKernel connection tracking table that NAT and firewalls rely on

References ​

Every URL below was fetched and its text saved under scratchpad/sources/vpn-tunnels-ssh-wireguard/ (one file per source); the HTTP status was 200 when fetched, except where noted.

Built by Morteza Negahi