download

Regex strips <script> tags. Why does XSS still run?

Security~10 minReviewed 3 Dec 2026Free · No sign-in

Question

A profile view renders three untrusted strings: name in HTML text, site in <a href="...">, and bio inside an inline JSON <script> tag. The starter strips <script> tags with a regex. Attackers still execute JavaScript via <img src=x onerror=alert(1)>, javascript:alert(1) in site, and </script><img src=x onerror=alert(1)> in bio.

  1. Why do regex tag denylists fail across HTML, URL, and JSON contexts?
  2. Rewrite render_profile(name, site, bio) using context-aware encoding and a strict http/https scheme allowlist.
  3. How does a strict nonce-based Content Security Policy (CSP) add defense in depth?
"CODE · PYTHON"
import json
import re


def render_profile(name, site, bio):
    def clean(s):
        return re.sub(r"</?script[^>]*>", "", s, flags=re.I)
    return (
        f"<p>{clean(name)}</p>"
        f'<a href="{clean(site)}">Site</a>'
        f'<script type="application/json">{json.dumps({"bio": bio})}</script>'
    )
Show hints (3)
  1. "THREE OUTPUT CONTEXTS"

    HTML body text, an <a href> URL, and inline JSON inside <script> each follow different browser parsing rules. One encoder cannot cover all three.

  2. "ESCAPE AND ALLOWLIST"

    Use html.escape(..., quote=True) for HTML text and quoted attributes. Parse site with urlparse to allow only http or https, and escape < as \u003c inside JSON.

  3. "STRICT NONCE CSP"

    A strict Content-Security-Policy with a fresh per-request nonce (script-src 'nonce-...' 'strict-dynamic') blocks injected inline handlers even if one template escapes wrongly.

Show checked explanation

Regex tag denylists miss event handlers (<img src=x onerror=...>), javascript: URLs, and </script> inside inline JSON. Encode every value for its exact output context: html.escape(..., quote=True) for HTML text and quoted attributes, an http/https allowlist for href, and < escaped to \u003c inside inline JSON. Layer a strict nonce-based CSP as defense in depth.

"SOLUTION · PYTHON"
import html
import json
from urllib.parse import urlparse


def safe_url(raw):
    u = urlparse(raw.strip())
    return raw.strip() if u.scheme in ("http", "https") and u.netloc else "#"


def render_profile(name, site, bio):
    href = html.escape(safe_url(site), quote=True)
    data = json.dumps({"bio": bio}).replace("<", "\\u003c")
    return (f"<p>{html.escape(name, quote=True)}</p>"
            f'<a href="{href}">Site</a>'
            f'<script type="application/json">{data}</script>')


print(render_profile("<img src=x onerror=alert(1)>",
                     "javascript:alert(1)", "</script>hi"))
"OUTPUT"
<p>&lt;img src=x onerror=alert(1)&gt;</p><a href="#">Site</a><script type="application/json">{"bio": "\u003c/script>hi"}</script>

Author-checked on CPython 3.12.10 against synthetic HTML, URL-scheme, quoted-attribute breakout, and inline-JSON breakout fixtures plus stdlib HTMLParser checks; official OWASP, MDN, and Python html links checked. Checked by an editor other than the author.

Walkthrough

Browsers parse an HTML document with several nested parsers at once. Stripping <script> with a regex leaves dozens of other execution paths wide open:

contextbypass payloadwhy starter failscontext-aware defense
HTML text (name)<img src=x onerror=alert(1)>No <script> tag to striphtml.escape(name, quote=True) turns < into &lt;
Link URL (href)javascript:alert(1)HTML escaping alone still allows javascript:Allow only http/https with urlparse, then html.escape
Inline JSON (bio)</script><img ...>HTML parser closes <script> before JSON parser runsjson.dumps(...) plus .replace("<", "\\u003c")

Match the encoder to the exact slot.

  1. HTML body and quoted attributes: html.escape(val, quote=True) escapes &, <, >, ", and '. That neutralizes injected tags and stops " onclick="... from escaping a quoted href="..." attribute.
  2. URL attributes (href, src): html.escape("javascript:alert(1)", quote=True) returns the exact same string, so clicking the link still executes JavaScript. Parse with urlparse, require u.scheme in ("http", "https") and a non-empty u.netloc, fall back to "#", and still HTML-escape the result.
  3. Inline JSON in <script>: The HTML parser scans for literal </script> before JavaScript ever reads the JSON. Replacing < with \u003c breaks every </script> and <!-- sequence while remaining valid JSON that JSON.parse decodes back to "</script>hi".

Add a strict nonce-based CSP as a second wall. Send a fresh random nonce per response:

"HTTP"
Content-Security-Policy: default-src 'self'; script-src 'nonce-9f3a8c21' 'strict-dynamic'; object-src 'none'; base-uri 'none'

Only <script nonce="9f3a8c21"> blocks run. Injected inline event handlers (onerror=...) and javascript: links are blocked by the browser even if one template misses an escape. Never reuse a static nonce across responses.

Common mistakes

  • HTML-escaping site inside href without checking the URL scheme. javascript:alert(1) has no < or ", so html.escape leaves it runnable.
  • Passing raw json.dumps(data) into an inline <script> block. The browser's HTML parser closes the block at the first literal </script> inside a JSON string.
  • Adding 'unsafe-inline' or broad CDN wildcards to script-src, which lets injected handlers or JSONP gadgets bypass the CSP.
  • Reusing one cached CSP nonce across users or responses. An attacker who reads the nonce once can stamp it onto injected tags.

Follow-up questions

  • "Why does a strict nonce-based CSP not replace context-aware output encoding?" CSP limits JavaScript execution, not HTML injection. Unescaped input can still inject fake login forms, phishing links, or dangling markup that steals tokens, and older clients or misconfigured endpoints may drop the header.
  • "How do you safely render user-authored rich HTML like Markdown previews?" Parse the HTML into a DOM tree with a vetted allowlist sanitizer, such as DOMPurify on the client or a tree-based server sanitizer. Keep only safe tags and attributes, and strip event handlers and javascript: URLs. Never sanitize rich HTML with regexes.
  • "Why does render_profile escape safe_url(site) with html.escape(..., quote=True) even after checking https?" A URL like https://ok.example/" onclick="alert(1) passes the https scheme check. Escaping quotes keeps the string trapped inside the double-quoted href attribute.

What a strong answer covers

Explains why regex tag stripping fails in HTML, URL, and inline-JSON contexts. Applies html.escape(..., quote=True), strict http/https scheme allowlisting, and \u003c JSON escaping, then layers a fresh per-response nonce CSP without 'unsafe-inline'.

Open in interactive practice deck →

Original OfferVibe question. OWASP XSS Prevention Cheat Sheet · OWASP CSP Cheat Sheet · MDN Content-Security-Policy · Python html.escape.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.