Ephemeral Nonce Cache with TTL Expiry
Attackers intercepting valid signed API requests can replay them across networks to duplicate financial transactions or unauthorized state changes. An ephemeral nonce cache tracks unique request identifiers (nonces) within a time window, rejecting duplicate replay requests.
# Check and record nonce:
if nonce in cache and now < cache[nonce]:
raise SecurityError("Replay attack detected!")
cache[nonce] = now + ttl_seconds
# Ephemeral Nonce Cache with TTL Expiry Even if an API request is signed with HMAC-SHA256, an attacker sitting on public Wi-Fi can sniff the encrypted HTTPS payload or eavesdrop on internal microservice traffic and replay the identical valid request 100 times: 🛑🔄 ```http POST /api/v1/transfer HTTP/1.1 Authorization: SignedHMAC(...) Content: {"recipient": "attacker", "amount": 500} ``` The recipient will receive $500 one hundred times! A **Nonce (Number Used Once)** pairs every signed request with a unique random UUID and a timestamp: 1. **Timestamp Check**: Reject any request older than 60 seconds. 2. **Nonce Cache**: Maintain a temporary cache of nonces seen in the last 60 seconds. 3. If an incoming request presents a nonce already in the cache, reject it immediately as a **Replay Attack**. 4. After 60 seconds, the nonce can be safely purged from memory because the timestamp check will reject it anyway. ```python import time class NonceCache: def __init__(self, ttl: float = 60.0): self.ttl = ttl self.seen = {} ``` ## Pop Quiz Why is tracking nonces within a sliding TTL window (e.g. 60 seconds) sufficient to prevent infinite replay attacks? - [ ] Requests older than the TTL window are rejected by timestamp validation, so nonces only need to be remembered during the valid window. - [ ] Nonces automatically expire from DNS server caches after 60 seconds. - [ ] The Linux kernel clears network socket buffers every minute. - [ ] Because SHA-256 signatures become invalid after 60 seconds of real-world time. ## Real-World Challenge Implement `EphemeralNonceCache(default_ttl: float = 60.0)`: - `use_nonce(nonce: str, ttl: float = None) -> bool`: - Cleans expired entries. - If `nonce` is already present and unexpired, return `False` (replay detected). - Otherwise, record `nonce` with expiry `now + ttl` and return `True`. <details> <summary>Solution</summary> ```python import time class EphemeralNonceCache: def __init__(self, default_ttl: float = 60.0): self.default_ttl = default_ttl self._cache = {} # nonce -> expires_at def use_nonce(self, nonce: str, ttl: float = None) -> bool: now = time.time() self._cleanup(now) if nonce in self._cache: if now < self._cache[nonce]: return False # Replay attack blocked! lifetime = ttl if ttl is not None else self.default_ttl self._cache[nonce] = now + lifetime return True def _cleanup(self, now: float): expired_keys = [k for k, exp in self._cache.items() if now >= exp] for k in expired_keys: del self._cache[k] # Verification cache = EphemeralNonceCache(default_ttl=0.05) # 1. First presentation is valid assert cache.use_nonce("tx_nonce_901") is True # 2. Immediate replay attempt is blocked assert cache.use_nonce("tx_nonce_901") is False # 3. Different nonce is accepted assert cache.use_nonce("tx_nonce_902") is True # 4. After TTL expiration, cache entries are cleanly reaped time.sleep(0.06) assert cache.use_nonce("tx_nonce_901") is True ``` </details>