Cross-site Scripting (DOM based)
Description
DOM-based Cross-Site Scripting (XSS) is a client-side vulnerability that occurs when a web application processes untrusted data within the browser's Document Object Model (DOM) without proper validation or sanitization. Unlike traditional XSS vulnerabilities that execute on the server, DOM-based XSS exploits client-side JavaScript code that dynamically writes user-controllable data to the page. Attackers can inject malicious scripts through URL parameters, hash fragments, or other client-side sources that are processed by vulnerable JavaScript code, causing the browser to execute arbitrary code in the context of the victim's session.
Remediation
Implement the following security measures to prevent DOM-based XSS vulnerabilities:
1. Validate and Sanitize All User Input:
• Treat all data from untrusted sources (URL parameters, hash fragments, referrer headers, postMessage data) as potentially malicious.
• Use allowlist validation to accept only expected input patterns.
2. Use Safe JavaScript APIs:
• Avoid dangerous DOM manipulation methods that interpret strings as HTML:
// UNSAFE - Avoid these methods with user input
element.innerHTML = userInput;
element.outerHTML = userInput;
document.write(userInput);
element.insertAdjacentHTML('beforebegin', userInput);• Instead, use safe alternatives that treat input as text:// SAFE - Use these methods instead
element.textContent = userInput;
element.setAttribute('attribute', userInput);
const textNode = document.createTextNode(userInput);
element.appendChild(textNode);3. Context-Aware Output Encoding:
• When user input must be inserted into HTML, JavaScript, or URLs, apply appropriate encoding for that specific context.
• Use established security libraries for encoding (e.g., DOMPurify for HTML sanitization):
// Example using DOMPurify const cleanHTML = DOMPurify.sanitize(userInput); element.innerHTML = cleanHTML;
4. Implement Content Security Policy (CSP):
• Deploy a strict CSP header to prevent inline script execution and restrict script sources:
Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none';
5. Avoid Dangerous JavaScript Patterns:
• Never use
eval(), setTimeout(), or setInterval() with string arguments containing user input.• Avoid
Function() constructor with user-controllable data.6. Regular Security Testing:
• Perform code reviews focusing on DOM manipulation and client-side data handling.
• Use automated security scanning tools to identify potential DOM XSS sinks.
• Conduct manual penetration testing with various XSS payloads.