Double Free
Last updated
Last updated
Learn & practice AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE) Learn & practice GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE)
If you free a block of memory more than once, it can mess up the allocator's data and open the door to attacks. Here's how it happens: when you free a block of memory, it goes back into a list of free chunks (e.g. the "fast bin"). If you free the same block twice in a row, the allocator detects this and throws an error. But if you free another chunk in between, the double-free check is bypassed, causing corruption.
Now, when you ask for new memory (using malloc
), the allocator might give you a block that's been freed twice. This can lead to two different pointers pointing to the same memory location. If an attacker controls one of those pointers, they can change the contents of that memory, which can cause security issues or even allow them to execute code.
Example:
In this example, after filling the tcache with several freed chunks (7), the code frees chunk h
, then chunk i
, and then h
again, causing a double free (also known as Fast Bin dup). This opens the possibility of receiving overlapping memory addresses when reallocating, meaning two or more pointers can point to the same memory location. Manipulating data through one pointer can then affect the other, creating a critical security risk and potential for exploitation.
Executing it, note how i1
and i2
got the same address:
We can only allocate Fast-Bin-sized chunks except for size 0x70
, which prevents the usual __malloc_hook
overwrite.
Instead, we use PIE addresses that start with 0x56
as a target for Fast Bin dup (1/2 chance).
One place where PIE addresses are stored is in main_arena
, which is inside Glibc and near __malloc_hook
We target a specific offset of main_arena
to allocate a chunk there and continue allocating chunks until reaching __malloc_hook
to get code execution.
Using Tcache bins and a null-byte overflow, we can achieve a double-free situation:
We allocate three chunks of size 0x110
(A
, B
, C
)
We free B
We free A
and allocate again to use the null-byte overflow
Now B
's size field is 0x100
, instead of 0x111
, so we can free it again
We have one Tcache-bin of size 0x110
and one of size 0x100
that point to the same address. So we have a double free.
We leverage the double free using Tcache poisoning
Learn & practice AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE) Learn & practice GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE)