Level 4: DOM XSS in innerHTML sink using source location.search
Objective
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.
Explanation
DOM-based XSS vulnerabilities occur when malicious user input is reflected into the DOM and executed in the browser. In this case, the vulnerability is introduced because the application uses innerHTML
to assign user-controlled data to the DOM without proper sanitization.
The innerHTML
property can be dangerous if the data is not validated or sanitized, as it allows the injection of HTML, which can lead to script execution. By exploiting this, an attacker can inject malicious JavaScript into the page, triggering an XSS attack.
In this particular lab, the search query from location.search
is used to populate the innerHTML
of a div element. If the search term contains a script or an invalid element that triggers an error (like an image with a non-existent source), the script will execute, achieving the desired cross-site scripting attack.
Resolution
In the search bar, input the following payload:
<img src=1 onerror=alert('XSS test')>
This payload attempts to load a non-existent image, triggering the
onerror
event and executing thealert()
function when the image fails to load.After submitting the search, the alert will appear, confirming the execution of the malicious script.
Once the alert is triggered, the lab will be marked as completed.
Mitigation
Avoid using
innerHTML
for inserting user input. Use safer alternatives such astextContent
orcreateElement
to safely append data to the DOM.Sanitize and encode user inputs to prevent the injection of malicious code.
Validate and filter input on both the client and server sides to ensure it does not contain harmful content.
Implement Content Security Policy (CSP) to restrict the types of content that can be executed on the page and mitigate the risk of XSS attacks.
Use JavaScript libraries or frameworks that automatically handle sanitization to reduce the risk of XSS vulnerabilities.
Last updated