# 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>


---

# Agent Instructions: 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:

```
GET https://xenon-2.gitbook.io/writeups/binary-exploitation/heap/heap-overflow.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
