Back
+30 XP
Concept

Capstone Security: Ephemeral HMAC Authentication & Replay Guard

Internal cluster network boundaries cannot rely on perimeter firewalls alone. The Capstone security layer signs every RPC packet with HMAC-SHA256, binding an ephemeral nonce and float timestamp into the digest. Storage nodes enforce constant-time verification, rejecting replayed or timed-out requests 🛡️🔑⏱️.

python
import hmac, hashlib, time

def sign_rpc(secret, nonce, ts, payload):
    msg = f"{nonce}:{ts}:{payload}".encode()
    return hmac.new(secret, msg, hashlib.sha256).hexdigest()

key = b"cluster_key_master"
t = time.time()
sig = sign_rpc(key, "n-001", t, "UPDATE_LEADER")
print(f"HMAC Signature: {sig[:16]}... 🚀")

# 114. Capstone Security: Ephemeral HMAC Authentication & Replay Guard Assuming that internal network traffic inside a Kubernetes pod network or VPC is inherently trustworthy is a fatal zero-trust violation. If an attacker compromises a single periphery container, they can sniff unencrypted TCP sockets and forge arbitrary internal replication RPCs 🛑. ```python # The Replay Attack Scenario: # Attacker sniffs legitimate RPC packet: # {"nonce": "n-42", "ts": 1700000000, "action": "TRANSFER_FUNDS", "sig": "a9f8..."} # # Attacker replays exact same packet 5,000 times! # Without Nonce + Freshness Window checks, server repeats the transfer 5,000 times! ``` ### The Nonce + Timestamp Defense 1. **Timestamp Freshness Window**: The receiver verifies that $|t_{\text{current}} - t_{\text{packet}}| \le 2.0\text{ seconds}$. This prevents attackers from replaying packets recorded hours or days earlier. 2. **Ephemeral Nonce Tracking**: Within that 2-second window, the receiver tracks all observed random nonce tokens. If the exact same packet arrives twice, the second is rejected immediately. 3. **Constant-Time Verification**: Use `hmac.compare_digest` to prevent microsecond side-channel timing leaks 🛡️🔑⏱️. --- ### Interactive Pop-Quiz 🧠 #### Why must HMAC verification combine both a strict timestamp freshness window AND a nonce tracking set? - [ ] The timestamp window bounds memory by allowing old nonces to be purged, while the nonce set prevents immediate replays within that active window 🛡️ - [ ] Because timestamps alone protect against power outages - [ ] Because nonces convert hashes into AES symmetric keys - [ ] Because HMAC requires two independent inputs to compile --- ### Practical Challenge 🎯 Implement `ReplayGuard(secret_key: bytes, max_skew_sec: float = 2.0)` with methods `generate_token(nonce, timestamp, payload) -> str` using HMAC-SHA256, and `verify_request(nonce, timestamp, payload, signature) -> bool`. Reject if timestamp skew $> max\_skew\_sec$, if nonce was already seen in an internal set, or if signature fails `hmac.compare_digest`. Verify valid request succeeds, repeated nonce fails, and expired timestamp fails. Print results. <details> <summary>Solution</summary> ```python import hmac, hashlib, time class ReplayGuard: def __init__(self, secret_key: bytes, max_skew_sec: float = 2.0): self.secret_key = secret_key self.max_skew_sec = max_skew_sec self.seen_nonces = set() def generate_token(self, nonce: str, timestamp: float, payload: str) -> str: msg = f"{nonce}:{timestamp}:{payload}".encode() return hmac.new(self.secret_key, msg, hashlib.sha256).hexdigest() def verify_request(self, nonce: str, timestamp: float, payload: str, signature: str) -> bool: now = time.time() if abs(now - timestamp) > self.max_skew_sec: return False if nonce in self.seen_nonces: return False expected = self.generate_token(nonce, timestamp, payload) if not hmac.compare_digest(expected, signature): return False self.seen_nonces.add(nonce) return True guard = ReplayGuard(b"secret_key_474", max_skew_sec=1.0) ts = time.time() n = "nonce-101" body = "LSN:474:COMMIT" sig = guard.generate_token(n, ts, body) assert guard.verify_request(n, ts, body, sig) is True assert guard.verify_request(n, ts, body, sig) is False # Replay blocked! assert guard.verify_request("n-new", ts - 5.0, body, sig) is False # Expired! print(f"ReplayGuard verified: Nonce replay and clock skew attacks neutralized") ``` </details>

Checkpoint

Why must HMAC verification combine both a strict timestamp freshness window AND a nonce tracking set? 🧠

Practice

Implement `ReplayGuard(secret_key: bytes, max_skew_sec: float = 2.0)` with methods `generate_token(nonce, timestamp, payload) -> str` using HMAC-SHA256, and `verify_request(nonce, timestamp, payload, signature) -> bool`. Reject if timestamp skew $> max skew sec$, if nonce was already seen in an internal set, or if signature fails `hmac.compare_digest`. Verify valid request succeeds, repeated nonce fails, and expired timestamp fails. Print results. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks