// gcc heap_uaf.c -o heap_uaf
int main(){
int DEBUG = 1;
char *user_input = malloc(0x30);
if(DEBUG) printf("user_input: %p\n", user_input);
char *flag_content = malloc(0x30);
if(DEBUG) printf("flag_content: %p\n", flag_content);
printf("Name? ");
scanf("%7s", user_input);
printf("Hello %s!\n", user_input);
/*
*
* If you uncomment free(), the output will be like this.
*
* Name? 1
* Hello 1!
* Auth: 0
* Password? 2
* Auth: 50
* < flag output here
* (fact: decimal 50 is representation of '2' string.)
* Why it works?
* Because when you free user_input
* authenticated variable address will be the same address of user_input.
* Which means, authenticated variable value will be changed and authentication will be broken as fuck.
* */
// comment this, it works as intented.
free(user_input);
long *authenticated = malloc(0x30);
if(DEBUG) printf("authenticated: %p\n", authenticated);
*authenticated = 0;
if(DEBUG) printf("Authenticated value: %x\n", *authenticated);
printf("Password? ");
scanf("%7s", user_input);
if (getuid() == 0 || strcmp(user_input, "hunter2") == 0){
*authenticated = 1;
}
if(DEBUG) printf("Authenticated value: %x\n", *authenticated);
if (*authenticated){
open("/flag",0);
read(3, flag_content, 0x30);
write(1, flag_content, 0x30);
}
return 0;
}