Heap2
This level examines what can happen when heap pointers are stale.
This level is completed when you see the “you have logged in already!” message
source code:
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <stdio.h>
struct auth {
char name[32];
int auth;
};
struct auth *auth;
char *service;
int main(int argc, char **argv)
{
char line[128];
while(1) {
printf("[ auth = %p, service = %p ]\n", auth, service);
if(fgets(line, sizeof(line), stdin) == NULL) break;
if(strncmp(line, "auth ", 5) == 0) {
auth = malloc(sizeof(auth));
memset(auth, 0, sizeof(auth));
if(strlen(line + 5) < 31) {
strcpy(auth->name, line + 5);
}
}
if(strncmp(line, "reset", 5) == 0) {
free(auth);
}
if(strncmp(line, "service", 6) == 0) {
service = strdup(line + 7);
}
if(strncmp(line, "login", 5) == 0) {
if(auth->auth) {
printf("you have logged in already!\n");
} else {
printf("please enter your password\n");
}
}
}
}
run it to see how it works:
When we logined, auth was allocated some space in heap at the address '0x804c008'. But after we freed auth, auth still points to the address. And when we used service hack, auth and service got the same address.
That's use-after-free.
run it in gdb:
and with command we can type what gdb commands shall be executed when we hit the breakpoint.
set a breakpoint before executing printf, and use command 'info proc mapping' to get the heap address.
let's run this binary
at first we got some memory errors because the heap dosen't exist yet, so let's malloc our first value by authenticating with "auth" as admin.
so let's free the auth object with reset, and pay attention to what changes.
Basically nothing changed. Except that the first word of the chunk data got replaced with 0. That's because the first word in a free chunk is defined as the previous free chunk address. Because free chunks are in a linked list. But we don't have another free chunk in the list, thus it's null.
Anyhow, we can now see that the auth object still exists with the pointer into the heap at the address '0x804c008'. But the name is now empty with nulls, and the integer is null still.
Let's use service to allocate a string on the heap.
we notice that auth and service points to the same address. use-after-free