InfoSec Notes
Understanding CSRF attacks, how they exploit authenticated sessions, prevention with tokens and SameSite cookies, and implementing anti-CSRF protection.
What is CSRF?
Cross-Site Request Forgery forces authenticated users to execute unwanted actions on a web application. Since browsers automatically include cookies with requests, an attacker can craft a malicious page that triggers actions on a site where the victim is already authenticated.
CSRF Attack Flow
===================
1. Victim logs into bank.com (session cookie set)
2. Victim visits evil.com (while still logged in to bank.com)
3. evil.com contains: <img src="https://bank.com/transfer?to=attacker&amount=10000">
4. Browser sends request to bank.com WITH victim's session cookie
5. bank.com processes transfer (valid session, valid request format)
6. Attacker receives $10,000
The attack works because
- Browser automatically attaches cookies to requests
- Server can't distinguish legitimate vs forged requests
- No user interaction needed beyond visiting the malicious page
CSRF Attack Examples
Prevention Techniques
1. CSRF Tokens (Synchronizer Token Pattern)
2. SameSite Cookie Attribute
# Set SameSite attribute on session cookies
app.config.update(
SESSION_COOKIE_SAMESITE='Lax', # Default in modern browsers
SESSION_COOKIE_SECURE=True, # HTTPS only
SESSION_COOKIE_HTTPONLY=True, # No JavaScript access
)
# SameSite values:
# Strict: Cookie never sent cross-site (breaks OAuth flows)
# Lax: Sent with top-level navigations (GET only), blocks POST/img/iframe
# None: Always sent (requires Secure flag, used for cross-site APIs)3. Double Submit Cookie
import hashlib
import hmac
def double_submit_csrf():
"""CSRF protection without server-side state."""
# Set CSRF cookie (readable by JavaScript)
csrf_cookie = secrets.token_hex(32)
response.set_cookie('csrf_token', csrf_cookie,
samesite='Lax', secure=True)
# JavaScript reads cookie and sends as header
# fetch('/api/transfer', {
# headers: {'X-CSRF-Token': getCookie('csrf_token')},
# ...
# })
# Server verifies cookie value matches header value
cookie_token = request.cookies.get('csrf_token')
header_token = request.headers.get('X-CSRF-Token')
if not cookie_token or not hmac.compare_digest(cookie_token, header_token):
abort(403)CSRF vs XSS Comparison
| Feature | CSRF | XSS |
|---|---|---|
| Attack target | Server-side actions | Client-side data/DOM |
| Requires authentication | Yes (exploits existing session) | No |
| Attacker can read response | No (blind attack) | Yes (full access) |
| User interaction | Minimal (visit malicious page) | Varies |
| Prevention | Tokens, SameSite cookies | Output encoding, CSP |
| Can bypass CSRF tokens | No (if implemented correctly) | Yes (XSS can read tokens!) |
Important: XSS can defeat CSRF protection because XSS can read the CSRF token from the page. Fix XSS first!
Interview Questions
- Why does CSRF work even when the victim didn't intend to make the request?
- Browsers automatically attach cookies (including session cookies) to any request to the cookie's domain, regardless of which site initiated the request. The server sees a valid session and processes the action as if the user intended it.
- How does the SameSite cookie attribute prevent CSRF?
- SameSite=Lax prevents cookies from being sent with cross-site POST requests (and sub-resource requests like img/iframe). Since CSRF relies on the browser sending the session cookie with the forged request, blocking cross-site cookie attachment defeats the attack.
- Can CSRF attacks steal data from the target site?
- Standard CSRF cannot read responses (Same-Origin Policy prevents it). It can only trigger actions (transfers, password changes, etc.). However, if combined with misconfigured CORS, an attacker might read responses. Login CSRF is an exception where the attacker logs the victim into the attacker's account.
- Why are GET requests less vulnerable to CSRF than POST?
- GET requests should be idempotent (no side effects) per HTTP spec. If a GET request changes state (like
/transfer?to=X), it's vulnerable via img tags and links. POST requests require form submission, which is slightly harder but still exploitable with auto-submitting forms.
- Explain how the Synchronizer Token Pattern prevents CSRF.
- The server generates a unique random token per session/request and embeds it in forms. On submission, the server verifies the token matches. An attacker cannot include the correct token because: (1) they can't read the victim's page (SOP), and (2) the token is unpredictable (cryptographically random).
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Cross-Site Request Forgery (CSRF).
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Information Security topic.
Search Terms
information-security, information security, information, security, web, csrf, attacks, cross-site request forgery (csrf)
Related Information Security Topics