Skip to content

Instantly share code, notes, and snippets.

@robgalvan
Created August 5, 2020 21:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robgalvan/f1a9ae3c38831c85c127db0556441500 to your computer and use it in GitHub Desktop.
Save robgalvan/f1a9ae3c38831c85c127db0556441500 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>
struct person {
int age;
char *name;
void (*func_ptr)(struct person*);
};
struct blob {
char data[12];
};
void print_name(struct person *ptr)
{
printf("Your Person's name: %s\n",ptr->name);
return;
}
void win()
{
puts("You win");
system("/bin/sh");
}
int main(int argc, char **argv)
{
//Allocate our person
struct person *my_person = (struct person*) malloc(sizeof(struct person));
//Fill out struct information
my_person->age = 23;
my_person->name = malloc(7);
strncpy(my_person->name,"Robert\x00",7);
my_person->func_ptr = &print_name;
//Print heap address of Person
printf("Addr of person: 0x%x\n", my_person);
printf("Size of object: %d\n", sizeof(struct person));
//Execute the function pointer that will print our person's name
my_person->func_ptr(my_person);
//Free person but keep ptr to it
free(my_person);
//Allocate blobs to try and fill freed space now
struct blob *my_blob = (struct blob*) malloc(sizeof(struct blob));
printf("Addr of blob: 0x%x\n", my_blob);
bool replaced = false;
for(int i = 0; i < 20; i++) {
if(my_blob->data[i] == 'R' && my_blob->data[i+1] == 'o'){
puts("We replaced the freed object with a blob!");
replaced = true;
}
printf("%x\n",my_blob->data[i]);
}
if(!replaced) {
puts("We did NOT replace the freed object!");
return -1;
}
//Use our blob to overwrite the func_ptr to win
my_blob->data[8] = &win;
//Use the ptr after it has been freed and now call system!
my_person->func_ptr(my_person);
read();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment