
Filtering Input Won't Stop XSS: Encode Output for Its Context
- كاتب موثّق
- OWASP Top 10 2025
محتويات المقال
<script> tags before a review is saved. A unit test proves it: <script>alert(1)</script> is stored as an empty string. Months later, a moderator opens the review queue and an alert box pops up. The review behind it has no script tag at all, just an image that fails to load and an onerror attribute.
The common misconception
<script> tags from user input when it's saved, and the stored data is clean, so every page that shows it is safe.
<script> tag, so removing script tags feels like removing the attack. "Validate input" is solid advice in general, and one filter at the door is easier to own than every template in the app. The tests pass, because they test the payload the filter was written for. And the filter does stop that one payload. Everything else HTML can execute walks around it.
What actually happens
XSS is decided at output, by the browser
A script tag is one of many ways in
javascript: URLs, inline styles and more. A filter is a list of what you thought of. We ran the filter from the story on three inputs:
input <script>alert(1)</script>Great productsaved Great productinput <img src=x onerror=alert(1)>Great productsaved <img src=x onerror=alert(1)>Great productinput <scr<script></script>ipt>alert(1)</script>saved <script>alert(1)</script>innerHTML, the second one fired its alert. In a server template that doesn't encode, the second and third both fired. Set with textContent, none did, and the page showed the characters exactly as typed.
At save time, you don't know where the data will go
title attribute, a link, a JSON blob inside a script, an email or a mobile app. Each has different rules, so no single cleanup on save is right for all of them. And data reaches the database without passing your filter: imports, other services, rows written before the filter existed. Microsoft's guidance counts "even data sourced from a database" as untrusted, and states the accepted practice: "encoding takes place at the point of output and encoded values should never be stored in a database."
Each context needs its own encoding
< into < in HTML text, protects quotes in an attribute, and percent-encodes a URL parameter. Some places can't be made safe at all: OWASP lists inline scripts, inline CSS and HTML comments as dangerous contexts where you shouldn't put untrusted data, even encoded.
Render the review safely
// Runs when the review is savedexport function stripScripts(text: string): string { return text.replace(/<script[\s\S]*?<\/script>/gi, "");}// Runs when the page shows it: stored text is parsed as HTMLexport function renderReview(card: HTMLElement, review: Review): void { card.innerHTML = `<h3>${review.author}</h3><p>${review.text}</p>`;}// Saved as typed; protection happens here, at outputexport function renderReview(card: HTMLElement, review: Review): void { const author = document.createElement("h3"); author.textContent = review.author; // a text node, never parsed const text = document.createElement("p"); text.textContent = review.text; const link = document.createElement("a"); link.textContent = "Website"; link.href = safeUrl(review.website); // URLs need a scheme check card.replaceChildren(author, text, link);}function safeUrl(raw: string): string { try { const url = new URL(raw); return ["https:", "http:"].includes(url.protocol) ? url.href : "#"; } catch { return "#"; }}dangerouslySetInnerHTML, Angular's bypassSecurityTrust* functions, Html.Raw and HtmlString. When users really must author HTML, sanitize it at output with a maintained library; OWASP recommends DOMPurify.
<p>…</p> | textContent | |
title="…" | ||
href="…" | https: and http: only, then encode | |
?q=… | encodeURIComponent | |
<script> or <style> | var x = '…' | data- attribute |
How to apply it in your project
Stop rewriting input on save Validate format, such as length, type or an allowed set of values, and store the text as typed. Never store HTML-encoded values. Let the framework encode Render with JSX, Angular templates or Razor, and treat every escape hatch as a review item that needs a written reason. Encode for the context Use text APIs in the DOM, quote attributes, encodeURIComponentfor URL parts, and an allow-list of schemes for any URL a user supplies.Sanitize only where HTML is required For rich text, run DOMPurify at render time and keep it updated, or accept Markdown and render it without raw HTML. Add a strict CSP Start with script-src 'nonce-…'; object-src 'none'; base-uri 'none'in report-only mode, fix what it reports, then enforce it.
Key takeaways
XSS is decided where data is rendered: the browser parses it as code or as text. Stripping <script>tags misses event handlers,javascript:URLs and the filter's own leftovers.Store input as typed, and encode at output for the exact context: HTML, attribute, URL or none. Trust your framework's default encoding, and audit every escape hatch. A strict CSP limits the damage when a bug slips through; it never replaces encoding.
التعليقات (0)