CSRF (Cross-Site Request Forgery)

What is CSRF?

Cross-Site Request Forgery (CSRF) is an attack that tricks authenticated users into submitting unwanted requests to a web application where they are currently logged in.

CSRF Impact Severity:

  • Unauthorized account changes
  • Financial transactions (transfers, purchases)
  • Data modification or deletion
  • Account takeover
  • Privilege escalation

Red Team Techniques (Offensive)

1. Basic CSRF

Basic Cross-Site Request Forgery (CSRF) occurs when an attacker tricks a logged-in user into submitting a forged request to a web application. Since the browser includes credentials (like cookies) automatically, the action is performed without the user’s consent—often via hidden forms or auto-loaded resources.

Simple Auto-Submitting Form:

<form action="https://bank.com/transfer" method="POST">
  <input type="hidden" name="amount" value="1000">
  <input type="hidden" name="to" value="attacker">
</form>
<script>document.forms[0].submit()</script>

This auto-submits a POST request to transfer funds when the victim visits the malicious page

Image Tag GET Exploit:

<img src="https://example.com/delete?id=123" />

A simple GET request sent via image loading can trigger unintended state changes

Common Exploitation Vectors:

  • Hidden forms: Auto-submitted with JavaScript or meta refresh
  • GET requests: Using image, iframe, or script tags
  • Misconfigured CORS: Allows JavaScript-based CSRF with credentials
  • Third-party embedding: Abuse of unsecured endpoints in embedded content

Delivery Methods:

  • Malicious email or blog post containing the auto-submitting form
  • Injected ads or scripts on compromised websites
  • Clickjacking combined with invisible CSRF triggers

2. GET-based CSRF

GET-based CSRF exploits web applications that perform sensitive state-changing actions using HTTP GET requests. Since browsers automatically include cookies with all requests, even a simple link or image load can trigger dangerous actions without user consent.

Classic Exploit Example:

<img src="https://vulnerable-site.com/deleteAccount?user=123" />

Automatically fires a GET request to a destructive endpoint when the image is loaded

Malicious Link Example:

<a href="https://vulnerable-site.com/upgradeRole?user=attacker&role=admin">
  Click here for a free gift!
</a>

Social engineering trick to entice the victim into clicking a URL that elevates attacker’s privileges

Exploitation Techniques:

  • Auto-loaded images: Simple, stealthy delivery via <img> tags
  • Invisible iframes: Triggers GET requests without user visibility
  • Clickable bait: Disguised malicious links or buttons
  • Injected HTML: In forums, comments, or ad platforms

Delivery Methods:

  • Phishing emails containing malicious images or links
  • Cross-posted content on social media
  • Compromised websites injecting hostile content
  • Browser redirects or meta-refresh tags

3. JSON-based CSRF

JSON-based CSRF targets APIs that accept JSON payloads via authenticated sessions, often over POST, PUT, or DELETE requests. Unlike basic CSRF, this attack typically requires bypassing protections like `Content-Type` validation, `CORS` policies, or CSRF tokens.

Exploit Attempt via JavaScript:

<script>
fetch("https://api.victim.com/change-email", {
  method: "POST",
  credentials: "include",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    email: "attacker@example.com"
  })
});
</script>

Sends an authenticated JSON request using cookies from the victim’s browser

Common Bypass Vectors:

  • Open CORS policies: Misconfigured Access-Control-Allow-Origin headers
  • Lack of CSRF tokens: APIs without token-based verification
  • Missing SameSite flags: Allows cookie leakage with cross-site requests
  • Content-Type misconfigurations: Accepts `application/json` from third-party origins

Delivery Methods:

  • Compromised scripts injecting fetch() calls
  • Malicious browser extensions or bookmarklets
  • Social engineering targeting developers/admins
  • Cross-site widget or iframe injection in trusted apps

4. Login CSRF

Login CSRF (Cross-Site Request Forgery during authentication) forces a user to log in as another account controlled by the attacker. This can lead to privilege confusion, data exfiltration, or unauthorized access, especially if the app uses session-based authentication without strong CSRF protections.

Exploit Example:

<form action="https://target.com/login" method="POST">
  <input type="hidden" name="username" value="attacker@example.com">
  <input type="hidden" name="password" value="attackerPassword123">
</form>
<script>document.forms[0].submit()</script>

Forces the victim to log in as the attacker's account, overwriting their own session

Impact Scenarios:

  • Session fixation: Victim is logged in under attacker’s account and data
  • Silent surveillance: Attacker monitors activity or harvests sensitive data
  • Misleading audit trails: Logs show attacker’s identity for victim's actions

Delivery Methods:

  • Malicious blog posts or comments with hidden login forms
  • Ad networks injecting silent auto-login scripts
  • Browser-based social engineering on forums or chat apps

Prevention Tips:

  • Implement CSRF tokens in all login forms
  • Use `SameSite=Strict` cookies to block cross-site credential sharing
  • Use two-factor authentication to bind sessions to trusted identity
  • Do not auto-login users purely based on a POST request

5. POST-based CSRF

POST-based CSRF targets endpoints that change state or sensitive data using HTTP POST requests. These attacks often involve silently submitting forged forms using the victim’s session cookies, bypassing user intention and sometimes lacking token-based validation.

Basic Exploit Example:

<form action="https://bank.com/transfer" method="POST">
  <input type="hidden" name="to" value="attacker_account">
  <input type="hidden" name="amount" value="5000">
</form>
<script>document.forms[0].submit()</script>

Auto-submits a POST request to transfer funds without user interaction

Common Targets:

  • Banking portals: Money transfers or account updates
  • Admin panels: Role changes or user deletions
  • Profile updates: Email or password changes
  • Settings APIs: Enabling/disabling features

Delivery Methods:

  • Malicious websites embedding hidden forms
  • HTML emails with auto-submitting content
  • Compromised forums or ad injections

Mitigation Techniques:

  • Include CSRF tokens in all POST forms
  • Enforce origin and referer header validation
  • Set `SameSite=Strict` or `Lax` for session cookies
  • Use CAPTCHAs to prevent silent submissions

CSRF Tools & Automation

Discovery & Scanning

  • Burp Suite Scanner – Identifies CSRF vulnerabilities via passive and active checks
  • OWASP ZAP – Includes CSRF detection capabilities through automated scanning
  • CSRF Tester – Lightweight tool to test form-based CSRF issues manually

Exploitation & PoC Generation

  • Burp Suite CSRF PoC Generator – Automatically creates proof-of-concept HTML forms
  • XSS Hunter – Used for stealing CSRF tokens via stored or reflected XSS
  • Custom JavaScript payloads – Tailored payloads for crafting targeted CSRF attacks

Analysis & Reporting

  • Browser Developer Tools – Inspect token placement, cookie flags, and form behavior
  • Token Analysis Scripts – Evaluate token strength, predictability, and regeneration
  • Request Analyzers – Review and replay CSRF-protected requests for weaknesses

Blue Team Defenses (Defensive)

1. Anti-CSRF Tokens

Synchronizer Token Pattern

// Node.js example
const csrf = require('csurf');
app.use(csrf());
app.get('/form', (req, res) => {
  res.render('form', { csrfToken: req.csrfToken() });
});

Double Submit Cookie

// Set cookie and form field with same random value
Set-Cookie: CSRF-TOKEN=abc123;
<input type="hidden" name="csrf_token" value="abc123">

2. Cookie Protections

SameSite Attribute

Set-Cookie: session=abc123; SameSite=Lax; Secure

Cookie Prefixes

Set-Cookie: __Secure-session=abc123; Secure; HttpOnly

3. Additional Protections

Custom Headers

// Require custom header for API requests
if (request.headers['X-Requested-With'] !== 'XMLHttpRequest') {
  return response.status(403).send('Forbidden');
}

Referer Validation

// Check request origin
if (!request.headers.referer.startsWith('https://yourdomain.com')) {
  return response.status(403).send('Forbidden');
}

4. Framework Protections

Django CSRF Middleware

# settings.py
MIDDLEWARE = [
    'django.middleware.csrf.CsrfViewMiddleware',
    ...
]

# Template
<form method="post">{% csrf_token %}</form>

Spring Security

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
    }
}

5. Monitoring & Response

Detection

  • Missing CSRF tokens
  • Invalid token submissions
  • Referer header anomalies

Logging

  • Failed CSRF validations
  • Sensitive action attempts
  • Origin header mismatches

Response

  • Session invalidation
  • User notification
  • Forensic analysis

CSRF Mitigation Checklist

  • Implement anti-CSRF tokens for state-changing requests
  • Set SameSite cookie attribute (Strict or Lax)
  • Validate Referer headers for sensitive actions
  • Require re-authentication for critical operations
  • Use framework-provided CSRF protections
  • Monitor for failed CSRF validations
  • Educate developers about CSRF risks
  • Regularly test your defenses

Additional Resources & References

Legal Notice

This content is provided for educational purposes only. Never test security vulnerabilities against systems without explicit permission. Unauthorized testing may violate laws.