DOM XSS in innerHTML sink using source location.search

Description

This lab contains a DOM-based cross-site scripting vulnerability in the search blog functionality. It uses an innerHTML assignment, which changes the HTML contents of a div element, using data from location.search.

To solve this lab, perform a cross-site scripting attack that calls the alert function.

Approach

After accessing the lab, I started examining the page code to identify any interesting JavaScript scripts. Initially, I didn't find anything notable. However, once I used the search functionality, a script tag appeared in the response:

<script>
function doSearchQuery(query) {
   document.getElementById('searchMessage').innerHTML = query;
}
var query = (new URLSearchParams(window.location.search)).get('search');
if(query) {
	doSearchQuery(query);
}
</script>

The script retrieves the search parameter from the URL query string using location.search and assigns it to the query variable. This value is then passed to the doSearchQuery function, which sets the innerHTML of an element with the ID searchMessage. This creates an opportunity for DOM-based XSS if the input is not properly sanitized.

To exploit this vulnerability, I crafted a simple XSS payload that includes an image tag with an onerror event handler:

<img src=0 onerror=alert(1)>

When this payload is injected into the search parameter, it will try to load the image from src=0. Since the image doesn't exist, the onerror event handler will be triggered, causing an alert box to pop up. By that the lab is solved.