Cookie Tampering and Integrity
What you'll learn: How to detect and prevent malicious modification of cookie values using cryptographic techniques.
Cookies travel back and forth between the browser and server with every request. Because users have full control over their browser environment, they can modify cookie values before sending them back—changing session IDs, privilege levels, prices in shopping carts, or any other data stored in cookies.
This is called cookie tampering, and it's a serious threat if your application trusts cookie data blindly.
Why Cookie Tampering Matters
Imagine storing role=user in a cookie. An attacker could simply change it to role=admin using browser developer tools. Without integrity checks, your server would accept the tampered value and grant admin privileges.
Detecting Tampering with HMAC Signatures
The most common defense is attaching a cryptographic signature (HMAC) to cookie values. The server creates a hash of the cookie's content using a secret key only it knows:
cookie_value = "userId=123"
signature = HMAC(secret_key, cookie_value)
actual_cookie = cookie_value + "|" + signature
When the cookie returns, the server recalculates the HMAC and compares it. If the user changed even one character, the signatures won't match—tampering detected.
Encryption for Confidentiality + Integrity
For sensitive data, encrypt the entire cookie using authenticated encryption (like AES-GCM). This provides both confidentiality (attackers can't read the data) and integrity (they can't modify it without detection).
Preventing Session Fixation via Cookies
Session fixation occurs when an attacker forces a known session ID onto a victim's browser. Defense: regenerate the session ID after login and use the __Host- prefix (covered in lesson 726) to ensure cookies are bound to the exact domain and sent only over HTTPS.
Key Takeaway: Never trust cookie data without verification—use HMAC signatures or encryption to detect tampering, and regenerate session IDs after authentication to prevent fixation attacks.