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

# DOM XSS хранимый

Заметки по DOM XSS хранимый для лабораторных работ PortSwigger Web Security Academy, включая процесс эксплуатации, тестирование полезной нагрузки, проверку в Burp Suite и контекст исправления.

### Сохранённый DOM XSS

В этой лабораторной работе демонстрируется уязвимость DOM, сохранённая в функции комментариев блога. Чтобы решить лабораторную, используйте эту уязвимость, чтобы выполнить `alert()` функцию.

если вы вставите классический `script` в область комментариев:

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

Мы заметили, что сайт удаляет часть комментария.

<figure><img src="https://4248209978-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-0358355ce17df0a670ca0a9342a620478887cbad%2F%7B4BB37EC5-B761-46BD-9EC4-FD5CF0A0CB2D%7D.png?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://4248209978-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-f4a94e93a47b2d6257d0e1286e6ae481b908e0a5%2F%7B51EBE8E6-EF84-4721-9597-2CA33135B2FD%7D.png?alt=media" 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="https://4248209978-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-f78e2d4b29ac3d7c11c66a1dbbb3c0b2ed2b36bc%2F%7BEB54F97A-8555-4C2D-AF79-A18288E9D71B%7D.png?alt=media" alt=""><figcaption></figcaption></figure>

* Используйте глобальную замену (`replaceAll` или глобальное регулярное выражение), чтобы экранировать **все** вхождения `<` и `>`.
* Избегайте использования `innerHTML` для ненадёжных данных; предпочитайте `textContent` или `createTextNode`

<figure><img src="https://4248209978-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-77ed68ace5fc6044a9c931920c21502126ebcdbb%2F%7B10F31C2E-40F6-4FF7-92C3-03DC5B7275D3%7D.png?alt=media" alt=""><figcaption></figcaption></figure>

Эксплуатируемые полезные нагрузки

* Закройте и внедрите скрипт:

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

* Вызовите ошибку изображения, чтобы сработал `onerror:`

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

Эти полезные нагрузки работают, потому что преобразуются лишь несколько символов, а дополнительные вхождения `<`/`>` остаются интерпретируемыми.

<figure><img src="https://4248209978-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-de062e0bfc5ed92a3683ea7bcf0fbc57d5f303dc%2F%7BE753AEC8-197D-4ABB-8F7E-CAAA0C60147E%7D.png?alt=media" 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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://hacking-notes.jord4n.pro/ru/web/xss/stored-dom-xss.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
