Estimated reading time: 4 minutes
1. What is CSRF?
Cross-Site Request Forgery (CSRF) is a web security vulnerability where an attacker tricks an authenticated user into unknowingly executing unwanted actions on a web application where they are logged in.
2. How CSRF Works
A CSRF attack exploits the trust a web application has in a user’s browser session. If the user is already authenticated, the browser automatically sends session cookies, authentication headers, or JWT tokens along with malicious requests, making them appear legitimate.
Attack Steps:
- Victim logs into a web application (e.g., online banking).
- The session cookie is stored in the browser.
- Victim visits a malicious website controlled by the attacker.
- The malicious site triggers a forged request (e.g., transferring funds).
- Browser automatically includes session credentials.
- The request is processed as a valid action on behalf of the victim.
3. CSRF Attack Example (Bank Transfer)
Assume a banking website allows fund transfers via this legitimate request:
POST /transfer HTTP/1.1
Host: bank.com
Cookie: session=abc123
amount=1000&to=attacker_account
Now, an attacker tricks the victim into executing this request without their knowledge by embedding it in a malicious webpage:
<html>
<body>
<form action="https://bank.com/transfer" method="POST">
<input type="hidden" name="amount" value="1000">
<input type="hidden" name="to" value="attacker_account">
</form>
<script>document.forms[0].submit();</script>
</body>
</html>
What happens?
- If the victim is logged in, their browser automatically sends the session cookie to
bank.com. - The bank’s server sees a valid request from the victim and transfers the money without their knowledge.
4. Types of CSRF Attacks
A. GET-Based CSRF
- If an application performs sensitive actions via GET requests, attackers can exploit it by embedding an image request or iframe:
<img src="https://bank.com/transfer?amount=1000&to=attacker_account">
Mitigation: Always use POST for state-changing actions.
B. POST-Based CSRF
- Uses hidden forms and JavaScript to submit a forged request, as shown in the example above.
C. JSON/XML CSRF (API Exploitation)
- CSRF can target REST APIs that use cookies for authentication.
- Example attack via fetch() in JavaScript:
fetch('https://api.example.com/update-email', {
method: 'POST',
credentials: 'include',
body: JSON.stringify({"email": "attacker@example.com"})
});
Mitigation: Use CSRF tokens and enforce same-origin policy.
5. Why is CSRF Dangerous?
- Potential Worst-Case Scenarios:
- Financial Fraud – Attacker transfers funds from the victim’s account.
- Account Takeover – Changes victim’s email, password, or enables 2FA for the attacker.
- Data Theft – Extracts sensitive user data by modifying profiles.
- Remote Code Execution (Chained Attack) – If an admin account is compromised, an attacker could escalate to full system control.
Real-World Example:
In 2008, Netflix was vulnerable to CSRF, allowing attackers to change account details just by tricking users into visiting a malicious site.
6. CSRF Mitigation Techniques
A. CSRF Tokens (Synchronizer Token Pattern)
- How it works: Every form request must include a random, unique token.
- Server validates token before processing the request.
- Example token:
<input type="hidden" name="csrf_token" value="4d5f6g7h8i">
- Server verifies:
pythonif request.POST['csrf_token'] != session['csrf_token']:
return "CSRF Attack Detected!"
B. SameSite Cookies
SameSite=StrictorSameSite=Laxprevents cookies from being sent with cross-origin requests.
Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Strict
C. Referer/Origin Header Validation
- Server checks the
RefererorOriginheader to verify request origin.
pythonif request.headers['Origin'] != "https://securebank.com":
return "CSRF Attack Detected!"
D. Use X-Requested-With Header (For APIs)
- Enforce
X-Requested-With: XMLHttpRequestin API requests to prevent CSRF:
javascriptfetch('/transfer', {
method: 'POST',
headers: { 'X-Requested-With': 'XMLHttpRequest' }
});
- Server validation:
pythonif request.headers.get('X-Requested-With') != 'XMLHttpRequest':
return "CSRF Blocked!"
E. Disable CORS Credential Sharing
- Prevent cross-origin API requests with authentication.
Access-Control-Allow-Credentials: false
7. CSRF vs. XSS: What’s the Difference?
| Attack Type | CSRF (Cross-Site Request Forgery) | XSS (Cross-Site Scripting) |
|---|---|---|
| What it exploits | Trust between browser & website | Trust between user & website |
| Attacker needs | Victim to visit a malicious site | A vulnerable web page |
| Impact | Forces victim to perform actions | Steals data, executes JS |
| Mitigation | CSRF tokens, SameSite cookies | Input sanitization, CSP |
8. Conclusion
CSRF is a high-impact vulnerability that allows attackers to force users into performing actions they never intended.
Mitigation requires CSRF tokens, SameSite cookies, and proper request validation.