A heap-based buffer overflow is an overflow that occurs in dynamically allocated space called the heap. Data is stored in the heap when you call malloc(size). The concept is exactly the same as a stack-based overflow in the fact that you put more data in a buffer than was allocated but they are exploited in a much different way.

Exploitation of a heap based overflow varies greatly. Some heap overflows techniques overwrite data that another function may use. Other techniques involve overwriting heap data which contain pointers to control what those pointers point too. And still others overwrite heap metadata that will cause future allocation calls to allocate data in the wrong place, perhaps overwriting a function!

Suppose the following code had to be run to configure an application with a secret key. Since it writes to /etc you can only run this code as ‘root’. Suppose you really wanted to see the secret key but you don’t have root access. You can use a heap-based overflow when you provide the input filename to overwrite the heap space that contains the directory to write too (like your home directory!).

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char **argv) {
	char *file_name, *dir;
	file_name = (char *) malloc(8);
	dir = (char *) malloc(128);
	// Get the filename from the cmdline
	strcpy(dir, "/etc/conf/key/");
	strcpy(file_name, argv[1]);
	strcat(dir, file_name);
	FILE *fd = fopen(dir, "w");
	if (fd == NULL) {
		fprintf(stderr, "File open error.");
	}
	fputs("zvsda34", fd);
	return 0;
}