Skip to content
KALANBLON
Show contents

Chapter 5 of 7 · 20 min

XSS and input validation

By the end of this chapter, you'll be able to

  • Explain how typed content can run in other people's browsers
  • Escape data before inserting it into HTML
  • Validate input with an allowlist rather than a blocklist
  • Name the complementary protections: CSP and HttpOnly cookies

The problem

A comments page built by pasting the texts into the HTML:

comments = [
    "Great initiative, well done!",
    "<script>send(document.cookie)</script>",
]

def page(items):
    return "\n".join(f"<p>{c}</p>" for c in items)

print(page(comments))
<p>Great initiative, well done!</p>
<p><script>send(document.cookie)</script></p>

For the browser, the second line is not text: it is a <script> tag, which it runs. Here, the send function is imaginary, but a real script could pass the visitor's cookies to the attacker. And since the comment is stored, the attack hits everyone who opens the page: this is called stored XSS.

The fix: escape on output

Escaping means replacing the characters that have a meaning in HTML with their text form: < becomes &lt;, > becomes &gt;, & becomes &amp;, and quotes &quot; and &#x27;. The browser then displays these characters instead of interpreting them.

import html

comments = [
    "Great initiative, well done!",
    "<script>send(document.cookie)</script>",
]

def page(items):
    return "\n".join(f"<p>{html.escape(c)}</p>" for c in items)

print(page(comments))
<p>Great initiative, well done!</p>
<p>&lt;script&gt;send(document.cookie)&lt;/script&gt;</p>

The visitor sees the malicious comment as text, harmless. The rule: escape at display time, according to where the data goes (HTML content, attribute, URL, JavaScript). Modern template engines (React, Jinja, Twig…) escape HTML content automatically: the vulnerability comes back as soon as you bypass this mechanism, with dangerouslySetInnerHTML in React, |safe in Jinja or innerHTML in JavaScript.

Every visitor sees an odd comment, but no code runs.

Step 5 of 5
Text description of the animation
  1. A visitor posts a comment containing a script tag.
  2. The database stores the text: it is data like any other, it does not run here.
  3. Without escaping, the data becomes HTML code in the page.
  4. Escaped, it stays text: the angle brackets are displayed, not interpreted.
  5. Every visitor sees an odd comment, but no code runs.

Validating input

Escaping protects the display; validation checks, on arrival, that a piece of data has the expected form. The right approach is the allowlist: describe precisely what is allowed, and reject everything else.

import re

PHONE = re.compile(r"\+?[0-9 ]{8,16}")

for value in ["+221 77 123 45 67", "77 123 45 67", "<b>77</b>", "1234"]:
    status = "accepted" if PHONE.fullmatch(value) else "rejected"
    print(f"{value!r:>22} → {status}")
   '+221 77 123 45 67' → accepted
        '77 123 45 67' → accepted
           '<b>77</b>' → rejected
                '1234' → rejected

fullmatch requires the whole input to match the pattern: an optional +, then 8 to 16 digits or spaces. Validation is always done on the server: the browser's (the required and pattern attributes) improves the user's comfort, but an attacker can send their request without going through your form.

Extra protections

  • the Content-Security-Policy (CSP) HTTP header tells the browser where scripts are allowed to come from: with a strict policy, a script injected into the page is blocked even if escaping was forgotten;
  • session cookies marked HttpOnly cannot be read by JavaScript: an injected script cannot steal them.

These protections are safety nets, not replacements: escaping remains the main defence.

Mini-lab: escape everything that comes from outsidePython 3.13

Output

Click “Run”: Python will load in your browser (about 10 MB the first time).

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Worked exercise: the guestbook

Write a function publish(name, message) for a guestbook. The name must contain 2 to 30 characters among letters (accented ones included), spaces and hyphens; otherwise, the function returns "Name rejected". The message is accepted if it is at most 200 characters long, but it must be escaped. The function returns the HTML fragment <li><b>NAME</b>: MESSAGE</li>.

Hint 1
Python's [^\W\d_] class means a letter, accented ones included: “neither a non-word character, nor a digit, nor an underscore”.
Hint 2
Escape the name too: validation and escaping are two complementary protections.
Show the solution and common mistakes
import html
import re

NAME = re.compile(r"[^\W\d_](?:[^\W\d_]| |-){1,29}")

def publish(name, message):
    if not NAME.fullmatch(name):
        return "Name rejected"
    if len(message) > 200:
        return "Message too long"
    return f"<li><b>{html.escape(name)}</b>: {html.escape(message)}</li>"

print(publish("Aïssatou Ba", "Thanks for the workshop <3"))
print(publish("<script>", "hi"))
print(publish("Kofi", "<img src=x onerror=steal()>"))
<li><b>Aïssatou Ba</b>: Thanks for the workshop &lt;3</li>
Name rejected
<li><b>Kofi</b>: &lt;img src=x onerror=steal()&gt;</li>

Kofi's message passes validation (you cannot forbid every special character in free text), but escaping neutralises it.

Common mistakes:

  • Escaping when saving rather than on output: the stored text is distorted, and it risks being escaped twice (&amp;lt;), or not at all if it is reused elsewhere.
  • Using re.match instead of re.fullmatch: match only checks the start of the input, and Awa<script> would get through.

Summary

  1. 1XSS happens when typed data is inserted as is into an HTML page.
  2. 2Escape on output (html.escape, templates' automatic escaping), according to the context.
  3. 3Validate on arrival, on the server, with an allowlist and fullmatch.
  4. 4Tag blocklists are always bypassed.
  5. 5CSP and HttpOnly cookies limit the damage if a vulnerability gets through anyway.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.