Regex strips <script> tags. Why does XSS still run?
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.
- Why do regex tag denylists fail across HTML, URL, and JSON contexts?
- Rewrite
render_profile(name, site, bio)using context-aware encoding and a stricthttp/httpsscheme allowlist. - How does a strict nonce-based Content Security Policy (
CSP) add defense in depth?
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)
- "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. - "ESCAPE AND ALLOWLIST"
Use
html.escape(..., quote=True)for HTML text and quoted attributes. Parsesitewithurlparseto allow onlyhttporhttps, and escape<as\u003cinside JSON. - "STRICT NONCE CSP"
A strict
Content-Security-Policywith a fresh per-requestnonce(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.
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"))
<p><img src=x onerror=alert(1)></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:
| context | bypass payload | why starter fails | context-aware defense |
|---|---|---|---|
HTML text (name) | <img src=x onerror=alert(1)> | No <script> tag to strip | html.escape(name, quote=True) turns < into < |
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 runs | json.dumps(...) plus .replace("<", "\\u003c") |
Match the encoder to the exact slot.
- HTML body and quoted attributes:
html.escape(val, quote=True)escapes&,<,>,", and'. That neutralizes injected tags and stops" onclick="...from escaping a quotedhref="..."attribute. - URL attributes (
href,src):html.escape("javascript:alert(1)", quote=True)returns the exact same string, so clicking the link still executes JavaScript. Parse withurlparse, requireu.scheme in ("http", "https")and a non-emptyu.netloc, fall back to"#", and still HTML-escape the result. - Inline JSON in
<script>: The HTML parser scans for literal</script>before JavaScript ever reads the JSON. Replacing<with\u003cbreaks every</script>and<!--sequence while remaining valid JSON thatJSON.parsedecodes back to"</script>hi".
Add a strict nonce-based CSP as a second wall. Send a fresh random nonce per response:
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
siteinsidehrefwithout checking the URL scheme.javascript:alert(1)has no<or", sohtml.escapeleaves 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 toscript-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_profileescapesafe_url(site)withhtml.escape(..., quote=True)even after checkinghttps?" A URL likehttps://ok.example/" onclick="alert(1)passes thehttpsscheme check. Escaping quotes keeps the string trapped inside the double-quotedhrefattribute.
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 →