Programming Search⌘K

Weaknesscore

Cross-site scripting

Also called XSS, cwe-79.

Cross-site scripting happens when a web application puts outside input into a page without the right encoding, so the browser reads part of the input as markup or script of the site.

Abstraction
base
OWASP Top 10 (2025)
A05
CWE Top 25 (2025)
rank 1
Languages affected
any-that-generates-html

Description

A web page is text that the browser parses. The parse decides which parts are tags, attributes and script, and which parts are text to show. Cross-site scripting (XSS) happens when a server or a script builds the page by joining fixed markup with input from outside. When the input holds a <, a quote or a URL scheme, the browser can read it as a new tag, a new attribute or a new script. The program meant to show a comment. The browser runs code.

The root cause is the same as in SQL injection: code and data share one channel. The difference is that a page has many languages in it. Text between tags, a quoted attribute, a URL, a <script> block and a style sheet each have their own syntax, so each needs its own encoding.5 An escape that is correct in one place is wrong in another.

The script runs in the origin of the site. It can read the page, read cookies that are not HttpOnly, send requests as the user, and change what the user sees.14 The attacker does not attack the server. The server carries the attack to its own users.

CWE-79 names this weakness. It is a base weakness under CWE-74, injection, and its variants cover narrower cases, such as script-related tags (CWE-80) and script in attributes (CWE-83).1 It is rank 1 of the 2025 CWE Top 25, and seven of its CVEs are in the CISA catalogue of known exploited vulnerabilities.3 In the OWASP Top 10:2025 it is part of A05:2025 Injection.2

Three kinds

CWE-79 describes three kinds.1

  • Reflected (type 1). The input comes in the request, often in a URL parameter, and the server writes it into the response. An attacker sends a crafted link to a victim.
  • Stored (type 2). The application stores the input, for example as a comment, and later writes it into pages for other users. One stored value reaches every reader. CWE-79 gives the Samy worm on MySpace as an example: script in a profile changed the profile of each user who viewed it.1
  • DOM-based (type 0). Script of the site reads input in the browser, for example from the URL, and writes it into the page with a sink that parses markup. The server may never see the input.

History

The CERT Coordination Center published advisory CA-2000-02, "Malicious HTML Tags Embedded in Client Web Requests", on 2 February 2000, together with DoD-CERT, JTF-CND, FedCIRC and NIPC.4 It described both a message board that shows one client's tags to another client and a link that makes a client send script to a site, which the site then reflects back. It said that because one source injects code into pages sent by another source, the problem "has also been described as "cross-site" scripting".4 Its advice to developers was to check the values that build a page against the characters that are explicitly allowed, at the time the page is made, and to set the character set of each page. It warned that removing dangerous characters from the input leaves risks.4

Vulnerable code

The function below builds HTML with an f-string. The second call uses the classic demonstration input <script>alert(1)</script>. In a browser, it opens a dialog box, which proves that the input runs as script.

This code runs but gives a wrong answer on purpose.

def comment_html(author, text):
    return f'<p class="comment"><b>{author}</b>: {text}</p>'


print(comment_html("alice", "Nice post."))
print(comment_html("mallory", "<script>alert(1)</script>"))
Output
<p class="comment"><b>alice</b>: Nice post.</p>
<p class="comment"><b>mallory</b>: <script>alert(1)</script></p>

The same weakness appears with every way to build a string: +, format, template literals, Sprintf, String.format and string interpolation. In the browser, it appears when script assigns input to innerHTML.5 The example files show it in each language.

Fixed code

html.escape replaces the characters that have a meaning in HTML text with character references.6 The browser then shows them as characters and does not parse them as markup.

from html import escape


def comment_html(author, text):
    return f'<p class="comment"><b>{escape(author)}</b>: {escape(text)}</p>'


print(comment_html("alice", "Nice post."))
print(comment_html("mallory", "<script>alert(1)</script>"))
Output
<p class="comment"><b>alice</b>: Nice post.</p>
<p class="comment"><b>mallory</b>: &lt;script&gt;alert(1)&lt;/script&gt;</p>

The comment is now text that reads <script>alert(1)</script> on the page. A user who writes I <3 cats also sees the right text. This is why an escape is better than a filter that removes <.

Encode for the context

The escape must match the place where the value goes.5

Context Example Protection
HTML text <p>VALUE</p> HTML entity encoding of &, <, >, " and '
Quoted attribute <input value="VALUE"> attribute encoding, and the value always in quotes
URL <a href="VALUE"> an allow-list of schemes such as https, then attribute encoding
Data in a script <script>const m = "VALUE"</script> an encoder made for JavaScript strings in HTML
CSS style="color: VALUE" an allow-list of values for the property

CWE-79 says that HTML entity encoding is only appropriate for the HTML body.1 In a URL attribute, the escape keeps the value inside the quotes, but a javascript: URL is still a script. The Python example file shows this case and the fix. The OWASP cheat sheet calls some places dangerous contexts, where no encoding is safe: directly in a script, in an HTML comment, directly in CSS, in a tag name or an attribute name, and in the code of an event handler such as onclick.5 Do not put input there.

Templates that know the context

A template engine with automatic escaping removes the need to remember each call. Go's html/template goes further: it parses the template, finds the context of each action, and picks the escape for it. It replaces a URL with an unsafe scheme by #ZgotmplZ.7 Razor in ASP.NET Core encodes each value that a view writes with @.8 Each engine also has a way to turn the escape off, such as template.HTML in Go, HtmlString in ASP.NET Core and mark_safe in Django.7811 Such a value must never come from input.

When users write HTML

Some applications let users write rich text. Encoding would show the tags as text. Here the defence is a sanitizer, a library that parses the HTML and keeps only an allow-list of tags and attributes. OWASP names DOMPurify, and says to keep the sanitizer up to date and not to change its output after the sanitize step.5

How to detect it

  • Static analysis with taint tracking. CodeQL follows input from a request to a write into the page. Its queries are py/reflective-xss, js/xss, js/reflected-xss, java/xss, go/reflected-xss and cs/web/xss.9
  • Pattern linters. Ruff rule S701 reports Jinja2 environments with autoescape=False, and S308 reports mark_safe.1011 gosec rule G203 reports data converted to the safe types of html/template, and G705 follows input to the response.12
  • Code review. Search for HTML built with +, format, f-strings or template literals, for innerHTML, and for each way to turn the escape of the template engine off. For each value, ask which context it lands in.
  • Tests. Put a value with <, " and ' through each input that reaches a page. The page must show it as text. A value that becomes part of the markup shows the weakness.

How to prevent it

  • Use a template engine that escapes by default. Coverage matters: one missed value in a page is enough.5 A context-aware engine such as html/template also picks the right escape.
  • Encode each value for its context. When there is no engine, call the encoder for the context: HTML text, attribute, JavaScript string or URL component.5 Validate URLs against an allow-list of schemes.
  • Use text sinks in the browser. Assign text to textContent and form values to value, not to innerHTML.5
  • Sanitize HTML that users write. Use a maintained sanitizer with an allow-list.5
  • Add defence in depth. A Content Security Policy is an allow-list that limits the content that a page can load. HttpOnly stops script from reading the session cookie.1 Trusted Types make DOM sinks reject plain strings.5 None of these fixes the code, and the OWASP cheat sheet warns against a CSP as the only defence.5
  • Validate input as a second layer. A check that a field holds a number rejects bad input early. CWE-79 says that validation is not enough for free text, which can contain < for valid reasons.1

Real cases

Case Date What happened
CA-2000-02 2000-02-02 CERT/CC warned that web sites that build pages from unvalidated input let one client run script in another client's browser, in the security context of the site.4
CVE-2020-3580 published 2020-10-21 XSS in the web services interface of Cisco ASA and FTD software. An unauthenticated attacker had to persuade a user of the interface to click a crafted link.14
CVE-2021-1879 published 2021-04-02 Crafted web content could lead to universal cross-site scripting in Apple WebKit. The fix improved the management of object lifetimes, and Apple said that the issue may have been actively exploited.13
PythonGitHub

This code runs but gives a wrong answer on purpose.

def comment_html(author, text):
    return f'<p class="comment"><b>{author}</b>: {text}</p>'


print(comment_html("alice", "Nice post."))
print(comment_html("mallory", "<script>alert(1)</script>"))
Output
<p class="comment"><b>alice</b>: Nice post.</p>
<p class="comment"><b>mallory</b>: <script>alert(1)</script></p>

The second comment is now a script element in the page. A browser that loads the page runs it with the rights of the site.

from html import escape


def comment_html(author, text):
    return f'<p class="comment"><b>{escape(author)}</b>: {escape(text)}</p>'


print(comment_html("alice", "Nice post."))
print(comment_html("mallory", "<script>alert(1)</script>"))
print(comment_html("bob", "I <3 \"quotes\" & 'apostrophes'"))
Output
<p class="comment"><b>alice</b>: Nice post.</p>
<p class="comment"><b>mallory</b>: &lt;script&gt;alert(1)&lt;/script&gt;</p>
<p class="comment"><b>bob</b>: I &lt;3 &quot;quotes&quot; &amp; &#x27;apostrophes&#x27;</p>

This code runs but gives a wrong answer on purpose.

from html import escape


def profile_link(url):
    return f'<a href="{escape(url)}">home page</a>'


print(profile_link("https://example.com/alice"))
print(profile_link("javascript:alert(1)"))
Output
<a href="https://example.com/alice">home page</a>
<a href="javascript:alert(1)">home page</a>

escape keeps the value inside the quotes of the attribute, but the attribute is a URL. The browser runs a javascript: URL when the user clicks the link. The context needs a second check.

from html import escape
from urllib.parse import urlsplit

ALLOWED_SCHEMES = {"http", "https"}


def profile_link(url):
    if urlsplit(url).scheme.lower() not in ALLOWED_SCHEMES:
        url = "#"
    return f'<a href="{escape(url)}">home page</a>'


print(profile_link("https://example.com/alice"))
print(profile_link("javascript:alert(1)"))
Output
<a href="https://example.com/alice">home page</a>
<a href="#">home page</a>
  • Verdict: stdlib. html.escape converts &, < and >, and with quote=True, the default, also " and '.
  • html.escape is correct for text between tags and for the value of a quoted attribute. It is not enough for a URL, for JavaScript or for CSS. The third and fourth examples show the URL case: the fix is an allow-list of schemes, applied before the escape.
  • Template engines do the escape for each value. Jinja2 escapes values only when the environment has autoescape on, and Ruff rule S701 reports autoescape=False. Django escapes by default, and mark_safe turns the escape off for one value, which Ruff rule S308 reports.
  • Do not build HTML with +, %, format or f-strings in a web handler. The examples here use f-strings only to show what the escape does.
JavaGitHub

This code runs but gives a wrong answer on purpose.

public class Main {
    static String commentHtml(String author, String text) {
        return String.format("<p class=\"comment\"><b>%s</b>: %s</p>", author, text);
    }

    public static void main(String[] args) {
        System.out.println(commentHtml("alice", "Nice post."));
        System.out.println(commentHtml("mallory", "<script>alert(1)</script>"));
    }
}
Output
<p class="comment"><b>alice</b>: Nice post.</p>
<p class="comment"><b>mallory</b>: <script>alert(1)</script></p>
public class Main {
    // Java SE has no HTML escape function. This one covers HTML text and
    // quoted attribute values, and nothing else.
    static String escapeHtml(String s) {
        StringBuilder out = new StringBuilder(s.length());
        for (char c : s.toCharArray()) {
            switch (c) {
                case '&' -> out.append("&amp;");
                case '<' -> out.append("&lt;");
                case '>' -> out.append("&gt;");
                case '"' -> out.append("&quot;");
                case '\'' -> out.append("&#x27;");
                default -> out.append(c);
            }
        }
        return out.toString();
    }

    static String commentHtml(String author, String text) {
        return String.format("<p class=\"comment\"><b>%s</b>: %s</p>",
                escapeHtml(author), escapeHtml(text));
    }

    public static void main(String[] args) {
        System.out.println(commentHtml("alice", "Nice post."));
        System.out.println(commentHtml("mallory", "<script>alert(1)</script>"));
    }
}
Output
<p class="comment"><b>alice</b>: Nice post.</p>
<p class="comment"><b>mallory</b>: &lt;script&gt;alert(1)&lt;/script&gt;</p>
  • Verdict: library. Java SE has no HTML escape function and no HTML template engine. The function in the second example covers the five characters of the OWASP table for HTML text. In real code, use a maintained encoder, such as the OWASP Java Encoder, and pick the encoder for the context of each value.
  • A template engine that escapes by default removes most of the work. Many engines also have a form that does not escape. Review each use of it.
  • A servlet that writes input to response.getWriter() has the weakness. CodeQL query java/xss follows input from a request to such a writer.

This code runs but gives a wrong answer on purpose.

static string CommentHtml(string author, string text) =>
    $"<p class=\"comment\"><b>{author}</b>: {text}</p>";

Console.WriteLine(CommentHtml("alice", "Nice post."));
Console.WriteLine(CommentHtml("mallory", "<script>alert(1)</script>"));
Output
<p class="comment"><b>alice</b>: Nice post.</p>
<p class="comment"><b>mallory</b>: <script>alert(1)</script></p>
using System.Text.Encodings.Web;

static string CommentHtml(string author, string text)
{
    var enc = HtmlEncoder.Default;
    return $"<p class=\"comment\"><b>{enc.Encode(author)}</b>: {enc.Encode(text)}</p>";
}

Console.WriteLine(CommentHtml("alice", "Nice post."));
Console.WriteLine(CommentHtml("mallory", "<script>alert(1)</script>"));
Console.WriteLine(System.Net.WebUtility.HtmlEncode("I <3 \"quotes\" & 'apostrophes'"));
Output
<p class="comment"><b>alice</b>: Nice post.</p>
<p class="comment"><b>mallory</b>: &lt;script&gt;alert(1)&lt;/script&gt;</p>
I &lt;3 &quot;quotes&quot; &amp; &#39;apostrophes&#39;
  • Verdict: stdlib. System.Text.Encodings.Web has HtmlEncoder, JavaScriptEncoder and UrlEncoder, one for each context. System.Net.WebUtility.HtmlEncode is a second HTML encoder in the base library.
  • The Razor engine of ASP.NET Core encodes each value that a view writes with @. A value of type HtmlString is not encoded on output, so never make one from input.
  • CodeQL query cs/web/xss follows input from a request to a write into the response.
JavaScriptGitHub

This code runs but gives a wrong answer on purpose.

function commentHtml(author, text) {
  return `<p class="comment"><b>${author}</b>: ${text}</p>`;
}

console.log(commentHtml("alice", "Nice post."));
console.log(commentHtml("mallory", "<script>alert(1)</script>"));
Output
<p class="comment"><b>alice</b>: Nice post.</p>
<p class="comment"><b>mallory</b>: <script>alert(1)</script></p>

In a browser, code like element.innerHTML = commentHtml(...) parses this string as markup. The same happens on a server that sends the string as the body of an HTML response.

const ENTITIES = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#x27;" };

function escapeHtml(value) {
  return String(value).replace(/[&<>"']/g, (ch) => ENTITIES[ch]);
}

// A tag function gets the fixed parts of the template apart from the values.
// It escapes each value and keeps each fixed part as it is.
function html(strings, ...values) {
  let out = strings[0];
  values.forEach((value, i) => {
    out += escapeHtml(value) + strings[i + 1];
  });
  return out;
}

function commentHtml(author, text) {
  return html`<p class="comment"><b>${author}</b>: ${text}</p>`;
}

console.log(commentHtml("alice", "Nice post."));
console.log(commentHtml("mallory", "<script>alert(1)</script>"));
Output
<p class="comment"><b>alice</b>: Nice post.</p>
<p class="comment"><b>mallory</b>: &lt;script&gt;alert(1)&lt;/script&gt;</p>
  • Verdict: stdlib. In a browser, the DOM has sinks that take text and never parse it as markup: textContent, createTextNode, insertAdjacentText and the value of a form field. innerHTML parses its value as markup. Node.js has no HTML escape function.
  • The safe form in the browser is element.textContent = text. It makes a text node and does no encoding, so do not escape the value first.
  • A tagged template sees the fixed parts and the values apart, as a parameterised query does. The second example uses this to escape only the values.
  • Many frameworks escape by default and have a way to turn the escape off, such as dangerouslySetInnerHTML in React. Review each use. HTML that users write needs a maintained sanitizer, such as DOMPurify, and not an escape.
  • eval, setTimeout and setInterval can run a string as code. Do not pass input to them.
  • CodeQL queries js/xss (client side) and js/reflected-xss (server) follow input to these sinks.

This code runs but gives a wrong answer on purpose.

package main

import (
	"os"
	"text/template"
)

const page = `<p><b>{{.Author}}</b>: {{.Text}}</p>
<a href="{{.Home}}">home page</a>
`

type comment struct {
	Author, Text, Home string
}

func main() {
	t := template.Must(template.New("page").Parse(page))
	t.Execute(os.Stdout, comment{"alice", "Nice post.", "https://example.com/alice"})
	t.Execute(os.Stdout, comment{"mallory", "<script>alert(1)</script>", "javascript:alert(1)"})
}
Output
<p><b>alice</b>: Nice post.</p>
<a href="https://example.com/alice">home page</a>
<p><b>mallory</b>: <script>alert(1)</script></p>
<a href="javascript:alert(1)">home page</a>
package main

import (
	"html/template"
	"os"
)

const page = `<p><b>{{.Author}}</b>: {{.Text}}</p>
<a href="{{.Home}}">home page</a>
`

type comment struct {
	Author, Text, Home string
}

func main() {
	t := template.Must(template.New("page").Parse(page))
	t.Execute(os.Stdout, comment{"alice", "Nice post.", "https://example.com/alice"})
	t.Execute(os.Stdout, comment{"mallory", "<script>alert(1)</script>", "javascript:alert(1)"})
}
Output
<p><b>alice</b>: Nice post.</p>
<a href="https://example.com/alice">home page</a>
<p><b>mallory</b>: &lt;script&gt;alert(1)&lt;/script&gt;</p>
<a href="#ZgotmplZ">home page</a>
  • Verdict: stdlib. html/template has the same API as text/template, and the only change between the two programs is the import path.
  • html/template escapes by context. It parses the template, finds that {{.Text}} is in HTML text and that {{.Home}} is in a URL attribute, and picks the escape for each place. It replaces a URL with an unsafe scheme by #ZgotmplZ.
  • text/template does no escaping. It is correct for plain text output and wrong for HTML.
  • The package trusts the template author and does not trust the data. The types template.HTML, template.JS and template.URL mark a value as safe and turn the escape off for it. Never convert input to these types. gosec rule G203 reports such conversions.
  • gosec rule G705 and CodeQL query go/reflected-xss follow input from a request to the response writer.

References

  1. CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting'), Description; Alternate Terms; Relationships; Potential Mitigations; Notes
  2. OWASP Top 10:2025, A05:2025 Injection, List of Mapped CWEs
  3. 2025 CWE Top 25 Most Dangerous Software Weaknesses, the ranked list, rank 1, CVEs in KEV
  4. Software Engineering Institute, 2000 CERT Advisories, CA-2000-02: Malicious HTML Tags Embedded in Client Web Requests, chapter 2, Overview and I. Description
  5. OWASP Cheat Sheet Series, Cross Site Scripting Prevention Cheat Sheet, XSS Defense Philosophy; Output Encoding; Dangerous Contexts; HTML Sanitization; Safe Sinks; Other Controls
  6. The Python Standard Library, html, Python 3.14, html.escape
  7. Go standard library, package html/template, Overview, Introduction, Contexts and Security Model
  8. ASP.NET Core documentation, Prevent Cross-Site Scripting (XSS) in ASP.NET Core, HTML Encoding using Razor; Accessing encoders in code
  9. CodeQL query help, Reflected server-side cross-site scripting (py/reflective-xss), the query description
  10. Ruff rules, jinja2-autoescape-false (S701), What it does; Why is this bad?
  11. Ruff rules, suspicious-mark-safe-usage (S308), What it does; Why is this bad?
  12. gosec rules, G203 and G705
  13. CVE-2021-1879, Apple WebKit, the description and the publication date
  14. CVE-2020-3580, Cisco ASA and FTD web services interface, the description and the publication date

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/BZDEXT/text.yaml