Back
+35 XP
Concept

Module 45 Capstone: Zero-Trust Cryptographic Auth Guard

Zero-trust architectures reject implicit perimeter trust, validating every network transaction independently. A zero-trust auth guard validates clock skew, enforces single-use ephemeral nonces, verifies request payload hashes, and checks HMAC-SHA256 signatures in constant time.

python
# Canonical signing representation:
# METHOD\nPATH\nTIMESTAMP\nNONCE\nPAYLOAD_HASH
canonical = f"{method}\n{path}\n{ts}\n{nonce}\n{payload_sha256}".encode()
sig = hmac.new(secret, canonical, hashlib.sha256).hexdigest()

# Module 45 Capstone: Zero-Trust Cryptographic Auth Guard In legacy networks, companies trusted anything behind the office VPN firewall: *"If the packet came from 10.0.0.4, it must be safe."* Today, a compromised developer laptop or rogue container compromises the entire internal mesh. 🏆🛡️ **Zero-Trust Security (NIST SP 800-207)** assumes the network is hostile at all times: 1. **Clock Skew Window**: Every request must carry a Unix timestamp valid within $\pm 30$ seconds of server time. 2. **Ephemeral Nonce Tracking**: Every request carries a single-use UUID; duplicate nonces within the window are rejected as replay attacks. 3. **Payload Binding**: The request body is hashed with SHA-256 so intermediate proxies cannot tamper with parameters. 4. **Canonical HMAC-SHA256**: The client and server sign a strict canonical string: $$\text{Canonical} = \text{METHOD} \parallel \text{"\n"} \parallel \text{PATH} \parallel \text{"\n"} \parallel \text{TS} \parallel \text{"\n"} \parallel \text{NONCE} \parallel \text{"\n"} \parallel \text{PAYLOAD\_HASH}$$ 5. **Constant-Time Verification**: Signatures are evaluated via `hmac.compare_digest`. ```python import hmac import hashlib canonical = f"{method}\n{path}\n{int(ts)}\n{nonce}\n{p_hash}".encode("utf-8") ``` ## Pop Quiz Why does the canonical signing string incorporate a SHA-256 hash of the request body payload? - [ ] It binds the cryptographic signature directly to body content, ensuring in-transit payload tampering immediately invalidates the signature. - [ ] It compresses binary payloads to fit within standard TCP maximum transmission units (MTU). - [ ] It instructs downstream reverse proxies to bypass TLS decryption. - [ ] Because HMAC algorithms can only process 32-byte hexadecimal strings. ## Real-World Challenge Build a production-grade `ZeroTrustAuthGuard`: - `sign_request(method: str, path: str, timestamp: float, nonce: str, payload: bytes) -> str`: Generates the hexadecimal HMAC-SHA256 signature over the canonical representation. - `authenticate_request(method: str, path: str, timestamp: float, nonce: str, payload: bytes, signature_hex: str) -> bool`: - Enforces clock skew within `max_clock_skew` seconds. - Rejects duplicate nonces using an internal cache. - Verifies signature in constant time. - Raises `PermissionError` with specific reasons on failure. <details> <summary>Solution</summary> ```python import hmac import hashlib import time class ZeroTrustAuthGuard: def __init__(self, secret_key: bytes, max_clock_skew: float = 30.0): self.secret_key = secret_key self.max_clock_skew = max_clock_skew self._nonce_cache = {} # nonce -> expiry_time def _build_canonical_string(self, method: str, path: str, timestamp: float, nonce: str, payload: bytes) -> bytes: payload_hash = hashlib.sha256(payload).hexdigest() raw = f"{method.upper()}\n{path}\n{int(timestamp)}\n{nonce}\n{payload_hash}" return raw.encode("utf-8") def sign_request(self, method: str, path: str, timestamp: float, nonce: str, payload: bytes) -> str: canonical = self._build_canonical_string(method, path, timestamp, nonce, payload) return hmac.new(self.secret_key, canonical, hashlib.sha256).hexdigest() def authenticate_request( self, method: str, path: str, timestamp: float, nonce: str, payload: bytes, signature_hex: str ) -> bool: now = time.time() # 1. Clock skew verification if abs(now - timestamp) > self.max_clock_skew: raise PermissionError("Request rejected: clock skew exceeds tolerance window") # 2. Replay attack verification via ephemeral nonce cache self._purge_expired_nonces(now) if nonce in self._nonce_cache: raise PermissionError("Request rejected: duplicate nonce replay detected") # Register nonce with expiration self._nonce_cache[nonce] = now + self.max_clock_skew # 3. Canonical signature recomputation expected_sig = self.sign_request(method, path, timestamp, nonce, payload) # 4. Constant-time comparison if not hmac.compare_digest(signature_hex, expected_sig): raise PermissionError("Request rejected: cryptographic signature mismatch") return True def _purge_expired_nonces(self, now: float): expired = [n for n, exp in self._nonce_cache.items() if now >= exp] for n in expired: del self._nonce_cache[n] # Verification root_secret = b"zero_trust_mesh_shared_secret_777" guard = ZeroTrustAuthGuard(root_secret, max_clock_skew=10.0) current_ts = time.time() test_nonce = "req_uuid_998877" body = b'{"action": "TRANSFER", "amount": 5000}' # 1. Client signs request sig = guard.sign_request("POST", "/api/v1/ledger", current_ts, test_nonce, body) # 2. Server authenticates successfully assert guard.authenticate_request("POST", "/api/v1/ledger", current_ts, test_nonce, body, sig) is True # 3. Replay attack with same nonce rejected replay_blocked = False try: guard.authenticate_request("POST", "/api/v1/ledger", current_ts, test_nonce, body, sig) except PermissionError: replay_blocked = True assert replay_blocked is True # 4. Tampered payload rejected tamper_blocked = False try: tampered_body = b'{"action": "TRANSFER", "amount": 999999}' guard.authenticate_request("POST", "/api/v1/ledger", current_ts, "fresh_nonce_1", tampered_body, sig) except PermissionError: tamper_blocked = True assert tamper_blocked is True ``` </details>