Security Resources

⌘K
  1. Home
  2. Security Resources
  3. Vulnerability Explain
  4. Cross-Site Request Forgery (CSRF)

Cross-Site Request Forgery (CSRF)

Welcome to another Vulnerability Explain breakdown. Today we explore Cross-Site Request Forgery (CSRF), a web vulnerability where an attacker tricks a victim's authenticated browser into submitting unauthorized, state-changing HTTP requests to a vulnerable application. Even in the era of modern SameSite cookie defaults, CSRF remains prevalent through method tampering, CORS preflight misconfigurations, and incomplete anti-CSRF token validation. Let's break down how CSRF works, how to test for it, and how to defend against it.

What is CSRF?

Cross-Site Request Forgery exploits the web browser's ambient authority model. When a user logs into a website, the browser stores authentication cookies. By default, whenever the browser issues an HTTP request to that website, it automatically includes those session cookies, regardless of whether the request originated from the target site or an external page.

If the application relies solely on ambient cookies to authorize state-changing operations (such as changing an email address, resetting a password, updating API keys, or transferring funds), an attacker hosting an external website can forge a request on behalf of the victim. When the victim visits the malicious page while logged in, the forged request executes with the victim's full permissions.

How does CSRF work?

CSRF attacks follow a predictable sequence from session establishment to unauthorized execution:

  • Active Victim Session
    • The victim logs into the target application (e.g., target.com) and receives an authenticated session cookie.
  • Attacker Crafting Exploit Page
    • The attacker creates a malicious webpage hosting an auto-submitting HTML form or a JavaScript script targeted at target.com/api/user/email.
  • Luring the Victim
    • The attacker lures the authenticated victim to visit the malicious website via phishing, forum links, or social engineering.
  • Browser Sends Credentials
    • The victim's browser processes the exploit and dispatches the HTTP request to target.com. The browser automatically attaches the victim's session cookies.
  • Server Executes State Change
    • The target server verifies the valid session cookie. Because the server lacks anti-CSRF validation, it processes the state-changing request as legitimate.

In short, CSRF weaponizes the browser's automatic credential handling. The server cannot distinguish between an intentional user submission and an externally forged request unless an explicit, unpredictable anti-CSRF token or strict origin check is enforced.

Tools and Techniques for CSRF Testing

Testing for CSRF involves inspecting request methods, cookie attributes, and token validation logic.

Manual Testing Methodologies

  • Inspect Cookie SameSite Attributes - Check whether session cookies specify SameSite=Strict, SameSite=Lax, or omit the attribute entirely (defaulting to browser-dependent Lax).
  • Generate CSRF Proof of Concept - Use Burp Suite's 'Generate CSRF PoC' or write a standalone HTML auto-submitting form targeting sensitive endpoints.
  • Method Tampering (POST to GET) - Change the HTTP method from POST to GET to verify if backend handlers permit state changes via URL query parameters.
  • Remove Anti-CSRF Tokens - Submit requests with the anti-CSRF token parameter omitted, blanked, or replaced with arbitrary values to test server enforcement.
  • Token Fixation and Cross-User Swapping - Test whether an anti-CSRF token issued to User A is accepted when submitted along with User B's session cookies.

Automated Scanning Tools

  • Burp Suite Professional - Automated scanner identifies forms and API endpoints lacking anti-CSRF protections.
  • OWASP ZAP - Scans for missing anti-CSRF tokens and weak cookie flags.
  • Nuclei - Community templates detect missing CSRF protections and dangerous GET-based state changes.
  • CSRF-Craft - Generates customized multi-format CSRF PoC exploits.

CSRF Protection Mechanisms

Best Practices for Secure Coding

  • Synchronizer Token Pattern
    • Description: Issue a unique, cryptographically random, unpredictable token per user session or form.
    • Benefits: Third-party sites cannot read or guess the token due to the Same-Origin Policy.
    • Implementation Tip: Store the token server-side in the user session and validate it on every POST, PUT, DELETE, and PATCH request.
  • SameSite Cookie Attribute Enforcement
    • Description: Configure all session and sensitive cookies with SameSite=Lax or SameSite=Strict.
    • Benefits: Prevents browsers from transmitting cookies on cross-origin requests.
    • Implementation Tip: Use SameSite=Strict for critical administrative sessions and Lax for standard portals.
  • Custom Request Headers for APIs
    • Description: Require custom headers such as X-CSRF-Token or X-Requested-With on API endpoints.
    • Benefits: Standard HTML forms cannot set custom headers, forcing cross-origin requests to trigger CORS preflights.
    • Implementation Tip: Reject API requests that omit the required header or supply invalid values.

Best Practices for Organizations

  • Framework-Level CSRF Protection
    • Enable built-in CSRF middleware provided by frameworks (Django CSRF, Spring Security, Rails protect_from_forgery, Express csurf/csrf-csrf).
    • Disallow developers from disabling CSRF protection globally or on sensitive routes.
  • Re-Authentication for Critical Actions
    • Require users to re-enter their current password or provide MFA verification before changing passwords, updating emails, or modifying payment methods.
    • Ensure password change workflows invalidate all existing sessions.
  • Continuous DAST and Code Audits
    • Audit all API endpoints accepting application/x-www-form-urlencoded or multipart/form-data for token validation.
    • Ensure internal admin panels enforce strict origin checks.

Top CSRF payloads used by Security Researchers

As a security researcher, knowing the most common payloads helps you detect and prevent these attacks. Use this knowledge ethically and only on systems you are authorized to test. Some sample payloads are shown below.

<!-- Standard Auto-Submitting Form POST CSRF PoC -->
<html>
  <body onload="document.forms[0].submit()">
    <form action="https://target.com/api/user/email/change" method="POST">
      <input type="hidden" name="email" value="attacker@evil.com" />
    </form>
  </body>
</html>
<!-- Fetch API JSON CSRF with Credentials (When CORS Misconfigured) -->
<script>
  fetch('https://target.com/api/user/password/reset', {
    method: 'POST',
    credentials: 'include',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ new_password: 'Password123!' })
  });
</script>
<!-- Image GET-Based CSRF Trigger -->
<img src="https://target.com/account/delete?confirm=true" width="0" height="0" />

Real-World Example: Account Takeover via Profile Email CSRF

During a web application penetration test on a SaaS customer support portal, the tester noticed that the endpoint responsible for updating user profile information (/settings/profile/update) accepted POST requests containing name and email parameters.

The application used cookie-based session management, but failed to validate any anti-CSRF token. Furthermore, the session cookie had no SameSite attribute specified. The tester crafted a simple HTML exploit page containing an auto-submitting form that updated the email address to an attacker-controlled inbox.

When an authenticated administrator was tricked into viewing the exploit page, the administrator's email address was silently updated. The tester then initiated a standard password reset, receiving the recovery token at their own address and achieving complete administrative account takeover.

Vulnerable and secure code of CSRF

The following example shows the contrast between vulnerable and secure code for CSRF. It helps you see how the flaw creeps into real code and the changes that shut it down.

🥺 Vulnerable Code:

# Vulnerable: Accepts state-changing POST requests without CSRF verification
from flask import Flask, request, session, jsonify

app = Flask(__name__)
app.secret_key = "insecure_dev_key"

@app.route("/api/user/email", methods=["POST"])
def update_email():
    # Only checks if the user session exists
    if "user_id" not in session:
        return jsonify({"error": "Unauthorized"}), 401
    
    # State change executes directly without CSRF token validation
    new_email = request.form.get("email")
    user_db.update_email(session["user_id"], new_email)
    return jsonify({"status": "success", "email": new_email})
  • The endpoint checks session authentication but never verifies an anti-CSRF token.
  • Any external website can submit a form to this route using the victim's ambient browser cookies.
  • State-changing actions executed without token validation result in silent account takeover.

😎 Secure Code:

# Secure: Enforces CSRF token validation on state-changing requests
from flask import Flask, request, session, jsonify, abort
from flask_wtf.csrf import CSRFProtect, generate_csrf
import secrets

app = Flask(__name__)
app.secret_key = secrets.token_hex(32)
csrf = CSRFProtect(app)

# Configure secure SameSite cookie attributes
app.config.update(
    SESSION_COOKIE_HTTPONLY=True,
    SESSION_COOKIE_SECURE=True,
    SESSION_COOKIE_SAMESITE="Lax"
)

@app.route("/api/user/email", methods=["POST"])
def update_email():
    # Flask-WTF CSRFProtect automatically validates the X-CSRFToken header or csrf_token form field
    if "user_id" not in session:
        return jsonify({"error": "Unauthorized"}), 401
    
    new_email = request.form.get("email")
    user_db.update_email(session["user_id"], new_email)
    return jsonify({"status": "success", "email": new_email})
  • CSRFProtect intercepts and validates an unpredictable anti-CSRF token on every POST request.
  • Session cookies are hardened with HttpOnly, Secure, and SameSite=Lax flags.
  • Requests lacking a valid token are rejected with HTTP 400 Bad Request before database updates occur.

Conclusion

Cross-Site Request Forgery highlights the danger of relying purely on ambient credentials for state-changing web operations. Modern defense requires defense-in-depth: strict SameSite cookie settings, cryptographically random synchronizer tokens or custom header checks, and explicit re-authentication on critical actions. When tokens are validated on every state change, CSRF is eliminated.