Introduction
Cross-Site Request Forgery (CSRF) allows attackers to trick authenticated users into performing unintended actions by crafting malicious forms or requests that the user's browser automatically submits with their session cookies. If a state-changing endpoint (POST, PUT, DELETE) does not validate a CSRF token, any website the user visits can trigger actions on your application on their behalf, such as changing passwords, transferring funds, or modifying account settings.
Symptoms
- Security audit reports missing CSRF protection:
`- [HIGH] CSRF token not validated on POST /api/account/change-password
- [HIGH] CSRF token not validated on POST /api/users/{id}/delete
`- Application accepts POST requests without any CSRF token:
- ```bash
- # This should be rejected but succeeds:
- curl -X POST https://your-app.example.com/api/account/change-password \
- -H "Cookie: session=abc123" \
- -d '{"new_password": "hacker123"}' \
- -H "Content-Type: application/json"
- # Returns: 200 OK (should be 403 Forbidden)
`- Evidence of forged requests in access logs:
`- Referer: https://evil-site.example.com/malicious-page
- Origin: https://evil-site.example.com
`- Users report unauthorized changes to their accounts
Common Causes
- API endpoints not configured with CSRF middleware
- CSRF token validation disabled for JSON/API endpoints (misunderstanding that JSON APIs are immune)
SameSitecookie attribute not set, allowing cross-site cookie sending- CORS misconfiguration allowing any origin to make authenticated requests
- State-changing operations using GET instead of POST
Step-by-Step Fix
Phase 1: Assess the Impact
- 1.Identify all endpoints missing CSRF protection:
- 2.```bash
- 3.# Search for POST/PUT/DELETE routes without CSRF middleware
- 4.# For Express.js:
- 5.grep -rn "app.post|app.put|app.delete" routes/ | \
- 6.grep -v "csrf|csrfProtection"
# For Django: grep -rn "@csrf_exempt" views/
# For Rails: grep -rn "skip_before_action :verify_authenticity_token" controllers/ ```
- 1.Review access logs for suspicious cross-origin requests:
- 2.```bash
- 3.# Look for state-changing requests from unknown origins
- 4.grep -E "POST|PUT|DELETE" /var/log/nginx/access.log | \
- 5.grep -v "Origin: https://your-app.example.com" | \
- 6.grep -v "Origin: https://www.your-app.example.com"
# Check for requests with suspicious referers grep -E "POST|PUT|DELETE" /var/log/nginx/access.log | \ grep "Referer:" | grep -v "your-app.example.com" ```
Phase 2: Implement CSRF Protection
- 1.Add CSRF middleware to the application:
Express.js with csurf: ```javascript const session = require('express-session'); const csrf = require('csurf');
// Session must be configured first app.use(session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false, cookie: { secure: true, httpOnly: true, sameSite: 'strict' // Additional CSRF protection } }));
// CSRF middleware const csrfProtection = csrf({ cookie: false }); // Use session-based CSRF app.use(csrfProtection);
// Add CSRF token to all responses app.use((req, res, next) => { res.locals.csrfToken = req.csrfToken(); next(); });
// Apply to all state-changing routes app.post('/api/account/change-password', csrfProtection, (req, res) => { // Handler - CSRF already validated });
// Apply globally (except for specific API routes) app.use('/api', (req, res, next) => { if (req.method === 'GET' || req.method === 'HEAD' || req.method === 'OPTIONS') { return next(); } csrfProtection(req, res, next); }); ```
Django (built-in protection): ```python # settings.py - ensure CSRF middleware is enabled MIDDLEWARE = [ # ... 'django.middleware.csrf.CsrfViewMiddleware', # ... ]
# For templates, add CSRF token to forms: # <form method="post"> # {% csrf_token %} # ... # </form>
# For API endpoints using session authentication: from django.views.decorators.csrf import ensure_csrf_cookie
@ensure_csrf_cookie def get_csrf_token(request): from django.middleware.csrf import get_token return JsonResponse({'csrfToken': get_token(request)}) ```
- 1.Set SameSite cookie attribute:
- 2.```nginx
- 3.# Nginx - add SameSite to Set-Cookie header
- 4.proxy_cookie_path / "/; secure; HttpOnly; SameSite=Strict";
- 5.
` - 6.```javascript
- 7.// Express session cookie
- 8.app.use(session({
- 9.cookie: {
- 10.secure: true,
- 11.httpOnly: true,
- 12.sameSite: 'strict' // or 'lax' for better UX
- 13.}
- 14.}));
- 15.
` - 16.For SPAs, use double-submit cookie pattern:
- 17.```javascript
- 18.// Server sets CSRF token in both cookie and JSON response
- 19.app.get('/api/csrf-token', (req, res) => {
- 20.const token = crypto.randomBytes(32).toString('hex');
- 21.res.cookie('XSRF-TOKEN', token, {
- 22.httpOnly: false, // Must be readable by JavaScript
- 23.secure: true,
- 24.sameSite: 'strict'
- 25.});
- 26.res.json({ csrfToken: token });
- 27.});
// Client sends token in header // Frontend code: fetch('/api/account/change-password', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-XSRF-TOKEN': getCookie('XSRF-TOKEN') // Read from cookie }, body: JSON.stringify({ new_password: 'secure123' }), credentials: 'same-origin' });
// Server validates that cookie token matches header token ```
Phase 3: Verify and Harden
- 1.Test CSRF protection:
- 2.```bash
- 3.# Without CSRF token - should be rejected
- 4.curl -X POST https://your-app.example.com/api/account/change-password \
- 5.-H "Cookie: session=abc123" \
- 6.-d '{"new_password": "hacker123"}'
- 7.# Should return: 403 Forbidden (CSRF token missing)
# With valid CSRF token - should succeed curl -X POST https://your-app.example.com/api/account/change-password \ -H "Cookie: session=abc123" \ -H "X-CSRF-Token: valid_token_here" \ -d '{"new_password": "secure123"}' # Should return: 200 OK ```
- 1.Add CSRF monitoring:
- 2.```python
- 3.# Log CSRF failures for security monitoring
- 4.@app.errorhandler(403)
- 5.def csrf_error(error):
- 6.if 'CSRF' in str(error):
- 7.app.logger.warning(
- 8.f"CSRF violation from IP: {request.remote_addr}, "
- 9.f"Referer: {request.headers.get('Referer', 'none')}, "
- 10.f"Origin: {request.headers.get('Origin', 'none')}"
- 11.)
- 12.return jsonify({'error': 'CSRF validation failed'}), 403
- 13.
`
Prevention
- Apply CSRF protection globally, exempting only specific public API endpoints
- Use
SameSite=StrictorSameSite=Laxcookies as defense-in-depth - Never disable CSRF validation for authenticated endpoints
- Use the double-submit cookie pattern for SPAs
- Include CSRF token validation in API testing suites
- Monitor and alert on CSRF validation failures
- Review CORS configuration to ensure it does not override CSRF protection