> 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/stored-dom-xss.md).

# XSS DOM Armazenado

### XSS DOM armazenado

Este laboratório demonstra uma vulnerabilidade DOM armazenada no recurso de comentários do blog. Para resolver o laboratório, use essa vulnerabilidade para executar o `alert()` função.

se você inserir o clássico `script` na área de comentários:

```javascript
<script>alert(0)</script>
```

Observamos que o site exclui parte do comentário.

<figure><img src="/files/2cc7d5ef5d1e02f7df6cc0ac58f5e2400a561b52" alt=""><figcaption></figcaption></figure>

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

A função é:

```javascript
function loadComments(postCommentPath) {
    let xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            let comments = JSON.parse(this.responseText);
            displayComments(comments);
        }
    };
    xhr.open("GET", postCommentPath + window.location.search);
    xhr.send();

    function escapeHTML(html) {
        return html.replace('<', '&lt;').replace('>', '&gt;');
    }

    function displayComments(comments) {
        let userComments = document.getElementById("user-comments");

        for (let i = 0; i < comments.length; ++i)
        {
            comment = comments[i];
            let commentSection = document.createElement("section");
            commentSection.setAttribute("class", "comment");

            let firstPElement = document.createElement("p");

            let avatarImgElement = document.createElement("img");
            avatarImgElement.setAttribute("class", "avatar");
            avatarImgElement.setAttribute("src", comment.avatar ? escapeHTML(comment.avatar) : "/resources/images/avatarDefault.svg");

            if (comment.author) {
                if (comment.website) {
                    let websiteElement = document.createElement("a");
                    websiteElement.setAttribute("id", "author");
                    websiteElement.setAttribute("href", comment.website);
                    firstPElement.appendChild(websiteElement)
                }

                let newInnerHtml = firstPElement.innerHTML + escapeHTML(comment.author)
                firstPElement.innerHTML = newInnerHtml
            }

            if (comment.date) {
                let dateObj = new Date(comment.date)
                let month = '' + (dateObj.getMonth() + 1);
                let day = '' + dateObj.getDate();
                let year = dateObj.getFullYear();

                if (month.length < 2)
                    month = '0' + month;
                if (day.length < 2)
                    day = '0' + day;

                dateStr = [day, month, year].join('-');

                let newInnerHtml = firstPElement.innerHTML + " | " + dateStr
                firstPElement.innerHTML = newInnerHtml
            }

            firstPElement.appendChild(avatarImgElement);

            commentSection.appendChild(firstPElement);

            if (comment.body) {
                let commentBodyPElement = document.createElement("p");
                commentBodyPElement.innerHTML = escapeHTML(comment.body);

                commentSection.appendChild(commentBodyPElement);
            }
            commentSection.appendChild(document.createElement("p"));

            userComments.appendChild(commentSection);
        }
    }
};
```

* O `escapeHTML(HTML)` a função não faz escape **que a primeira** ocorrência de `<` e `>` (uso de `substituir` simples).
* Como o código então usa `innerHTML` para inserir valores, tags maliciosas podem permanecer e ser interpretadas pelo navegador.
* A filtragem é, portanto, eficaz apenas para a primeira ocorrência; as ocorrências seguintes permanecem vulneráveis.

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

* Use uma substituição global (`replaceAll` ou uma expressão regular global) para escapar **todas as** ocorrências de `<` e `>`.
* Evite usar `innerHTML` para dados não confiáveis; prefira `textContent`  ou `createTextNode`

<figure><img src="/files/41f479cab588fe264b629807ab4d980e4b482cbf" alt=""><figcaption></figcaption></figure>

Payloads exploráveis

* Feche e injete um script:

```javascript
<><script>alert(0)</script>
```

* Force um erro de imagem para acionar `onerror:`

```javascript
<><img src=0 onerror=alert(0)>
```

Esses payloads funcionam porque apenas alguns caracteres são transformados e ocorrências adicionais de `<`/`>` permanecem interpretáveis.

<figure><img src="/files/abea049275214322b1c51b4a6f6920266ac24e3f" 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/stored-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.
