Heap overflow

Heap overflow, like a Stack Overflow, involve too much data being written to the heap resulting in overwriting data.

Overwriting pointers within this data can lead to arbitrary code execution if the program blindly trust data on the heap.

How it works ?

When malloc() is used, a pointer to the allocated space of memory is returned.

Data will be written to this location.

char *a = malloc(0x20); // Return a pointer, here 0x4052a0
char *b = malloc(0x20); // Return a pointer, here 0x4052d0

strcpy(b, "SuperSecretValue");
strcpy(a, "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); // Write 32 A
  address   |   values
------------+-------------------------------------------------
            |   +----------------- chunk 1 ------------------+
0x405290:   |   | 0x0000000000000000      0x0000000000000021 | <-- chunk 1 Metadata
0x4052a0:   |   | 0x4141414141414141      0x4141414141414141 | <-- chunk 1 Data
0x4052b0:   |   | 0x4141414141414141      0x4141414141414141 | <-- chunk 1 Data
            |   +----------------- chunk 2 ------------------+
0x4052c0:   |   | 0x0000000000000000      0x0000000000000021 | <-- chunk 2 Metadata
0x4052d0:   |   | 0x5375706572536563      0x72657456616c7565 | <-- chunk 2 Data
0x4052e0:   |   | 0x0000000000000000      0x0000000000000000 | <-- chunk 2 Data
0x4052f0:   |   +--------------------------------------------+
  ...       |    ...

But there is no size control, if data bigger than size space is written, then it will overwrite the data after the chunk :

char *a = malloc(0x20); // Return a pointer, here 0x4052a0
char *b = malloc(0x20); // Return a pointer, here 0x4052d0

strcpy(b, "SuperSecretValue");
// Write 64 A
strcpy(a, "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); 
  address   |   values
------------+-------------------------------------------------
            |   +----------------- chunk 1 ------------------+
0x405290:   |   | 0x0000000000000000      0x0000000000000021 | <-- chunk 1 Metadata
0x4052a0:   |   | 0x4141414141414141      0x4141414141414141 | <-- chunk 1 Data
0x4052b0:   |   | 0x4141414141414141      0x4141414141414141 | <-- chunk 1 Data
            |   +----------------- chunk 2 ------------------+
0x4052c0:   |   | 0x4141414141414141      0x4141414141414141 | <-- chunk 2 Metadata
0x4052d0:   |   | 0x4141414141414141      0x4141414141414141 | <-- chunk 2 Data
0x4052e0:   |   | 0x0000000000000000      0x0000000000000000 | <-- chunk 2 Data
0x4052f0:   |   +--------------------------------------------+
  ...       |    ...

Note that the matadatas are overwritten, but it do not really matter at the usage.

Resources

Last updated