Overview
The unsorted bin into stack technique exploits the unsorted bin’s freelist mechanism to makemalloc() return a pointer to a nearly-arbitrary location, such as the stack. This is achieved by corrupting the bk pointer of a freed chunk in the unsorted bin.
Glibc Version Compatibility
Working Versions
glibc 2.23 - 2.28
Patched
glibc 2.29+ (April 2019)
What Does This Technique Achieve?
This attack allows you to:- Get malloc to return a stack address - control where malloc allocates
- Overwrite return addresses - achieve code execution by writing to the stack
- Bypass stack canaries - write beyond the canary without triggering protection
The returned pointer can point to any writable address where you can craft a fake chunk with an appropriate size field.
The Vulnerability
The attack requires:- Heap overflow or UAF - ability to overwrite a freed chunk’s metadata
- Writable target location - place to create a fake chunk (e.g., stack)
- Size mismatch - next allocation must differ from freed chunk size
Technical Details
Unsorted Bin Behavior
Whenmalloc() is called:
- It searches the unsorted bin for a suitable chunk
- If size doesn’t match exactly, it removes the chunk and sorts it into appropriate bin
- During removal, it performs:
victim->bk->fd = unsorted_chunks(av)
victim->bk, we control where this write goes and what chunk gets “linked” into the unsorted bin.
Fake Chunk Requirements
Memory Layout
Step-by-Step Exploitation
1
Allocate and Free Victim
Create a chunk and free it to place it in the unsorted bin:
2
Create Fake Chunk on Stack
Set up a fake chunk structure on the stack:
3
Corrupt Victim Metadata
Exploit vulnerability to overwrite victim’s size and bk:
The size must be different from the next allocation to force unsorted bin processing.
4
Trigger Allocation
Call malloc to get the fake chunk returned:The unsorted bin processing:
- Sees victim with size 32 (doesn’t match request of 0x100)
- Removes victim from unsorted bin
- Follows
victim->bkto our fake chunk - Returns
&stack_buffer[2]as the allocation
5
Exploit the Stack Pointer
Use the stack pointer to overwrite return addresses:
Full Source Code
View Complete Exploit Code
View Complete Exploit Code
Why This Works
The unsorted bin processing in glibc < 2.29:victim->bk = stack_buffer, we control where bck->fd writes. The fake chunk on the stack is then treated as a valid unsorted bin chunk.
The Patch (glibc 2.29)
The patch added this check:Bypassing Stack Canaries
One powerful aspect of this technique is that it can overwrite return addresses without triggering stack canary protection, as the write happens beyond the canary’s location on the stack.
Practice
Try it in your browser
Debug this technique interactively on Ret2 Wargames (glibc 2.23)
Related Techniques
- Unsorted Bin Attack - Write large value instead of arbitrary allocation
- [House of Lore/techniques/house/house-of-lore) - Similar concept with smallbins
