Перейти к основному содержимому
Cross-Site Scripting (XSS): Reflected, Stored & DOM
Урок 5 из 18

Cross-Site Scripting (XSS): Reflected, Stored & DOM

Understand how reflected, stored, and DOM-based XSS turn untrusted input into executable JavaScript in a victim's browser, how to verify injection contexts in a lab, and how context-aware encoding and CSP block it.

Средний 28 мин Веб-безопасность
Этого урока пока нет на выбранном языке — показана версия на другом языке. Перевод готовится.
Только в разрешённой среде — Описанные здесь приёмы применяются только в учебных лабораториях и в системах, которые принадлежат вам или на которые есть письменное разрешение.

Цели обучения

  • Explain why mixing untrusted data into HTML, attribute, or script contexts lets attackers run JavaScript under a site's origin
  • Distinguish reflected, stored, and DOM-based XSS by tracing the source and sink of untrusted input
  • Verify injection contexts safely in an authorised lab using Browser DevTools and Burp Suite
  • Prevent XSS with context-aware output encoding, safe DOM APIs, HttpOnly cookies, and Content Security Policy

Рекомендуется заранее: HTTP-запросы и ответы, cookie и управление сессиямиHTML/JS Execution, Same-Origin Policy, CORS & CSP

#Why this matters

Just as SQL injection happens when user data is parsed as database code, Cross-Site Scripting (XSS) happens when untrusted data is parsed as browser code. When a web page inserts input into HTML, attributes, URLs, or JavaScript without proper escaping, the browser treats that data as executable markup or script.

Because the injected script runs inside the victim's browser under the site's origin, the Same-Origin Policy treats it as trusted application code. It can read the DOM, steal anti-CSRF tokens, send authenticated fetch() requests, and access cookies that lack HttpOnly. Even with HttpOnly, the script can still perform actions inside the victim's session.

#Three ways XSS reaches the browser

XSS falls into three types based on where input is stored and how it reaches the browser.

Type Where payload lives How it triggers Visible in server logs
Reflected URL parameter, form field, or header in one request Victim opens a crafted link or form Yes
Stored Database, profile, or log entry on the server Any user or admin views the rendered page Yes, on submission
DOM-based Client-side source (location.hash, location.search) Browser JS writes the source to a sink Not always (fragments stay local)
Stored XSS hitting an administrator sessionStored XSS hitting an administrator sessionAttackerAppDatabaseAdminPOST /comment (unescaped script payload)Save comment textGET /moderate (loads pending comments)200 OK (HTML with raw comment text)Admin browser runs script under app origin

In reflected and stored XSS, the server's response already contains the untrusted payload. In DOM-based XSS, the server delivers a static page, and client-side JavaScript copies a controllable source into an unsafe sink. Fragments after # (location.hash) stay in the browser and never reach server logs or WAFs.

In veb-tahlil labs, a simulated admin bot often visits a submitted URL or saved post. Knowing what the bot executes and whether HttpOnly or CSP blocks access is central to both testing and defence.

#Contexts, sources, and sinks

Testing begins by finding where input lands, not by pasting one payload everywhere. Sending a harmless canary like probe99 lets you inspect the surrounding syntax in Browser DevTools or Burp Suite Repeater.

Each execution context breaks out differently:

  1. HTML body: Between element tags, angle brackets (<, >) open a new element such as an img element with an onerror attribute or an inline script element.
  2. Quoted attribute: Inside value="probe99", angle brackets stay inside the string until you close the double quote ("), then add an event handler such as onfocus with autofocus, or close the element.
  3. URL and JS contexts: Inside href, javascript:alert(1) runs on click even when <, >, and quotes are HTML-encoded. Inside a JavaScript string literal, closing the quote breaks into code execution without angle brackets.
  4. DOM sink: Even on a static page, JavaScript can read a source (location.search, location.hash, document.referrer) and pass it to an unsafe sink (innerHTML, outerHTML, document.write(), eval()).
javascript
// Vulnerable DOM flow: source -> sink
const params = new URLSearchParams(location.search);
document.getElementById("greeting").innerHTML = "Hello, " + params.get("name");
document.getElementById("profile-link").setAttribute("href", params.get("next"));
Probing a reflected parameter in a lab (authorised range only)
$ curl -s "http://lab.local/search?q=probe99%3C%3E%22%27" | grep probe99
  search_value = value="probe99&lt;&gt;"'"

Here < and > were encoded as &lt; and &gt;, blocking a new element tag. However, the raw double quote " inside value="..." still lets an attacker break out and inject " onfocus="alert(1)" autofocus=".

#Defending against XSS

Effective defence treats untrusted input strictly as data across both server templates and browser JavaScript.

  • Context-aware output encoding: Encode right before rendering for the exact context. Use HTML entity encoding (&lt;, &gt;, &amp;, &quot;, &#x27;) for HTML text and quoted attributes. For links (href, src), enforce an http: or https: allow-list so javascript: and data: URLs are rejected. Template engines (Jinja2 autoescape, React JSX) encode HTML text and attributes by default unless bypassed with |safe or dangerouslySetInnerHTML.
  • Safe DOM APIs: Avoid innerHTML, outerHTML, document.write(), and eval(). Use textContent or innerText so the browser inserts literal text.
javascript
// Safe text insertion and URL allow-list check
const params = new URLSearchParams(location.search);
document.getElementById("greeting").textContent = "Hello, " + (params.get("name") || "guest");

const parsed = new URL(params.get("next") || "/", location.origin);
if (parsed.protocol === "http:" || parsed.protocol === "https:") {
  document.getElementById("profile-link").setAttribute("href", parsed.href);
}
  • HTML sanitization: When users must submit formatted HTML, clean it with a maintained sanitizer such as DOMPurify rather than custom regexes.
  • Defence in depth: Set HttpOnly and SameSite on session cookies to block document.cookie reads, and enforce a strict Content Security Policy (default-src 'self'; script-src 'nonce-...' 'strict-dynamic'; object-src 'none'; base-uri 'self') without unsafe-inline or unsafe-eval.

#Common mistakes

  • Keyword blocklists: Stripping the word script fails against event handlers on img (onerror) or svg (onload) elements, mixed case, or nested strings.
  • Relying on HttpOnly alone: Even when document.cookie is hidden, an XSS payload still runs inside the authenticated session and can send fetch() requests as the victim.
  • Wrong-context encoding: HTML-encoding quotes does not stop javascript:alert(1) inside an href attribute, nor is it safe inside inline JavaScript variable assignments.
  • Ignoring DOM sinks: Server-side escaping does not protect client scripts that read location.hash and assign directly to innerHTML.

#Summary

  • Reflected, stored, and DOM-based XSS execute untrusted JavaScript inside a victim's browser under the site's origin.
  • Probe with a benign canary first to identify the exact HTML, attribute, URL, or JS context, and trace sources to DOM sinks.
  • Prevent XSS with context-aware output encoding, URL allow-lists, and safe DOM APIs like textContent, reinforced by HttpOnly cookies and a strict CSP.

Проверка знаний

Войдите, чтобы проходить тест, завершать уроки и сохранять прогресс. Войти в систему

Практика: проверьте свои знания