๐ŸŸ  DOM-based XSS Lab

location.hash Vulnerability

โš ๏ธ FOR EDUCATIONAL PURPOSES ONLY - DO NOT USE ON REAL SYSTEMS

๐Ÿ“š What is DOM-based XSS?

DOM-based Cross-Site Scripting occurs when JavaScript reads data from a controllable source (like URL parameters, hash, or localStorage) and writes it to a dangerous sink (like innerHTML) without proper validation.

Unlike reflected or stored XSS, DOM-based XSS happens entirely in the browser's DOM - the server is not involved. The vulnerability exists in client-side code.

๐Ÿงช Try It Yourself

This page reads content from the URL hash (location.hash) and displays it. Modify the URL to inject malicious code.

Output:

๐Ÿ’ก Try These Payloads

Add these to the URL hash or use the input field above:

#<img src=x onerror=alert('DOM XSS')>
#<script>alert('DOM-based XSS!')</script>
#<iframe src="javascript:alert('XSS')"></iframe>

๐Ÿ” Understanding the Vulnerability

Vulnerable Code:

// โŒ VULNERABLE: Reading from location.hash and using innerHTML
window.addEventListener('hashchange', function() {
  const hash = location.hash.substring(1); // Remove # symbol
  document.getElementById('display').innerHTML = hash;
});

The problem: User-controlled data from location.hash is directly inserted into the DOM using innerHTML, allowing HTML and JavaScript execution.

Secure Code:

// โœ… SECURE: Using textContent instead
window.addEventListener('hashchange', function() {
  const hash = location.hash.substring(1);
  document.getElementById('display').textContent = hash;
});

// โœ… SECURE: Or sanitize input
const sanitized = DOMPurify.sanitize(hash);
document.getElementById('display').innerHTML = sanitized;

๐ŸŽฏ Common Sources (User-Controllable)

๐Ÿ’ฅ Dangerous Sinks

โš ๏ธ Real-World Impact

๐Ÿ”’ Prevention Techniques