XSS Prevention & Sanitization — Security

Turn user data into text right where it is placed. In HTML, escape five characters with entities (codes the browser shows as ordinary characters): & to &amp…

In XSS Basics, one comment containing <script> made a pop-up appear in every reader's browser. The question now: how can that comment still appear with its text whole, but never run as code?

The answer is one rule: data from a user is turned into text right where it is placed. Picture a newspaper quoting someone. The quote goes inside quotation marks, so readers know those are someone else's words, not the paper's own statement. Escaping works like those quotation marks, but for the browser: the data from a user is the quote, and the browser is the reader. With escaping, < is written &lt;. The browser shows a < sign but doesn't open a tag.

Escaping HTML: five characters

Five characters have a special meaning in HTML. Escaping replaces them with entities, codes the browser reads as ordinary characters:

Character Becomes
& &amp;
< &lt;
> &gt;
" &quot;
' &#39;

In the exercise, you finish the escape function sanitizeHTML. The complete version:

function sanitizeHTML(input) {
  return input
    .replace(/&/g, "&amp;") // must come first
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#39;");
}

console.log(sanitizeHTML("<script>alert(1)</script>")); // &lt;script&gt;alert(1)&lt;/script&gt;
console.log(sanitizeHTML('Hi "Budi"')); // Hi &quot;Budi&quot;
console.log(sanitizeHTML("a & b < c")); // a &amp; b &lt; c

Before you read on, guess: if the order is flipped (< replaced first, then &), what does a & b < c become?

It depends on where it goes

The right defence depends on where the data is placed. The Lab uses one template (a piece of HTML with an empty spot ... for the user's data) for each place:

Place Template Defence a & b < c becomes
Element content <p>Comment: ...</p> sanitizeHTML a &amp; b &lt; c
Attribute value <input value="..."> sanitizeHTML, attributes always quoted a &amp; b &lt; c
URL <a href="/search?q=..."> encodeURIComponent a%20%26%20b%20%3C%20c

Let the template escape

Modern template engines (tools that build HTML from a template and data) escape automatically. What you need to recognise are the shortcuts that turn that escaping off. Here is how escaping and its shortcuts look in plain PHP, in Blade (Laravel's template engine), and in React:

// Plain PHP: escape it yourself
echo htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');
{{-- Blade --}}
<p>{{ $comment->body }}</p>   {{-- safe: escaped --}}
<p>{!! $comment->body !!}</p> {{-- dangerous: printed raw --}}
// React: {name} is escaped automatically
<h1>Hi, {name}</h1>
// dangerouslySetInnerHTML skips escaping: never for user text
<div dangerouslySetInnerHTML={{ __html: userInput }} />

When you really need HTML: a sanitizer

Sometimes a comment may contain bold and italic text. Escaping would show <b> as text, not as bold text. So here you use an allowlist sanitizer: a library that cleans HTML with a list of allowed tags and drops everything else. Here is an example with DOMPurify:

import DOMPurify from "dompurify";

const comment = "<b>Budi</b> <img src=x onerror=alert(1)>";
const clean = DOMPurify.sanitize(comment, { ALLOWED_TAGS: ["b", "i"], ALLOWED_ATTR: [] });
console.log(JSON.stringify(clean)); // "<b>Budi</b> "
box.innerHTML = clean;

💡 CSP: the last safety net

Content Security Policy (CSP) is a response header that tells the browser which scripts may run:

Content-Security-Policy: script-src 'self' 'nonce-abc123'

CSP is a safety net, not a replacement for escaping. The Content Security Policy lesson covers it in detail.

⚠️ Escaping in the wrong order or the wrong place

TL;DR: Turn user data into text right where it is placed. In HTML, escape five characters with entities (codes the browser shows as ordinary characters): & to &amp; (first), < to &lt;, > to &gt;, " to &quot;, ' to &#39;. In attributes, always use quotes; in URLs, use encodeURIComponent. PHP: htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8'). In Blade (Laravel's templates), {{ }} escapes automatically, and {!! !!} prints raw. When user data really may contain HTML, use an allowlist sanitizer such as DOMPurify, which lets only the tags on its list through. CSP (a header that limits which scripts may run) is the last safety net, not a replacement for escaping.

⚡ Five characters, & first

Write:

return input
  .replace(/&/g, "&amp;") // must come first
  .replace(/</g, "&lt;")
  .replace(/>/g, "&gt;")
  .replace(/"/g, "&quot;")
  .replace(/'/g, "&#39;");
Guess first: if < is replaced before &, what does a & b < c become?

a &amp; b &amp;lt; c. < has already become &lt;, and then the & of &lt; gets replaced too. The page shows the text &lt;, not a < sign.

Meaning: input is the text from a user. Escaping writes HTML's five special characters as entities (codes the browser shows as ordinary characters), so the browser doesn't open a tag. & is replaced first because every entity starts with &.

⚡ The defence depends on the place

Meaning: In element content, escape those five characters. In an attribute value, escape too, and always use quotes. In a URL, use encodeURIComponent, which turns & into %26 and a space into %20.

⚡ Let the template escape

Write:

<p>{{ $comment->body }}</p>   {{-- safe: escaped --}}
<p>{!! $comment->body !!}</p> {{-- dangerous: printed raw --}}

Meaning: $comment->body is the comment text from a user. In Blade (Laravel's template engine), {{ }} calls htmlspecialchars, PHP's escape function, automatically. {!! !!}, like React's dangerouslySetInnerHTML, prints raw with no escaping, so never use them for user data.

⚡ When HTML really is allowed

Meaning: When a comment may contain tags like <b>, use an allowlist sanitizer such as DOMPurify. It lets only the tags on its list through and drops the rest. CSP (a header that tells the browser which scripts may run) is the last safety net, not a replacement for escaping.

What you will learn