Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 38 ยท Cryptographic Failures and Injection

Cross-Site Scripting and Output Encoding

Learn reflected, stored and DOM-based XSS, why output encoding by context is the main fix, and how sanitizing, HttpOnly cookies and Content Security Policy add defense in depth.

Cross-site scripting (XSS) is injection into the browser. If an application puts untrusted text into a page without making it safe, the browser may treat that text as HTML or JavaScript and run it in the context of your site. The script then has the user's cookies (unless HttpOnly), can read the page, call your APIs as the user and rewrite what the user sees. XSS was a separate Top 10 item until 2021 and is now part of Injection (A03).

The three types

Type Where the payload lives Example
Reflected In the request (URL, form), echoed immediately in the response A search page printing You searched for: <query>
Stored Saved by the server (comment, profile, message) and shown to other users later A forum post with a script that runs for every reader
DOM-based Entirely in client-side JavaScript that writes untrusted data into the page element.innerHTML = location.hash

Stored XSS is the most dangerous, since victims need not click a crafted link.

Why it works

HTML mixes markup and text. The characters <, >, &, " and ' have meaning. If user text containing <script> is inserted directly, the browser parses it as a real tag. The fix is to encode the characters that matter in the place where the data is inserted, so the browser shows them as text.

Output encoding in the HTML body

Python Escape on output

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In the safe output the dangerous characters become entities (&lt;, &gt;, &amp;, &quot;, &#x27;). The browser displays them as ordinary text and never builds an element from them.

(The demo only prints strings. Nothing here runs a script.)

Context matters

The correct encoding depends on where the data lands:

Context Example Required approach
HTML body <p>NAME</p> HTML-entity encode
HTML attribute <input value="NAME"> Encode and always quote the attribute
JavaScript data <script>var n = NAME;</script> Avoid; if needed, JSON-encode and escape </script> or pass data via data- attributes
URL parameter <a href="/q?x=NAME"> URL-encode (percent-encode) the value
URL as a whole <a href="NAME"> Validate the scheme: allow https:/http:, reject javascript:
CSS style="color: NAME" Avoid; allow-list values
Python Why a link needs scheme validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

HTML-escaping alone does not neutralise a javascript: URL, because it contains no special HTML characters. The scheme must be checked.

Use the framework's auto-escaping

Modern template engines escape by default:

  • Blade {{ $name }} escapes; {!! $html !!} does not.
  • Django and Jinja2 templates escape; |safe turns it off.
  • React escapes text in JSX; dangerouslySetInnerHTML bypasses it.
  • Vue escapes {{ }}; v-html bypasses it.

The pattern: the unsafe escape hatches are named loudly. Search your codebase for them and treat every use as a code-review item.

When users may submit HTML

If you must allow rich text (a blog editor, comments with formatting), do not hand-roll a filter. Use a proven sanitizer (DOMPurify in the browser, HTMLPurifier in PHP, nh3 or bleach in Python, OWASP Java HTML Sanitizer) with a strict allow-list of tags and attributes. Alternatively accept a safe markup such as Markdown and render it with raw HTML disabled.

Python Stand-in: a minimal allow-list idea

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The stand-in drops attributes (where onclick and onerror live) and keeps only a few harmless tags. Real sanitizers handle malformed markup, encodings and browser quirks that this toy ignores, so use one in production.

Defense in depth

Even with encoding in place, add layers:

  • Content Security Policy (CSP): a response header that restricts where scripts may load from and blocks inline script. Example: Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'none'. A strict CSP can stop an XSS that slipped through.
  • HttpOnly cookies so injected script cannot read the session cookie.
  • X-Content-Type-Options: nosniff so uploaded files are not interpreted as scripts.
  • Trusted Types (a browser feature) to lock down DOM sinks such as innerHTML.

DOM-based XSS and safe DOM APIs

On the client, prefer APIs that insert text, not markup:

JavaScript
// UNSAFE: parses the string as HTML
el.innerHTML = userInput;

// SAFE: inserts text only
el.textContent = userInput;

Treat innerHTML, outerHTML, document.write, eval and setTimeout("string") as dangerous sinks and the URL parts (location.hash, location.search) and postMessage data as untrusted sources.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which XSS type affects every visitor who views a saved comment?

    Stored XSS keeps the payload on the server, so every reader who loads the page runs it.
  2. 2. What is the main defense against XSS?

    Encoding on output turns special characters into harmless text in the context where they appear.
  3. 3. Does HTML-escaping make a user-supplied href value safe?

    A javascript: URL contains no characters that HTML escaping changes, so scheme validation is needed.
  4. 4. Which JavaScript property inserts text without parsing HTML?

    textContent treats the value as plain text, so markup is not created.
  5. 5. What does a strict Content Security Policy add?

    CSP is defense in depth: it limits which scripts the browser executes, even if an injection slips through.

Summary

  • XSS is injection into the browser: reflected, stored or DOM-based.
  • Encode untrusted data for the exact output context and rely on auto-escaping templates; avoid |safe, {!! !!}, v-html and innerHTML.
  • Validate URL schemes, sanitize any allowed HTML with a proven library and prefer textContent.
  • Add CSP, HttpOnly cookies, nosniff and Trusted Types as extra layers.

Next: Command Injection and Other Injection Types