Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 80 ยท Web Application Security

Cross-Site Scripting and Output Encoding

Understand reflected, stored and DOM-based XSS, why context-aware output encoding is the main defense, and how sanitizers and CSP add extra layers.

Cross-site scripting (XSS) happens when a web page includes data from an attacker in its HTML in a way that the browser runs as code. The browser trusts everything a page delivers, so a script injected into your page runs with all the powers of your page: it can read what the user sees, make requests as them, change the page to show a fake login form, or read data that JavaScript can reach. It is the browser-side cousin of SQL injection: data crosses into the code channel.

The central defense is output encoding: when you put untrusted data into a page, convert it so the browser treats it as text, in the way that is correct for where you are putting it. In this lesson you will learn the three types of XSS, see encoding work with Python's html.escape, learn why context matters, and add sanitizers and Content Security Policy as extra layers. The examples only generate and inspect strings; nothing executes any script.

The three kinds of XSS

  • Reflected XSS. The payload is part of the request (a query string or form field) and the server immediately echoes it into the response. The attacker must get the victim to open a crafted link, for example /search?q=<payload>.
  • Stored XSS. The payload is saved (a comment, profile name, support ticket) and served to everyone who views it later. This is the most dangerous kind because no crafted link is needed. A hostile comment on a popular page can hit thousands of visitors.
  • DOM-based XSS. The server's HTML is harmless, but JavaScript in the page reads attacker-influenced data (the URL fragment, location, postMessage) and writes it into the page with something like innerHTML. The payload may never reach the server at all.
flowchart TD
    A["Attacker supplies payload"] --> B{"Where does it travel?"}
    B -->|"In a crafted link"| C["Reflected:<br/>server echoes it back"]
    B -->|"Saved in a database"| D["Stored:<br/>served to every viewer"]
    B -->|"URL fragment or message"| E["DOM-based:<br/>page script writes it into the DOM"]
    C --> F["Browser runs it as part of your page"]
    D --> F
    E --> F

All three end the same way: the browser mistakes attacker data for your own code.

Why it is so powerful

Because the injected script runs in your site's origin, the browser's same-origin policy treats it as you. It can send requests with the victim's cookies, read anything shown on the page (including anti-forgery tokens, which is why XSS defeats CSRF protection), capture what the user types and change what they see. Cookies marked HttpOnly cannot be read by scripts, which protects the session cookie itself, but an attacker's script can still act as the user while the page is open. So HttpOnly limits damage; it does not fix XSS.

Output encoding with html.escape

Encoding replaces the characters that have special meaning in HTML with entities. In HTML text, the important ones are <, > and &; in attribute values, quotes too. Python's html.escape does this.

Python Rendering a comment unsafely and safely

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.

After escaping, <script> becomes &lt;script&gt;. The browser displays the characters instead of treating them as a tag. Most template engines (Jinja2 with autoescape, Django templates, Blade {{ }}, React JSX) do this by default. XSS usually appears when someone turns that off (|safe, {!! !!}, dangerouslySetInnerHTML) or builds HTML by hand.

Context matters

One encoding does not fit all places. Where the data lands decides which characters are dangerous:

  • HTML text: encode <, >, &.
  • Quoted attribute value: also encode the quote characters, and always quote attributes. An unquoted attribute can be broken by a space.
  • URL attribute (href, src): validate the scheme with an allow-list (https, http, mailto). javascript: URLs run code even if the characters are perfectly escaped.
  • JavaScript string or inline script: avoid putting untrusted data there at all. If you must, pass it as JSON in a data- attribute or a JSON script block.
  • CSS: do not put untrusted data into style sheets or style attributes.

The next demo shows a URL-scheme check and why html.escape alone is the wrong tool for links.

Python Context-aware output: links and attributes

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.

Notice the third example: URL schemes are case-insensitive, so the check lowercases. Notice also the last link: the quote that would have closed the href attribute is turned into &quot;, so it stays inside the value.

Sanitizers: when users may submit HTML

Sometimes users are meant to supply HTML, for example in a rich-text editor. Encoding would show the tags as text, so instead you use a sanitizer that parses the HTML and keeps only an allow-list of safe tags and attributes. Rules for using one:

  • Use a well-maintained library (DOMPurify in the browser, nh3 or bleach in Python, HTMLPurifier in PHP). Never write your own with regular expressions; HTML parsing is full of tricks that regexes miss.
  • Sanitize on output, or on input and output, and keep the sanitizer updated.
  • Prefer a restricted format such as Markdown, rendered by a library that escapes raw HTML, when users do not truly need HTML.

To see why a naive "remove script tags" filter fails, try the one below. It is a bad filter built on purpose so you can see how it is bypassed; it is the thing not to do.

Python Why blacklist filters fail

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 nested trick <scr<script>ipt> becomes a real <script> tag after the filter removes the inner one, and the <img onerror> payload does not contain the word at all. Encoding handles all three because it never tries to guess what is bad.

Content Security Policy as a safety net

A Content Security Policy (CSP) is an HTTP header that tells the browser which sources of scripts, styles and other resources are allowed. Even if an attacker injects a script tag, a strict policy can stop the browser from running it. A solid starting point:

HTTP
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-R4nd0m'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'
  • default-src 'self' allows resources only from your own origin by default.
  • script-src with a nonce (a fresh random value for each response, added to your legitimate <script nonce="..."> tags) lets only your tagged scripts run. Inline event handlers and unsigned inline scripts are blocked.
  • object-src 'none' and base-uri 'none' close off old plugin and base-tag tricks.
  • frame-ancestors 'none' stops other sites framing yours.

Avoid 'unsafe-inline' in script-src, which gives away most of the benefit. Roll a policy out in Content-Security-Policy-Report-Only mode first to see what it would break. CSP is a second line of defense: encode output and send a CSP. The full set of headers is covered in HTTP Security Headers.

DOM-based XSS: safe sinks

In client-side code, the dangerous "sinks" are innerHTML, outerHTML, document.write, eval, setTimeout with a string and location assignment with untrusted data. Safe alternatives are textContent (treats the value as text) and setAttribute for harmless attributes. If you need HTML, run it through a sanitizer first. Newer browsers also support Trusted Types, which lets a CSP require that dangerous sinks receive only values created by an approved policy.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which type of XSS is stored in the application and affects everyone who views the page?

    Stored XSS saves the payload (for example in a comment) and delivers it to every viewer, so it needs no crafted link.
  2. 2. What is the primary defense against XSS?

    Encoding makes the browser treat data as text. Blacklist filters are easily bypassed, as the nested-tag example showed.
  3. 3. Why is html.escape alone not enough for <a href="...">?

    The scheme itself is the problem, so URLs must be checked against an allow-list of schemes such as http, https and mailto.
  4. 4. What does a nonce-based Content Security Policy do?

    An injected script has no valid nonce, so the browser refuses to execute it. CSP is a safety net on top of encoding.
  5. 5. In browser JavaScript, which is the safer way to show untrusted text?

    textContent inserts the value as plain text, so it can never create elements or run scripts.

Summary

  • XSS makes the browser run attacker data as code on your origin; the types are reflected, stored and DOM-based.
  • The main defense is output encoding that matches the context: HTML text, attribute, URL, JavaScript.
  • Rely on auto-escaping templates and treat any opt-out (|safe, innerHTML, dangerouslySetInnerHTML) as a red flag.
  • Validate URL schemes with an allow-list; never trust javascript: links.
  • Use a maintained sanitizer when users may submit HTML, and never write regex filters.
  • Add a strict CSP with nonces, HttpOnly cookies and safe DOM sinks as extra layers.

Next: CSRF, SameSite and CORS, about attacks that make the user's browser send requests the user never intended.