Understanding DOM-Based Attacks
DOM-based attacks exploit vulnerabilities in client-side JavaScript code that improperly handles user input when modifying the Document Object Model. Unlike traditional server-side exploits, these attacks execute entirely in the browser, making them harder to detect and prevent. Attackers manipulate insecure data flows from sources (user-controlled input) to sinks (dangerous DOM manipulation functions) to execute malicious actions like redirection, data theft, or script injection.
Key Points
- Sources are entry points for untrusted data (e.g.,
location.hash,document.URL,document.referrer) - Sinks are dangerous JavaScript functions or properties (e.g.,
eval(),innerHTML,location) - Vulnerabilities occur when data flows from source to sink without proper validation or sanitization
- DOM-based attacks bypass server-side security controls entirely
- These attacks are client-side only, making traditional server logs ineffective for detection
How DOM-Based Attacks Work
The Attack Flow
DOM-based vulnerabilities follow a predictable pattern:
- Attacker identifies a source - User-controlled input that the application reads
- Traces data flow - Follows how the application processes this input
- Locates a dangerous sink - Finds where unvalidated data reaches a risky function
- Crafts malicious payload - Creates input that exploits the weakness
- Executes attack - Triggers the vulnerability in the victim's browser
Critical Insight: Because these attacks execute entirely client-side, server-side security measures like WAFs and input filters may not detect them.
Common Sources
| Source | Description | Risk Level |
|---|---|---|
location.hash | URL fragment after # | High |
location.search | Query string parameters | High |
document.URL | Full current URL | High |
document.referrer | Previous page URL | Medium |
window.name | Window name property | Medium |
Common Sinks
| Sink | Purpose | Why Dangerous |
|---|---|---|
eval() | Executes JavaScript code | Direct code execution |
innerHTML | Sets HTML content | Allows script injection |
document.write() | Writes to document | Can inject malicious content |
location / location.href | Navigation control | Enables phishing redirects |
setTimeout() / setInterval() | Delayed execution | Can execute arbitrary code |
DOM-Based Open Redirection Attack
Vulnerable Code Example
goto = location.hash.slice(1);
if (goto.startsWith('https:')) {
location = goto;
}
Why This Is Vulnerable
| Component | Value | Issue |
|---|---|---|
| Source | location.hash.slice(1) | Extracts user-controlled URL fragment |
| Sink | location = goto | Direct assignment without sanitization |
| Validation | goto.startsWith('https:') | Only checks protocol, not domain |
Exploitation Example
Malicious URL: https://realwebsite.com/#https://attacker.com
What happens:
- JavaScript extracts
https://attacker.comfrom the hash - Validation passes because it starts with
https: - Browser redirects to attacker's domain
- User believes the redirect is legitimate (came from trusted site)
- Attacker can now phish credentials or deliver malware
Mitigation Strategies
1. Implement Proper Input Validation
Bad approach - Protocol checking only:
if (goto.startsWith('https:')) {
location = goto;
}
Good approach - Domain whitelisting:
const allowedDomains = ['realwebsite.com', 'trusted-partner.com'];
const goto = location.hash.slice(1);
try {
const url = new URL(goto);
if (allowedDomains.includes(url.hostname)) {
location = goto;
} else {
console.error('Redirect to unauthorized domain blocked');
}
} catch (e) {
console.error('Invalid redirect URL');
}
Why this works:
- Uses the
URLAPI to properly parse URLs - Validates against a whitelist of trusted domains
- Catches malformed URLs with try-catch
- Rejects any destination not explicitly allowed
2. Avoid Dangerous Sinks
Replace risky functions with safer alternatives:
| Instead of | Use | Reason |
|---|---|---|
innerHTML | textContent or createTextNode() | Prevents HTML/script injection |
eval() | JSON.parse() or direct function calls | Avoids arbitrary code execution |
document.write() | DOM manipulation methods | More controlled content insertion |
Direct location assignment | location.href with validation | Explicit and easier to audit |
Example - Safe DOM manipulation:
// Unsafe
element.innerHTML = userInput;
// Safe
element.textContent = userInput;
// or
const textNode = document.createTextNode(userInput);
element.appendChild(textNode);
3. Encode Output Properly
Always encode data before inserting into the DOM:
// For URLs
const safeURL = encodeURIComponent(userInput);
// For HTML attributes
const safeAttr = userInput.replace(/"/g, '"');
// For JavaScript strings
const safeJS = userInput.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
4. Implement Content Security Policy (CSP)
Add CSP headers to restrict script execution:
Content-Security-Policy: default-src 'self';
script-src 'self';
object-src 'none';
base-uri 'self';
Benefits:
- Blocks inline scripts by default
- Restricts external resource loading
- Prevents
eval()and similar functions - Mitigates impact of successful XSS attacks
5. Conduct Security Audits
Code review checklist:
- Trace all data flows from sources to sinks
- Identify user-controlled input points
- Verify validation exists at every sink
- Check for dangerous function usage
Automated tools:
- ESLint with security plugins (eslint-plugin-security)
- SonarQube for static code analysis
- Snyk for dependency vulnerability scanning
- OWASP ZAP for dynamic testing
Prevention Checklist
- Validate all user-controlled input before use
- Use domain whitelisting instead of protocol checking
- Replace dangerous sinks (
eval(),innerHTML) with safe alternatives - Implement Content Security Policy headers
- Encode dynamic content before DOM insertion
- Use the
URLAPI for parsing and validating URLs - Conduct regular code reviews focusing on data flows
- Run static analysis tools in CI/CD pipeline
- Perform penetration testing for DOM-based vulnerabilities
- Monitor third-party library advisories
- Train developers on secure coding practices
Real-World Impact
DOM-based vulnerabilities have affected major platforms:
- Social media platforms - Open redirects used for phishing campaigns
- E-commerce sites - Session hijacking through DOM XSS
- Banking applications - Credential theft via malicious redirects
- SaaS platforms - Data exfiltration through client-side attacks
The client-side nature makes these attacks particularly dangerous because:
- Traditional server logs don't capture the attack
- WAFs and server-side filters are ineffective
- Attacks can persist in bookmarks and shared links
- Users trust URLs from legitimate domains
Learn More
- OWASP DOM-Based XSS Prevention Cheat Sheet: Comprehensive guide to preventing DOM-based attacks - [owasp.org/www-project-cheatsheets](https://cheatsheetseries.owasp.org/cheatsheets/DOM_based_XSS_Prevention_Cheat_Sheet