> 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


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://alham-rizvi.gitbook.io/alhamrizvi/picoctf-writeups/picoctf/binary-exploitation/flag-leak.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
