CSRF vs XSS
You'll learn the key differences between two common web attacks that exploit trust in different directions.
Understanding the Core Distinction
Both CSRF and XSS are web security vulnerabilities, but they exploit trust from opposite directions:
XSS (Cross-Site Scripting) exploits a user's trust in a website. The attacker injects malicious scripts into a trusted site, and your browser executes them because it trusts that site. The attack manipulates what the website shows you.
CSRF (Cross-Site Request Forgery) exploits a website's trust in an authenticated user. The attacker tricks your browser into making unwanted requests to a site where you're already logged in. The attack manipulates what actions you perform.
Target Vulnerabilities
- XSS targets: Input validation weaknesses, improper output encoding, lack of sanitization
- CSRF targets: Missing anti-CSRF tokens, predictable request patterns, reliance on cookies alone for authentication
Attack Vectors
- XSS: Malicious JavaScript injected via form inputs, URL parameters, or stored data
- CSRF: Hidden forms, image tags, or links that trigger state-changing requests on victim sites
Defensive Mechanisms
Against XSS:
- Input validation and sanitization
- Output encoding/escaping
- Content Security Policy (CSP)
Against CSRF:
- Anti-CSRF tokens (synchronizer tokens)
- SameSite cookie attribute
- Checking Referer/Origin headers
- Re-authentication for sensitive actions
Think of it this way: XSS is like a burglar disguising themselves as furniture inside your house, while CSRF is like someone forging your signature while you're away.
Key Takeaway: XSS injects malicious code into trusted sites to attack users; CSRF forges requests from authenticated users to attack sites. Different vulnerabilities require different defenses.