DOM XSS in document.write sink using source location.search

In this post we will walk step by step through how to solve DOM XSS in document.write sink using source location.search on PortSwigger. This lab’s difficulty is Apprentice and it is the third lab in the  Cross-Site Scriping labs on Portswigger.

Link to lab: https://portswigger.net/web-security/cross-site-scripting/dom-based/lab-document-write-sink

To start the lab click the ‘Access the Lab’ button.

When we begin the lab we will be presented with a blog featuring a search field and a few blog posts. Don’t worry if the content differs from the screenshot; PortSwigger Labs can modify the content each time the lab is initiated.

To start our test let’s begin by using the ‘Search’ field. We can type anything into this field to test and then click the ‘SEARCH’ button. This example we can use asd123. This action will load the page with ‘what we typed’ being reflected back and displayed on the page.

Upon inspecting the HTML code it becomes evident that JavaScript is used on the page, and the img tags’s src attribute corresponds to ‘asd123’ within the ‘searchTerms’ parameter.

When examining the JavaScript code we can see the code utilize the document.write function to write content to the DOM and has the capability to process user input from location.search.

The document.write function in JavaScript can be considered potentially dangerous in certain situations, particularly in modern web development practices. The function can overwrite the entire content of a webpage if it’s called after the document has fully loaded.

Understanding this, we can exploit the document.write function and location.search to inject a JavaScript payload into the application.

Using the payload '"><script>alert(1)</script> we can bypass the img tag’s src attribute and inject our JavaScript code into the web page. The code will go into location.search and then be interpreted by document.write function.

When clicking the search button we’ll observe the alert function displaying 1. This serves as a clear demonstration of successfully injecting JavaScript into the page and exploiting the document.write function.

We should examine the HTML source code. After the img tag with the lone double quote we discover <script>alert(1)</script>. This is a result of our previous escape of the img tag’s src attribute using “>.

We should also take note of the payload reflected in the URL.

By successfully executing JavaScript on the web page we’ve effectively solved the lab!

That completes the lab! Well done! If you found this helpful, please send me a tweet and tell me what you thought! Feedback is always appreciated!

Jarrod