PHP 5.6.3 unserialize() execute arbitrary code

Reported by Stefan Esser :

A while ago the function “process_nested_data” was changed to better
handle object properties. Before it was possible to create numeric
object properties which would cause trouble down the road. So the
following code was added:

Whoever wrote this code did not know about the history of the
unserialize() function and that in earlier times (2004) I found a use
after free vulnerability in it. A non detailed write up can be found in [Bug 7].

The problem with the above code is that when there are two identical
keys in the object’s serialized properties the second key will delete
the first one from memory and destroy the ZVAL associated with it. This
means that ZVAL and all its children is freed from memory. However the
unserialize() code will still allow to use R: or r: to set references to
that already freed memory. It has been demonstrated many times before
that use after free inside unserialize() allows an attacker to execute
arbitrary code. Also some programs do not only unserialize() user input
but they also sent a serialized() reply back to the caller. In such a
setup an attacker can not only trigger code execution but also leak
memory content from remote. This together means he can write a fully
working remote exploit that bypasses all modern mitigations. Examples
how that was possible before you can see from this slide deck (starting
from slide 30)

Last time I checked one prominent example of PHP code that uses
unserialize() and serialize() in this way is: SugarCRM

The following code shows the leak:

And the following code should crash PHP:

As you can see here:

Somewhen before you fix and release this I will prepare a POC that
demonstrates full control over the program counter and to leak specific
stuff from the system.