XSS
Cross-Site Scripting (XSS) is a web security vulnerability that lets an attacker inject malicious client-side scripts into pages viewed by other users. When unsanitized input is rendered as executable HTML or JavaScript, the injected…
Definition
Cross-Site Scripting (XSS) is a web security vulnerability that lets an attacker inject malicious client-side scripts into pages viewed by other users. When unsanitized input is rendered as executable HTML or JavaScript, the injected script runs in the victim's browser under the site's trust context, enabling session hijacking, credential theft, or defacement.
Overview
XSS exploits the browser's trust in content served from a given origin. If an application embeds untrusted input directly into HTML output without proper encoding, an attacker can smuggle a `<script>` tag or event handler that executes in the context of the victim's session — with access to cookies, local storage, and the DOM. There are three main types. Stored (persistent) XSS occurs when malicious input is saved on the server (e.g., in a comment or profile field) and served to every visitor. Reflected XSS occurs when input from a request (such as a URL query parameter) is echoed back in the response without sanitization, requiring a victim to click a crafted link. DOM-based XSS happens entirely in client-side JavaScript, where a script reads attacker-controlled data from the URL or DOM and writes it back unsafely, without the payload ever touching the server. Mitigation relies on layered defenses: output encoding appropriate to context (HTML, attribute, JavaScript, URL), using frameworks that auto-escape by default (React, Vue), a strict Content-Security-Policy (CSP) header that blocks inline scripts and untrusted origins, HttpOnly cookies to limit token theft, and input validation as a secondary control. Because modern frameworks escape output automatically, most real-world XSS today comes from `dangerouslySetInnerHTML`-style escape hatches, third-party widgets, or manually constructed HTML strings.
Key Concepts
- Three primary forms: stored, reflected, and DOM-based
- Executes attacker JavaScript in the victim's browser under the site's origin
- Can steal cookies, session tokens, and perform actions as the victim
- Mitigated primarily through context-aware output encoding
- Content-Security-Policy headers add defense-in-depth against script injection
- Modern frameworks (React, Angular, Vue) auto-escape output by default
- OWASP Top 10 category, historically one of the most common web vulnerabilities