Cross-site scripting
| Class | Injection |
|---|---|
| Also known as | XSS; HTML injection; CSS (old acronym) |
| CWE | CWE-79: Improper Neutralization of Input During Web Page Generation |
| OWASP Top 10 | A05:2025 Injection |
| Typical severity | Medium |
| Affects | Pages that put request data or saved user content into HTML: innerHTML, dangerouslySetInnerHTML, the Django and Jinja safe filter, PHP output without htmlspecialchars |
When a web application copies input that a user can control into a page served to other people and does not neutralize it,1 the visitor's browser can run part of that input as code. The vulnerability is called cross-site scripting (XSS).2 The injected script runs in the context of the target site, as though the site had shipped it, with every power the site's own code has.3
Description
An XSS attack needs a site that accepts input an attacker could have crafted and includes it in a page without sanitizing it.3 Untrusted input is anything the application did not create itself: form input, URL parameters, data stored by users and responses from other services.4
CWE-79 ranks first in the 2025 CWE Top 25 Most Dangerous Software Weaknesses.5 The OWASP Top 10:2025 counts more than 30,000 CVEs for XSS under Injection (A05), against more than 14,000 for SQL injection.2
The weakness has three variants (Table 1).1 Stored and reflected say how the payload reaches the victim; server side and client side say where the input is handled unsafely. The two axes are independent, so a DOM-based flaw can itself be stored or reflected.6
| Variant | Also called | Where the input comes from | Where it is put into the page |
|---|---|---|---|
| Reflected | Non-persistent, Type 1 | The current HTTP request, usually a parameter in a link posted publicly or emailed to the victim | On the server, in the response to that request |
| Stored | Persistent, Type 2 | A database, message forum, visitor log or other store | On the server, each time the page is served |
| DOM-based | Type 0 | Data the page's script reads, such as the address | In the browser, by the page's own JavaScript |
Mechanism
An Express route repeats the search term on the results page:
app.get("/results", (req, res) => {
const searchQuery = req.query.search;
res.send(`<h1>You searched for ${searchQuery}</h1>`);
});A link to http://example.org/results?search=<img src=x onerror=alert('hello')> makes the server return an image tag inside the heading. The image at x fails to load, so the onerror event handler runs its code. The same payload works where the page's own script reads user from window.location.search and writes it into the page:
welcome.innerHTML = `Welcome back, ${user}!`;Saved as a comment, the same text is served to every user who opens the page, every time.3 A payload can also sit in a log message until an administrator views it.1
Which characters are dangerous depends on where the value lands. In an unquoted attribute such as <div class={{ my_class }}>, the input some_id onmouseover=alert(1) adds an event handler without any angle bracket.3 Encoding does not reliably protect a value placed directly inside a <script> element, an HTML comment or CSS, used as a tag or attribute name, or passed to eval(), setTimeout() or setInterval().4
Impact
The injected code can read and change all content of the site's loaded pages and local storage, and send HTTP requests with the user's credentials.3 The most common attack steals session information from cookies, and it does the most harm when the victim is an administrator. Stored and reflected XSS have the same consequences, which run from an annoyance to complete account compromise.1
Notable incidents
Roundcube Webmail (2023)
On 11 October 2023 the Winter Vivern group began exploiting a zero-day stored XSS in Roundcube Webmail, against servers of governmental entities and a think tank in Europe. The attack was an HTML email ending in an SVG document whose image element had an invalid URL in href, so its onerror attribute ran eval(atob(...)) on a base64 payload. The server-side script rcube_washtml.php did not sanitize the SVG before adding it to the page, and viewing the message was enough. The payload listed the account's folders and emails and sent messages to the attackers' server.7
ESET reported the flaw on 12 October, Roundcube patched it on 14 October, and versions 1.6.4, 1.5.5 and 1.4.15 followed on 16 October.78 The flaw is CVE-2023-5631, scored 6.1 by ESET and 5.4 by NVD, both Medium, and CISA added it to its Known Exploited Vulnerabilities catalogue on 26 October 2023.9
Detection
Search the code for innerHTML, document.write, eval, dangerouslySetInnerHTML, Angular's bypassSecurityTrustAs functions and Lit's unsafeHTML,4 and in templates for the safe filter, Markup and {% autoescape false %}.10 A match is a vulnerability when untrusted data reaches it.
To test your own page, enter <img src=x onerror=alert(1)> in a field or URL parameter that the page shows back. A page that encodes output shows the text as typed, and its source holds <img src=x; a vulnerable page runs the alert.3
Prevention
Output encoding
Output encoding converts the characters HTML treats as syntax into entities before a value enters the page: & to &, < to <, > to >, " to " and ' to '. Applications built with modern frameworks have fewer XSS bugs because their templates escape by default; flaws remain where a developer turns escaping off (Table 2).4
| Stack | Escaped by default | Escaping turned off |
|---|---|---|
| React | <h1>{title}</h1> | dangerouslySetInnerHTML |
| Django | {{ value }} in templates | safe filter |
| Flask, Jinja | .html, .htm, .xml, .xhtml and .svg templates rendered with render_template() | |safe, Markup, {% autoescape false %} |
| PHP | echo htmlspecialchars($value); (default flags ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401 since PHP 8.1.0) | Values printed without it |
| Express | A templating engine that performs output encoding | Request values in a template string passed to res.send |
Put attribute values in double or single quotes, and attach event handlers with addEventListener() instead of building them from text. A URL from a user that goes into href or src needs a check that allows only http and https; React 19 blocks javascript: URLs there, which does not replace that check.4
Safe DOM properties
In browser code, use properties that insert text in place of innerHTML:4
elem.textContent = dangerVariable;
elem.insertAdjacentText("beforeend", dangerVariable);
elem.setAttribute(safeName, dangerVariable);
formfield.value = dangerVariable;
document.createTextNode(dangerVariable);HTML written by users
Where users may submit formatted HTML, pass it through a sanitizer such as DOMPurify, which covers HTML, MathML and SVG:13
// npm install dompurify
import DOMPurify from 'dompurify';
// post.content is HTML written by a user
return <div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(post.content) }} />;React allows dangerouslySetInnerHTML only with trusted and sanitized data.14 On the server DOMPurify needs a DOM, and its authors recommend the latest jsdom, as older versions can let XSS through.13 Patch the sanitizer regularly and leave the HTML unchanged after sanitizing it.4
Second layers
A cookie with the HttpOnly attribute cannot be read by JavaScript through document.cookie, for example Set-Cookie: id=a3fWa; Secure; HttpOnly.15 The flag is defence in depth.1 An injected script can no longer copy the session cookie, yet it can still send requests with the user's credentials.
Under a strict Content Security Policy the browser runs only scripts that carry the right nonce or hash, so it does not execute an inserted <script> element; the policy also disallows inline event handlers, javascript: URLs and eval().3 A nonce-based policy:16
Content-Security-Policy:
script-src 'nonce-{RANDOM}' 'strict-dynamic';
object-src 'none';
base-uri 'none';A policy is easy to get wrong, so CSP sits on top of encoding as an extra layer. Input validation enforces expected formats and leaves the encoding still needed. A web application firewall may miss DOM-based XSS, which happens entirely in the browser.4
Prompt for a coding agent
Find every place in this project where text that comes from a request, a URL, a form, a database field users can write, or another service is put into a page. That includes innerHTML, document.write, eval, setTimeout or setInterval with a string, dangerouslySetInnerHTML, the safe filter in Django or Jinja, Markup and autoescape false in Flask, PHP output without htmlspecialchars, and Express res.send with a template string. For each one: show the value as text (textContent, JSX, an escaping template) where no HTML is needed; where users must submit HTML, sanitize it with DOMPurify at the point of use; quote every HTML attribute; allow only http and https URLs in href and src. Check that session cookies are set with HttpOnly and Secure. List each file and line you changed, and any place you were unsure about.
In SecFlash
On the Security page, SecFlash reports reflected XSS found by the attack test as SF-SEC-602, stored XSS as SF-SEC-604 and DOM-based XSS as SF-SEC-610. HTML built from values without escaping in source code is SF-SEC-710. A value from the address or a form inside an HTML attribute (SF-SEC-635) and eval or innerHTML in a page's script (SF-SEC-646) mark places where XSS can start. The same page shows the second layers: a missing policy as SF-SEC-103, 'unsafe-inline' or a wildcard in script-src as SF-SEC-104, a session cookie without HttpOnly as SF-SEC-501, and code that switches the flag off as SF-SEC-761.
See also
- Common types of attack on web applications
- SQL injection
- Output encoding
- Content Security Policy
- Input validation
- Session hijacking
- Defence in depth
- Category: Injection
References
- a b c d e "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')". Common Weakness Enumeration. MITRE.
- a b "A05:2025 Injection". OWASP Top 10:2025. OWASP Foundation.
- a b c d e f g h "Cross-site scripting (XSS)". MDN Web Docs. Mozilla.
- a b c d e f g h "Cross Site Scripting Prevention Cheat Sheet". OWASP Cheat Sheet Series.
- back "2025 CWE Top 25 Most Dangerous Software Weaknesses". Common Weakness Enumeration. MITRE.
- back "DOM based XSS Prevention Cheat Sheet". OWASP Cheat Sheet Series.
- a b Faou, Matthieu (25 October 2023). "Winter Vivern exploits zero-day vulnerability in Roundcube Webmail servers". WeLiveSecurity. ESET.
- back Roundcube (16 October 2023). "Security update 1.6.4 released". roundcube.net.
- back "CVE-2023-5631". National Vulnerability Database. NIST.
- a b "Templates". Flask documentation. Pallets.
- back "Introducing JSX". React documentation (legacy).
- back "htmlspecialchars". PHP Manual.
- a b cure53. "DOMPurify". GitHub.
- back "Common components (e.g. <div>)". React documentation.
- back "Content Security Policy Cheat Sheet". OWASP Cheat Sheet Series.
External links
- Cross Site Scripting Prevention Cheat Sheet, OWASP Cheat Sheet Series
- DOM based XSS Prevention Cheat Sheet, OWASP Cheat Sheet Series