Lesson · Networking
Security & Reliability: TLS, trust stores, retries and SSRF
15 min readSecurity & Reliability
A network call crosses machines you do not control. TLS is the part that makes the call private and proves who answered; trust stores decide whose certificates you accept. Then the operational half: timeouts, retries that do not amplify an outage, and the SSRF rule that your server must never fetch a URL the caller chose.
TLS in one idea
Two processes that have never met want to exchange data over a path where anyone can read, modify or impersonate. TLS turns that path into an encrypted channel, and has the server prove its identity with a certificate that chains to a root the client already trusts.
HTTPS is exactly HTTP inside TLS: the same methods, the same headers, wrapped in encrypted records. The machinery is protocol-agnostic, so the same two guarantees can wrap a database connection or your own protocol through SSLSocket.
- Confidentiality: a passive observer on the path sees byte counts and timing, not content.
- Integrity: each record is authenticated, so bytes changed in flight are detected instead of trusted.
- Server identity: the certificate chain and the hostname check are what turn a claim into something verifiable. Client certificates can reverse the direction, which is what mTLS does.
TLS is two promises, not one: a private channel, and a verified peer. The rule later in this lesson exists because teams keep buying the first one and switching off the second.
The handshake, in its TLS 1.3 shape
Everything happens in one round trip. The client opens with a ClientHello carrying the hostname it wants (SNI), the cipher suites it supports, and a key share: a fresh public value generated for this connection. The server answers with a ServerHello (its chosen suite, its own key share) and its certificate chain.
The client then runs the two checks that matter. It walks the chain of signatures up to a root it already trusts in its trust store, and it checks that the leaf certificate is valid for the hostname it asked for. A perfectly valid certificate for a different name fails the second check, which is why the name is part of the request.
Both sides combine their own private key with the other side's public share to derive the session keys, exchange a Finished check over the handshake transcript, and everything after that travels as encrypted records. TLS 1.2 needed two round trips for the same result; 1.3 needs one.
TLS 1.3 handshake · client and server
client
tcp connected
server
tcp accepted
Client verification
TCP is connected: bytes flow, but nothing is private and nobody has proven who they are. TLS runs before any HTTP.
In Java: SSLContext, trust stores and mTLS
Java compresses the handshake into a small object graph. An SSLContext is the configured factory: the protocol family ("TLS"), the trust material used to verify peers, and optionally the key material used to identify this process. Build it once and hand it to every client that talks to the outside.
TrustManagerFactory reads a trust store, which is a container of public CA certificates. With a null keystore argument it uses the JDK's default cacerts; for an internal CA you load your own store (PKCS12 for anything you generate today). KeyManagerFactory is the mirror image for your own private key and chain, which is what a server asks for when it wants the client to authenticate too: mutual TLS.
From there you either build an SSLSocketFactory and wrap raw sockets, or pass the context to HttpClient.Builder.sslContext. The default HttpClient already verifies certificates and hostnames, so an explicit context changes which roots you trust, never whether to check at all.
SSLContext ctx = SSLContext.getInstance("TLS"); // protocol family, not a version pin TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init((KeyStore) null); // null = the JDK's default cacerts ctx.init(null, tmf.getTrustManagers(), null); // no client key material: server-auth only HttpClient client = HttpClient.newBuilder().sslContext(ctx).build(); // one context, all requests
| Piece | What it holds | When you touch it |
|---|---|---|
| SSLContext | Protocol family plus the trust and key managers | Once per application, shared from there |
| TrustManagerFactory | The roots used to verify peer certificates | Point it at a custom store for an internal CA |
| KeyManagerFactory | This process's private key and certificate chain | mTLS: when the peer must authenticate you |
| SSLSocketFactory / HttpClient | The sockets or HTTP calls built from the context | Thread the context into whichever client you use |
Never disable verification
The famous way to break TLS while keeping its symbol is to switch off its checks: an X509TrustManager that accepts every chain without validating signatures, and a hostname verifier that returns true for every name. Both usually enter a codebase as a quick fix for a development endpoint.
With either one in place, the handshake still completes and the padlock still appears, but an attacker on the path presents a self-signed certificate for your hostname and no check exists to stop them. A certificate error is fixed in the chain, the trust store or the clock; a private CA is fixed by adding its root to a trust store, never by removing the check.
Fixing trust means adding the right root, never removing the verification. Every shortcut around this ends with the same word: impersonation.
Timeouts, retries and a service that is down
Every network call needs a connect timeout for establishing the connection and a read (request) timeout for the response. java.net.http gives you no read timeout until you ask for one, so a hung peer happily pins your thread until the process ends. A slow dependency becomes your outage, one blocked thread at a time.
Retrying turns a blip into a success, but a careless retry turns one failure into a self-inflicted denial of service. Retry only what is safe to repeat, and treat the four points below as one design:
- Idempotent only: safe GETs, PUTs that set a value to a known state, and DELETEs are repeatable; a bare POST that charges a card is not.
- Backoff with jitter: 200 ms, 400 ms, 800 ms plus a random offset, so a thousand clients do not retry in lockstep and flatten the recovering service.
- A cap and a breaker: limit attempts and total time, and let a circuit breaker stop calling a service that is clearly down until it recovers.
- Idempotency keys: a read timeout does not prove the server did not execute, so retrying a non-idempotent operation needs a key the server can use to detect the duplicate.
Timeouts bound one call; backoff, a cap and a breaker bound the blast radius. A retry policy without jitter is a load test you scheduled against your own dependency.
SSRF: the URL your server fetches for the user
Server-side request forgery is what happens when user input decides where your server connects. The feature is always innocent: a webhook target, a URL importer, an image proxy. The destination the attacker picks is not public: 169.254.169.254 (the cloud metadata service), an admin panel on localhost, or any internal system that trusts traffic arriving from inside your network.
The request is made with your credentials and from your network position, so it is worth more than the same request from the attacker's own machine. The defences below stack; none of them is a proof on its own.
- Allowlist first: when the legitimate targets are known, a strict host allowlist beats every heuristic.
- Resolve, then refuse: resolve the hostname yourself and reject loopback, private and link-local address ranges before you connect.
- Redirects are part of the surface: a permitted host can redirect to a private address, so re-check every hop or turn redirects off.
- DNS rebinding: a name can resolve to a public address at check time and to a private one at connect time, so verify as close to the connection as you can and treat the whole stack as defence in depth.
SSRF is borrowed trust. The request leaves from your server, with your credentials and your network position, so validate the destination the way you would validate an inbound request.
Virtual threads and where they fit
Virtual threads (Java 21) make the straightforward blocking design viable again: a socket read that parks a virtual thread costs almost nothing, so thread-per-request scales to very many connections without an event loop. What they do not remove is the cost of the call itself, and the same timeouts and retries still apply.
They also do not remove the fan-out problem. When one request must call ten services, HttpClient.sendAsync expresses that as ten in-flight calls with continuations, instead of ten parked threads. Keep blocking for the request path, and reach for async when one request multiplies into many calls.
Blocking got cheap, not free. Virtual threads remove the thread cost of waiting, not the cost of the request, and nothing about them relaxes the timeout and retry rules above.
A read timeout does not mean the server did not execute
Your request can arrive, be processed, and only the response gets lost. Retrying a GET repeats a read and costs nothing; retrying a charge repeats a charge. That is why non-idempotent retries are built around an idempotency key the server can deduplicate on, and why "we will just retry" is a dangerous sentence next to a payment.
Interview angles
What does HTTPS give you that plain HTTP does not?+
An encrypted, tamper-evident channel plus a verified server identity: the chain is checked against your trust store and the hostname against the certificate's SANs. Without the identity check you have only hidden the conversation from observers, not from an impostor on the path.
Why does the ClientHello carry the hostname?+
One address can serve many names, so the client states which name it wants (SNI) and the server sends the matching certificate. The same name is what the later hostname check validates, so it is both a routing input and a security input.
What happens when you disable certificate verification?+
The chain check and the hostname check become no-ops: any certificate for any name passes, and a man in the middle is indistinguishable from the real server. The connection still encrypts, which is worse than plaintext because it looks safe.
Common misconception: Trusting everything is not a temporary workaround for a self-signed certificate. Add the internal CA to a trust store once; a trust-all context is a permanent downgrade that ships.
How do you call a flaky endpoint safely?+
Retry only idempotent requests, with exponential backoff plus jitter, an attempt cap, a total time budget and a circuit breaker. A read timeout does not prove the operation did not execute, so non-idempotent calls need an idempotency key the server deduplicates on.
Follow-up: What changes for a POST that creates an order? The retry needs the key, and the server must return the same result for a repeated key instead of creating a second order.
How do you defend a URL-fetching feature against SSRF?+
Prefer a host allowlist. Otherwise resolve the destination and reject loopback, private and link-local ranges, re-check after every redirect, and remember that DNS rebinding can change the answer between check and connect: layers narrow the window, none closes it alone.
Do virtual threads change how you write clients?+
They change the server side: blocking calls no longer hold an expensive platform thread, so thread-per-request is viable again. For fan-out inside one request, async (HttpClient.sendAsync) is still the better shape, because one thread owns many in-flight calls.