Cryptographic Protocol Design and Analysis Questions
Designing and reasoning about cryptographic protocols and secure channels: how message flows, key-exchange handshakes, and end-to-end encryption systems are constructed so that composing individual primitives yields a provably or informally verified secure whole. Covers authentication and key-exchange protocol design (mutual authentication, forward secrecy, key confirmation, key-compromise-impersonation resistance), message-flow and state-machine security, formal and informal protocol verification (BAN logic, symbolic tools such as ProVerif and Tamarin, game-based reduction proofs), protocol-level vulnerability analysis (downgrade, replay, padding-oracle, algorithm-confusion attacks), TLS handshake and key-schedule internals, and end-to-end encryption system design (ratcheting, group key agreement, key transparency, post-compromise security). This is the design and analysis layer: why a protocol construction is secure, not which library call or key-management process to run in production. Distinct from selecting and operating cryptographic primitives day to day (certificate lifecycle management, TLS deployment monitoring and incident response, key rotation operations, algorithm and parameter selection for a given constraint set), which belongs to applied cryptography and key management; from core cryptographic vocabulary and primitive fundamentals; and from implementation-level bugs (side-channel leakage, memory-safety flaws, timing attacks in code), which belong to cryptographic implementation security.
Given the handshake:
- A -> B: A, {Na, g^a}_Bpub
- B -> A: B, {Na, Nb, g^b}_Apub
- A -> B: {Nb}_Bpub
Perform a BAN-logic analysis: idealize the messages, state assumptions and initial beliefs, and show step-by-step whether A and B can be shown to believe they share a fresh secret or authenticate each other. Be explicit about freshness assumptions.
Sample Answer
Direct answer
Running the actual BAN-logic (Burrows-Abadi-Needham logic, a modal logic for reasoning about what principals can justifiably believe after exchanging messages) postulates on this handshake shows that neither A nor B can derive belief in each other's identity, because every "encrypted" message here uses the recipient's public key for confidentiality, not a signature or a shared secret, and BAN's message-meaning rule has no basis to attribute authorship to an encryption anyone could have produced. The nonces do make any resulting key fresh, but freshness of a value is not authentication of who you share it with; the protocol is vulnerable to an unknown-key-share attack in which B ends up computing the identical secret as A while genuinely believing his peer was someone else.
Structured elaboration
Notation. P|≡X = P believes X. P◁X = P sees X. P|~X = P once said X. #(X) = X is fresh. {X}_K = X encrypted under K.
Initial assumptions a designer would plausibly intend (stated explicitly, since BAN analysis lives or dies on what you assume): A and B each believe Kpub_A/Kpub_B are genuinely each other's public keys; each believes their own freshly generated nonce is fresh (A|≡#(Na), B|≡#(Nb)); each is willing to trust the other's jurisdiction over the session key material if authentication succeeds.
Idealizing the three messages, field by field. Message 1, A -> B: A, {Na, g^a}_Bpub: Bpub is a public key, known to everyone, not a secret shared only by A and B. BAN's message-meaning rule for encryption requires the encrypting key to be something only the claimed sender (and the verifier) could have used, either a shared symmetric secret or the sender's own signing key. Bpub is neither: anyone can encrypt to it. So the correct idealization is B ◁ (Na, g^a), plain content B has decrypted, with no attributable "A said (Na, g^a)" belief, because no postulate licenses one. The plaintext label "A" in the message is a routing hint, not a cryptographic claim.
The same problem repeats at message 2 (B -> A: B, {Na, Nb, g^b}_Apub, encrypted to A's public key) and message 3 (A -> B: {Nb}_Bpub). It is tempting to reason informally that "only B could have decrypted message 1 to learn Na, so whoever echoes Na in message 2 must be B", but that is a decryption-capability argument, not one of BAN's postulates (message-meaning, nonce-verification, jurisdiction); classical BAN logic was built around encryption-as-attribution (shared secrets or signatures), not around "being able to read something implying you produced the reply." Treating that informal intuition as if it were a derived belief is exactly the mistake a disciplined idealization is meant to prevent.
Consequence for the derivation. Because no message-meaning inference fires for any of the three messages, A|≡B|~X and B|≡A|~X are both underivable for any X. The nonce-verification rule (P|≡#(X), P|≡Q|~X ⟹ P|≡Q|≡X) needs Q|~X as a precondition, so it never fires either. Neither party can reach A|≡B|≡(shared key) or B|≡A|≡(shared key): the handshake fails to establish authentication in the BAN sense, on both sides, even though it looks superficially like an authenticated Diffie-Hellman exchange.
Worked example
A concrete unknown-key-share (UKS) attack realizes the gap the idealization exposes. Mallory is an active network attacker holding no private keys belonging to A or B, only her own, real, separately-registered keypair (needed for the leg where B genuinely addresses a reply to her). She never decrypts anything encrypted to A or B; she only relabels the unauthenticated plaintext identity tag that rides alongside each ciphertext. Toy RSA keypairs and a toy Diffie-Hellman group make every step concrete and checkable:
# Executable demonstration of the unknown-key-share (UKS) attack on the
# handshake's identity binding: Mallory relays the SAME ciphertexts
# unmodified (she holds no private keys and cannot decrypt anything
# encrypted to A or B), only rewriting the UNAUTHENTICATED plaintext
# identity label that rides alongside each ciphertext. A and B still end
# up computing the identical Diffie-Hellman secret; what breaks is which
# identity each of them believes they share it with.
# ---- toy RSA keypairs (textbook RSA, no padding: illustrative only) ----
# A: p=17, q=11 -> N=187, phi=160, e=7, d=23 (7*23 = 161 = 1 mod 160)
A_N, A_E, A_D = 187, 7, 23
# B: p=13, q=19 -> N=247, phi=216, e=5, d=173 (5*173 = 865 = 1 mod 216)
B_N, B_E, B_D = 247, 5, 173
assert (A_E * A_D) % 160 == 1 and (B_E * B_D) % 216 == 1
def rsa_enc(m, e, N):
assert 0 <= m < N
return pow(m, e, N)
def rsa_dec(c, d, N):
return pow(c, d, N)
# ---- toy DH group ----
P, G = 23, 5
def dh_pub(secret_exp):
return pow(G, secret_exp, P)
def dh_shared(their_pub, my_secret_exp):
return pow(their_pub, my_secret_exp, P)
# =====================================================================
# A believes she is running the handshake with B. Every ciphertext really
# IS encrypted to the real B's public key throughout; Mallory never holds
# A_D or B_D and never decrypts anything.
# =====================================================================
a_secret = 6
Na = 71
ga = dh_pub(a_secret)
print("Step 1: A encrypts (Na, g^a) to B's real public key and labels it 'A'.")
msg1_real = {"label": "A", "Na_ct": rsa_enc(Na, B_E, B_N), "ga_ct": rsa_enc(ga, B_E, B_N)}
print(" ", msg1_real)
print("\nStep 2: Mallory intercepts. She cannot decrypt (no B_D), so she forwards")
print("the SAME ciphertexts unmodified, only rewriting the plaintext label.")
msg1_relabeled = {"label": "Mallory", "Na_ct": msg1_real["Na_ct"], "ga_ct": msg1_real["ga_ct"]}
print(" ", msg1_relabeled)
print(" ciphertexts identical to the real message:",
msg1_relabeled["Na_ct"] == msg1_real["Na_ct"] and msg1_relabeled["ga_ct"] == msg1_real["ga_ct"])
print("\nStep 3: B decrypts with his own real private key (this step is entirely")
print("genuine; only the label told him who sent it).")
Na_at_B = rsa_dec(msg1_relabeled["Na_ct"], B_D, B_N)
ga_at_B = rsa_dec(msg1_relabeled["ga_ct"], B_D, B_N)
print(f" B recovers Na={Na_at_B}, g^a={ga_at_B} -- correct values, wrong believed sender")
b_secret = 15
Nb = 54
gb = dh_pub(b_secret)
print(f" B believes his peer is 'Mallory' and replies, encrypted to MALLORY's real public key")
print(" (this is what the protocol specifies: reply to whoever you believe you're talking to).")
# Mallory needs her own real keypair to receive this leg, since B genuinely
# addresses it to her -- toy keypair: p=19, q=23 -> N=437, phi=396, e=5, d=317
M_N, M_E, M_D = 437, 5, 317
assert (M_E * M_D) % 396 == 1
msg2_to_mallory = {"label": "B", "Na_ct": rsa_enc(Na_at_B, M_E, M_N),
"Nb_ct": rsa_enc(Nb, M_E, M_N), "gb_ct": rsa_enc(gb, M_E, M_N)}
print(" ", msg2_to_mallory)
print("\nStep 4: Mallory DOES hold her own private key, so she genuinely decrypts")
print("this leg (it really was addressed to her), then re-encrypts the SAME")
print("plaintext to A's real public key, forwarding it as if it came from B.")
Na_at_M = rsa_dec(msg2_to_mallory["Na_ct"], M_D, M_N)
Nb_at_M = rsa_dec(msg2_to_mallory["Nb_ct"], M_D, M_N)
gb_at_M = rsa_dec(msg2_to_mallory["gb_ct"], M_D, M_N)
print(f" Mallory recovers Na={Na_at_M}, Nb={Nb_at_M}, g^b={gb_at_M} from her own leg")
msg2_relayed_to_A = {"label": "B", "Na_ct": rsa_enc(Na_at_M, A_E, A_N),
"Nb_ct": rsa_enc(Nb_at_M, A_E, A_N), "gb_ct": rsa_enc(gb_at_M, A_E, A_N)}
print(" ", msg2_relayed_to_A)
print("\nStep 5: A decrypts with her own real private key, sees her own Na echoed")
print("back correctly, and reasonably believes this is B's genuine reply.")
Na_at_A = rsa_dec(msg2_relayed_to_A["Na_ct"], A_D, A_N)
Nb_at_A = rsa_dec(msg2_relayed_to_A["Nb_ct"], A_D, A_N)
gb_at_A = rsa_dec(msg2_relayed_to_A["gb_ct"], A_D, A_N)
print(f" A recovers Na={Na_at_A} (matches her own {Na}), Nb={Nb_at_A}, g^b={gb_at_A}")
print(f" Na echoed correctly: {Na_at_A == Na}")
k_at_A = dh_shared(gb_at_A, a_secret)
k_at_B = dh_shared(ga_at_B, b_secret)
print(f"\nStep 6: A computes K = (g^b)^a mod {P} = {k_at_A}")
print(f" B computes K = (g^a)^b mod {P} = {k_at_B}")
print(f" A and B hold the IDENTICAL secret: {k_at_A == k_at_B}")
print(f" Mallory never learns K (she only ever held ciphertexts and her own decrypted view of Na/Nb/g^b,")
print(f" never A's or B's private key), so confidentiality of K itself is intact.")
print()
print(" A's belief about who she shares K with: 'B' (matches the label she saw)")
print(" B's belief about who he shares K with: 'Mallory' (matches the label he saw)")
print(" These are DIFFERENT identities for the SAME shared secret: an unknown-key-share.")
Output:
Step 1: A encrypts (Na, g^a) to B's real public key and labels it 'A'.
{'label': 'A', 'Na_ct': 67, 'ga_ct': 164}
Step 2: Mallory intercepts. She cannot decrypt (no B_D), so she forwards
the SAME ciphertexts unmodified, only rewriting the plaintext label.
{'label': 'Mallory', 'Na_ct': 67, 'ga_ct': 164}
ciphertexts identical to the real message: True
Step 3: B decrypts with his own real private key (this step is entirely
genuine; only the label told him who sent it).
B recovers Na=71, g^a=8 -- correct values, wrong believed sender
B believes his peer is 'Mallory' and replies, encrypted to MALLORY's real public key
(this is what the protocol specifies: reply to whoever you believe you're talking to).
{'label': 'B', 'Na_ct': 124, 'Nb_ct': 384, 'gb_ct': 57}
Step 4: Mallory DOES hold her own private key, so she genuinely decrypts
this leg (it really was addressed to her), then re-encrypts the SAME
plaintext to A's real public key, forwarding it as if it came from B.
Mallory recovers Na=71, Nb=54, g^b=19 from her own leg
{'label': 'B', 'Na_ct': 113, 'Nb_ct': 164, 'gb_ct': 145}
Step 5: A decrypts with her own real private key, sees her own Na echoed
back correctly, and reasonably believes this is B's genuine reply.
A recovers Na=71 (matches her own 71), Nb=54, g^b=19
Na echoed correctly: True
Step 6: A computes K = (g^b)^a mod 23 = 2
B computes K = (g^a)^b mod 23 = 2
A and B hold the IDENTICAL secret: True
Mallory never learns K (she only ever held ciphertexts and her own decrypted view of Na/Nb/g^b,
never A's or B's private key), so confidentiality of K itself is intact.
A's belief about who she shares K with: 'B' (matches the label she saw)
B's belief about who he shares K with: 'Mallory' (matches the label he saw)
These are DIFFERENT identities for the SAME shared secret: an unknown-key-share.
A and B end up computing the identical Diffie-Hellman secret (K = 2 on both sides), confirmed directly in the output: Mallory never recovers it, since she never holds A's or B's private key, so no confidentiality is broken. What breaks is belief about identity: A correctly believes she now shares a fresh secret with B, while B believes he shares it with Mallory. If B later authorizes anything on the strength of "this session belongs to Mallory" (billing an account, granting access, logging an action), the misattribution is exploitable even though the cryptographic secret itself was never recovered by the attacker.
Trade-offs and pitfalls
- This exact message shape (an identity label plus a nonce sent to the peer's public key, echoed back with a fresh nonce of the peer's own) is structurally the classic Needham-Schroeder Public-Key protocol. That protocol was believed correct, including under BAN-style analysis, for years, until Gavin Lowe published a 1995 attack showing an active attacker who is a legitimate-but-dishonest participant in ONE session can relay a captured value into a SECOND, unrelated session with a different peer and complete it while impersonating the original initiator, the same identity-relay shape as the Mallory attack above generalized to a peer who is a real (if dishonest) protocol participant rather than an outsider. The historical lesson matters as much as the math: manual, optimistic idealization missed this for years precisely because nobody constructed the cross-session relay trace by hand, which is exactly why this class of protocol is now routinely run through an automated model checker (Tamarin, ProVerif) in addition to, not instead of, manual BAN reasoning.
- A narrower, complementary issue is worth naming separately: even after fixing identity binding, a receiver still needs to reject an already-consumed nonce (simple replay of a stale, previously-completed exchange). That is a different failure mode from the identity-relay attack above, defended by endpoint state (an outstanding-nonce table that consumes each value on first use) rather than by anything in the message idealization itself, and a complete implementation needs both defenses, not just one.
- The general lesson: encrypting to a public key authenticates confidentiality of content, never sender identity. Only a signature made with the sender's own private key (or a MAC under an already-mutually-authenticated shared secret) gives BAN's message-meaning rule something to attribute. Swapping "sign with your own key" for "encrypt to the peer's key" silently deletes the entire authentication guarantee while leaving the message flow looking almost the same.
- The standard fix is to bind identity cryptographically into what is checked: either have each party sign their nonce and DH share with their own private key (turning this into something close to the signed-Diffie-Hellman Station-to-Station construction), or add an explicit key-confirmation MAC, computed over both identities and both DH shares using a key derived from
g^(ab)itself, so relabeling either party's identity after the fact breaks the MAC. - BAN logic does not catch this automatically just by "running the postulates"; the analyst has to notice, while idealizing, exactly which fields are inside the cryptographic envelope and which are unauthenticated plaintext labels. A sloppy idealization that reflexively assumes "it's encrypted, so treat it as attributed to the labeled sender" would hide this exact bug, which is why disciplined field-by-field idealization matters more than mechanically applying the rule set.
- Freshness of Na and Nb still holds trivially (each party knows its own nonce is new) and is not in question here; the failure is specifically that freshness alone never implies authentication, it only feeds the nonce-verification rule after a message-meaning belief already exists, and here that belief never arises.
Analyze the concept of channel binding in secure protocols (binding application-layer authentication to transport-level channels). Give an example attack that exploits missing channel binding in an E2EE or TLS-based system, and propose concrete mitigations both at the protocol and implementation levels to prevent such attacks.
Sample Answer
Direct answer
Channel binding cryptographically ties an application-layer authentication event (a login, a token exchange) to the specific transport-level channel it happened on (a particular TLS session), so an attacker who relays or forwards that authentication over a different channel cannot be accepted. Without it, an authentication credential is only "proof of who you are," never "proof of who you are, on this exact connection," which lets an attacker terminate one TLS session, open a second one elsewhere, and forward the credential across the gap: a credential-forwarding, or cut-and-paste, attack.
Structured elaboration
Example attack. An end-to-end encrypted (E2EE) chat client authenticates to a cloud key-store using an OAuth bearer token, after establishing TLS to the key-store. A network attacker sits in the middle: it terminates the client's TLS session (session 1) and opens its own, separate TLS session to the key-store (session 2). It forwards the bearer token it captured from session 1 into session 2. Because the token is not bound to any particular session, the key-store accepts it on session 2 exactly as if it had arrived on session 1, and the attacker walks away with key material. The root cause: the credential is f(user) only, with no dependency on which channel carried it.
Protocol-level mitigations.
- Bind the credential to TLS-exported keying material (EKM, a value both endpoints can independently derive from a specific TLS session per RFC 5705): include
TLS-Exporter(label, context, length)inside the authentication assertion, or MAC the assertion with it. - Add explicit key confirmation: have both parties prove possession of the same session key, for example by covering the handshake transcript and the application-auth exchange with a signature or MAC.
- Use mutual TLS (mTLS) or OAuth's Mutual-TLS Client Authentication so a token is only valid when presented over the same TLS connection whose certificate it was issued to.
Implementation-level mitigations.
- Use the TLS library's exporter API directly rather than reimplementing key derivation from internal TLS state.
- Fail closed: reject a channel-binding mismatch outright, do not merely log it.
- Give tokens short lifetimes and bind refresh flows to the same channel-binding check as the original exchange.
Worked example
Simulating the attack and the fix directly: an unbound token, versus a token whose HMAC (keyed-hash message authentication code) includes the session's exported keying material.
import hmac, hashlib, os
def hmac_sha256(key, msg): return hmac.new(key, msg, hashlib.sha256).digest()
ekm_session1 = os.urandom(32) # TLS-Exporter() output, session 1 (genuine)
ekm_session2 = os.urandom(32) # TLS-Exporter() output, session 2 (attacker's)
user_secret = b"user-long-term-auth-secret"
# Unbound bearer token: token = f(user) only.
unbound_token = hmac_sha256(user_secret, b"session-independent-token")
def keystore_accepts_unbound(token):
return hmac.compare_digest(token, hmac_sha256(user_secret, b"session-independent-token"))
print("unbound token accepted when replayed on session 2?", keystore_accepts_unbound(unbound_token))
# Channel-bound token: token = f(user, EKM).
def make_bound_token(ekm): return hmac_sha256(user_secret, b"bound-token" + ekm)
def keystore_accepts_bound(token, ekm_seen): return hmac.compare_digest(token, make_bound_token(ekm_seen))
bound_token = make_bound_token(ekm_session1)
print("bound token accepted on its own session?", keystore_accepts_bound(bound_token, ekm_session1))
print("bound token accepted when forwarded to session 2?", keystore_accepts_bound(bound_token, ekm_session2))
Output:
unbound token accepted when replayed on session 2? True
bound token accepted on its own session? True
bound token accepted when forwarded to session 2? False
The unbound token is accepted wherever it is presented, exactly the forwarding vulnerability the attack scenario describes. The bound token is accepted only on the session whose exported keying material produced it; forwarding it to a different session (a different EKM value) fails the HMAC check, which is the concrete mechanism refusing the attack.
Trade-offs & pitfalls
EKM-based binding requires both endpoints to support the exporter API, so rollout needs a compatibility plan: either reject clients that cannot present a binding value, or require mTLS as a stronger substitute during a transition period. A pitfall worth naming explicitly: some older implementations bound to tls-unique, a value derived from the Finished message, which changes meaning (or is undefined) across renegotiation and in TLS 1.3's simplified handshake; prefer the TLS exporter (RFC 5705), not tls-unique, for anything built or maintained today. Logging binding-mismatch events is useful for detecting active attacks, but log only the fact of a mismatch, never the secret values being compared.
Evaluate the security and operational trade-offs between choosing a deterministic AEAD primitive (e.g., AES-SIV) and a nonce-based AEAD (e.g., AES-GCM) for a messaging protocol that requires forward secrecy, server-side deduplication, and occasional offline message replay. Which would you select and why? Describe migration and interoperability considerations.
Sample Answer
Direct answer
Use a hybrid, not one primitive everywhere: keep the end-to-end payload under a nonce-based AEAD (authenticated encryption with associated data, an encryption mode that provides both confidentiality and tamper-detection in one primitive) such as AES-GCM with ephemeral, forward-secret keys, and use a deterministic construction (a keyed HMAC token, or AES-SIV, Synthetic IV mode, a deterministic AEAD construction where the same plaintext and key always produce the same ciphertext, only for that narrow purpose) solely to give the server something stable to deduplicate on. Pure AES-SIV everywhere sacrifices forward secrecy (a deterministic key that survives long enough to detect duplicates is also long-lived enough to matter if it leaks) and leaks message equality to the server; pure AES-GCM with server-visible ciphertext gives the server nothing to deduplicate on without either seeing plaintext or being handed a second, purpose-built signal.
Structured elaboration
- Forward secrecy needs ephemeral session keys (for example from an X25519 Diffie-Hellman exchange per session) feeding a nonce-based AEAD with a fresh nonce per message. That pushes payload encryption toward AES-GCM or ChaCha20-Poly1305, not a deterministic mode.
- Server-side deduplication without handing the server plaintext: derive a separate, long-lived dedup token,
dedup_token = HMAC(K_dedup, message_id || H(payload)), whereK_dedupis a key used only for this purpose and rotated on its own schedule, distinct from the per-session AEAD keys. The server compares tokens, never plaintext. - Offline replay detection: include a monotonic per-sender counter or timestamp inside the signed/authenticated payload, and have the server maintain a replay window keyed on the dedup token plus counter, so a message replayed after the client comes back online is caught deterministically without weakening the payload's forward secrecy.
- Migration and interoperability: put an explicit AEAD-mode and key-derivation-version field in a protocol header so old and new clients can be told apart; support both modes on the server during rollout, and require dedup keys to be versioned (key IDs) so tokens can be validated against the correct key even as
K_deduprotates.
Worked example
The security argument for "AES-GCM's random-nonce requirement is manageable" is a birthday-bound calculation, not a hand-wave. For a 96-bit random nonce (AES-GCM's standard nonce size) and k messages encrypted under one key, the probability of two messages colliding on the same nonce is approximately:
P(collision)≈297k2
For k = 2^32 messages under one key, the exponents work out to 2 x 32 - 97 = -33, so:
P(collision)≈2−33
That matches NIST SP 800-38D's own guidance to cap random-nonce AES-GCM usage at roughly 2^32 invocations per key, the point past which the birthday bound stops being comfortably negligible. This is exactly why a key-rotation policy (rotate well before 2^32 messages per key) belongs in the design alongside the AEAD choice itself: the "nonce-based AEAD is safe" claim is conditional on staying under that bound, not unconditional.
Trade-offs & pitfalls
The single biggest same-basis error here is conflating the AEAD's own nonce-collision risk (an operations-per-key bound, bits of nonce space) with the dedup token's linkability risk (a privacy bound, independent of nonce size); they are different quantities and need separate mitigations. AES-SIV's misuse-resistance (it degrades gracefully on nonce reuse instead of catastrophically) is attractive, but determinism means two identical plaintexts under the same key always produce the same ciphertext, which is exactly the equality-linkability that must be kept out of the forward-secret payload path and confined to a dedicated, rotatable dedup key. A dedup token salted per-recipient reduces cross-user linkability but does not eliminate within-recipient linkability (the server can still tell if the same recipient got the same message twice), which is usually the intended trade-off, not a bug, but should be stated explicitly rather than discovered later.
A protocol you maintain allows third-party negotiated extensions at handshake time. A new extension that bypasses a key confirmation step caused a security regression. Design an extension-safety policy that allows safe extensibility without weakening core security guarantees. The policy should cover a specification language for extensions, static checks, dynamic runtime guards, and the vetting and deployment process.
Sample Answer
Direct answer
The policy needs four layers working together, because no single layer alone would have caught a real extension that "bypassed a key confirmation step": a machine-checkable specification language that forces every extension to declare its security-relevant behavior, static checks (including formal verification) run before an extension ships, runtime guards that enforce a monotonic security floor regardless of what an extension claims, and a staged vetting and deployment process with a kill switch. The specific regression described, an extension silently skipping key confirmation, is caught by the runtime guard layer even if the static-check layer misses it, which is exactly why the design needs both, not either.
Structured elaboration
- Specification language. A small, typed, signed manifest per extension declaring: capabilities requested, intended state changes, cryptographic primitives used, and explicit security properties it claims to preserve (for example, "does not bypass key confirmation"). Machine-checkable structure, not free-text documentation, is what makes the next two layers possible.
- Static checks (pre-deployment). Type and schema validation of the manifest; semantic checks that enforce protocol invariants (an extension cannot declare that it skips key confirmation and still be accepted); where feasible, translate the extension's effect on the handshake into a model for a symbolic verification tool (ProVerif or Tamarin) and prove no downgrade of authentication or confidentiality properties results.
- Runtime guards. Capability negotiation with least privilege: an extension is granted only the specific capabilities its manifest requested, nothing implicit. A monotonic security lattice: no operation an extension performs is allowed to lower the security level already established, specifically including a hard rule that key confirmation cannot be skipped by any extension, full stop, enforced by the core handshake state machine rather than by trusting the extension to behave. Unknown or invalid extensions fail closed (handshake aborts) rather than silently degrading.
- Vetting and deployment. Design review, formal verification, cryptographic peer review, fuzzing and interoperability testing, then a staged canary rollout with monitoring, in that order. Require signed manifests and reproducible builds so what was reviewed is provably what ships. Keep an operational kill switch that can disable a specific extension fleet-wide without a full deployment cycle.
Worked example
Applying this concretely to the described regression: the offending extension's manifest would have had to declare either "skips key confirmation" (a static check rejects this outright, since it directly contradicts the core-guarantee invariant) or nothing about key confirmation at all (a runtime guard still catches it, because the guard does not trust the manifest's silence; it independently verifies, at the protocol state-machine level, that a key-confirmation message was actually exchanged before the session is marked established, regardless of which extensions ran). This is the concrete difference between a policy that only checks what an extension says it does, versus one that also verifies what the core protocol actually did happen, and it is why the runtime-guard layer exists even when static checks look sufficient on paper.
Trade-offs & pitfalls
Formal verification (ProVerif/Tamarin, symbolic tools for proving properties of cryptographic protocols) is powerful but has real limits: it verifies the model you gave it, and a mismatch between that model and the actual implementation is a known failure mode, so pair it with implementation-level testing rather than trusting the proof alone. A fail-closed policy on unknown extensions is safer but has an availability cost: a legitimate new extension that has not yet been reviewed will simply not negotiate, which needs to be an accepted trade-off up front, not discovered as a surprise outage during a partner integration. Finally, a kill switch is only useful if it was exercised before the incident it is meant to handle; an untested kill switch is a false sense of security, so it belongs in the same staged-rollout testing the extension itself goes through.
Design a handshake and server-side anti-replay strategy that supports 0-RTT data while preserving replay protection and forward secrecy for non-0-RTT data. Specify client state to reuse, server-side caches or tokens, KDF binding of 0-RTT to context, and operational limitations to impose on 0-RTT traffic.
Sample Answer
Direct answer
Combine two independent mechanisms: a PSK (pre-shared key) binder that cryptographically ties an offered resumption ticket to this specific ClientHello, so a captured ticket can't be spliced onto a different one, and single-use redemption of that ticket for early data specifically, so a replayed ClientHello can still complete the connection as ordinary 1-RTT but can never get its early data applied twice. Non-0-RTT data keeps its forward secrecy by using psk_dhe_ke mode, PSK combined with a fresh (EC)DHE (elliptic-curve Diffie-Hellman Ephemeral) contribution, once the full handshake completes.
Structured elaboration
- Client state to reuse. The resumption ticket issued by the server after a prior full handshake, and the resumption PSK it names; the client presents the ticket identifier and computes a binder over the new ClientHello using a key derived from that PSK.
- Server-side caches or tokens. A small map from ticket identifier to (PSK, expiry); on top of that, a separate, bounded set of ticket identifiers already redeemed for 0-RTT, checked and updated atomically at connection time and evicted once the ticket's own validity window ends, so this state never grows past "recent tickets currently valid."
- KDF (key derivation function) binding of 0-RTT to context. The binder itself is
HMAC(binder_key, transcript_so_far), an HMAC being a keyed cryptographic checksum, wherebinder_keyis derived from the PSK via HKDF (HMAC-based key derivation function). Because it covers the ClientHello bytes up to that point, an attacker who captured a valid (ticket, binder) pair cannot reuse it with a different ClientHello, changing even one byte before the binder invalidates the match; this is a distinct property from anti-replay of the identical message, it stops splicing rather than resending. - Operational limitations on 0-RTT traffic. Restrict early data to requests the application has independently marked idempotent (the same discipline that keeps a mutating request safe under any replay, not just this transport's); bound ticket lifetime tightly enough that the anti-replay set never needs to hold more than one lifetime's worth of identifiers; and, per RFC 8446 (the TLS, Transport Layer Security, 1.3 specification), section 8.1 (Single-Use Tickets, the mechanism implemented below) together with the fallback rule in section 4.2.10, never abort the handshake purely because early data was rejected as a replay, fall back to completing the connection as 1-RTT so the mechanism can't be turned into a denial-of-service lever against legitimate retries.
Worked example
"""
0-RTT (zero round-trip time: the client sends encrypted application data
in its very first flight, before the handshake finishes) anti-replay design.
Two mechanisms shown together, matching real TLS 1.3 (RFC 8446):
(a) a PSK (pre-shared key) binder: an HMAC over the ClientHello-so-far that
cryptographically ties the offered resumption ticket to THIS specific
ClientHello, so a captured ticket can't be spliced into a different one.
(b) single-use ticket redemption for early data: replaying the exact same
ClientHello+ticket a second time must not let the *early data* (e.g. a
purchase) execute twice, even though the connection itself may still be
allowed to proceed as ordinary 1-RTT.
Stdlib only, pinned inputs.
"""
import hashlib
import hmac
HASH = hashlib.sha256
def hkdf_extract(salt: bytes, ikm: bytes) -> bytes:
return hmac.new(salt, ikm, HASH).digest()
def hkdf_expand(prk: bytes, info: bytes, length: int) -> bytes:
t, okm, counter = b"", b"", 1
while len(okm) < length:
t = hmac.new(prk, t + info + bytes([counter]), HASH).digest()
okm += t
counter += 1
return okm[:length]
class Server:
def __init__(self):
# ticket_id -> (resumption_psk, expiry_epoch)
self.tickets = {}
# ticket_ids already redeemed for 0-RTT early data (bounded by ticket lifetime)
self.zero_rtt_redeemed = set()
def issue_ticket(self, resumption_psk: bytes, now: int, lifetime: int = 3600) -> bytes:
ticket_id = bytes.fromhex("560b7ff61ec849cfa8cd145a46e66520")[:16] # pinned, synthetic
self.tickets[ticket_id] = (resumption_psk, now + lifetime)
return ticket_id
def handle_client_hello(self, ticket_id: bytes, binder: bytes, transcript_prefix: bytes,
early_data: bytes | None, now: int):
entry = self.tickets.get(ticket_id)
if entry is None:
return {"psk_accepted": False, "early_data_accepted": False, "reason": "unknown/expired ticket"}
psk, expiry = entry
if now > expiry:
return {"psk_accepted": False, "early_data_accepted": False, "reason": "ticket expired"}
# (a) PSK binder check: proves the client possesses the PSK AND that
# this exact ClientHello (not a different one) is what was bound.
binder_key = hkdf_expand(hkdf_extract(b"", psk), b"res binder", 32)
expected_binder = hmac.new(binder_key, transcript_prefix, HASH).digest()
if not hmac.compare_digest(binder, expected_binder):
return {"psk_accepted": False, "early_data_accepted": False, "reason": "binder mismatch"}
result = {"psk_accepted": True, "early_data_accepted": False, "reason": None}
if early_data is not None:
# (b) anti-replay: a ticket may fund early data AT MOST ONCE,
# the "Single-Use Tickets" mechanism of RFC 8446 section 8.1.
# Per section 4.2.10, a replayed early-data attempt does not
# abort the handshake; it just falls back to ordinary 1-RTT
# (early data is simply not applied) so we don't hand the
# attacker a free connection-establishment DoS lever either.
if ticket_id in self.zero_rtt_redeemed:
result["reason"] = "early data rejected: ticket already redeemed for 0-RTT (falling back to 1-RTT)"
else:
self.zero_rtt_redeemed.add(ticket_id)
result["early_data_accepted"] = True
return result
def client_hello(ticket_id: bytes, resumption_psk: bytes, session_nonce: bytes) -> tuple[bytes, bytes]:
transcript_prefix = b"ClientHello||" + ticket_id + b"||" + session_nonce
binder_key = hkdf_expand(hkdf_extract(b"", resumption_psk), b"res binder", 32)
binder = hmac.new(binder_key, transcript_prefix, HASH).digest()
return transcript_prefix, binder
if __name__ == "__main__":
server = Server()
resumption_psk = bytes.fromhex("deadbeef" * 8)
now = 100_000
ticket_id = server.issue_ticket(resumption_psk, now=now, lifetime=3600)
print("ticket issued:", ticket_id.hex())
# -- legitimate client sends 0-RTT early data (e.g. "PUT /cart/checkout") --
session_nonce = bytes.fromhex("a1a2a3a4a5a6a7a8") # pinned, synthetic
transcript_prefix, binder = client_hello(ticket_id, resumption_psk, session_nonce)
early_data = b'{"op":"checkout","cart":"c_501"}'
r1 = server.handle_client_hello(ticket_id, binder, transcript_prefix, early_data, now=now + 1)
print("live 0-RTT attempt: ", r1)
# -- network attacker captures and replays the exact same ClientHello+early data --
r2 = server.handle_client_hello(ticket_id, binder, transcript_prefix, early_data, now=now + 2)
print("replayed 0-RTT attempt: ", r2)
# -- connection can still proceed WITHOUT early data (1-RTT fallback) --
r3 = server.handle_client_hello(ticket_id, binder, transcript_prefix, early_data=None, now=now + 3)
print("1-RTT fallback (no early data claimed):", r3)
# -- attacker tries to splice the captured ticket_id+binder onto a DIFFERENT
# ClientHello transcript (different session_nonce) -> binder fails to verify --
forged_prefix = b"ClientHello||" + ticket_id + b"||" + bytes.fromhex("b1b2b3b4b5b6b7b8") # pinned, different nonce
r4 = server.handle_client_hello(ticket_id, binder, forged_prefix, early_data, now=now + 4)
print("binder spliced onto a different ClientHello:", r4)
Output:
ticket issued: 560b7ff61ec849cfa8cd145a46e66520
live 0-RTT attempt: {'psk_accepted': True, 'early_data_accepted': True, 'reason': None}
replayed 0-RTT attempt: {'psk_accepted': True, 'early_data_accepted': False, 'reason': 'early data rejected: ticket already redeemed for 0-RTT (falling back to 1-RTT)'}
1-RTT fallback (no early data claimed): {'psk_accepted': True, 'early_data_accepted': False, 'reason': None}
binder spliced onto a different ClientHello: {'psk_accepted': False, 'early_data_accepted': False, 'reason': 'binder mismatch'}
The live 0-RTT attempt is accepted. The identical replayed ClientHello is rejected for early data specifically but the PSK itself still validates, so a later attempt with no early-data claim still succeeds as a normal 1-RTT-equivalent connection. A binder computed for one ClientHello transcript, spliced onto a different one, fails immediately, independent of the anti-replay cache.
Trade-offs and pitfalls
- The binder and the single-use cache defend against different attacks and are not substitutes for each other: the binder stops transcript-splicing, the cache stops verbatim replay of an otherwise-identical message; a design with only one of the two is still exploitable by the attack the other one covers.
- Sharding the redemption cache across a load-balanced fleet (the same operational concern as a high-throughput mesh) trades a slightly weaker replay guarantee (a ticket might briefly be usable on two different shards before state converges) for avoiding a single shared-cache bottleneck; this is a deliberate, stated trade, not an oversight, as long as the window of inconsistency is bounded and short.
- It is tempting to reject the whole connection on a detected 0-RTT replay; doing so turns an attacker's captured, replayed ClientHello into a way to deny service to the legitimate client's own retries, which is why the correct response is to drop only the early data and continue the handshake normally.
Unlock Full Question Bank
Get access to all Cryptographic Protocol Design and Analysis interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.