Back
+30 XP
Concept

Cross-Site Request Forgery (CSRF) Token Generator

Cross-Site Request Forgery (CSRF) tricks authenticated users into submitting unwanted commands via third-party websites. An HMAC-signed CSRF token binds the user's active session ID to an expiration timestamp, cryptographically ensuring state-changing requests originate from legitimate application forms.

python
import hmac, hashlib

# Stateless signed CSRF token:
sig = hmac.new(secret, f"{session_id}:{expires_at}".encode(), hashlib.sha256).hexdigest()
token = f"{session_id}:{expires_at}:{sig}"

# Cross-Site Request Forgery (CSRF) Token Generator If Alice logs into `bank.com`, the browser stores her session cookie. If Alice visits `evil.com`, an invisible form on `evil.com` can auto-submit: ```html <form action="https://bank.com/api/transfer" method="POST"> <input name="to" value="attacker" /> <input name="amount" value="1000" /> </form> ``` Alice's browser automatically attaches her `bank.com` session cookies, and the transfer succeeds! This is **Cross-Site Request Forgery (CSRF)**. 🛑🎭 A **Synchronizer Token / Signed CSRF Token** defends against this: - Every rendered HTML form embeds a hidden CSRF token signed with the server's secret: $$\text{Token} = \text{base64url}(\text{session\_id} \parallel \text{":"} \parallel \text{expires\_at} \parallel \text{":"} \parallel \text{HMAC})$$ - Because `evil.com` cannot read Alice’s cookies or HTML pages due to the **Same-Origin Policy**, it cannot include the valid signed token. Requests missing or presenting mismatched CSRF tokens are rejected. ```python import hmac import hashlib import time def sign_csrf(session_id: str, secret: bytes) -> str: exp = int(time.time() + 3600) data = f"{session_id}:{exp}".encode() sig = hmac.new(secret, data, hashlib.sha256).hexdigest() return f"{session_id}:{exp}:{sig}" ``` ## Pop Quiz Why does attaching a cryptographically signed CSRF token to forms protect against cross-origin forgery attacks? - [ ] Browser same-origin policy prevents malicious third-party sites from reading or forging the user's secret CSRF token. - [ ] The CSRF token automatically clears the user's local browser storage upon submission. - [ ] CSRF tokens convert HTML POST requests into idempotent HTTP GET queries. - [ ] Because web servers reject form submissions that do not contain base64-encoded CSS files. ## Real-World Challenge Implement `CSRFTokenManager(secret: bytes, lifetime_sec: float = 3600.0)`: - `generate_token(session_id: str) -> str`: Produces a base64url-encoded string binding `session_id`, `expires_at`, and HMAC-SHA256 signature. - `validate_token(token_str: str, session_id: str) -> bool`: Decodes token, asserts matching session ID, verifies expiration, and compares HMAC signatures using `hmac.compare_digest`. <details> <summary>Solution</summary> ```python import hmac import hashlib import time import base64 class CSRFTokenManager: def __init__(self, secret: bytes, lifetime_sec: float = 3600.0): self.secret = secret self.lifetime_sec = lifetime_sec def generate_token(self, session_id: str) -> str: expires_at = int(time.time() + self.lifetime_sec) payload = f"{session_id}:{expires_at}".encode("utf-8") sig = hmac.new(self.secret, payload, hashlib.sha256).hexdigest() token_raw = f"{session_id}:{expires_at}:{sig}" return base64.urlsafe_b64encode(token_raw.encode("utf-8")).decode("ascii") def validate_token(self, token_b64: str, session_id: str) -> bool: try: raw_bytes = base64.urlsafe_b64decode(token_b64.encode("ascii")) token_str = raw_bytes.decode("utf-8") tok_session, exp_str, provided_sig = token_str.split(":") expires_at = int(exp_str) except Exception: return False # Session must match and token must not be expired if tok_session != session_id or time.time() > expires_at: return False # Verify cryptographic HMAC signature in constant time payload = f"{tok_session}:{expires_at}".encode("utf-8") expected_sig = hmac.new(self.secret, payload, hashlib.sha256).hexdigest() return hmac.compare_digest(provided_sig, expected_sig) # Verification key = b"csrf_secret_signing_seed_909" csrf = CSRFTokenManager(key, lifetime_sec=10.0) # 1. Valid token for user session token = csrf.generate_token("session_alice_99") assert csrf.validate_token(token, "session_alice_99") is True # 2. Rejection on forged session assert csrf.validate_token(token, "session_bob_attacker") is False # 3. Rejection on corrupted signature tampered = token[:-4] + "AAAA" assert csrf.validate_token(tampered, "session_alice_99") is False ``` </details>