Skip to content

Secure Access: VPNs, SSH and Multi-Factor Authentication

Intermediate 53 min read Part 13 of 18

How people and machines reach private systems safely: VPNs (IPsec, WireGuard), zero trust, SSH keys and certificates, bastions, and TOTP to FIDO2 MFA.

Summary#

Every real system has things that must not be on the public internet: databases, admin panels, internal dashboards, Kubernetes APIs, build servers and the servers themselves. Yet engineers, support staff, partner networks and other services need to reach them. "Secure access" is the set of techniques that let the right people and machines in, and keep everyone else out:

  • VPNs (virtual private networks) create an encrypted tunnel so a laptop (remote-access VPN) or a whole office or data centre (site-to-site VPN) behaves as if it were on the private network. The main protocols are IPsec (IKEv2 plus ESP, the enterprise and cloud standard), OpenVPN (TLS-based, runs on almost anything) and WireGuard (modern, small, fast, built into Linux).
  • Split tunnelling decides which traffic goes through the tunnel (only corporate ranges, or everything). It's a trade-off between performance and visibility.
  • Zero trust (Google's BeyondCorp is the famous example) drops the idea that "inside the network = trusted". Every request is authenticated and authorised on user identity plus device health, via an identity-aware proxy, wherever the user sits.
  • SSH (Secure Shell) is how engineers log into servers. It does a key exchange, verifies the server's host key, and authenticates the user, ideally with a public key rather than a password. The access is then funnelled through bastion hosts (jump boxes). Agent forwarding is risky, and SSH certificates (short-lived keys signed by a CA) replace sprawling authorized_keys files.
  • Multi-factor authentication (MFA) combines something you know, have and are. Authenticator apps implement HOTP (RFC 4226) and TOTP (RFC 6238): an HMAC over a counter or the current 30-second time step, truncated to 6 digits.
  • Push-notification MFA can be "bombed" until a tired user taps Approve, and OTP codes can be phished in real time. Phishing-resistant factors (FIDO2/WebAuthn security keys and passkeys, smart cards) bind the login to the real website and stop both attacks.

The modern direction is clear: fewer network-level "castle walls", more identity- and device-aware access to each application. Short-lived credentials replace long-lived keys and passwords, and phishing-resistant MFA covers everything privileged.

Why It Exists#

The basic problem comes from how IP networks work. Every machine has an IP address. Public IPs are allocated through Regional Internet Registries (RIRs such as ARIN, RIPE NCC and APNIC), and internet routers know how to reach them. Private IPs (the RFC 1918 ranges 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16) are free for anyone to use inside their own network, so they are not routable on the internet. Your database at 10.0.3.17 (usually given that address by DHCP or by your cloud VPC) is unreachable from a coffee shop. That's good for security, but it means engineers working from home, branch offices and partner companies have no path to it either.

Historically there were two bad options:

  1. Expose services publicly ("just open port 22 / 3306 / 5432 to the internet"). Internet-wide scanners like Shodan and masscan find every open port within hours. SSH servers on public IPs see thousands of brute-force login attempts per day. Exposed databases and admin consoles are a leading cause of breaches and ransomware.
  2. Trust the network perimeter. Put everything behind a firewall, and anyone inside the office network (or connected by VPN) is trusted. This "castle and moat" model fails badly when one laptop is compromised. The attacker is now "inside" and can move laterally to everything. Major breaches have followed exactly this pattern: phish one employee, get VPN or internal network access, then pivot.

Secure-access technology fixes these problems in layers:

  • Encrypted, authenticated tunnels (VPNs) give private connectivity across the public internet without exposing services.
  • Strong authentication of machines and people (SSH keys, certificates, MFA) means a stolen password alone isn't enough.
  • Identity-aware, per-application access (zero trust) means that even an attacker who gets onto a network or a VPN gets nothing without a valid identity, a healthy device and an explicit policy for each resource.
  • Short-lived credentials and auditing (SSH certificates, just-in-time access, session recording) shrink the damage window and give you evidence after an incident.

These matter in system design because access paths are part of the architecture: how operators reach production, how two data centres or a cloud VPC and an on-premises network connect, how partners integrate, and how you meet compliance rules. PCI DSS requires MFA for access into the cardholder data environment, and SOC 2 and ISO 27001 auditors expect controlled, logged administrative access.

They also differ from API authentication (covered in authentication and authorization). API keys and JWTs authenticate applications and user sessions calling your public API. This page is about network-level and administrative access, the doors into the building rather than the forms at the counter.

How It Works#

The access landscape at a glance#

There are three families of access path, and most organisations use all three:

VPN types: remote access and site-to-site#

A VPN wraps your packets inside encrypted, authenticated packets ("encapsulation") and sends them across an untrusted network to a VPN gateway, which unwraps them and forwards them onto the private network. To the applications on either end, it looks as if the two sides were on the same network.

Remote-access VPN (also called client-to-site):

  • An individual device runs a VPN client: Cisco AnyConnect/Secure Client, Palo Alto GlobalProtect, Fortinet FortiClient, an OpenVPN client, a WireGuard client, or the OS's built-in IKEv2 client.
  • The client authenticates the user (ideally through SSO plus MFA) and often checks the device (managed? disk encrypted? OS patched?).
  • The gateway assigns the client a virtual IP from a pool (say 10.200.0.0/16) and pushes routes: which destination ranges should go through the tunnel. It also pushes DNS settings, so db.internal.example.com resolves to a private IP.
  • Use cases: employees working remotely; admins reaching a cloud VPC without public endpoints; contractors given limited network access.

Site-to-site VPN:

  • Two gateways (routers, firewalls or cloud VPN gateways such as AWS Site-to-Site VPN, Azure VPN Gateway and GCP Cloud VPN) keep a permanent tunnel between two networks, such as an office and a data centre, or an on-premises network and a cloud VPC.
  • Hosts behind each gateway need no VPN software. The gateways route traffic for the remote network's CIDR into the tunnel.
  • Routing is either static (configured prefixes) or dynamic via BGP over the tunnel, so routes update automatically and redundant tunnels fail over. AWS Site-to-Site VPN gives each connection two tunnels to different endpoints for redundancy, and BGP lets the customer gateway prefer one.
  • Throughput is limited. An AWS VPN tunnel is quoted at up to about 1.25 Gbps. Because traffic goes over the public internet, latency and jitter vary. For predictable bandwidth, organisations use dedicated private links (AWS Direct Connect, Azure ExpressRoute, Google Cloud Interconnect, typically 1–100 Gbps). They often run IPsec over the private link when encryption is required.
  • Overlapping address ranges are the classic pain. If both the office and the VPC use 10.0.0.0/16, routes collide. You need NAT on the tunnel, or a renumbering. Plan non-overlapping CIDRs across all sites, VPCs and partners from day one.

There are related designs too:

  • Hub-and-spoke (AWS Transit Gateway or Azure Virtual WAN as the hub) instead of a full mesh of tunnels. n sites need n tunnels rather than n(n−1)/2.
  • SD-WAN for many branch offices, with path selection across multiple ISPs.
  • Partner/extranet VPNs, which are site-to-site, but with strict firewalling to only the APIs the partner needs.

IPsec, OpenVPN and WireGuard#

IPsec is a suite of IETF standards that secures traffic at the IP layer (Layer 3). It has two halves:

  • IKE (Internet Key Exchange; IKEv2 is RFC 7296). It runs over UDP 500, or UDP 4500 when NAT is detected (NAT traversal, RFC 3948, wraps ESP in UDP so it passes through home routers). IKE authenticates both peers, with pre-shared keys, certificates or EAP (which allows username/password plus MFA for remote access). It then negotiates security associations (SAs): agreed algorithms, keys and lifetimes. IKE first builds its own encrypted channel (the IKE SA), then negotiates "child SAs" for data, and rekeys periodically.
  • ESP (Encapsulating Security Payload, IP protocol 50) carries the data: encrypted and integrity-protected, typically with AES-GCM. In tunnel mode (site-to-site and remote access) the whole original IP packet is wrapped in a new one. In transport mode (host to host) only the payload is protected. AH (Authentication Header) provides integrity without encryption, is incompatible with NAT, and is rarely used today.

IPsec's strengths: it's a universal standard (every firewall, router and cloud VPN speaks it), it's interoperable between vendors, and it often has hardware acceleration. Its weaknesses: complex configuration (proposal mismatches between vendors are the #1 cause of tunnels that won't come up), a large attack surface, and awkward NAT and firewall behaviour.

OpenVPN is an open-source VPN that runs its own protocol on top of TLS (it uses OpenSSL for crypto). Its features:

  • It runs in user space, creating a TUN (layer 3, routed IP) or TAP (layer 2, bridged Ethernet) virtual interface.
  • It's typically on UDP 1194, but can run on TCP 443, where it looks like HTTPS and passes most firewalls and captive portals. "TCP over TCP" (tunnelling TCP inside a TCP tunnel) suffers from compounded retransmissions under packet loss ("TCP meltdown"), so prefer UDP.
  • Authentication uses certificates, username/password and MFA through plugins.
  • It's flexible and battle-tested, but slower than kernel implementations (user-space packet copies) and has a large codebase (tens of thousands of lines, plus OpenSSL).

WireGuard (designed by Jason Donenfeld, presented in "WireGuard: Next Generation Kernel Network Tunnel", NDSS 2017) takes the opposite approach:

  • Tiny: about 4,000 lines of kernel code at merge time, small enough to audit. It was merged into the Linux kernel in version 5.6 (2020), and runs on Windows, macOS, iOS, Android and BSDs.
  • Fixed, modern cryptography, with no negotiation: Curve25519 for key exchange, ChaCha20-Poly1305 for encryption, BLAKE2s for hashing. There's no cipher negotiation, so there are no downgrade attacks. When the crypto needs to change, the protocol version changes.
  • The Noise protocol framework handshake (the Noise_IK pattern): one round trip (1-RTT) to establish a session, with keys rotated every couple of minutes.
  • Peers are identified by public key, like SSH keys. The configuration is just "this peer's public key is allowed these IPs" (cryptokey routing). An incoming packet decrypted with peer A's key is only accepted if its source IP is in A's allowed IPs. An outgoing packet to an IP is encrypted for the peer that owns that range.
  • Silent and stateless-looking: it doesn't respond to unauthenticated packets (port scanners see nothing), it has cookie-based DoS protection under load, and it supports roaming. If your laptop changes IP (Wi-Fi to LTE), the session continues on the next authenticated packet.
  • Performance: kernel-level and very fast, typically multi-Gbps per core.
  • What it doesn't do: user authentication, IP address assignment, or configuration distribution. Products like Tailscale, Netbird and Cloudflare WARP add identity (SSO and MFA), key distribution, NAT traversal and policy on top.
IPsec (IKEv2 + ESP)OpenVPNWireGuard
LayerL3, in kernelL3/L2 via TUN/TAP, user spaceL3, in kernel (or user space on some OSes)
CryptoNegotiated suites (AES-GCM, SHA-2, DH groups)TLS via OpenSSL, negotiatedFixed: Curve25519, ChaCha20-Poly1305, BLAKE2s
PortsUDP 500/4500, ESP protocol 50UDP 1194 or TCP 443One UDP port (51820 by convention)
Code sizeLarge (strongSwan, Libreswan, vendor stacks)Large (plus OpenSSL)About 4,000 lines in the kernel
SetupComplex; vendor interop issuesModerate; PKI neededSimple key-pair configuration
Best forSite-to-site between vendors and clouds; standards complianceRemote access through restrictive firewallsModern remote access, mesh networks, server-to-server

Split tunnelling#

Once the tunnel is up, the client must decide which traffic goes through it:

  • Full tunnel (the default route 0.0.0.0/0 goes to the VPN): all traffic, including Netflix and Zoom, goes via the corporate gateway. The security team gets visibility and filtering (a secure web gateway, DLP) on everything, and a public Wi-Fi network sees only encrypted VPN traffic. The cost is hairpinning: a user in Singapore reaching a SaaS app in Singapore via a VPN gateway in Virginia adds about 200–250 ms of round trip, and gateway bandwidth must carry everyone's video calls. During the 2020 shift to remote work, many companies' VPN concentrators were overwhelmed in exactly this way.
  • Split tunnel: only routes for corporate ranges (10.0.0.0/8, specific VPC CIDRs) go through the tunnel, and everything else goes directly to the internet. It's faster, with much lower gateway load. But traffic to the internet bypasses corporate inspection, and a compromised device is simultaneously on the internet and the corporate network, which is a bridge for an attacker.
  • Inverse split tunnel: everything goes through the tunnel except listed high-volume, trusted destinations (Microsoft 365, Zoom media ranges). This is a common compromise.
  • Application-based split tunnelling: per-app rules (only the corporate browser or SSH client uses the tunnel).

Split-tunnelling pitfalls:

  • DNS leaks: in split mode, internal names must resolve via the corporate DNS (split DNS for *.corp.example.com) and public names via the local resolver. Misconfiguration leaks internal hostnames to public resolvers, or breaks internal name resolution.
  • IPv6 leaks: a tunnel that only captures IPv4 lets IPv6 traffic bypass it.
  • Overlapping home and corporate ranges: a home router on 10.0.0.0/24 conflicts with corporate routes.
  • Local network exposure: a full tunnel usually blocks LAN access (printers), which some setups allow deliberately. The TunnelVision technique (2024) showed that a malicious DHCP server on the local network can push routes (DHCP option 121) that pull traffic outside the tunnel on many VPN clients.

Zero-trust architectures largely remove this dilemma. Instead of choosing between "all traffic through HQ" and "corporate traffic through a network tunnel", each application is accessed through a nearby identity-aware edge. Internet traffic can be filtered by a cloud security edge (SASE: secure access service edge) close to the user.

Zero-trust access and BeyondCorp#

Zero trust is the principle that network location grants no trust. Every access request must be authenticated, authorised and encrypted, based on who is asking (user identity, with strong MFA), what they're using (device identity and health) and what they want (a specific application or resource), evaluated per request or per session, with least privilege. The term was popularised by Forrester analyst John Kindervag around 2010. NIST formalised it in Special Publication 800-207, "Zero Trust Architecture" (2020).

BeyondCorp is Google's implementation, described in a series of papers starting with "BeyondCorp: A New Approach to Enterprise Security" by Rory Ward and Betsy Beyer (;login:, 2014). Google began it after Operation Aurora (2009), a sophisticated attack that compromised its internal network. The core ideas:

  1. Access doesn't depend on the network you connect from. The office network is treated like a coffee-shop network. Google's corporate apps are reached through an access proxy on the internet, and employees work without a traditional VPN.
  2. Device inventory and identity. Every managed device has a certificate in a hardware-backed store (a TPM or secure enclave), and an inventory database tracks its state: OS version, patch level, disk encryption, management agent.
  3. A trust inferer computes a trust tier for each device from its state, such as "fully managed and patched" or "unpatched for 30 days".
  4. An access control engine evaluates policies per application: "the payroll app needs an HR group member + a high-trust device + a recent MFA".
  5. An access proxy (an identity-aware reverse proxy) terminates TLS, authenticates the user via SSO, checks the device certificate and the policy decision, and only then forwards the request to the backend.

NIST 800-207 names the same components:

  • the Policy Decision Point (PDP: the policy engine plus a policy administrator);
  • the Policy Enforcement Point (PEP: the proxy or gateway in the data path);
  • data sources such as identity, device posture (CDM), threat intelligence and activity logs.

How zero trust differs from a VPN in practice:

Traditional VPNZero-trust access (ZTNA)
Unit of accessThe network (all of 10.0.0.0/8 once connected)One application or host per policy
Trust basisSuccessful VPN loginIdentity + device health + context, re-evaluated continuously
Lateral movementEasy once connectedHard: each resource needs its own authorisation
ExposureVPN gateway open to the internet (a frequent target of critical CVEs)Apps invisible. Often outbound-only connectors ("dark" services), the proxy at a provider edge
User experienceConnect, then everything works; hairpinningTransparent per-app; uses the nearest edge
VisibilityNetwork flowsPer-request logs with user identity

Real implementations:

  • Google Cloud Identity-Aware Proxy (IAP), BeyondCorp Enterprise;
  • Cloudflare Access/Zero Trust (outbound cloudflared tunnels from your network to Cloudflare's edge);
  • Zscaler Private Access;
  • Tailscale (a WireGuard mesh with identity-based ACLs);
  • AWS Verified Access and AWS Systems Manager Session Manager (shell access to instances without SSH or open ports);
  • Teleport and HashiCorp Boundary (identity-aware access to SSH, Kubernetes, databases and RDP with session recording);
  • Pomerium (open source).

Zero trust between services applies the same principle inside the data centre:

  • Every service has a cryptographic identity: SPIFFE IDs with short-lived X.509 certificates issued by SPIRE, or service-mesh identities in Istio/Linkerd.
  • Services talk over mutual TLS (mTLS).
  • Authorisation policies are written as "service A may call service B's /charge endpoint", not "the 10.1.0.0/16 subnet can reach 10.2.0.0/16".

See microservices patterns for the service-mesh mechanics. Network segmentation (security groups, Kubernetes NetworkPolicies) still adds defence in depth. It just stops being the only control.

Adoption reality. Most companies are hybrid. Zero-trust access serves web apps and SSH, and a VPN or private connectivity stays for legacy thick-client apps, site-to-site links and some protocols. Migration typically goes in this order:

  1. inventory apps and their users;
  2. put web apps behind an identity-aware proxy;
  3. move SSH and database access to a ZTNA or access-broker tool;
  4. shrink the VPN to the remaining cases;
  5. remove broad network trust.

The SSH protocol: key exchange, host keys and public-key authentication#

SSH (Secure Shell, created by Tatu Ylönen in 1995 to replace telnet and rlogin, which sent passwords in cleartext) gives you an encrypted, authenticated channel to a remote machine, usually on TCP port 22. SSH-2 is defined in a family of RFCs (4251–4254, 2006). It has three layers:

  1. The transport layer (RFC 4253) sets up an encrypted, integrity-protected connection and authenticates the server.
  2. The user authentication layer (RFC 4252) authenticates the client user.
  3. The connection layer (RFC 4254) multiplexes channels over the one connection: interactive shells, command execution, SFTP/SCP file transfer, port forwarding (-L local, -R remote, -D dynamic SOCKS), X11 forwarding and agent forwarding.

Step by step, what happens when you type ssh alice@db1.example.com:

  1. TCP connect and version exchange. Both sides send an identification string such as SSH-2.0-OpenSSH_9.6.
  2. Algorithm negotiation (KEXINIT). Each side lists its supported algorithms in preference order for key exchange, host key type, cipher, MAC and compression. The first client preference that the server also supports wins. Modern OpenSSH defaults include:
    • key exchange: sntrup761x25519-sha512 (a post-quantum hybrid, the default since OpenSSH 9.0 in 2022), mlkem768x25519-sha256 (newer releases) and curve25519-sha256;
    • host keys: ssh-ed25519, ecdsa-sha2-nistp256 and rsa-sha2-512;
    • ciphers: chacha20-poly1305@openssh.com and aes256-gcm@openssh.com.
  3. Key exchange. An ephemeral Diffie–Hellman exchange (over Curve25519, for example) gives both sides a shared secret K that an eavesdropper can't compute. Because keys are ephemeral, the session has forward secrecy: stealing the server's long-term key later doesn't decrypt recorded sessions.
  4. Server authentication. The server signs the exchange hash H (a hash over both version strings, both KEXINIT messages, the server's public host key, both DH public values and K) with its host private key, and sends the signature plus its host public key. The client verifies the signature and checks that this host key belongs to db1.example.com. The first H becomes the session ID.
  5. Keys derived. Encryption and integrity keys for each direction are derived from K, H and the session ID. From the NEWKEYS message on, everything is encrypted.
  6. User authentication. The client requests the ssh-userauth service and tries methods: publickey, password, keyboard-interactive (used for OTP/MFA prompts via PAM) or gssapi-with-mic (Kerberos).
  7. Session. The client opens a session channel, and requests a PTY and a shell (or an exec command). Rekeying happens periodically (by default after about 1 GB of data or an hour, depending on cipher and configuration).

Host keys: authenticating the server. The host key check is what stops a man-in-the-middle from impersonating the server. There are three ways to establish trust:

  • TOFU (trust on first use). On the first connection, the client shows the key fingerprint ("The authenticity of host … can't be established. ED25519 key fingerprint is SHA256:…") and saves it in ~/.ssh/known_hosts. Later connections compare against it, and a change produces the loud "REMOTE HOST IDENTIFICATION HAS CHANGED" warning. In practice, almost everyone types "yes" without checking, and in auto-scaling fleets where hosts are rebuilt constantly, people disable checking (StrictHostKeyChecking no), which destroys MITM protection.
  • SSHFP DNS records (RFC 4255): publish host key fingerprints in DNS, which is only meaningful with DNSSEC.
  • Host certificates (covered below): a host CA signs each server's host key, and clients trust the CA with one @cert-authority line. That's the scalable answer for fleets.

Public-key user authentication. The user has a key pair, preferably Ed25519 (ssh-keygen -t ed25519). The private key stays on their machine, encrypted with a passphrase, or better, in hardware: a FIDO2 security key via ed25519-sk (supported since OpenSSH 8.2), a TPM, or a smart card. The server lists allowed public keys in ~/.ssh/authorized_keys. To log in, the client signs data that includes the session ID with the private key. The server verifies the signature with the listed public key. Advantages over passwords:

  • Nothing reusable crosses the wire. The signature is bound to this session ID, so a malicious server can't replay it to another server.
  • Brute force is infeasible, unlike guessing passwords. Disabling password authentication (PasswordAuthentication no) removes the entire class of internet brute-force attacks.
  • Hardware-backed keys (-sk types) can require a physical touch per use, which stops malware from silently using the key.

Problems with plain public keys at scale:

  • authorized_keys files spread across thousands of servers with no central view of who can access what.
  • Keys never expire. A departed employee's key may remain on 300 servers, and offboarding becomes a hunt.
  • Users copy private keys between machines, and keys get committed to git.
  • No good audit trail: keys are anonymous blobs unless you maintain a mapping.

These problems motivate bastions, centralised access brokers and SSH certificates.

Bastion hosts, agent forwarding risks and SSH certificates#

Bastion hosts. A bastion (or jump host) is a hardened server that is the only SSH entry point into a private network. Production servers accept SSH only from the bastion's address (a security group rule such as "port 22 from sg-bastion"). The bastion itself:

  • has a minimal OS, no other services, MFA on login, and aggressive patching;
  • logs every session, sometimes recording full keystrokes or terminal output (tools: Teleport, the tlog session recorder, auditd);
  • is reached via VPN or ZTNA, or (less ideally) from the internet with tight IP allow-lists;
  • is often deployed redundantly (one per AZ) behind a load balancer or DNS name.

The modern way to hop through a bastion is ProxyJump (ssh -J bastion.example.com db1.internal, or ProxyJump in ~/.ssh/config). The client opens a TCP forward through the bastion to the target, and runs end-to-end SSH with the target over it. The bastion only relays encrypted bytes. Your private key never leaves your laptop, and the bastion can't read the inner session. (The bastion still sees which hosts you connect to, which is useful for audit.)

Agent forwarding: why it's risky. ssh-agent holds your decrypted private keys in memory and signs authentication challenges on request. Agent forwarding (ssh -A, or ForwardAgent yes) exposes that agent to the remote host through a Unix socket, so you can SSH onward from the bastion using your laptop's keys. The danger: anyone with root (or your user) on the intermediate host can use the forwarded socket while you're connected, and authenticate as you to any server your keys can reach. They can't copy the key, but they can borrow it, which is just as bad for the session's duration. A compromised bastion with agent forwarding turns every connected admin into a skeleton key. Mitigations:

  • Use ProxyJump instead of -A. It covers almost every use of agent forwarding.
  • If forwarding is unavoidable, use ssh-add -c (confirm each use with a prompt), keys that require a hardware touch (-sk keys), and per-destination restrictions. OpenSSH 8.9 added agent destination constraints (ssh-add -h) that limit where a forwarded key can be used.
  • Never forward agents to hosts you don't fully trust (shared bastions, customer machines).
  • Similar care applies to port forwarding. -R remote forwards and -D SOCKS proxies can tunnel around firewalls, so restrict them in sshd_config (AllowTcpForwarding, PermitOpen) on sensitive hosts.

SSH certificates. OpenSSH (since version 5.4, 2010) supports its own lightweight certificate format, separate from X.509. A certificate authority (an SSH CA key pair) signs:

  • user certificates: a user's public key plus a key ID (for logs), principals (the usernames or roles it may log in as, such as alice or db-admins), a validity window (e.g. 8 hours), and extensions and critical options (permit-pty, force-command, source-address restrictions);
  • host certificates: a host's public key plus its hostnames, so clients trust hosts by CA rather than by TOFU.

Server configuration:

  • TrustedUserCAKeys /etc/ssh/user_ca.pub makes the server trust any user certificate signed by that CA.
  • AuthorizedPrincipalsFile maps each local account to the principals allowed to use it (root only for breakglass-admins, for example).
  • HostCertificate /etc/ssh/ssh_host_ed25519_key-cert.pub presents the host certificate.

Client configuration: a single line @cert-authority *.example.com ssh-ed25519 AAAA… in known_hosts trusts every host the host CA signed.

The workflow:

  1. The engineer runs a login command (step ssh login, tsh login, vault ssh, or an internal CLI).
  2. The command authenticates them via SSO plus MFA.
  3. The CA service checks policy (groups, on-call status, ticket for just-in-time access).
  4. The CA signs the engineer's public key with the right principals for a short TTL (1–12 hours).
  5. The certificate goes into ssh-agent and is used automatically.

There is no authorized_keys management. Offboarding is instant (no new certificates get issued, and the old ones expire within hours), and logs show the key ID (alice@example.com, ticket INC-1234) on every server. Examples include Netflix's BLESS (a Lambda-based SSH CA, open-sourced in 2016), Facebook's described use of SSH certificates at scale (a 2016 engineering post), and products such as Smallstep, Teleport, HashiCorp Vault's SSH secrets engine and cloud-native options (GCP OS Login, AWS EC2 Instance Connect pushing a one-time key for 60 seconds).

CA key security is everything. Whoever holds the user CA private key can log in anywhere. Keep it in an HSM or KMS, give the signing service tight IAM, keep an audit log of every issuance, and plan CA rotation: trust old and new CAs during the transition. Revocation exists (RevokedKeys with key revocation lists), but short TTLs are the main defence, because distributing revocation lists to every host is operationally hard.

Beyond SSH: access brokers and no-SSH designs. Many teams now avoid direct SSH to production for routine work:

  • Session Manager-style agents (AWS SSM, GCP OS Login with IAP TCP forwarding) open shells over the cloud's control plane, authorised with cloud IAM. There's no inbound port, no keys, and logs go to CloudTrail and S3.
  • Immutable infrastructure: servers are never patched by hand. Fix the image, redeploy, and the "SSH into prod" need mostly disappears (see deployment and CI/CD).
  • Break-glass accounts cover emergencies: strongly protected credentials (in a safe, or split between people), with alerts whenever they're used.
  • Just-in-time (JIT) access: no standing admin access. Engineers request elevated access for a bounded time with a reason, a peer or automated approval grants it, and it's revoked automatically. This cuts the number of always-privileged accounts that attackers can phish.

MFA factors#

Multi-factor authentication requires evidence from two or more different categories:

  1. Something you know: a password, PIN or security question (weak, because the answers are often public).
  2. Something you have: a phone with an authenticator app, a hardware security key, a smart card, or a device-bound passkey.
  3. Something you are: biometrics, such as a fingerprint, face or iris. Biometrics usually unlock a local key (Touch ID unlocking a passkey) rather than being sent to the server.

"Two passwords" isn't MFA. Both are "know". Some systems add contextual signals (device, location, IP reputation, behaviour) to raise or lower the required assurance. That's risk-based or adaptive authentication, not a factor in itself.

NIST SP 800-63B (Digital Identity Guidelines) grades authenticator assurance levels:

  • AAL1: single factor.
  • AAL2: two factors, with an approved cryptographic or OTP authenticator.
  • AAL3: hardware-based, phishing-resistant, verifier-impersonation-resistant authenticators.

NIST restricts SMS/voice OTP (classed as a "restricted" authenticator) because of SIM-swap and SS7 interception risks.

The common factors, from weakest to strongest:

FactorHow it worksMain weaknesses
SMS / voice OTPServer texts a 6-digit codeSIM swapping, SS7 interception, real-time phishing, delivery delays and cost
Email OTP / magic linkCode or link sent to emailOnly as strong as the email account; phishable
TOTP app (Google Authenticator, Authy, 1Password)Shared secret + clock → 6-digit codeReal-time phishing (an attacker relays the code within 30 seconds); secret can be exported or synced
Push approval (Duo, Okta Verify, Microsoft Authenticator)Server pushes "Approve sign-in?" to a registered appPush fatigue / MFA bombing; phishable unless number matching plus context is used
FIDO2 / WebAuthn security key or passkeyPublic-key challenge–response bound to the website originLoss or recovery planning; device support; cost of hardware keys
Smart card / PIV / CACCertificate on a chip, PIN-unlockedHardware and PKI infrastructure

HOTP and TOTP: how authenticator codes work#

HOTP (HMAC-Based One-Time Password, RFC 4226, 2005) and TOTP (Time-Based One-Time Password, RFC 6238, 2011) are both from the Initiative for Open Authentication (OATH). They're what Google Authenticator and similar apps implement.

Enrolment.

  1. The server generates a random shared secret K (RFC 4226 requires at least 128 bits and recommends 160).
  2. It shows K to the user as a QR code containing an otpauth://totp/Example:alice?secret=BASE32SECRET&issuer=Example&algorithm=SHA1&digits=6&period=30 URI (the "Key URI format" Google popularised). The secret is Base32-encoded.
  3. The app stores K.
  4. The server stores K encrypted at rest. Unlike a password, it can't be hashed, because the server must compute codes from it.
  5. The user confirms enrolment by entering a code, which proves the app has the right secret and clock.

HOTP algorithm. For a counter C (an 8-byte big-endian integer):

  1. Compute HS = HMAC-SHA1(K, C), a 20-byte value.
  2. Dynamic truncation: take the low 4 bits of the last byte as an offset o (0–15). Read the 4 bytes HS[o..o+3] as a 31-bit integer (mask off the top bit to avoid signed-integer issues).
  3. The code is that integer mod 10^digits, zero-padded to 6 (or 8) digits.

The counter increments on every code generated (by a button press on a hardware token, for example). The server keeps its own counter and accepts codes within a look-ahead window (say the next 10 counters) to resynchronise if the user pressed the button without logging in. RFC 4226's appendix gives test vectors: with the ASCII secret 12345678901234567890, counter 0 yields 755224 and counter 1 yields 287082.

TOTP is just HOTP with the counter derived from time:

  • T = floor((unix_time − T0) / X), with T0 = 0 and step X = 30 seconds by default.
  • TOTP = HOTP(K, T). RFC 6238 also allows HMAC-SHA256 and SHA-512, but most apps use SHA-1.

There's no network connection between the phone and the server. Both compute the same code because they share K and roughly agree on the time.

Server-side verification details that matter:

  • Clock drift window. Accept T−1, T and T+1 (±30 seconds) to tolerate skew and typing delay. Larger windows weaken security.
  • Replay prevention. Record the last accepted time step per user and reject any code for a step ≤ that one, so a code observed over someone's shoulder can't be reused within its validity window.
  • Rate limiting and lockout. A 6-digit code has 10^6 possibilities. With 3 valid codes in the window, a random guess succeeds with probability 3 × 10^-6. That sounds tiny, but an attacker who already has the password and unlimited attempts would win in about 333,000 guesses. Limit verification attempts (say 5 per 15 minutes per account; see rate limiting).
  • Constant-time comparison of codes, to avoid timing leaks.
  • Secret protection. TOTP secrets are as sensitive as password-equivalents for the second factor. Encrypt them with a KMS key, and restrict which services can decrypt. A database leak of plaintext TOTP secrets lets an attacker generate every user's codes. (The 2011 RSA SecurID breach, where attackers stole data related to token seeds, forced RSA to offer replacement tokens to customers.)
  • Recovery. Provide single-use backup codes (hashed like passwords), and support multiple registered factors. Account-recovery flows are the most attacked part of any MFA system, because a social-engineered support desk reset bypasses everything.

Push-MFA fatigue and phishing-resistant factors#

Push fatigue (MFA bombing). Push MFA is convenient: tap "Approve" on your phone. Attackers who've stolen a password (via phishing, an infostealer or reuse) simply trigger login after login. The victim gets dozens of prompts, often late at night, sometimes accompanied by a message impersonating IT support ("we're fixing your account, please approve"). Eventually they tap Approve to make it stop. The 2022 Uber breach was publicly attributed to exactly this: an attacker with a contractor's password spammed push requests and then contacted the contractor on WhatsApp pretending to be Uber IT, until they accepted. Cisco's 2022 incident similarly combined voice phishing with MFA push fatigue.

Mitigations for push:

  • Number matching: the login screen shows a 2-digit number that must be typed into the app. A blind approve no longer works, because the attacker must get the victim to type a number from the attacker's screen. Microsoft made number matching mandatory for Authenticator push in 2023.
  • Additional context in the prompt: app name, location, IP. A request from another country is visibly suspicious.
  • Rate-limit prompts per user (e.g. at most 3 per 10 minutes), and alert the security team on repeated denials.
  • A "Report fraud" button that blocks further prompts and locks the account.

Real-time phishing defeats OTPs too. Adversary-in-the-middle phishing kits (Evilginx and Modlishka are well-known open-source examples) act as a reverse proxy between the victim and the real login page. The victim types username, password and TOTP code into a look-alike domain. The proxy relays them to the real site instantly, then captures the session cookie the real site issues. MFA "succeeds", but the attacker owns the session. Any factor where the user transfers a secret (a code) or makes a decision (approve) can be proxied like this. The 2022 "0ktapus" campaign used SMS phishing pages that harvested credentials and OTP codes from employees of over 100 organisations, including Twilio. Cloudflare reported that it was targeted in the same wave but stopped the attack because its employees used FIDO2 hardware keys.

Phishing-resistant factors close this hole cryptographically:

  • FIDO2/WebAuthn (security keys like YubiKey and Titan, and passkeys synced through Apple, Google or Microsoft accounts or stored in password managers) uses a per-site public/private key pair. At login, the browser passes the authenticator a challenge plus the origin (the real domain, e.g. https://login.example.com). The authenticator only uses the key registered for that origin, and the signed response includes the origin. A phishing domain gets either no key or a signature for the wrong origin, which the real server rejects. There's no code to relay and no decision to trick. The authentication and authorization page covers passkey registration and login flows.
  • Smart cards / PIV with client-certificate TLS (mutual TLS) bind authentication to the TLS channel.
  • Device-bound certificates in zero-trust setups (a TPM-held device certificate plus user WebAuthn) also resist proxying, because the proxy can't present the device's key.

Google reported that after it required security keys for all employees in 2017, it had no confirmed account takeovers via phishing of employee accounts (as reported by KrebsOnSecurity in 2018). That's the strongest public evidence for hardware-backed, origin-bound authentication. CISA and the US federal zero-trust strategy (OMB memo M-22-09, 2022) direct agencies toward phishing-resistant MFA for these reasons.

Rollout reality. Use phishing-resistant MFA everywhere privileged: admins, engineers with production access, finance and support staff with account-reset powers. Offer it to all users (passkeys make it easy). Keep TOTP as a fallback, and SMS only as a last resort for consumers. Protect recovery and enrolment as strongly as login, because attackers will target the help desk ("I lost my phone, please reset my MFA"). Verify identity out of band before resets, and add a delay and notifications to all registered channels.

When to Use It#

Every production system needs a deliberate access design. The signals that tell you which tools to use:

  • Private resources that people must reach (databases, admin UIs, Kubernetes APIs, internal dashboards) → give them no public endpoints, and access them through an identity-aware proxy or access broker (zero trust). Use a VPN only where protocols or legacy apps need network-level access.
  • Two networks that must talk permanently (office ↔ data centre, on-premises ↔ cloud, VPC ↔ partner) → site-to-site IPsec VPN, which is quick to set up and cheap, for up to roughly 1 Gbps per tunnel with internet-grade latency. Use Direct Connect, ExpressRoute or Interconnect for multi-Gbps, predictable latency or compliance.
  • Engineers need shell access to servers → SSH with public keys or, better, SSH certificates from SSO, through a bastion or access broker. Or remove SSH with Session Manager-style tools and immutable infrastructure.
  • Any human login to sensitive systems → MFA. Make it phishing-resistant (FIDO2/passkeys) for admins, engineers and anyone with power over money, customer data or account recovery.
  • A mesh of servers across clouds or a home lab → WireGuard, or a WireGuard-based mesh (Tailscale, Netbird) with identity ACLs.
  • Compliance requirements: PCI DSS (MFA for all access into the cardholder data environment), SOC 2, ISO 27001, HIPAA and FedRAMP all expect controlled, logged and strongly authenticated admin access.

Pick something else instead when:

  • Service-to-service authentication within your platform is better served by mTLS with workload identities (SPIFFE, a service mesh), not VPN tunnels between every pair of services.
  • Third-party developers calling your public API should use API keys or OAuth client credentials, not VPN access to your network (see authentication and authorization).
  • Consumer app users need passkeys, TOTP or risk-based MFA in your login flow. VPNs and SSH are irrelevant to them.
  • Cross-cloud private connectivity between your own VPCs is often simpler with cloud-native peering, Transit Gateway or PrivateLink than with self-managed VPN gateways.

When NOT to Use It#

  • Don't open SSH (22), RDP (3389) or database ports to 0.0.0.0/0, even "temporarily". Scanners find them in minutes.
  • Don't use a VPN as your only security control. "On the VPN = trusted" is the perimeter model that lets one phished laptop reach everything. Pair it with per-app authorisation and segmentation.
  • Don't build your own VPN protocol, OTP algorithm or SSH crypto. Use WireGuard, IPsec or OpenVPN; RFC 6238 libraries; and OpenSSH.
  • Don't rely on SMS OTP for privileged accounts. SIM swaps and real-time phishing make it weak. It's acceptable only as a consumer fallback.
  • Don't deploy push MFA without number matching and rate limits on prompts.
  • Don't use shared accounts or shared SSH keys ("deploy@" with a key everyone has). They give you no attribution and no clean offboarding.
  • Don't make a bastion a general-purpose server. No developer tools, no stored keys, no agent forwarding into it.

How to Implement It#

  1. Inventory and classify access. List the resources (apps, hosts, databases, clusters, cloud consoles), who needs them, and at which privilege. Classify them by sensitivity (production data, payments, PII).
  2. Remove public exposure. Give private resources no public IPs, and keep security groups or firewall rules default-deny. Admin endpoints are reachable only via the access layer.
  3. Centralise identity. One identity provider (Okta, Entra ID, Google Workspace, Keycloak) with SSO for every tool, group-based roles, and automated joiner/mover/leaver provisioning (SCIM).
  4. Enforce MFA by tier. Phishing-resistant (FIDO2/passkeys) for privileged users, plus number matching for any push. Block legacy protocols that bypass MFA (basic auth for IMAP/SMTP, for example). Harden recovery flows.
  5. Choose access paths. An identity-aware proxy for web apps. An access broker or SSH CA for servers and databases. Site-to-site IPsec or private interconnect for networks. A remote-access VPN or WireGuard mesh only for what remains.
  6. Issue short-lived credentials. SSH certificates (hours), database credentials from a secrets manager (Vault dynamic secrets, cloud IAM database authentication), cloud console sessions via SSO, just-in-time elevation with approval.
  7. Harden SSH. Public key or certificate only (PasswordAuthentication no, KbdInteractiveAuthentication no unless used for MFA), PermitRootLogin no (or prohibit-password with CA principals), modern algorithms, AllowTcpForwarding restricted, host certificates, and ProxyJump rather than agent forwarding.
  8. Log and monitor. VPN and proxy access logs with user identity, SSH session logs and recordings for production, alerts on unusual access (new country, a burst of MFA denials, break-glass use), all shipped to a SIEM (see observability).
  9. Test and review. Quarterly access reviews (who still needs what), phishing simulations, red-team tests of help-desk resets, and DR tests of the access path. Can you still get into production when the IdP is down? Keep break-glass procedures for that case.
// TOTP verification (RFC 6238) with drift window and replay protection
import { createHmac, timingSafeEqual } from "node:crypto";
 
function hotp(secret: Buffer, counter: bigint, digits = 6): string {
  const msg = Buffer.alloc(8);
  msg.writeBigUInt64BE(counter);
  const hs = createHmac("sha1", secret).update(msg).digest(); // 20 bytes
  const o = hs[hs.length - 1] & 0x0f;                         // dynamic truncation
  const bin = (hs.readUInt32BE(o) & 0x7fffffff) % 10 ** digits;
  return bin.toString().padStart(digits, "0");
}
 
interface OtpState { secret: Buffer; lastStep: bigint } // secret decrypted via KMS
 
export function verifyTotp(state: OtpState, code: string, nowMs = Date.now(),
                           stepSec = 30, window = 1): bigint | null {
  if (!/^\d{6}$/.test(code)) return null;
  const t = BigInt(Math.floor(nowMs / 1000 / stepSec));
  for (let d = -window; d <= window; d++) {
    const step = t + BigInt(d);
    if (step <= state.lastStep) continue;                  // replay protection
    const expected = Buffer.from(hotp(state.secret, step));
    if (timingSafeEqual(expected, Buffer.from(code))) return step; // persist as lastStep
  }
  return null; // caller increments a rate-limit counter on failure
}
 
// RFC 4226 test vectors: secret "12345678901234567890"
// hotp(secret, 0n) === "755224", hotp(secret, 1n) === "287082"
TechnologyFits when
strongSwan / Libreswan (IPsec)Self-managed site-to-site or IKEv2 remote access with standard interop
AWS Site-to-Site VPN, Azure VPN Gateway, GCP Cloud VPNManaged IPsec between on-premises and a cloud VPC, with BGP and redundant tunnels
Direct Connect / ExpressRoute / Cloud InterconnectMulti-Gbps, predictable-latency private connectivity to the cloud
OpenVPN (Community, Access Server)Remote access through restrictive firewalls on TCP 443; broad client support
WireGuardFast, simple tunnels for servers, remote access and meshes; Linux kernel native
Tailscale, Netbird, Cloudflare WARPWireGuard mesh with SSO, ACLs and NAT traversal handled for you
Google IAP / BeyondCorp, Cloudflare Access, Zscaler ZPA, AWS Verified Access, PomeriumZero-trust per-app access to internal web apps and TCP services
Teleport, HashiCorp Boundary, StrongDMAccess brokers for SSH, Kubernetes, databases and RDP with session recording and JIT access
Smallstep, Vault SSH secrets engine, Netflix BLESS-style CAShort-lived SSH certificates from SSO
AWS SSM Session Manager, GCP OS Login + IAP, EC2 Instance ConnectShell access via cloud IAM without open SSH ports or managed keys
Okta, Microsoft Entra ID, Google Workspace, KeycloakIdentity provider with SSO, MFA policies and SCIM provisioning
YubiKey, Google Titan, platform passkeysPhishing-resistant FIDO2/WebAuthn authenticators
Duo, Okta Verify, Microsoft AuthenticatorPush MFA with number matching, plus TOTP and device trust

Trade-offs#

OptionProsConsPick when
Remote-access VPN (full tunnel)Simple mental model; all traffic inspectedHairpin latency; gateway bottleneck; broad network trustLegacy apps and strict inspection requirements
Remote-access VPN (split tunnel)Fast; low gateway loadUnmonitored internet path; dual-homed device risk; DNS leak risksPerformance matters and endpoint security is strong
Zero-trust proxy (ZTNA)Per-app least privilege; no network exposure; identity-aware logsNeeds app inventory and IdP maturity; some protocols harderWeb apps, SSH and DBs; the long-term default
Site-to-site IPsecUniversal interop; quick; cheapInternet latency; ~1 Gbps per tunnel; complex configurationOffice ↔ cloud and partner links
Private interconnectHigh bandwidth; stable latency; no internet pathCost; lead time; physical presenceHeavy hybrid traffic, latency-sensitive replication
SSH keys in authorized_keysSimple; no infrastructureKey sprawl; no expiry; painful offboardingA handful of servers and admins
SSH certificatesShort-lived; central policy; easy offboarding; host trustMust run and protect a CAFleets of tens of servers or more, and teams beyond a few people
Session Manager / no SSHNo open ports or keys; IAM-based auditCloud lock-in; agent dependencyCloud-native fleets, immutable infrastructure
TOTPFree; offline; universalPhishable in real time; secret-sharing modelConsumer MFA baseline; fallback factor
Push with number matchingConvenient; contextualStill phishable by AiTM proxies; needs appWorkforce MFA where FIDO2 isn't yet deployed
FIDO2 / passkeysPhishing-resistant; fast; no shared secretHardware cost or platform dependence; recovery planningPrivileged users always; all users where possible

Common Pitfalls#

  • The VPN appliance as the weak point. Internet-facing VPN gateways from major vendors have had repeated critical, actively exploited vulnerabilities (Pulse Secure, Fortinet, Citrix and Ivanti advisories over 2019–2024). Patch them urgently, minimise their exposure, and prefer architectures where apps aren't reachable even after a gateway compromise.
  • "MFA everywhere" with gaps. Legacy protocols, service accounts, API tokens and break-glass accounts that bypass MFA are where attackers go.
  • TOFU fatigue. Users accepting unknown or changed host keys, or StrictHostKeyChecking no in scripts, which removes MITM protection. Use host certificates.
  • Agent forwarding to shared hosts. It lets anyone with root there act as you.
  • Long-lived credentials: never-expiring SSH keys, static database passwords in config files, cloud access keys on laptops.
  • Weak recovery: help desks resetting MFA on a phone call. Social engineering of support staff has been the entry point in several major 2022–2023 breaches.
  • TOTP secrets stored in plaintext, or no replay or rate-limit protection on code verification.
  • Overlapping CIDRs between VPCs, offices and partners, which block VPN routing and need NAT hacks.
  • IPv6 and DNS leaks in VPN configurations.
  • No access reviews: departed staff and old contractors keep access, and permissions only ever grow.

Real-World Examples#

  • Google BeyondCorp. After Operation Aurora (2009), Google moved its workforce off a privileged corporate network to per-request, identity- and device-based access through an internet-facing access proxy. This is documented in a series of ;login: papers from 2014 onward. The commercial descendants are Google Cloud IAP and BeyondCorp Enterprise.
  • Google security keys. Google required FIDO U2F security keys for employees in 2017 and reported no successful phishing of employee accounts afterwards (KrebsOnSecurity, 2018). Google's earlier paper "Security Keys: Practical Cryptographic Second Factors for the Modern Web" (Lang, Czeskis, Balfanz, Schilder and Srinivas, Financial Cryptography 2016) describes the deployment and its usability benefits over OTPs.
  • Netflix BLESS and Facebook SSH certificates. Netflix open-sourced BLESS (2016), an SSH CA running in AWS Lambda that issues short-lived certificates after SSO+MFA, with access brokered through bastions. Facebook described (2016) how it moved its fleet to SSH certificates with principals mapped to roles, making access policy central and offboarding immediate.
  • Uber 2022 and MFA fatigue. Public reports of the September 2022 Uber breach describe an attacker who bought a contractor's credentials, flooded them with push MFA prompts, and then social-engineered approval over WhatsApp. They then found admin credentials in an internal network share. The lessons are number matching, prompt rate limits, phishing-resistant factors and no secrets in scripts.
  • Twilio/"0ktapus" vs Cloudflare (2022). The same SMS-phishing campaign that compromised Twilio employee accounts also targeted Cloudflare. Cloudflare publicly wrote that some employees entered credentials on the phishing site, but the attack failed because logins required FIDO2 hardware keys, which can't be relayed.
  • Tailscale. A WireGuard-based mesh VPN where a coordination server distributes peers' public keys and ACLs tied to SSO identities, while data flows peer to peer (relayed via DERP servers when NAT traversal fails). It's a popular way for small teams to get zero-trust-style access without running gateways.
  • AWS Systems Manager Session Manager. Shell access to EC2 instances with no inbound ports, no bastions and no SSH keys. Access is authorised by IAM policies, with session logs to S3 and CloudWatch, and API calls in CloudTrail. Many cloud-native teams use it to close port 22 entirely.
  • VPN gateway vulnerabilities. CISA and other agencies have repeatedly issued emergency directives about actively exploited flaws in internet-facing VPN and remote-access appliances (for example, Ivanti Connect Secure in early 2024). This is a structural argument for minimising what such gateways expose and for zero-trust designs.

Case studies that use this pattern#

In the Interview#

Common follow-ups:

  • "Why isn't a VPN enough?" It grants network-level trust: one compromised device or credential reaches everything routable. The VPN gateway is also an internet-facing target with a history of critical CVEs. Zero trust authorises each request on identity, device and policy, and keeps apps unexposed.
  • "How does Google Authenticator know the right code without the internet?" A shared secret from the QR code, plus time. Both compute HMAC-SHA1(secret, floor(time / 30)), dynamically truncated to 6 digits. The server accepts ±1 step and rejects reused steps.
  • "Why are passkeys phishing-resistant but TOTP isn't?" A TOTP code is a bearer secret the user can type into any site, and a proxy relays it within the 30-second window. WebAuthn signatures are bound to the origin by the browser, so a look-alike domain can't obtain a valid assertion for the real site.
  • "What's wrong with SSH agent forwarding?" Root on the intermediate host can use your agent socket to authenticate as you while you're connected. Use ProxyJump, or confirm-on-use and hardware-touch keys.
  • "How do you offboard an engineer from 5,000 servers instantly?" SSH certificates with short TTLs from an SSO-backed CA. Disable the IdP account and no new certificates are issued. For immediacy, revoke active sessions at the broker, and add the key to a revocation list if needed.
  • "How do two data centres connect securely?" Redundant IPsec tunnels (IKEv2, AES-GCM) between gateway pairs with BGP failover, or a private interconnect with MACsec or IPsec on top. Non-overlapping CIDRs, and firewall policy on what may cross.
  • "Full or split tunnel?" A trade-off between inspection and performance. Hybrid answer: split tunnel with a cloud security edge (SASE) for internet traffic, and ZTNA for private apps.
Deep Dive: inside WireGuard and IPsec: handshakes, overhead and failure modesShow

WireGuard's handshake. WireGuard uses the Noise_IKpsk2 pattern. "IK" means the initiator already knows the responder's static public key (from configuration) and transmits its own static key encrypted in the first message. The exchange is:

  1. Handshake initiation (148 bytes): the initiator's ephemeral public key; its static public key encrypted under a DH between its ephemeral key and the responder's static key; and an encrypted TAI64N timestamp. The timestamp defeats replay of old initiation messages, because the responder keeps the greatest timestamp seen per peer.
  2. Handshake response (92 bytes): the responder's ephemeral key plus an empty encrypted payload that proves key possession.

Session keys come from mixing four DH results (ephemeral–ephemeral, ephemeral–static both ways, static–static) plus an optional pre-shared key into a chaining key with HKDF over BLAKE2s. That gives mutual authentication, forward secrecy (ephemeral keys are discarded) and identity hiding for the initiator.

The optional PSK is also WireGuard's hedge against "harvest now, decrypt later" quantum attacks. Projects such as Rosenpass compute a post-quantum PSK out of band and rotate it in.

Timers make it stateless from the user's view:

  • Rekey after 120 seconds or 2^60 messages.
  • Sessions older than 180 seconds are rejected.
  • Keepalives are optional (PersistentKeepalive = 25 keeps NAT mappings open).
  • If data needs sending and there's no valid session, a handshake happens transparently. A lost handshake retries every 5 seconds.

There are no "connection up/down" states for an operator to manage.

DoS resistance. A handshake costs the responder several Curve25519 operations, so a flood of initiations could exhaust CPU. Every message carries two MACs. mac1 is keyed by the responder's public key, so only parties who know the server's public key can elicit any response at all. That's why WireGuard is "invisible" to scanners. Under load, the responder replies with an encrypted cookie (bound to the source IP, rotated every 2 minutes) instead of doing the handshake. The initiator must then include mac2 computed with that cookie, which proves it owns its IP address before the expensive DH work happens.

Data packets and anti-replay. Each data packet carries a 64-bit counter used as the nonce for ChaCha20-Poly1305. The receiver keeps a sliding window bitmap (a window of a few thousand packets, following the design in RFC 6479) to reject duplicates, while accepting reordering inside the window. IPsec ESP does the same with 32-bit or extended 64-bit sequence numbers and a configurable replay window. Too small a window drops legitimately reordered packets on multi-queue NICs or ECMP paths, a classic performance pitfall on fast links.

Encapsulation overhead and MTU math. WireGuard over IPv4 adds:

  • an outer IPv4 header: 20 bytes;
  • UDP: 8 bytes;
  • the WireGuard data header (type, receiver index, counter): 16 bytes;
  • the Poly1305 tag: 16 bytes.

That's 60 bytes (80 over IPv6). On a 1,500-byte path the inner MTU must be ≤ 1,440 (IPv4) or 1,420 (IPv6). WireGuard's default MTU is 1,420, to be safe for both.

IPsec ESP tunnel mode with AES-GCM adds:

  • an outer IP header: 20 bytes;
  • the ESP header (SPI plus sequence number): 8 bytes;
  • the IV: 8 bytes;
  • padding plus trailer: 2–5 bytes;
  • the ICV tag: 16 bytes;
  • plus 8 bytes of UDP when NAT traversal is active.

That's about 54–73 bytes depending on alignment and NAT-T. OpenVPN over UDP adds roughly 40–70 bytes depending on cipher and options.

If the inner MTU is set wrong and Path MTU Discovery is broken (because firewalls drop ICMP "fragmentation needed" messages), large packets vanish. You get the classic symptom: "SSH logs in but hangs when I run ls on a big directory", or HTTPS handshakes stall on large certificates. The fixes are TCP MSS clamping on the tunnel interface (rewriting the TCP MSS option in SYNs to MTU − 40), correct MTUs, and allowing ICMP type 3 code 4 (and ICMPv6 Packet Too Big).

Throughput intuition. Encryption with AES-NI (AES-GCM) or SIMD ChaCha20 runs at several GB/s per core, so the bottleneck is usually per-packet overhead: syscalls, copies and interrupts. Kernel implementations (WireGuard, kernel IPsec) avoid user-space copies. Offloads such as GSO/GRO batching (added to WireGuard's and Tailscale's user-space paths around 2022–2023) let tunnels reach 10+ Gbps. OpenVPN's traditional user-space, single-threaded design capped it far lower until its data-channel offload (DCO) kernel module.

IKEv2 in four messages.

  • IKE_SA_INIT (request and response) negotiates algorithms, exchanges DH values and nonces, and creates the IKE SA keys.
  • IKE_AUTH (request and response, now encrypted) carries identities, authenticates (certificate signatures, PSK, or EAP for user credentials) and creates the first child SA for ESP.

That's 2 round trips to a working tunnel. Additional child SAs or rekeys use CREATE_CHILD_SA, ideally with a fresh DH for PFS. Dead peer detection (liveness checks) triggers failover. With two tunnels and BGP, convergence after a tunnel failure takes roughly the BGP hold time (AWS VPN uses 30 seconds; many routers default to 90–180 seconds; BFD can cut detection to around a second).

Typical IPsec outage causes:

  • mismatched proposals (one side wants AES-256-GCM with DH group 20, the other offers AES-128 with group 14);
  • mismatched traffic selectors in policy-based VPNs (which subnets are "interesting");
  • rekey collisions;
  • clock skew breaking certificate validation;
  • NAT devices timing out UDP 4500 mappings without keepalives.

Monitor tunnel state, the BGP session and actual end-to-end probes, not just "the tunnel is up".

Deep Dive: SSH internals, the Terrapin attack, and running an SSH CA at scaleShow

Why the exchange hash matters. Everything in SSH's security hangs on the exchange hash H. It's computed over both identification strings, both KEXINIT payloads, the host key, both ephemeral public values and the shared secret. The server's signature over H authenticates the server and the whole negotiation. If an attacker tampered with the algorithm lists to force a weak cipher, H would differ and the signature check would fail. The first H becomes the permanent session ID that client signatures bind to. That's why a malicious server can't forward your publickey signature to another server: that server's session ID differs.

Terrapin (CVE-2023-48795). Fabian Bäumer, Marcus Brinkmann and Jörg Schwenk showed in "Terrapin Attack: Breaking SSH Channel Integrity by Sequence Number Manipulation" (USENIX Security 2024) that the protection had a gap. SSH packet sequence numbers are implicit counters that aren't reset when encryption starts. A man-in-the-middle could inject a message during the unencrypted handshake (incrementing the receiver's counter) and then delete the first encrypted message (an extension-info message that negotiates security features). The counters line up again, and the integrity check doesn't notice the truncated prefix. This worked with chacha20-poly1305@openssh.com and with CBC/CTR plus encrypt-then-MAC modes. The practical effect was downgrading security extensions (such as disabling keystroke-timing obfuscation in some cases), not decrypting sessions, but it broke a long-assumed property of the protocol. The fix is "strict KEX" (OpenSSH 9.6, December 2023, and other implementations): reset sequence numbers at each NEWKEYS, and abort if any unexpected message appears during the initial key exchange. Both sides must support it. It's a reminder that "secure channel" proofs depend on every detail of the state machine.

Post-quantum key exchange. A recorded SSH session protected only by classical ECDH could be decrypted in future by a large quantum computer ("harvest now, decrypt later"). OpenSSH therefore made the hybrid sntrup761x25519-sha512 the default in 9.0 (2022), and added mlkem768x25519-sha256 based on NIST's ML-KEM (FIPS 203, 2024) in later releases. Hybrid means the shared secret combines a classical X25519 result with a post-quantum KEM result, so an attacker must break both. Signatures (host and user keys) are a lesser concern for recorded traffic, because forging them later doesn't help decrypt past sessions.

Certificate anatomy. An OpenSSH certificate (ssh-ed25519-cert-v01@openssh.com) contains:

  • a nonce;
  • the subject public key;
  • a serial number;
  • the type (user or host);
  • the key ID;
  • the list of valid principals;
  • valid_after / valid_before;
  • critical options (force-command, source-address, verify-required for FIDO user verification);
  • extensions (permit-pty, permit-port-forwarding, permit-agent-forwarding, permit-X11-forwarding, permit-user-rc);
  • the CA's signature over all of the above.

Leaving out permit-agent-forwarding and permit-port-forwarding lets the CA centrally ban those risky features for a class of users.

# Create CA keys (store private halves in HSM/KMS in production)
ssh-keygen -t ed25519 -f user_ca -C "user-ca-2026"
ssh-keygen -t ed25519 -f host_ca -C "host-ca-2026"
 
# Sign alice's key: principals, 8h validity, no agent/port forwarding
ssh-keygen -s user_ca -I "alice@example.com ticket=INC-1234" \
  -n alice,db-admins -V +8h -O clear -O permit-pty id_ed25519.pub
 
# Sign a host key at boot for its DNS names
ssh-keygen -s host_ca -h -I "db1 i-0abc123" \
  -n db1.internal.example.com,10.0.3.17 -V +30d ssh_host_ed25519_key.pub
 
# /etc/ssh/sshd_config on every server
TrustedUserCAKeys /etc/ssh/user_ca.pub
AuthorizedPrincipalsFile /etc/ssh/principals/%u
HostCertificate /etc/ssh/ssh_host_ed25519_key-cert.pub
PasswordAuthentication no
AllowAgentForwarding no
RevokedKeys /etc/ssh/revoked.krl
 
# Client known_hosts: trust every host signed by the host CA
@cert-authority *.internal.example.com ssh-ed25519 AAAAC3Nza...

Running the CA as a service. The signing service sits behind SSO. It enforces policy (group-to-principal mapping, maximum TTL by role, ticket references for production root access) and signs with a key that never leaves a KMS or HSM. Use an asymmetric KMS key and build the certificate around the KMS signature, or use a CA product that supports this. Issuance volume is small: 2,000 engineers × 2 certificates a day ≈ 4,000 signatures/day, which any KMS handles trivially. Hosts get certificates at boot by proving their identity to the CA with a cloud instance identity document or attestation, so host trust is automatic in auto-scaling groups.

Rotation: publish the new CA public key alongside the old one in TrustedUserCAKeys (it accepts multiple keys) and in clients' @cert-authority lines, switch signing, wait out the maximum TTL, then remove the old key.

Revocation: OpenSSH key revocation lists (KRLs) are compact. They can revoke by serial range or key ID, so even large revocation sets stay small. Distribute them via configuration management. But with 8-hour TTLs, the window a revoked certificate stays usable is already small.

Bastion and broker design at scale:

  • Statelessness: bastions keep no user keys (certificates do the authentication), so they can be autoscaled behind a network load balancer.
  • Audit: log sshd authentication events (they include the certificate key ID and serial) to a SIEM.
  • Session recording: brokers like Teleport record sessions at the proxy. Recording at the target host catches activity even if the proxy is bypassed.
  • Kubernetes and databases: the same pattern applies. Short-lived client certificates or tokens are issued after SSO (kubectl via OIDC, database IAM authentication, Vault dynamic credentials with TTLs). Every human-to-infrastructure path then shares one identity source, one MFA policy and one audit trail.
Deep Dive: the mathematics and attack surface of OTPs, push and WebAuthnShow

Brute-force math for OTPs, worked through. A 6-digit TOTP with a ±1 step window has 3 valid codes out of 10^6, so each guess succeeds with probability p = 3 × 10^-6. Suppose the attacker has the password, and the server allows 5 attempts per 15 minutes per account and never locks out. That's 480 attempts per day, 175,200 per year. The expected number of successes is 175,200 × 3 × 10^-6 ≈ 0.53, so the probability of at least one success within a year is 1 − (1 − p)^175200 ≈ 41%.

That's far from negligible for a determined attacker targeting one high-value account. Defences:

  • Exponential backoff or lockout after N consecutive failures, with alerts. 10 failures allowed in total before a manual reset gives 3 × 10^-5.
  • Detect distributed guessing across many accounts (credential stuffing that also guesses OTPs).
  • Phishing-resistant factors, which make guessing meaningless.

Eight-digit codes reduce p by 100×, at a usability cost.

Truncation bias. HOTP reduces a 31-bit integer mod 10^6. Since 2^31 = 2,147,483,648 isn't a multiple of 10^6, codes 000000–483647 occur 2,148 times in the range and the rest 2,147 times, a bias of about 0.05%. It's irrelevant to security, but it illustrates why RFC 4226 caps digits: with 10 digits, the 31-bit range would leave large parts of the code space unused.

The secret-sharing weakness. TOTP is a symmetric scheme. The server holds the same secret as the user, so a server-side database leak compromises every user's second factor. That's unlike WebAuthn, where the server stores only public keys, which are useless to an attacker. QR-code enrolment can also be shoulder-surfed or screenshotted. Cloud-synced authenticator apps (Google Authenticator added account sync in 2023) trade loss-resilience for a larger attack surface: the secret's security becomes the cloud account's security.

Why push is phishable, and how number matching helps. In a push flow the server sends "Approve?" to the enrolled device. The victim can't tell which login they're approving. An attacker's login from a phishing proxy and the victim's own login look identical. Number matching forces the human to carry a value from the login screen to the app, so a blind approval no longer works. But a victim on a phishing page sees the attacker's relayed number on the fake page, types it, and approves. Number matching stops fatigue attacks, not adversary-in-the-middle phishing. Only origin binding stops AiTM.

How WebAuthn binds to the origin. At registration the authenticator creates a key pair scoped to a relying party ID (RP ID: a registrable domain, e.g. example.com), and returns the public key plus a credential ID. At authentication:

  1. The server sends a random challenge (at least 16 bytes) and, optionally, allowed credential IDs.
  2. The browser builds clientDataJSON, containing the challenge, the origin it actually sees (e.g. https://login.example.com) and the type webauthn.get. The browser enforces that the RP ID is a registrable suffix of the current origin, so example-login.com can't ask for example.com credentials.
  3. The authenticator signs authenticatorData (the SHA-256 of the RP ID, flags for user presence and user verification, and a signature counter) concatenated with the hash of clientDataJSON.
  4. The server verifies the signature with the stored public key, checks the challenge, checks the origin equals the expected origin, checks the RP ID hash, and requires the UV flag when it needs two-factor-in-one (PIN or biometric on the device).

A phishing site at a different origin either can't obtain an assertion (wrong RP ID) or gets one whose clientDataJSON.origin names the phishing domain, which the real server rejects. A relaying proxy can't rewrite the origin without breaking the signature. Note the sign counter: it can help detect cloned authenticators, but synced passkeys often report 0, so it isn't a reliable control.

Passkeys: synced vs device-bound. Synced passkeys (Apple, Google, Microsoft and password-manager ecosystems) replicate private keys across a user's devices via end-to-end-encrypted cloud sync. That solves the lost-device problem and makes phishing-resistant login usable by everyone, but the security boundary becomes the sync account. Device-bound credentials (hardware security keys, or platform keys that don't sync) never leave one authenticator. They're preferred for the highest-assurance roles, and NIST's 2024 supplement to SP 800-63B discusses syncable authenticators at AAL2 and device-bound ones for AAL3. A pragmatic policy: synced passkeys for the workforce and consumers, hardware keys (two per person, one stored safely) for admins and break-glass.

After MFA: session theft. MFA protects the login. The resulting session cookie or token is a bearer credential. Infostealer malware that copies browser cookies, and AiTM proxies that capture them, bypass MFA entirely by replaying the session. Defences:

  • Shorter session lifetimes for privileged apps, with re-authentication (step-up) for sensitive actions (changing MFA, exporting data, production deploys).
  • Binding sessions to device keys: mTLS client certificates in zero-trust proxies, or the Device Bound Session Credentials (DBSC) proposal from Chrome (2024), which ties cookies to a TPM-held key.
  • Anomaly detection on session use (new IP or ASN mid-session).
  • Continuous access evaluation: the IdP revokes tokens promptly when risk changes (OpenID's Shared Signals/CAEP work).

Recovery is the real attack surface. The strength of an account equals the strength of its weakest recovery path. Design rules:

  • Require possession of an already-enrolled factor to add a new one.
  • Out-of-band identity verification for help-desk resets (a manager or video verification for the workforce; a waiting period and notifications to every channel for consumers).
  • Single-use, hashed backup codes.
  • Alerts on every factor change.

Measure how often each recovery path is used, and treat sudden spikes as possible attacks.

Key Takeaways#

  • Private resources get no public endpoints. Access comes through a controlled path: an identity-aware proxy, an access broker, a VPN or a private link.
  • Remote-access VPNs connect devices; site-to-site VPNs connect networks. Use IPsec (IKEv2 + ESP) for standards and cloud interop, WireGuard for simple and fast modern tunnels, and OpenVPN when you must traverse restrictive firewalls on TCP 443.
  • Split tunnelling trades inspection for performance. Watch for DNS and IPv6 leaks and overlapping CIDRs. SASE plus ZTNA largely removes the dilemma.
  • Zero trust (BeyondCorp, NIST 800-207) authorises every request on identity + device health + policy, through a policy enforcement point. Network location grants nothing, which limits lateral movement.
  • SSH security rests on an ephemeral key exchange with forward secrecy, a host-key signature over the exchange hash, and user signatures bound to the session ID. Verify host keys properly, using host certificates rather than blind TOFU.
  • Use bastions with ProxyJump, not agent forwarding. Replace authorized_keys sprawl with short-lived SSH certificates from an SSO-backed CA whose key lives in an HSM or KMS, plus just-in-time access and session logs.
  • MFA means different factor categories. TOTP is HMAC-SHA1(secret, floor(time / 30)) truncated to 6 digits. Verify with a ±1 step window, replay protection, rate limits and encrypted secrets.
  • Push MFA can be bombed (Uber 2022), so require number matching and rate limits. OTPs and push can both be relayed by AiTM phishing.
  • FIDO2/WebAuthn passkeys and security keys are phishing-resistant because signatures are bound to the real origin. Require them for privileged users, and protect recovery flows as strongly as login.