Cross-Site Scripting (XSS) Overview
What you'll learn: How attackers inject malicious JavaScript into trusted websites to execute code in other users' browsers.
Cross-Site Scripting (XSS) is one of the most common web security vulnerabilities. Unlike SQL injection that targets databases, XSS attacks target your users directly by injecting malicious scripts into web pages that other people view.
How XSS Works
Imagine you run a community forum. A user posts a comment containing <script>alert('Hacked!')</script>. If your application doesn't properly sanitize this input, that script gets stored in your database and rendered on every visitor's browser when they view that comment. The browser can't tell the difference between your legitimate JavaScript and the attacker's malicious code—it executes everything.
The Real Danger
While alert() is harmless, attackers can do much worse:
- Steal session cookies and hijack accounts
- Capture keystrokes (including passwords)
- Redirect users to phishing sites
- Modify page content to spread misinformation
- Perform actions on behalf of the victim
Types of XSS
There are three main variants (we'll explore each separately):
- Stored XSS: Malicious script is saved in your database
- Reflected XSS: Script comes from the URL or request and is immediately echoed back
- DOM-based XSS: Vulnerability exists in client-side JavaScript itself
Trust Boundary Violation
XSS exploits the browser's trust in your website. When your site serves content, the browser assumes all scripts in that page are authorized. If attacker-controlled data becomes executable code, you've crossed a trust boundary—violating the principle of Complete Mediation we learned earlier.
Key Takeaway: XSS allows attackers to inject malicious JavaScript into trusted websites, turning your site into a weapon against your own users by executing unauthorized code in their browsers.