> For the complete documentation index, see [llms.txt](https://xenon-2.gitbook.io/writeups/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://xenon-2.gitbook.io/writeups/binary-exploitation/heap/heap-overflow.md).

# Heap Overflow

### Protostar 1

```cpp
int __cdecl main(int argc, const char **argv, const char **envp)
{
  object *v4; // [esp-18h] [ebp-20h]
  object *v5; // [esp-14h] [ebp-1Ch]

  v4 = (object *)malloc(8u);
  v4->value = 1;
  v4->ptr = malloc(8u);
  v5 = (object *)malloc(8u);
  v5->value = 2;
  v5->ptr = malloc(8u);
  strcpy((char *)v4->ptr, argv[1]);
  strcpy((char *)v5->ptr, argv[2]);
  puts("and that's a wrap folks!");
  return 0;
}
```

#### Solve

1. Two structs are being allocated, strcpy to the value of the ptr stored in struct, (no bounds checking so can overflow)
2. First argument to overflow to the next struct, second argument is to overflow the contents of the ptr in the next struct
3. Perform a GOT overwrite of the puts function as it is called at the end of main()

This is so that when puts is called after the overwrite, it redirects to win() instead

```c
struct buffer {
    int value;
    void* ptr;
}
```

```cpp
// First Argument 
struct buffer1 {
    int value;
    void* ptr -> 0xAAAAAAAA (8 bytes)
}
metadata of buffer2 -> 0xAAAAAAAA (8 bytes)
struct buffer2 {
    int value; -> 0xAAAA (4 Bytes)
    void *ptr -> Puts@plt Address (4 Bytes) 
}
```

<pre class="language-cpp"><code class="lang-cpp"><strong>// Second Argument
</strong>struct buffer2 {
    int value;  
    void *ptr -> Puts@plt Address -> win function address (4 Bytes)
}
</code></pre>
