Skip to curriculum
Jump to the editor

18.5. Sanitize HTML to an allowlist

Hard
Topics
40–60 min

Comments, rich-text editors, emails and CMS fields all hand you HTML written by someone else, and showing it with innerHTML runs whatever it contains: <img src=x onerror=…>, a javascript: link, a <script>. A sanitizer turns untrusted HTML into HTML that is safe to insert, by keeping only what you explicitly allow. This is a security problem: a sanitizer that is right for ninety-nine inputs and wrong for one is a vulnerability.

Write sanitizeHtml(html, allowed) in sanitize.js.

Signature

JAVASCRIPT
function sanitizeHtml(html, allowed) // returns a string of HTML
  • html: untrusted HTML (a fragment).
  • allowed: an object from lower-case tag name to the attribute names that tag may keep, for example { p: [], a: ["href", "title"], img: ["src", "alt"] }.

Requirements

  1. Parse the input into an inert tree (nothing runs or loads while you work), clean the tree, and return its HTML. Empty input gives "". Text is escaped in the output.
  2. An element whose tag is an own key of allowed stays, with only the attributes its list names.
  3. An element that is not allowed is unwrapped: it is removed and its (cleaned) children take its place.
  4. These elements are removed with everything inside, even when allowed names them: script, style, template, iframe, frame, frameset, object, embed, noscript, noembed, noframes, xmp, plaintext, svg, math, base, link, meta.
  5. Attributes whose name starts with on and the srcset attribute are always removed, even when listed.
  6. URL attributes (href, src, cite, action, formaction, poster, background) are kept only if the URL is relative or uses http:, https: or mailto:, judged the way the browser reads it (case, spaces, tabs, newlines and character references cannot hide a javascript:). A kept URL keeps its original value.
  7. Comments are removed.
  8. Upper-case tags and attributes work, quotes in attribute values stay inside their attribute, and malformed or nested tricks (a broken <scr<script>ipt>, an unclosed tag, the noscript and mglyph mutations) leave nothing unsafe.
  9. Cleaning the output again gives the same output.
  10. The output inserted into a live page runs nothing. The allowlist object is not changed.

Examples

JAVASCRIPT
const allowed = { p: [], b: [], a: ["href", "title"], img: ["src", "alt"] };

sanitizeHtml('<p onclick="steal()">Hi <b>there</b><script>steal()</script></p>', allowed);
// '<p>Hi <b>there</b></p>'
JAVASCRIPT
sanitizeHtml('<div><a href=" JaVaScRiPt:steal()" title="x">link</a></div>', allowed);
// '<a title="x">link</a>'   (div unwrapped, unsafe href removed)
JAVASCRIPT
sanitizeHtml('<img src="cat.png" alt="cat" onerror="steal()"><!-- note -->1 < 2', allowed);
// '<img src="cat.png" alt="cat">1 &lt; 2'

Environment

  • Plain JavaScript in a browser page; the tests call the global sanitizeHtml from sanitize.js. Its payloads call window.__xss() if they ever run.
  • DOMParser, <template>, URL and every DOM method are available. Do not use regular expressions on the markup: parse it.
  • Out of scope: CSS inside style attributes (allow style only if you trust it), DOM clobbering through id and name, and adding rel to links.

Hints

  1. Which of DOMParser, <template> and document.createElement("div") start loading an <img> the moment you set its HTML?
  2. When you remove nodes while looping over childNodes, what happens to the loop?
  3. allowed["constructor"] is not undefined. Why?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…