DEV Community

Cover image for Mitigating DOM clobbering attacks in JavaScript
SnykSec for Snyk

Posted on • Originally published at snyk.io

Mitigating DOM clobbering attacks in JavaScript

The Document Object Model (DOM) acts as an interface between HTML and JavaScript, bridging the gap between static content and dynamic interactivity. This function makes the DOM indispensable for modern web developers.

However, the DOM has a pitfall — DOM clobbering. DOM clobbering occurs when HTML elements conflict with global JavaScript variables or functions, which can lead to unexpected behavior and a potential security loophole in your web application.

Addressing the issue requires diligent programming practices, substantive knowledge of JavaScript, and a firm grasp of web application security. This article explores the concept of DOM clobbering and provides strategies for building more secure and robust web applications.

How DOM clobbering occurs

Every HTML element can have a unique ID or name attribute for easy reference to specific elements in JavaScript. For example, the following HTML button has an ID attribute with the value "myButton":

Click Me!
Enter fullscreen mode Exit fullscreen mode

We can use this ID in our JavaScript code to manipulate the button by, for example, changing its text when clicked:

document.getElementById('myButton').onclick = function() {
    this.textContent = 'Clicked!';
};
Enter fullscreen mode Exit fullscreen mode

The DOM facilitates this interaction between HTML and JavaScript. But what happens if the HTML element’s ID or name attribute conflicts with a global JavaScript variable or function?

When a browser loads an HTML page, it automatically creates global JavaScript variables for every ID and name attribute in the HTML DOM. If we have an HTML element named "myButton", the browser makes a global JavaScript variable, myButton, referencing that HTML element.

Now, let’s consider a scenario in which we’ve declared a JavaScript function named myButton:

function myButton() {
    // some code
}
Enter fullscreen mode Exit fullscreen mode

But we also have an HTML element with the ID or name "myButton". When the page loads, the browser’s automatic process overwrites the JavaScript function myButton with reference to the HTML element:

Click Me!

console.log(myButton); // This will log the HTML button element, not the function
Enter fullscreen mode Exit fullscreen mode

This process is DOM clobbering, which may cause unpredictable behavior and security vulnerabilities. If an attacker can control the attributes, they may be able to inject malicious code into the webpage, leading to security issues like cross-site scripting (XSS).

To illustrate, consider the following scenario:

Enter your name: 
Greet

function greet() {
    var username = document.getElementById('username').value;
    alert(`Hello ${username}`);
}
Enter fullscreen mode Exit fullscreen mode

An attacker could type something like ![](x), creating a new HTML component with an 'id' of 'alert'. This component replaces — or clobbers — the normal alert function in JavaScript. The next time the website tries to use this function, it won’t work properly and could even run malicious code.

Identifying DOM clobbering vulnerabilities

Consider a basic web application with a user feedback form. Users input their name and a feedback message, then submit it. The page displays the feedback:

HTML:

Feedback Form
-------------



 Name:  



 Feedback:  







Enter fullscreen mode Exit fullscreen mode

JavaScript:

document.querySelector('form').onsubmit = function(event) {
    event.preventDefault();

    let name = document.getElementById('name').value;
    let feedback = document.getElementById('feedback').value;

    let feedbackElement = document.getElementById('feedbackDisplay');

    feedbackElement.innerHTML = `**${name}**: ${feedback}

`;
};
Enter fullscreen mode Exit fullscreen mode

This code takes the user’s name and feedback and displays it in a paragraph element within the feedbackDisplay div.

An attacker could exploit this code by submitting HTML in the feedback form. For example, if they entered the following code in the name field and submitted the form, the feedback display area would be replaced by the script tag:

window.location.href='http://maliciouswebsite.com';
Enter fullscreen mode Exit fullscreen mode

When the form attempts to display the next piece of feedback, it would instead execute the script, redirecting the user to a malicious website.

This scenario creates a vulnerability because the application takes user-provided input to create HTML, generating a script tag with the same ID as an existing element. This is an example of DOM clobbering with serious consequences — the attacker can gain control of the user’s browser, which enables them to steal sensitive data or install malware.

Secure coding practices to prevent DOM clobbering

With a deeper understanding of these vulnerabilities, we can move on to some best practices that mitigate the risk of DOM clobbering.

Properly scope variables and functions

One of the most common causes of DOM clobbering is misusing global scope in JavaScript. By defining variables and functions within a specific scope, we can restrict overwriting to that scope or any nested scopes and minimize potential conflicts. 

Let’s apply JavaScript’s scoping rules and refactor the previous example to show how this can be done:

(function() {
    // All variables and functions are now in this function's scope
    const form = document.querySelector('form');
    const feedbackElement = document.getElementById('feedbackDisplay');

    form.onsubmit = function(event) {
        event.preventDefault();

        const name = document.getElementById('name').value;
        const feedback = document.getElementById('feedback').value;

        // Sanitize user input
        name = DOMPurify.sanitize(name);
        feedback = DOMPurify.sanitize(feedback);

        const newFeedback = document.createElement('p');
        newFeedback.textContent = `${name}: ${feedback}`;
        feedbackElement.appendChild(newFeedback);
    };
})();
Enter fullscreen mode Exit fullscreen mode

Note: We’ve used DOMPurify to sanitize the HTML in the above code block. You can install it in Node.js with npm install dompurify. Include it in your HTML with .

In this version of the code, we’ve enclosed everything inside an Immediately Invoked Function Expression (IIFE), which creates a new scope. The form and feedbackElement variables and the function assigned to the onsubmit event handler are not in the global scope, so they can’t be clobbered.

Use unique identifiers

Ensuring every element on our webpage has a unique ID reduces the risk of inadvertently overwriting an important function or variable. Also, avoid using common names or names that might conflict with global JavaScript objects or functions.

Avoid global namespace pollution

Keeping the global namespace clean is a vital aspect of writing secure JavaScript. The more variables and functions in the global scope, the greater the risk of DOM clobbering. Use JavaScript’s function scope or ES6’s block scope to keep your variables and functions contained. Here’s an example using the latter:

    // All variables and functions are now in this block's scope
    let form = document.querySelector('form');
    let feedbackElement = document.getElementById('feedbackDisplay');

    form.onsubmit = function(event) {
        event.preventDefault();

        let name = document.getElementById('name').value;
        let feedback = document.getElementById('feedback').value;

        // Sanitize user input
        name = DOMPurify.sanitize(name);
        feedback = DOMPurify.sanitize(feedback);

        let newFeedback = document.createElement('p');
        newFeedback.textContent = `${name}: ${feedback}`;
        feedbackElement.appendChild(newFeedback);
    };
Enter fullscreen mode Exit fullscreen mode

In this code, we used a block (defined by the {}) to create a new scope. All variables and functions are now confined to this block and are not in the global scope.

Note: The code examples in this guide are simplified for demo purposes and not intended for use in a production website or app.

Using JavaScript features to mitigate DOM clobbering

Modern JavaScript provides several features that help minimize the risk of DOM clobbering. In particular, the let and const keywords introduced in ES6 offer more control over declaring variables.

Traditionally, we’ve declared JavaScript variables using the var keyword. However, var has a few quirks, one of which is that it doesn’t have block scope — only function scope and global scopes. This means a variable declared with var can be accessed and overwritten outside the block where we declared it.

On the other hand, let and const both have block scope, meaning they’re only accessible within the block in which they were declared. This characteristic often makes them a better choice for variable declaration, as it limits the possibility of overwritten variables.

We can also use const to declare constants — values we can’t change after assigning them. They represent another useful tool for preventing unintended changes to important variables.

Let’s look at how to implement these features in our feedback form code to prevent DOM clobbering:

    const form = document.querySelector('form');
    const feedbackElement = document.getElementById('feedbackDisplay');

    form.onsubmit = function(event) {
        event.preventDefault();

        const name = document.getElementById('name').value;
        const feedback = document.getElementById('feedback').value;

        // Sanitize user input
        name = DOMPurify.sanitize(name);
        feedback = DOMPurify.sanitize(feedback);

        const newFeedback = document.createElement('p');
        newFeedback.textContent = `${name}: ${feedback}`;
        feedbackElement.appendChild(newFeedback);
    };
Enter fullscreen mode Exit fullscreen mode

In this code, we replaced all uses of var with const. We confined all variables to the block in which we declared them, and the constants cannot be overwritten.

Remember that using let and const does not eliminate the risk of DOM clobbering, but the practice remains a critical aspect of secure coding. Understanding and implementing these JavaScript features can make your web applications more secure.

Monitoring and detecting DOM clobbering vulnerabilities

Secure coding practices can help prevent DOM clobbering, but detecting vulnerabilities when they arise is equally critical. Let’s look at some tools and techniques that can help.

Static code analysis

Static application security testing (SAST) tools like Snyk Code can effectively detect potential security vulnerabilities, including DOM clobbering. These tools analyze your source code without executing it, identifying patterns that could lead to security issues. Snyk’s comprehensive JavaScript coverage makes it an excellent choice for web developers.

Browser developer tools

Browser developer tools, such as those available in Chrome or Firefox, can be powerful allies in detecting DOM-clobbering vulnerabilities. 

Let’s walk through a brief example of how to use these tools to identify a potential issue:

  1. On your webpage, right-click anywhere and select Inspect to open developer tools. You can also use Ctrl+Shift+I on Windows or Cmd+Option+I on macOS.
  2. Navigate to the Console tab, where JavaScript errors or logs are displayed.
  3. Type “window” into the console and press Enter to examine the global scope with all global variables and functions. Check for any variables that seem out of place, especially those with the same name as your HTML element IDs or names.
  4. Using the Elements tab, edit the HTML of the page to manipulate the DOM and test for potential vulnerabilities. For example, add an element with an ID that matches a global variable or function to see if it gets overwritten.

Conclusion

This article has explained how DOM clobbering happens, its associated dangers, and how to guard against it. Implementing proper variable scoping, using unique identifiers, and correctly selecting JavaScript’s let and const features are crucial for mitigating this vulnerability. 

Maintaining code security requires balancing prevention and detection efforts. Using recommended coding practices, browser developer tools, and a SAST solution like Snyk can help pinpoint existing and potential issues. 

By incorporating these techniques into your JavaScript applications and staying updated on web application security trends, you can remain proactive in securing your coding practices.

Top comments (0)