zend_mm_huge_list nodes are allocated with zend_mm_alloc_heap(), from
the very heap they describe, so a heap overflow can reach them. Their size
field is then handed to munmap() in three places:
- zend_mm_free_huge(), directly via zend_mm_chunk_free(),
- the huge block loop in zend_mm_shutdown(), likewise,
- zend_mm_realloc_huge(), which takes it as old_size and passes it to
zend_mm_chunk_truncate(), which unmaps the tail with
munmap(addr + new_size, old_size - new_size).
The ptr is constrained a bit, as it has to match the pointer being freed and is
checked for chunk alignment, but size is used as-is. Corrupting it turns a
free of a legitimate huge block into an unmap of an arbitrary amount of
adjacent address space, which a later mmap() can then occupy.
This commit bounds it before use: A live huge block has to satisfy three cheap
invariants: its size is not zero, it is a multiple of REAL_PAGE_SIZE (since it
was produced by ZEND_MM_ALIGNED_SIZE_EX(size, REAL_PAGE_SIZE)), and it is still
accounted for in heap->real_size, which is only decremented after the block has
been freed. This narrows the primitive rather than removing it, as doing so
would be more invasive.
This commit was validated under gdb by tampering with size on a live 4MB block
and freeing it: 0, 0x400001 (unaligned) and 0x800000 (exceeding a 6MB real_size)
all abort with "zend_mm_heap corrupted", where all three were previously passed
to munmap().
zend_mm_huge_list nodes are allocated with zend_mm_alloc_heap(), from the very heap they describe, so a heap overflow can reach them. Their size field is then handed to munmap() in three places:
The ptr is constrained a bit, as it has to match the pointer being freed and is checked for chunk alignment, but size is used as-is. Corrupting it turns a free of a legitimate huge block into an unmap of an arbitrary amount of adjacent address space, which a later mmap() can then occupy.
This commit bounds it before use: A live huge block has to satisfy three cheap invariants: its size is not zero, it is a multiple of REAL_PAGE_SIZE (since it was produced by ZEND_MM_ALIGNED_SIZE_EX(size, REAL_PAGE_SIZE)), and it is still accounted for in heap->real_size, which is only decremented after the block has been freed. This narrows the primitive rather than removing it, as doing so would be more invasive.
This commit was validated under gdb by tampering with size on a live 4MB block and freeing it: 0, 0x400001 (unaligned) and 0x800000 (exceeding a 6MB real_size) all abort with "zend_mm_heap corrupted", where all three were previously passed to munmap().