# Stonks

## Problem

> I decided to try something noone else has before. I made a bot to automatically trade stonks for me using AI and machine learning. I wouldn't believe you if you told me it's unsecure! vuln.c `nc mercury.picoctf.net 16439`

* [Program](https://github.com/HHousen/PicoCTF-2021/blob/master/Binary%20Exploitation/Stonks/vuln/README.md)
* [Source](https://github.com/HHousen/PicoCTF-2021/blob/master/Binary%20Exploitation/Stonks/vuln.c)

## Solution

1. We can compile the c source code using `gcc -g -m32 vuln.c -o vuln` and then we can generate a `pwntools` template using `pwn template --host mercury.picoctf.net --port 16439 vuln`.
2. This is a standard format string vulnerability. It even tells us that the program is vulnerable to a format string attack when we compile it.
3. Resources to learn about format string attacks: [Syracuse University Lecture Notes](https://web.ecs.syr.edu/~wedu/Teaching/cis643/LectureNotes_New/Format_String.pdf) / [OWASP](https://owasp.org/www-community/attacks/Format_string_attack) / [LiveOverflow on YouTube](https://www.youtube.com/watch?v=0WvrSfcdq1I) / [John Hammond PicoCTF 2017 'I've Got a Secret' on YouTube](https://www.youtube.com/watch?v=rkoP2mtwFNI) / [PicoCTF 2018 'echooo' Writeup](https://tcode2k16.github.io/blog/posts/picoctf-2018-writeup/binary-exploitation/#echooo)
4. However, my solution is based on [this writeup](https://github.com/shiltemann/CTF-writeups-public/tree/master/PicoCTF_2018#binary-exploitation-300-echooo).
5. Essentially, the [solution script](https://github.com/HHousen/PicoCTF-2021/blob/master/Binary%20Exploitation/Stonks/script/README.md) works by sending a string of repeating `%p` to the format string function in the program. The program replaces these `%p`s with values from the stack. Eventually, we work our way up the stack far enough to get to the `api_buf` and print that out in little endian hexadecimal. We can not use the looping `'%{}$s'.format(i)` trick from [this PicoCTF 2018 'echooo' Writeup](https://tcode2k16.github.io/blog/posts/picoctf-2018-writeup/binary-exploitation/#echooo) because the program is in little endian adn thus the flag would not be displayed correctly.
6. Once we dump the stack, we convert the hexadecimal into ascii by converting it to a byte array, reversing the array, and then filtering out bad ascii characters. Then, we simply print the flag.

### Flag

`picoCTF{I_l05t_4ll_my_m0n3y_c7cb6cae}`
