> 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/binary-exp/04.-stack-overflow/challenge/easy/solution1.md).

# solution1

<img src="https://github.com/user-attachments/assets/59c31461-9045-4b78-be2a-4db4fc3103ba" alt="image" height="624" width="694">

&#x20;

<img src="https://github.com/user-attachments/assets/d0c4cafc-f451-40e2-a6a3-8d4ae415aa41" alt="image" height="687" width="1412">

The binary presents a simple stack buffer overflow inside the `vulnerable()` function. A struct is used to control memory layout, where a 64-byte buffer `buf` is placed directly before an integer variable `magic`. The program reads user input using `gets()`, which does not enforce any bounds checking, allowing us to overflow past `buf` and overwrite adjacent memory.

At runtime, the binary even confirms the layout by printing the distance between `buf` and `magic`, which is 64 bytes. This tells us that after writing 64 bytes into the buffer, the next 4 bytes will overwrite the `magic` variable.

To avoid guessing offsets, a cyclic pattern was used. A 100-byte cyclic string was generated using pwntools and sent as input to the program. After execution, the program showed that `magic` had been overwritten with the value `0x61616171`. This value was passed into `cyclic_find()`, which returned an offset of 64, confirming the exact overwrite position.

The goal of the challenge is to set `magic` to `0xdeadbeef`. Since the system uses little-endian architecture, the value must be written in reverse byte order as `\xef\xbe\xad\xde`. With the offset known, the final payload consists of 64 bytes of padding followed by this 4-byte value.

The exploit is constructed by sending 64 bytes of junk data followed by the little-endian representation of `0xdeadbeef`. This successfully overwrites the `magic` variable with the required value, satisfying the condition in the program and triggering the flag.

The final payload is generated and sent using Python:

```
python3 -c "from pwn import *; print(b'A'*64 + p32(0xdeadbeef))" | ./v1
```

Upon execution, the program confirms that `magic` is now `0xdeadbeef` and prints the flag.

This challenge demonstrates a fundamental stack buffer overflow where control over adjacent variables is achieved through unchecked input. It reinforces key concepts such as offset calculation using cyclic patterns, understanding memory layout, and handling little-endian byte order for correct value injection.
