Cross-Site Request Forgery (CSRF)

An attack that tricks authenticated users into executing unwanted actions on a web application where they're logged in.

Cross-Site Request Forgery (CSRF) is a web security vulnerability that forces authenticated users to perform unintended actions on applications where they're currently logged in. In Web3 contexts, CSRF attacks can target APIs that trigger blockchain transactions, modify user settings, or interact with connected wallets. While smart contracts themselves aren't directly vulnerable to CSRF, the backend services and APIs that interact with them often are.

How CSRF Works

CSRF exploits the browser's automatic inclusion of credentials (cookies, session tokens) with requests:

  1. User logs into legitimate DeFi application (establishes session)
  2. User visits malicious site (in another tab)
  3. Malicious site triggers request to DeFi application
  4. Browser automatically includes user's credentials
  5. DeFi application processes the request as if user initiated it
1<!-- Malicious site embeds this image -->
2<img src="https://defi-app.com/api/transfer?to=attacker&amount=1000" />
3
4<!-- Or this form that auto-submits -->
5<form action="https://defi-app.com/api/transfer" method="POST" id="csrf">
6 <input type="hidden" name="to" value="attacker" />
7 <input type="hidden" name="amount" value="1000" />
8</form>
9<script>document.getElementById('csrf').submit();</script>

CSRF in Web3 Applications

While blockchain transactions require explicit wallet signing (providing natural CSRF protection), many DeFi operations don't:

Vulnerable operations:

  • API calls that prepare transactions for signing
  • User profile and settings modifications
  • Withdrawal address changes
  • Email/notification preference updates
  • API key generation or rotation

Attack scenario:

1// Legitimate API endpoint
2POST /api/settings/withdrawal-address
3Body: { "address": "0xNEW_ADDRESS" }
4
5// Attacker's page triggers this request
6// If no CSRF protection, attacker can change withdrawal address
7// Next withdrawal goes to attacker

Why Some Web3 Apps Are Vulnerable

Over-reliance on wallet signatures: Teams assume all sensitive operations require signing, missing traditional API security.

Hybrid architectures: Backend services with traditional session management alongside blockchain interactions.

API-first design: RESTful APIs designed without considering browser-based attacks.

Third-party integrations: Webhooks and callbacks that trust origin headers.

CSRF Prevention Techniques

Synchronizer Token Pattern

Include a random token in forms that attackers can't guess:

1<form action="/api/settings" method="POST">
2 <input type="hidden" name="csrf_token" value="random-token-12345" />
3 <!-- Form fields -->
4</form>

Server validates the token matches the user's session:

1app.post('/api/settings', (req, res) => {
2 if (req.body.csrf_token !== req.session.csrfToken) {
3 return res.status(403).json({ error: 'Invalid CSRF token' });
4 }
5 // Process request
6});

SameSite Cookies

Modern cookie attribute that prevents cross-site sending:

1// Express.js session configuration
2app.use(session({
3 cookie: {
4 sameSite: 'strict', // or 'lax'
5 secure: true,
6 httpOnly: true
7 }
8}));
SameSite ValueBehavior
StrictCookie never sent cross-site
LaxSent on top-level GET navigations only
NoneAlways sent (requires Secure)

Double Submit Cookie

Store token in both cookie and request:

1// Set CSRF token in cookie
2res.cookie('csrf', token, { sameSite: 'strict' });
3
4// Client includes token in header
5fetch('/api/action', {
6 method: 'POST',
7 headers: {
8 'X-CSRF-Token': getCookie('csrf')
9 }
10});
11
12// Server compares cookie value with header value

Origin/Referer Validation

Check request origin matches expected domain:

1function validateOrigin(req: Request): boolean {
2 const origin = req.headers.origin || req.headers.referer;
3 const allowedOrigins = ['https://app.example.com'];
4 return allowedOrigins.some(allowed => origin?.startsWith(allowed));
5}

Framework Implementations

Express.js with csurf

1import csrf from 'csurf';
2
3const csrfProtection = csrf({ cookie: true });
4
5app.get('/form', csrfProtection, (req, res) => {
6 res.render('form', { csrfToken: req.csrfToken() });
7});
8
9app.post('/process', csrfProtection, (req, res) => {
10 // Token validated automatically
11});

Next.js

1// pages/api/protected.ts
2import { withIronSession } from 'next-iron-session';
3
4export default withIronSession(async (req, res) => {
5 const token = req.headers['x-csrf-token'];
6 if (token !== req.session.csrfToken) {
7 return res.status(403).json({ error: 'CSRF validation failed' });
8 }
9 // Process request
10});

CSRF Testing in Audits

When auditing for CSRF:

  1. Identify state-changing operations: All POST, PUT, DELETE, PATCH endpoints
  2. Check token presence: Verify CSRF tokens in forms and AJAX requests
  3. Test token validation: Try requests without tokens or with invalid tokens
  4. Review cookie settings: Check SameSite and Secure flags
  5. Test cross-origin requests: Attempt requests from different origins

CSRF vs Wallet Signing

OperationCSRF RiskProtection
Blockchain transactionLowWallet signature required
API state changeHighCSRF tokens required
Read-only APINoneNo protection needed
Hybrid (prepare + sign)MediumProtect preparation step

Audit Checklist

  • All state-changing APIs require CSRF tokens
  • Tokens validated server-side on every request
  • SameSite cookie attribute set appropriately
  • Origin/Referer headers validated for sensitive operations
  • API endpoints don't accept GET for state changes
  • CORS configured to reject unauthorized origins
  • Sensitive operations require re-authentication or wallet signature

CSRF protection is essential for any Web3 application with traditional backend services. While blockchain transactions have built-in protection through wallet signatures, the surrounding infrastructure—settings, profiles, API keys, and preparation endpoints—remains vulnerable without proper CSRF defenses.

Need expert guidance on Cross-Site Request Forgery (CSRF)?

Our team at Zealynx has deep expertise in blockchain security and DeFi protocols. Whether you need an audit or consultation, we're here to help.

Get a Quote

oog
zealynx

Subscribe to Our Newsletter

Stay updated with our latest security insights and blog posts

© 2024 Zealynx