CSRF Attacks: Understanding Cross-Site Request Forgery and Session Hijacking
Cross-Site Request Forgery (CSRF) is a devastating vulnerability that forces an authenticated user to execute unwanted actions on a web application in which they are currently authenticated. Unlike Cross-Site Scripting (XSS), which exploits the trust a user has for a particular site, CSRF exploits the trust that a site has in a user's browser. In this deep dive by Cayvora Security, we will explore the anatomy of CSRF attacks, real-world HTTP examples, and modern prevention techniques such as SameSite cookies and Anti-CSRF tokens for 2025.
The Anatomy of a CSRF Attack
For a CSRF attack to be viable, three key conditions must be met:
- A Relevant Action: There must be an action within the application that the attacker has a reason to induce. This might be a privileged action (like modifying permissions for an administrator) or an action specific to the user (like changing the password or transferring funds).
- Cookie-Based Session Handling: The application relies entirely on HTTP cookies to identify the user making the requests. Crucially, the browser must automatically append the session cookie without requiring any manual interaction.
- No Unpredictable Request Parameters: The request that performs the action cannot contain any parameters whose values the attacker cannot guess or determine.
Real Exploitation Example: The Fund Transfer
Consider a banking application that allows a user to transfer funds using the following HTTP GET request:
GET /transfer.do?acct=ATTACKER_ACCOUNT&amount=10000 HTTP/1.1
Host: bank.example.com
Cookie: sessionid=abcdef1234567890
If the victim is logged into bank.example.com in their browser, the session cookie is active.
The Exploit:
The attacker creates a malicious webpage http://attacker.com/evil.html containing an invisible image tag that points to the vulnerable endpoint:
<img src="https://bank.example.com/transfer.do?acct=ATTACKER_ACCOUNT&amount=10000" width="0" height="0" border="0" style="display:none;">
When the victim visits attacker.com, their browser automatically attempts to load the image. Because the URL belongs to bank.example.com, the browser automatically attaches the victim's valid sessionid cookie to the request. The bank's server processes the request, assuming it was legitimately initiated by the victim, and transfers the funds.
State-Changing Requests via POST
Modern applications usually use POST requests for state-changing actions, which cannot be triggered via an <img> tag. However, attackers can bypass this by dynamically creating an invisible form and submitting it using JavaScript.
<form action="https://bank.example.com/api/user/email/update" method="POST" id="csrf_form">
<input type="hidden" name="email" value="[email protected]" />
</form>
<script>
document.getElementById('csrf_form').submit();
</script>
When the victim visits the malicious page, the form is immediately submitted. The browser still appends the session cookie, resulting in a successful email update. The attacker can then use the updated email to initiate a password reset.
Advanced CSRF Considerations
Bypassing Referer Validation
Some applications attempt to prevent CSRF by checking the HTTP Referer header to ensure the request originated from a trusted domain. Attackers can bypass this using several techniques:
- Referrer-Policy Spoofing: Instructing the browser not to send the Referer header via
<meta name="referrer" content="no-referrer">. If the server fails open (allows requests with missing Referers), the attack succeeds. - Open Redirects: Leveraging an open redirect on the target domain to launder the Referer.
CSRF vs XSS
CSRF is often combined with XSS. If an application is vulnerable to XSS on the same domain or a subdomain, the attacker can use the XSS payload to extract anti-CSRF tokens and forge requests dynamically. This is why addressing XSS vulnerabilities is critical for overall security posture.
Prevention and Remediation Strategies
Preventing CSRF requires forcing the browser to prove that the request was intentionally initiated by the user on the legitimate application.
1. Anti-CSRF Tokens (Synchronizer Token Pattern)
The most robust defense against CSRF is the inclusion of an unpredictable, user-specific token in every state-changing request.
- The server generates a cryptographically strong random token during the session creation.
- The server embeds this token in HTML forms (typically as a hidden input field) or provides it to client-side frameworks via a meta tag or custom HTTP header.
- Upon receiving a state-changing request, the server compares the submitted token with the token stored in the user's session.
Example implementation in PHP:
// Server-side generation
session_start();
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
// Client-side form inclusion
<form action="/transfer" method="POST">
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
<!-- Other fields -->
</form>
2. SameSite Cookie Attribute
The SameSite attribute instructs the browser whether to send cookies along with cross-site requests. This provides a massive layer of defense against CSRF at the infrastructure level.
SameSite=Strict: The cookie is only sent if the request originates from the same site. This completely neutralizes CSRF but can impact user experience (e.g., following an external link to the site strips the session).SameSite=Lax: The cookie is sent on cross-site sub-requests (like images) but is sent when navigating to the origin site (e.g., following a link). This is the default in modern browsers and prevents POST-based CSRF.
Secure Cookie Configuration:
Set-Cookie: JSESSIONID=xyz123; Secure; HttpOnly; SameSite=Lax
3. Check Origin and Referer Headers
While not a complete solution, validating the Origin and Referer headers provides defense-in-depth. Reject requests where these headers are present but do not match the expected origin.
4. Require Re-authentication
For highly sensitive actions (password change, wire transfer, changing 2FA settings), require the user to re-authenticate or provide a one-time password (OTP).
Conclusion
CSRF attacks exploit the very mechanism that makes the modern web seamless: automatic credential inclusion. By understanding how attackers forge requests and implementing a combination of Anti-CSRF tokens and proper SameSite cookie attributes, developers can build resilient applications that definitively protect user sessions.
Is your session management secure?
Ensure your authentication flows are immune to CSRF and session hijacking. Contact Cayvora Security for an architecture review.
📱 Chat with us on WhatsApp