Level 3: DOM XSS in document.write sink using source location.search
Objective
This lab contains a DOM-based cross-site scripting vulnerability in the search query tracking functionality. It uses the JavaScript document.write
function, which writes data out to the page. The document.write
function is called with data from location.search
, which you can control using the website URL.
To solve this lab, perform a cross-site scripting attack that calls the alert function.
Explanation
DOM-based XSS occurs when malicious scripts are injected and executed as a result of client-side JavaScript interacting with the Document Object Model (DOM). In this case, the vulnerability occurs because the document.write
function is called using data from location.search
, which represents the query string in the URL. This means that user-controlled input from the URL (e.g., the search query) is directly written into the page's content without proper sanitization or encoding.
By injecting a payload into the location.search
parameter, we can manipulate the DOM and execute a script that calls the alert()
function.
Resolution
Perform a search on the application with any search term.
Open the browser’s developer tools (Inspector) and analyze the code.
In the HTML, you will notice that the search term is reflected inside an
<img>
tag.
To exploit this, inject the following payload into the search query:
"><svg onload=alert(1)>
Once the payload is entered, submit the search again.
Upon page load, the alert box will appear, confirming the execution of the malicious script.
You will then see the lab completion notification.
Mitigation
Sanitize user inputs from the URL and other sources to prevent the injection of malicious code.
Use safe methods for DOM manipulation such as
textContent
orsetAttribute
, which automatically escape special characters and prevent script execution.Implement a Content Security Policy (CSP) to reduce the risk of malicious scripts being executed.
Regularly test your web applications for DOM-based XSS vulnerabilities using tools like browser developer tools and automated scanners
Last updated