Heap Overflow
Heap Overflow
1
What is a heap?
• Heap is a collection of variable-size memory
chunks allocated by the program
– e.g., malloc(), free() in C,
creating a new object in Java
creating a new object in Java script
2
Heap overflow attacks
• What if heap memory is corrupted?
– If a buffer is allocated on the heap and
overflown, we could overwrite the heap meta
data
– This can allow us to modify any memory
location with any value of our chosen
– This could lead to running arbitrary code
3
Doug Lea’s malloc and free
4
Double-linked free chunk list
struct chunk {
int prev_size;
int size;
struct chunk *fd;
struct chunk *bk;
};
5
heap.c
#define BUFSIZE 128
if(argc < 2) {
printf("Usage: %s <buffer>\n", argv[0]);
exit(-1);
}
a = (char *) malloc(BUFSIZE);
b = (char *) malloc(BUFSIZE+16);
c = (char *) malloc(BUFSIZE+32);
strcpy(b, "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB");
strcpy(c, "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC");
strcpy(a, argv[1]);
free(a);
free(b);
free(c); 6
}
The heap in memory
bin_forward bin_back
prev_free_size=0
Size=0x88 1
char *a
Data free(a)
(AAAAAAAAAAAAAAAAA
AAAA)
prev_free_size=0
Size=0x98 1
char *b
Data
(BBBBBBBBBBBBBBBBB
BBBBB)
prev_free_size=0
Size=0xa8 1
char *c
Data
(CCCCCCCCCCCCCCCC
CCCCC) 7
After free(a)
bin_forward bin_back
prev_free_size=0
Size=0x88 1
char *a
forward free(a)
back
prev_free_size=0x88
Size=0x98 0
char *b
Data free(b)
(BBBBBBBBBBBBBBBBB
BBBBB)
prev_free_size=0
Size=0xa8 1
char *c
Data
(CCCCCCCCCCCCCCCC
CCCCC) 8
After free(b)
bin_forward bin_back
prev_free_size=0
Size=0x120 1
char *a
forward free(a)
back
char *b
free(b)
prev_free_size=0x120
Size=136 0
char *c
Data
(CCCCCCCCCCCCCCCC
CCCCC) 9
What if “b” was freed first?
bin_forward bin_back
prev_free_size=0
Size=0x88 1
char *a
Data free(a)
(AAAAAAAAAAAAAAAAA
AAAA)
prev_free_size=0
Size=0x98 1
char *b
forward free(b)
back
prev_free_size=0x98
Size=0xa8 0
char *c
Data
(CCCCCCCCCCCCCCCC
CCCCC) 10
Then “a” was freed
bin_forward bin_back
prev_free_size=0
Size=0x120 1
char *a
forward
back
char *b
prev_free_size=0x120
Size=0xa8 0
char *c
Data
(CCCCCCCCCCCCCCCC
CCCCC) 11
Key Observation
• When the chunk (A) to be free’ed is
followed by a free chunk (B), chunk B will
be unlinked from the free list, and A will be
inserted into the free list.
• If the heap meta data in B has been
corrupted, the unlink operation will be
dangerous.
– Why?
12
Remove a chunk from the
double-linked free list
• unlink(P)
P->fd->bk = P->bk;
P->bk->fd = P->fd; Will create
P some trouble
for us
prev_free_size=0
Size=0x88 1
char *a
Data
(AAAAAAAAAAAAAAAAA
AAAA)
prev_free_size=0
Size=0x98 1
char * b
Data
(BBBBBBBBBBBBBBBBB
BBBBB)
prev_free_size=0x98
The second next chunk’s “size”
Size=0xa8 0
char *c word shall be an even number
Data
(CCCCCCCCCCCCCCCC
CCCCC) 18
Assembled heap-overflow
payload
buffer
XXXX YYYY
This word will be \x90\x90\x90\x90 nop, nop, jmp + 4
overwritten by the ZZZZ Shellcode…
second part of
unlink statement Shellcode…
fake heap
Padding
structure
19