الانتقال إلى المحتوى
الأمان (Security)OWASP Top 10· 6 دقائق للقراءة

Filtering Input Won't Stop XSS: Encode Output for Its Context

A filter on save misses most of what HTML can execute. Encode each value where it's rendered, for the place it lands, and keep CSP as the backup.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • OWASP Top 10 2025
محتويات المقال

A product page shows customer reviews. When the feature launched, a security review asked about XSS, and the team added a filter that strips <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

The belief: XSS is a dangerous-input problem. Strip <script> tags from user input when it's saved, and the stored data is clean, so every page that shows it is safe.

It sounds like good engineering. The textbook XSS example is a <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

OWASP's XSS Prevention Cheat Sheet puts it in one sentence: "XSS happens when an application puts untrusted data into a page in a way that lets the browser treat it as code." The same string is harmless in a JSON response, a text node or a CSV file, and dangerous when it's parsed as HTML. Once it runs, MDN warns, the attacker's code can do anything the site's own code can, including "Make HTTP requests with the user's credentials, enabling them to impersonate the user or access sensitive data". The OWASP Top 10 2025 files under A05 Injection, next to SQL injection, for the same reason: data reaching an interpreter that treats it as commands.

A script tag is one of many ways in

HTML runs code through event-handler attributes, 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:

text
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>

The second input passes untouched. In the third, removing the inner tag rebuilds the outer one. We then rendered each saved value in headless Chromium 156. Inserted with 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

A review may end up in an HTML paragraph, a 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

OWASP explains why there's no single fix: "There are many different output encoding methods because browsers parse HTML, JS, URLs, and CSS differently." turns < into &lt; 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

TypeScript ReviewCard.ts
// 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>`;}

Frameworks do most of this for you. MDN notes that values embedded in React's JSX "are automatically encoded", and Microsoft says Razor "automatically encodes all output sourced from variables, unless you work to prevent this behavior." The bugs live in the escape hatches: 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.

Where the value landsExampleDefense
HTML text<p>…</p>HTML encoding, or textContent
Quoted attributetitle="…"Attribute encoding, always quoted
A link or image URLhref="…"Allow https: and http: only, then encode
A query parameter?q=…encodeURIComponent
Inside <script> or <style>var x = '…'Don't; pass it in a data- attribute
User-authored HTMLRich textSanitize with DOMPurify

How to apply it in your project

  1. Stop rewriting input on saveValidate format, such as length, type or an allowed set of values, and store the text as typed. Never store HTML-encoded values.
  2. Let the framework encodeRender with JSX, Angular templates or Razor, and treat every escape hatch as a review item that needs a written reason.
  3. Encode for the contextUse text APIs in the DOM, quote attributes, encodeURIComponent for URL parts, and an allow-list of schemes for any URL a user supplies.
  4. Sanitize only where HTML is requiredFor rich text, run DOMPurify at render time and keep it updated, or accept Markdown and render it without raw HTML.
  5. Add a strict CSPStart 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.

📚 المصادر

  1. Cross Site Scripting Prevention Cheat Sheet — OWASP Cheat Sheet Series
  2. Cross-site scripting (XSS) — MDN Web Docs
  3. Content Security Policy (CSP) — MDN Web Docs
  4. A05:2025 Injection — OWASP Top 10:2025
  5. Prevent Cross-Site Scripting (XSS) in ASP.NET Core — Microsoft Learn

التعليقات (0)