TExcelTAD
Home › Security Foundations: Concepts, Law, Ethics & Your Lab › Man-in-the-Middle and Replay Attacks

Man-in-the-Middle and Replay Attacks

When you send a message across a network, you trust every device between you and the other end not to read it, change it or send it again. A man-in-the-middle (MITM) attacker is someone sitting at one of those devices, or who has tricked the network into routing traffic through them. A replay attacker needs even less: a copy of one valid message, sent again later. Both are defeated by the same two ideas, applied carefully: authenticate the other end and authenticate every message, including when it was sent. The on-ramp lessons on TLS and HMAC introduce the tools; this lesson shows where they stop these attacks and where they do not.

Mechanism: getting into the path

client10.10.0.5 attacker10.10.0.66 server10.10.0.10 connection 1connection 2 what the client believes: one connection to the server

A MITM gets into the path in one of a few ways:

  • On the local network, by poisoning ARP so the victim sends its frames to the attacker's MAC address, or by running a rogue Wi-Fi access point with a familiar name (DNS and ARP Spoofing).
  • In name resolution, by answering DNS queries with the attacker's address.
  • On a device already in the path: a compromised router, a malicious proxy, a browser extension, or malware on the endpoint itself.
  • At the routing level, by announcing someone else's network prefix (BGP hijacking), which needs control of a network operator and is rare but real.

Once in the path, the attacker can read cleartext traffic (passwords, cookies), modify it (inject a script into a page, change an account number), or downgrade it (strip the redirect from HTTP to HTTPS so the victim never upgrades).

Impact and warning signs. Stolen credentials and sessions, altered transactions, malware served instead of downloads. On the user's side the signs are certificate warnings, a site that suddenly loads over http://, and a login page on an unexpected domain; on the network side, duplicate or changing ARP entries and DNS answers that disagree with the authoritative servers.

What an on-path observer sees

The lab capture http.pcap was recorded on the lab network 10.10.0.0/24. A sensor (or an attacker) on that path reads a login in plain text with one command. Scope: this runs in your sandbox, on a sample file only.

bash · try it yourself
tshark -r $SAMPLES/pcap/http.pcap -Y 'http.request.method == "POST"' -T fields -E header=y \
  -e ip.src -e ip.dst -e http.request.uri -e urlencoded-form.value
ip.src	ip.dst	http.request.uri	urlencoded-form.value
10.10.0.5	10.10.0.10	/login	alice,lab-only-123

This is also the detection view: a security team that finds credentials in cleartext in its own captures has found a service to move to TLS before anyone else finds it.

Defeating MITM: authenticate the other end

Encryption alone does not stop a MITM: the attacker can simply run two encrypted connections, one with each side. What stops it is authentication of the server: TLS checks that the server's certificate chains to a trusted CA, is valid now, and names the host the client asked for. Each check rejects a different trick. The session below verifies four certificates against the lab CA (lab-only keys made from a fixed seed): the real one, the real one for the wrong host name, an expired one, and a certificate an attacker made for lab.test on the spot.

bash · try it yourself
P=$SAMPLES/pki
openssl verify -CAfile $P/ca.crt -verify_hostname lab.test $P/lab.test.crt
openssl verify -CAfile $P/ca.crt -verify_hostname bank.lab.test $P/lab.test.crt 2>&1
openssl verify -CAfile $P/ca.crt $P/expired.lab.test.crt 2>&1
openssl req -x509 -newkey rsa:2048 -nodes -keyout fake.key -out fake.crt -days 30 -subj "/CN=lab.test" 2>/dev/null
openssl verify -CAfile $P/ca.crt fake.crt 2>&1
/opt/sec-samples/pki/lab.test.crt: OK
C = XX, O = ExcelTAD Lab, OU = Web, CN = lab.test
error 62 at 0 depth lookup: hostname mismatch
error /opt/sec-samples/pki/lab.test.crt: verification failed
C = XX, O = ExcelTAD Lab, OU = Web, CN = expired.lab.test
error 10 at 0 depth lookup: certificate has expired
error /opt/sec-samples/pki/expired.lab.test.crt: verification failed
CN = lab.test
error 18 at 0 depth lookup: self-signed certificate
error fake.crt: verification failed

The attacker's certificate says CN = lab.test exactly, but nobody the client trusts signed it, so verification fails. A browser shows that failure as a full-page warning, and a user who clicks through it hands the connection to the MITM. Code that disables verification (verify=False, InsecureSkipVerify: true, curl -k) does the same silently.

Further protections close the gaps around TLS:

  • HSTS (Strict-Transport-Security) tells the browser to use HTTPS only for the site, so a stripped http:// link is upgraded before any request leaves; the preload list covers even the very first visit.
  • Certificate Transparency makes every publicly trusted certificate appear in public logs, so a mis-issued certificate for your domain can be spotted.
  • Mutual TLS and pinning (for apps and service-to-service traffic) authenticate the client too, or accept only expected keys.
  • SSH host keys play the same role for SSH: the "host key has changed" warning is a possible MITM and must never be clicked away.

Replay: authenticate when, not only what

A replay attacker resends a captured valid message: an API call that pays someone, a door-unlock radio signal, a login token. A MAC or a signature does not help on its own, because the replayed message is genuine. The message must also carry something that makes it valid once: a nonce (a number used once, remembered by the receiver), a timestamp checked against a window, or a sequence number. All of them must be inside what the MAC covers, or the attacker just changes them.

The program signs a payment request with HMAC-SHA256 over the method, path, body, timestamp and nonce, as many webhook and API signing schemes do, and tries the classic replays. The key, time and nonce are fixed so the output is stable; real code takes them from secrets and the clock.

python · try it yourself
import hmac, hashlib

KEY = b"lab-only-shared-key"        # real systems draw keys from secrets.token_bytes()
WINDOW = 300                        # accept requests at most 5 minutes old
seen_nonces = set()

def sign(method, path, body, ts, nonce):
    msg = f"{method}\n{path}\n{ts}\n{nonce}\n{body}".encode()
    return hmac.new(KEY, msg, hashlib.sha256).hexdigest()

def server_accepts(req, now):
    expected = sign(req["method"], req["path"], req["body"], req["ts"], req["nonce"])
    if not hmac.compare_digest(expected, req["sig"]):
        return "reject: bad signature"
    if abs(now - req["ts"]) > WINDOW:
        return "reject: stale timestamp"
    if req["nonce"] in seen_nonces:
        return "reject: nonce already used (replay)"
    seen_nonces.add(req["nonce"])
    return "accept"

# The client sends one payment instruction (fixed nonce and time for a stable example)
req = {"method": "POST", "path": "/pay", "body": "to=bob&amount=50", "ts": 1_000_000, "nonce": "n-7f3a91"}
req["sig"] = sign(**{k: req[k] for k in ("method", "path", "body", "ts", "nonce")})

tests = [
    ("original request", req, 1_000_002),
    ("same bytes replayed 10 s later", req, 1_000_012),
    ("replayed with a fresh nonce", {**req, "nonce": "n-000001"}, 1_000_020),
    ("amount changed on the path", {**req, "body": "to=bob&amount=5000"}, 1_000_003),
    ("captured, replayed next day", {**req}, 1_086_400),
]
for label, r, now in tests:
    print(f"{label:32} {server_accepts(r, now)}")
original request                 accept
same bytes replayed 10 s later   reject: nonce already used (replay)
replayed with a fresh nonce      reject: bad signature
amount changed on the path       reject: bad signature
captured, replayed next day      reject: stale timestamp

Each line is one defence at work: the nonce store stops the exact copy, the signature stops a copy with a new nonce or a changed amount, and the time window stops old captures and means the server needs to remember nonces for only five minutes. TLS itself does the same inside a connection with sequence numbers, which is why replaying recorded TLS records does nothing; TLS 1.3's optional 0-RTT data is the exception, can be replayed, and should only carry requests that are safe to repeat.

How it is detected

  • ARP and DNS anomalies on the local network (next lessons), new or unknown access points with your network's name.
  • Certificate errors in client logs and monitoring; CT log alerts for certificates you did not request.
  • Replays: duplicate nonces or request IDs, requests with old timestamps, the same signed request from two different sources. Log rejections; a burst of "nonce already used" is an attack or a broken client.

How it is prevented

  1. TLS everywhere, with verification on, HSTS (and preload) for websites, no plaintext fallbacks.
  2. Signed requests that include a timestamp and a nonce, checked in constant time (hmac.compare_digest).
  3. Idempotency keys for payment and order APIs, so a repeated request does not repeat the effect.
  4. Short-lived tokens and one-time codes that expire; challenge-response protocols for logins and physical access.
  5. Network hygiene: WPA2/WPA3-Enterprise instead of shared Wi-Fi passwords, switch protections against ARP spoofing, VPNs on untrusted networks.

Pitfalls

  • "It is encrypted, so it is safe." Encryption to an unauthenticated peer is encryption to the attacker.
  • Turning off certificate checks to make a test work, then shipping it.
  • A nonce or timestamp outside the signature. The attacker edits it freely.
  • Comparing signatures with ==. It can leak timing; use a constant-time comparison.
  • Clock skew. A window that is too tight rejects real clients; one that is too wide lets replays in. Use the window together with nonces.

Practice

1. In the replay program, remove the nonce check. Which test now succeeds that should not?

"same bytes replayed 10 s later" is accepted: its signature is valid and its timestamp is inside the window. Without nonces, any captured request can be replayed for up to five minutes.

2. Why does the attacker's self-made certificate fail although its CN is exactly lab.test?

Verification checks who signed the certificate, not only what it says. fake.crt is self-signed, and its signer is not in the trusted ca.crt, so the chain cannot be built (error 18).

3. A user types lab.test into a browser on a hotel network. Which protection keeps the first request from going out over plain HTTP?

HSTS, if the browser has seen the site before or the domain is on the HSTS preload list. Without it the first request goes to http://lab.test/, which a MITM can answer.

Test yourself

What stops a MITM that runs two separate TLS connections, one with each side?

  1. Stronger encryption
  2. Verifying the server's certificate chain and host name
  3. A longer password
  4. Compressing the traffic

In the replay demo, why is a replay with a fresh nonce rejected?

  1. Nonces must be numbers
  2. The nonce is covered by the HMAC, so changing it breaks the signature
  3. The timestamp is too old
  4. The server rejects all POST requests

Which header makes a browser use HTTPS only for a site, defeating SSL stripping?

  1. Content-Security-Policy
  2. Strict-Transport-Security
  3. X-Frame-Options
  4. Set-Cookie

Why does the server in the demo only need to remember nonces for five minutes?

  1. Nonces expire by themselves
  2. Older requests are rejected by the timestamp window anyway
  3. HMAC keys rotate every five minutes
  4. It does not need to remember them at all