Ephemeral Tokens & Replay Attack Defense
Signing a token prevents tampering, but an eavesdropper can replay the exact same signed packet 1,000 times to drain a wallet. Binding a timestamp TTL and a single-use random Nonce inside the signed payload guarantees one-time, time-bounded execution ⏳🛑.
import time
import hmac
import hashlib
import secrets
SECRET = b"cluster_auth_secret_v1"
seen_nonces = set()
def make_token(user_id):
nonce = secrets.token_hex(8)
ts = int(time.time())
body = f"{user_id}:{ts}:{nonce}".encode()
sig = hmac.new(SECRET, body, hashlib.sha256).hexdigest()
return f"{user_id}:{ts}:{nonce}:{sig}"
def consume_token(token_str, max_age=5):
uid, ts_str, nonce, sig = token_str.split(":")
body = f"{uid}:{ts_str}:{nonce}".encode()
# 1. Signature validity (constant-time)
if not hmac.compare_digest(sig, hmac.new(SECRET, body, hashlib.sha256).hexdigest()):
return False, "FORGED"
# 2. Expiration check
if int(time.time()) - int(ts_str) > max_age:
return False, "EXPIRED"
# 3. Nonce uniqueness (anti-replay)
if nonce in seen_nonces:
return False, "REPLAY"
seen_nonces.add(nonce)
return True, "ACCEPTED"
tok = make_token("alice")
print(f"First attempt: {consume_token(tok)[1]} 🚀")
print(f"Replay attempt: {consume_token(tok)[1]} 🛑")
# 69. Ephemeral Tokens & Replay Attack Defense A classic vulnerability in payment APIs is the "replay attack". If an attacker intercepts your HTTP request `POST /transfer?to=bob&amount=100&sig=abcdef`, they don't need to forge a new signature. They can script a curl loop sending that exact same valid request 5,000 times, emptying the victim's account 🛑. ```python # The Anatomy of a Replay Defense: # Token = { UserID } + { Timestamp } + { Unique Nonce } + { Signature } # 1. Verify HMAC(Secret, UserID + Timestamp + Nonce) # 2. Assert: current_time - Timestamp <= TTL (e.g. 30 seconds) # 3. Assert: Nonce NOT in Redis cache (SET key EX 30 NX) ``` ### The Three-Layer Guard 1. **Timestamp TTL Window**: Limits the lifespan of the token. If an attacker captures it, it is only usable within a tiny time window (e.g. 5–30 seconds), preventing delayed attacks. 2. **Cryptographic Nonce ("Number used ONCE")**: A random unique token. The server records seen nonces in an in-memory set or Redis cache with a TTL equal to the window size. 3. **Automatic Cache Expiry**: Because tokens older than the TTL are rejected by rule 1, the server only needs to retain nonces in memory for the duration of the TTL window, preventing unbounded RAM consumption ⏳🛑. --- ### Interactive Pop-Quiz 🧠 #### Why is a cryptographic signature alone insufficient to prevent a replay attack? - [ ] Because an attacker does not need to modify the signed message; they simply retransmit the verbatim valid packet ⏳ - [ ] Because signatures expire after 100 milliseconds in Linux TCP stacks - [ ] Because digital signatures are vulnerable to DNS spoofing - [ ] Because HMAC hashes decrypt to plain text on proxy routers --- ### Practical Challenge 🎯 Implement `create_ephemeral_token(secret, uid, nonce, ts)` and `verify_ephemeral_token(secret, token, seen_nonces, max_age, current_ts)`. Token format: `f'{uid}:{ts}:{nonce}:{sig}'`. Test a valid token (passes, adds nonce to `seen_nonces`), test replaying the same token (returns `(False, 'REPLAY')`), and test an expired token with `ts = current_ts - 100` (returns `(False, 'EXPIRED')`). Print `'ANTI_REPLAY_OK'`. <details> <summary>Solution</summary> ```python import hmac import hashlib def create_ephemeral_token(secret, uid, nonce, ts): body = f"{uid}:{ts}:{nonce}".encode() sig = hmac.new(secret, body, hashlib.sha256).hexdigest() return f"{uid}:{ts}:{nonce}:{sig}" def verify_ephemeral_token(secret, token, seen_nonces, max_age, now): uid, ts_str, nonce, sig = token.split(":") ts = int(ts_str) body = f"{uid}:{ts_str}:{nonce}".encode() if not hmac.compare_digest(sig, hmac.new(secret, body, hashlib.sha256).hexdigest()): return False, "INVALID" if now - ts > max_age: return False, "EXPIRED" if nonce in seen_nonces: return False, "REPLAY" seen_nonces.add(nonce) return True, "OK" secret = b"KEY123" nonces = set() now = 1000 t1 = create_ephemeral_token(secret, "u1", "n1", now) assert verify_ephemeral_token(secret, t1, nonces, 10, now) == (True, "OK") assert verify_ephemeral_token(secret, t1, nonces, 10, now) == (False, "REPLAY") t_old = create_ephemeral_token(secret, "u2", "n2", now - 50) assert verify_ephemeral_token(secret, t_old, nonces, 10, now) == (False, "EXPIRED") print("ANTI_REPLAY_OK") ``` </details>