> For the complete documentation index, see [llms.txt](https://riteshs4hu.gitbook.io/infosec-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://riteshs4hu.gitbook.io/infosec-notes/web-appsec/injections/cross-site-scripting-xss/dom-xss.md).

# DOM XSS

DOM-Based Cross-Site Scripting (DOM XSS) occurs when client-side JavaScript reads data from a user-controlled source and writes it to the page in an unsafe manner. Unlike Reflected XSS and Stored XSS, the vulnerability exists entirely within the browser and does not require the server to return malicious content.

The attack happens because JavaScript modifies the Document Object Model (DOM) using untrusted data without proper sanitization or encoding.

Common sources of user-controlled data include:

* URL parameters
* URL fragments (`#`)
* Query strings
* Cookies
* Local storage
* User input fields

***

### Vulnerable PHP Code Example

```php
<?php
echo "Welcome to our website";
?>
```

```html
<script>
var name = location.hash.substring(1);

document.getElementById("welcome").innerHTML =
    "Welcome " + name;
</script>

<div id="welcome"></div>
```

***

### Code Explanation

The PHP code itself is not vulnerable:

```php
<?php
echo "Welcome to our website";
?>
```

The vulnerability exists in the client-side JavaScript.

The application reads data from the URL fragment:

```javascript
var name = location.hash.substring(1);
```

The value is then inserted into the page using:

```javascript
document.getElementById("welcome").innerHTML =
    "Welcome " + name;
```

Because `innerHTML` interprets content as HTML, untrusted data can become active content within the page.

The server never processes or stores the malicious input. Everything happens inside the victim's browser.

***

### How to Exploit

1. Identify JavaScript code that reads data from a user-controlled source such as a URL parameter, URL fragment, cookie, or input field.
2. Determine whether the application inserts that data into the DOM using unsafe methods.
3. Verify whether the browser interprets the supplied content as HTML instead of plain text.
4. If untrusted data is written directly to the page, the browser may execute the injected content.
5. The attacker crafts a URL or input value containing malicious content.
6. When the victim opens the page, the client-side JavaScript processes the attacker-controlled data and inserts it into the DOM.
7. The payload executes entirely within the browser without requiring a malicious server response.

Unlike Reflected XSS and Stored XSS, the server may never see the payload because the vulnerability exists entirely in client-side code.
