> For the complete documentation index, see [llms.txt](https://cajac.gitbook.io/ctf-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://cajac.gitbook.io/ctf-notes/bin-exp/stack-exploitation/stack-based-buffer-overflows.md).

# Stack-based Buffer Overflows

## Exploitation Procedure

General procedure to overwrite a return address of a function call.

### Find function memory address

To find out the virtual address of the function we want to call, in this case the `win` function, we can

#### With gdb

Use `gdb`

```bash
┌──(kali㉿kali)-[/mnt/…/picoCTF/picoCTF_2022/Binary_Exploitation/Buffer_Overflow_1]
└─$ gdb -batch -ex 'info func' -ex 'quit' vuln | grep win
0x080491f6  win
```

#### With nm

Or use `nm`

```bash
┌──(kali㉿kali)-[/mnt/…/picoCTF/picoCTF_2022/Binary_Exploitation/Buffer_Overflow_1]
└─$ nm -a vuln | grep win
080491f6 T win
```

#### With objdump

This can also be done with `objdump`

```bash
┌──(kali㉿kali)-[/mnt/…/picoCTF/picoCTF_2022/Binary_Exploitation/Buffer_Overflow_1]
└─$ objdump -t vuln | grep win
080491f6 g     F .text  0000008b              win
```

#### With pwntools

We can also let pwntools examine the binary and **dynamically** find the address for us

```python
exe = context.binary = ELF('./binary')
# more code here
win_addr = p64(exe.sym.win)
```

### Finding Offset

We need to identify the **offset** on the stack to the return address from the function.&#x20;

If we send a specific sequence of characters that is a [de Bruijn sequence](https://en.wikipedia.org/wiki/De_Bruijn_sequence) we can easily calculate the offset to the memory address.

Creation of such a sequence can be done with [pwntools](https://docs.pwntools.com/en/stable/index.html) `cyclic` or [metasploit's](https://www.metasploit.com/) `msf-pattern_create`.

```bash
┌──(kali㉿kali)-[~]
└─$ source ~/Python_venvs/PwnTools/bin/activate    

┌──(PwnTools)─(kali㉿kali)-[~]
└─$ pwn cyclic 100
aaaabaaacaaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaamaaanaaaoaaapaaaqaaaraaasaaataaauaaavaaawaaaxaaayaaa
```

And the lookup of the offset can then be done with `cyclic` or `msf-pattern_offset`.

## Resources

de Bruijn sequence - Wikipedia: <https://en.wikipedia.org/wiki/De_Bruijn_sequence>

GDB (The GNU Project Debugger) - Documentation: <https://sourceware.org/gdb/documentation/>

GDB (The GNU Project Debugger) - Homepage: <https://sourceware.org/gdb/>

Metasploit - Documentation: <https://docs.metasploit.com/>

Metasploit - Homepage: <https://www.metasploit.com/>

Metasploit-Framework - Kali Tools: <https://www.kali.org/tools/metasploit-framework/>

objdump - Linux manual page: <https://man7.org/linux/man-pages/man1/objdump.1.html>

pwntools - Documentation: <https://docs.pwntools.com/en/stable/index.html>

pwntools - GitHub: <https://github.com/Gallopsled/pwntools>

Stack Binary Exploitation - Cybersecurity Notes: <https://ir0nstone.gitbook.io/notes/binexp/stack>
