CCyberwiki

HTML sanitization

HTML sanitization
TypeDefence against cross-site scripting
ClassInjection
CWECWE-79: Improper Neutralization of Input During Web Page Generation
OWASP Top 10A05:2025 Injection
LibrariesDOMPurify (JavaScript), nh3 (Python), the HTML Sanitizer API (browsers)

A site that lets readers format their comments with bold text, lists and links has to accept HTML from strangers and show it to other visitors. Output encoding, the usual defence against XSS, would stop the attack but print the tags as visible text and lose the formatting.1 With HTML sanitization, a program reads the submitted HTML instead, keeps the elements and attributes it considers harmless and removes the rest, such as <script> elements and event handlers like onclick. What comes out is still HTML and still renders as formatting.2 A library that does this is an HTML sanitizer.

How a sanitizer decides

A sanitizer works from an allowlist. DOMPurify, a JavaScript sanitizer, hands the string to the browser's own HTML parser, walks the resulting DOM tree, deletes every node that is not on its list and turns the tree back into a string.3 Its default list allows HTML, SVG and MathML. An app that only needs HTML can say so, and a comment field can narrow the list further:4

import DOMPurify from 'dompurify';

const clean = DOMPurify.sanitize(dirty, { USE_PROFILES: { html: true } });
const strict = DOMPurify.sanitize(dirty, { ALLOWED_TAGS: ['b', 'i', 'p'] });

No list of HTML attributes is safe in every case, and an attribute that holds a URL also needs the URL itself checked. Rejecting odd input on the way in, input validation, does not replace sanitizing.1

Parsing with the browser's parser lets the sanitizer see the markup the way the browser will. On a server there is no browser, so DOMPurify needs a DOM implementation in Node.js. Its authors strongly recommend the newest jsdom: version 19.0.0 had flaws, fixed in 20.0.0, that let XSS through even when DOMPurify itself behaved correctly. They consider happy-dom unsafe for this purpose.4

import { JSDOM } from 'jsdom';
import DOMPurify from 'dompurify';

const purify = DOMPurify(new JSDOM('').window);
const clean = purify.sanitize(dirty);

Parsed twice: mutation XSS

The string a sanitizer returns is parsed a second time when the page assigns it to innerHTML. The HTML specification warns that a tree written out as markup and parsed again may not come back the same. Mutation XSS uses those differences: the markup is harmless in the tree the sanitizer inspected and dangerous in the tree the browser builds afterwards.3

In September 2020 Michał Bentkowski published a DOMPurify bypass built on two parser rules. A form element may not contain another form, yet mis-nested end tags can produce a nested one, and the markup written from that tree parses into a different shape. Inside svg or math, the parser builds SVG or MathML elements instead of HTML ones (a different namespace), and there a style element may hold child elements; in plain HTML it holds only text.3 His payload combined form, math, mtext, mglyph and style so that an img element with an onerror handler got past the sanitizer and ran after the second parse. It is recorded as CVE-2020-26870, rated 6.1 (medium) on CVSS 3.1, and DOMPurify 2.0.17 fixed it.5 Browsers change and bypasses like this one turn up regularly, so the sanitizer library needs regular updates.1

After sanitizing

Editing sanitized output, or passing it to code that rewrites it, can undo the sanitizing.1 A DOMPurify advisory published in March 2026, fixed in version 3.3.2, describes one such case. An application placed the clean string inside an xmp, script, iframe, noembed, noframes or noscript element and parsed the whole thing again. Text inside an attribute, such as </xmp>, then closed the wrapper early, and the rest of the attribute became an element with an event handler.6

// unsafe: the clean string is reparsed in a different context
sink.innerHTML = "<xmp>" + DOMPurify.sanitize(input) + "</xmp>";

Markdown

Markdown renderers turn user text into HTML, so their output needs the same treatment. Marked does not sanitize what it produces, and its documentation points to DOMPurify for that step.7 react-markdown builds React elements without dangerouslySetInnerHTML and is safe in its default settings. A custom urlTransform, plugins or components can open the hole again; the rehype-sanitize plugin filters the final result against a schema the app defines.8

const html = DOMPurify.sanitize(marked.parse(comment.body));

Libraries by stack

Table 1. Sanitizers in common stacks
StackSanitizer
BrowserDOMPurify.sanitize(dirty), or el.setHTML(dirty) where supported
Node.js serverDOMPurify with a current jsdom
Pythonnh3.clean(html, tags={"b", "i", "p"})
React with Markdownreact-markdown, with rehype-sanitize when plugins are added

nh3 is a Python binding to ammonia, a sanitizer written in Rust, and takes sets of allowed tags, attributes and URL schemes.9 Bleach, the older Python choice, has been unmaintained since 5 June 2026 and will get no further releases, security fixes included.10

The HTML Sanitizer API, inspired by DOMPurify, adds Element.setHTML() to browsers: it parses a string, drops unsafe elements and attributes, drops elements that do not belong inside the target element, and inserts what remains. With no options, it can replace innerHTML in most code. A custom configuration can narrow the list, but setHTML() removes XSS-unsafe markup whatever the configuration says; setHTMLUnsafe() leaves that decision to the configuration.24 The API is not yet available in some of the most used browsers.2 DOMPurify can also return a TrustedHTML object for pages that enforce Trusted Types.4

Prompt for a coding agent

Find every place in this project where HTML written by users, or produced from their Markdown, is put into a page: innerHTML, dangerouslySetInnerHTML, v-html, the safe filter in templates, and Markdown renderers such as marked. Pass each one through DOMPurify (or nh3 in Python) with the smallest list of tags and attributes the feature needs, right before it is inserted. Do not change or wrap the sanitized string afterwards. On the server, use DOMPurify with the newest jsdom. List each file and line you changed.

In SecFlash

When content a user saved is shown to other visitors as HTML and runs script, SecFlash reports SF-SEC-604 on the Security page. Code that writes to innerHTML or calls eval is reported as SF-SEC-646 on the same page.

See also

References

  1. a b c d "Cross Site Scripting Prevention Cheat Sheet". OWASP Cheat Sheet Series.
  2. a b c "HTML Sanitizer API". MDN Web Docs. Mozilla.
  3. a b c Bentkowski, Michał (21 September 2020). "Mutation XSS via namespace confusion: DOMPurify 2.0.17 bypass". Securitum.
  4. a b c d cure53. "DOMPurify". GitHub.
  5. back "CVE-2020-26870". National Vulnerability Database. NIST.
  6. back "GHSA-h8r8-wccr-v5f2: DOMPurify mutation XSS on reinsertion into special wrappers". GitHub Advisory Database.
  7. back "Marked documentation". marked.js.org.
  8. back "react-markdown". GitHub.
  9. back "nh3". nh3 documentation.
  10. back "Bleach". Bleach documentation.