MOPB-44-2007:PHP 5.2.0 Memory Manager Signed Comparision Vulnerability
Summary
The new Zend Memory Manager that shipped with PHP 5.2.0 contains a comparison that wrongly casts some numbers to signed integers. Therefore a request for a very large amount of memory will be handled as a negative number and therefore result in only a minimum sized memory block being allocated. This can lead to a bunch of exploitable buffer overflows all over the PHP code. For example the PHP HTTP SOAP client can be exploited remotely, due to this vulnerability.
Affected versions
Affected is PHP 5.2.0
Detailed information
When memory is allocated through the emalloc() function the new Zend Memory Manager will handle this request within the internal _zend_mm_alloc_int() function that first determines the true size of the requested memory block with the ZEND_MM_TRUE_SIZE macro.
The allocation is handled by the following piece of code.
static void *_zend_mm_alloc_int(zend_mm_heap *heap, size_t size ZEND_FILE_LINE_DC ...)
{
size_t true_size, best_size = 0x7fffffff;
zend_mm_free_block *p, *end, *best_fit = NULL;
true_size = ZEND_MM_TRUE_SIZE(size);
The macro expands to
(((long)size<(long)ZEND_MM_MIN_SIZE)?(ZEND_MM_ALIGNED_MIN_HEADER_SIZE):
(ZEND_MM_ALIGNED_SIZE(size+ZEND_MM_ALIGNED_HEADER_SIZE+END_MAGIC_SIZE)))
For an unknown reason the original author of the code casted the size to a signed long before the comparison. Therefore a request to a very large memory block that under normal circumstances would result in an out of memory condition or a violation of the memory will be handled like a request for a block of 0 bytes.
Because of this many different places within the PHP code suddenly become exploitable because a too small memory block is returned where under normal circumstances the script would have been terminated.
Proof of concept, exploit or instructions to reproduce
Because this vulnerability is considered very critical by us, we will wait until we disclose a POC. The POC we have prepared exploits the problem remotely against PHP's builtin HTTP SOAP client.
Notes
This highy critical vulnerability is the end of this Month of PHP Bugs. Of course we will look into the things we promised during the month and update the advisories when new discoveries are made, but the new bugs per day are stopped for now. The MOPB might however return in a few months, because auditing a project of the size of PHP is not done in a few days and day by day new code is merged into the source tree. We do not claim that we have found all security problems in PHP by now. We actually claim the opposite that PHP still has several more undisclosed vulnerabilities.
And our offer is still valid, if someone wants to take part in another audit of PHP hosted by us (or wants to sponsor it), feel free to contact us.