00:00

#0605

Signed Cookie Tamper

Medium+100 XPA02:2021 Cryptographic FailuresCWE-347
Cookie TamperingSignatureHMAC

Scenario

Your application encodes session data as a base64 JSON payload and appends a signature — forming a cookie like `PAYLOAD_B64.SIGNATURE`.

The buggy implementation decodes and returns the payload without ever checking the signature, so an attacker can craft a cookie with an arbitrary payload (e.g., elevating their role to `admin`) and the server accepts it as authentic.

The fix must compute HMAC-SHA256 of the base64 payload with a secret key and reject any cookie whose signature does not match.

Skipping signature verification on session cookies has caused critical authentication bypasses in real-world applications. Without HMAC, any user can forge any session payload and impersonate any account, including administrators.

Your Tasks

  1. Split `cookieStr` on the first `.`; if no `.` is present, throw `Error('Invalid cookie format')`.
  2. Compute the expected HMAC-SHA256 of the base64 payload using `secret`, then compare it to the provided signature.
  3. If the signatures do not match (or the signature is missing/empty), throw `Error('Invalid signature')`.
  4. On success, base64-decode the payload, parse it as JSON, and return the resulting object.

Examples

Example 1Exploit — forged admin cookie accepted by buggy code

verifyCookie('supersecret', 'eyJ1c2VySWQiOiJhbGljZSIsInJvbGUiOiJhZG1pbiJ9.FAKE_SIG')
// BUG returns: {userId:'alice', role:'admin'} — privilege escalation!
// FIX throws: Error('Invalid signature')

Example 2Safe — malformed cookie (no dot separator)

verifyCookie('supersecret', 'invaliddatanocookie')
// throws: Error('Invalid cookie format')

Constraints

  • Throw exactly `'Invalid cookie format'` when there is no `.` separator.
  • Throw exactly `'Invalid signature'` for any HMAC mismatch, including an empty signature.
  • Use HMAC-SHA256 — not a plain SHA256 hash — so the signature is unforgeable without the secret.
  • The comparison must be constant-time (or use the language's built-in secure-compare) to prevent timing attacks.

Hint

References

solution.js
Ln 1, Col 1UTF-8JavaScript
Sandbox ready
0/0/0not run