Lesson 5.5: Cross-site request forgery (CSRF)
The same-origin policy stops other sites from reading your answers, but not from sending requests in your name: the browser adds your cookies to a form another site submits. That's cross-site request forgery. How an attacker changes a victim's e-mail address and then takes over the account through 'forgot password', and the defences: secret per-session tokens checked with hash_equals, SameSite cookies, Origin checks and asking for the password again on sensitive changes. In the lab the shop's e-mail change form already contains a token that nobody checks. You forge the request, add the check, and prove that the forged request fails and the real form still works.
18 min
You will learn to
- Explain CSRF and why the same-origin policy doesn't stop it
- Explain how a CSRF token works
- Check a token safely with hash_equals
- Explain the role of SameSite and Origin checks
- Prove a CSRF fix in both directions
Key terms
- Cross-site request forgery (CSRF)
- Making a logged-in user's browser send a request that changes something on another site, without the user meaning to.
- CSRF token
- A secret random value tied to the session and included in every legitimate form; the server rejects state-changing requests without it.
- hash_equals
- PHP function that compares two strings in constant time.
- State-changing request
- A request that changes data: buying, deleting, changing settings. It should never be a GET.
- Re-authentication
- Asking for the password (or MFA) again before sensitive changes such as e-mail, password or payout details.
← Kernel and AppArmor hardening · All lessons · TLS in practice →