RESEARCH | October 23, 2014

Bad Crypto 101

This post is part of a series about bad cryptography usage . We all rely heavily on cryptographic algorithms for data confidentiality and integrity, and although most commonly used algorithms are secure, they need to be used carefully and correctly. Just as holding a hammer backwards won’t yield the expected result, using cryptography badly won’t yield the expected results either.

 

To refresh my Android skillset, I decided to take apart a few Android applications that offer to encrypt personal files and protect them from prying eyes. I headed off to the Google Play Store and downloaded the first free application it recommended to me. I decided to only consider free applications, since most end users would prefer a cheap (free) solution compared to a paid one.

 

I stumbled upon the Encrypt File Free application by MobilDev. It seemed like the average file manager/encryption solution a user would like to use. I downloaded the application and ran it through my set of home-grown Android scanning scripts to look for possible evidence of bad crypto. I was quite surprised to see that no cryptographic algorithms where mentioned anywhere in the source code, apart from MD5. This looked reasonably suspicious, so I decided to take a closer look.

 

Looking at the JAR/DEX file’s structure, one class immediately gets my attention: the Crypt class in the com.acr.encryptfilefree package. Somewhere halfway into the class you find an interesting initializer routine:

 

public void init()
    {
        encrypt[0] = (byte)-61;
        encrypt[1] = (byte)64;
        encrypt[2] = (byte)43;
        encrypt[3] = (byte)-67;
        encrypt[4] = (byte)29;
        encrypt[5] = (byte)15;
        encrypt[6] = (byte)118;
        encrypt[7] = (byte)-50;
        encrypt[8] = (byte)-28;
        encrypt[9] = (byte)6;
        encrypt[10] = (byte)-75;
        encrypt[11] = (byte)87;
        encrypt[12] = (byte)-128;
        encrypt[13] = (byte)40;
        encrypt[14] = (byte)13;
        encrypt[15] = (byte)63;
        encrypt[16] = (byte)124;
        encrypt[17] = (byte)-68;
        …
        decrypt[248] = (byte)52;
        decrypt[249] = (byte)-51;
        decrypt[250] = (byte)123;
        decrypt[251] = (byte)105;
        decrypt[252] = (byte)-112;
        decrypt[253] = (byte)-86;
        decrypt[254] = (byte)-38;
        decrypt[255] = (byte)81;
    }

 

Continuing forward through the code, you immediately spot the following routine:
    // cleaned up decompiler code
    public byte[] decrypt(byte[] inputBuffer)
    {
        byte[] output = new byte[inputBuffer.length];
        int i = 0;
        while(i < inputBuffer.length)
        {
            int temp = inputBuffer[i];
            if(temp >= -128)
            {
                int temp = inputBuffer[i];
                if(temp < 128)
                {
                    int inputByte = inputBuffer[i];
                    int lookupPosition = 128 + inputByte;
                    int outputByte = decrypt[lookupPosition];
                    output[i] = (byte)i4;
                }
            }
            i = i + 1;
        }
        return output;

    }

 

This is basically a pretty bad substitution cipher. While looking through the code, I noticed that the values set in the init() function aren’t really used in production, they’re just test values which are likely a result of testing the code while it’s being written up. Since handling signedness is done manually, it is reasonable to assume that the initial code didn’t really work as expected and that the developer poked it until it gave the right output. Further evidence of this can be found in one of the encrypt() overloads in that same class, which contains a preliminary version of the file encryption routines.

 

Going further through the application reveals that the actual encryption logic is stored in the Main$UpdateProgress.class file, and further information is revealed about the file format itself. Halfway through the doInBackground(Void[] a) function you discover that the file format is basically the following:

 

The password check on the files itself turns out to be just a branch instruction, which can be located in Main$15$1.class and various other locations. Using this knowledge, an attacker could successfully modify a copy of the application that would allow unrestricted access to all of the files encoded by any password. Apart from rolling your own crypto, this is one of the worst offenses in password protecting sensitive data: make sure you use the password as part of the key for the data, and not as part of a branch instruction. Branches can be patched, keys need to be brute forced, or, in the event of a weak algorithm, calculated.

 

The substitution vector in the file is remarkably long–it seems that the vector stored is 1024 bytes. But, don’t be fooled–this is a bug. Only the first 256 bytes are actually used, the rest of them are simply ignored during processing. If we forget for a moment that a weak encoding is used as a substitute for encryption, and assume this is a real algorithm, reducing the key space from 1024 byte to 256 byte would be a serious compromise. Algorithms have ended up in the “do not use” corner for lesser offenses.

 

 

Yvan Janssens
PRESENTATION | June 16, 2014

Video: Building Custom Android Malware for Penetration Testing

By Robert Erbes  @rr_dot 
 
In this presentation, I provide a brief overview of the Android environment and a somewhat philosophical discussion of malware. I also take look at possible Android attacks in order to help you pentest your organization’s defenses against the increasingly common Bring Your Own Device scenario.

INSIGHTS | May 7, 2013

Bypassing Geo-locked BYOD Applications

In the wake of increasingly lenient BYOD policies within large corporations, there’s been a growing emphasis upon restricting access to business applications (and data) to specific geographic locations. Over the last 18 months more than a dozen start-ups in North America alone have sprung up seeking to offer novel security solutions in this space – essentially looking to provide mechanisms for locking application usage to a specific location or distance from an office, and ensuring that key data or functionality becomes inaccessible outside these prescribed zones.
These “Geo-locking” technologies are in hot demand as organizations try desperately to regain control of their networks, applications and data.

Over the past 9 months I’ve been asked by clients and potential investors alike for advice on the various technologies and the companies behind them. There’s quite a spectrum of available options in the geo-locking space; each start-up has a different take on the situation and has proposed (or developed) a unique way in tackling the problem. Unfortunately, in the race to secure a position in this evolving security market, much of the literature being thrust at potential customers is heavy in FUD and light in technical detail.
It may be because marketing departments are riding roughshod over the technical folks in order to establish these new companies, but in several of the solutions being proposed I’ve had concerns over the scope of the security element being offered. It’s not because the approaches being marketed aren’t useful or won’t work, it’s more because they’ve defined the problem they’re aiming to solve so narrowly that they’ve developed what I could only describe as tunnel-vision to the spectrum of threat organizations are likely to face in the BYOD realm.
In the meantime I wanted to offer this quick primer on the evolving security space that has become BYOD geo-locking.
Geo-locking BYOD
The general premise behind the current generation of geo-locking technologies is that each BYOD gadget will connect wirelessly to the corporate network and interface with critical applications. When the device is moved away from the location, those applications and data should no longer be accessible.
There are a number of approaches, but the most popular strategies can be categorized as follows:
  1. Thick-client – A full-featured application is downloaded to the BYOD gadget and typically monitors physical location elements using telemetry from GPS or the wireless carrier directly. If the location isn’t “approved” the application prevents access to any data stored locally on the device.
  2. Thin-client – a small application or driver is installed on the BYOD gadget to interface with the operating system and retrieve location information (e.g. GPS position, wireless carrier information, IP address, etc.). This application then incorporates this location information in to requests to access applications or data stored on remote systems – either through another on-device application or over a Web interface.
  3. Share-my-location – Many mobile operating systems include opt-in functionality to “share my location” via their built-in web browser. Embedded within the page request is a short geo-location description.
  4. Signal proximity – The downloaded application or driver will only interface with remote systems and data if the wireless channel being connected to by the device is approved. This is typically tied to WiFi and nanocell routers with unique identifiers and has a maximum range limited to the power of the transmitter (e.g. 50-100 meters).

The critical problem with the first three geo-locking techniques can be summed up simply as “any device can be made to lie about its location”.

The majority of start-ups have simply assumed that the geo-location information coming from the device is correct – and have not included any means of securing the integrity of that device’s location information. A few have even tried to tell customers (and investors) that it’s impossible for a device to lie about its GPS location or a location calculated off cell-tower triangulation. I suppose it should not be a surprise though – we’ve spent two decades trying to educate Web application developers to not trust client-side input validation and yet they still fall for web browser manipulations.
A quick search for “fake location” on the Apple and Android stores will reveal the prevalence and accessibility of GPS fakery. Any other data being reported from the gadget – IP address, network MAC address, cell-tower connectivity, etc. – can similarly be manipulated. In addition to manipulation of the BYOD gadget directly, alternative vectors that make use of private VPNs and local network jump points may be sufficient to bypass thin-client and “share-my-location” geo-locking application approaches.
That doesn’t mean that these geo-locking technologies should be considered unicorn pelts, but it does mean that organization’s seeking to deploy these technologies need to invest some time in determining the category of threat (and opponent) they’re prepared to combat.
If the worst case scenario is of a nurse losing a hospital iPad and that an inept thief may try to access patient records from another part of the city, then many of the geo-locking approaches will work quite well. However, if the scenario is that of a tech-savvy reporter paying the nurse to access the hospital iPad and is prepared in install a few small applications that manipulate the geo-location information in order to remotely access celebrity patient records… well, then you’ll need a different class of defense.
Given the rapid evolution of BYOD geo-locking applications and the number of new businesses offering security solutions in this space, my advice is two-fold – determine the worst case scenarios you’re trying to protect against, and thoroughly assess the technology prior to investment. Don’t be surprised if the marketing claims being made by many of these start-ups are a generation or two ahead of what the product is capable of performing today.
Having already assessed or reviewed the approaches of several start-ups in this particular BYOD security realm, I believe some degree of skepticism and caution is warranted.
— Gunter Ollmann, CTO IOActive
INSIGHTS | November 7, 2012

Hacking an Android Banking Application

This analysis of a mobile banking application from X bank illustrates how easily anyone with sufficient knowledge can get install and analyze the application, bypassing common protections.

 

1. Installing and unpacking the application

 

Only users located in Wonderland can install the X Android application with Google Play, which uses both the phone’s SIM card and IP address to determine the location of the device. To bypass this limitation, remove the SIM card and reset the phone to factory defaults.

 

Complete the initial Android setup with a Wonderland IP address, using an L2TP VPN service (PPTP encryption support is broken). If Google Play recognizes the device as located in Wonderland, install the application. Once installed in a rooted phone, copy the application APK from /data/app/com.X.mobile.android.X.apk.

 

These are some of the many reversing tools for unpacking and decompiling the APK package:

 

   apktool                                    http://code.google.com/p/android-apktool/

   smali/baksmali http://code.google.com/p/smali/
   dex2jar                                    http://code.google.com/p/dex2jar/
   jd-gui                          http://java.decompiler.free.fr/?q=jdgui
   apkanalyser                https://github.com/sonyericssondev
 

In this example, the code was decompiled using jd-gui after converting the apk file to jar using the dex2jar tool. The source code produced by jd-guifrom Android binary files is not perfect, but is a good reference. The output produced by the baksmali tool is more accurate but difficult to read. The smalicode was modified and re-assembled to produce modified versions of the application with restrictions removed. A combination of decompiled code review, code patching, and network traffic interception was used to analyze the application.

 

 

2. Bypassing the SMS activation

 

The application, when started for the first time, asks for a Wonderland mobile number. Activating a new account requires an activation code sent by SMS. We tested three different ways to bypass these restrictions, two of which worked. We were also able to use parts of the application without a registered account.

 

2.1 Intercepting and changing the activation code HTTPS request

 

The app GUI only accepts cell phone numbers with the 0X prefix; always adding the +XX prefix before requesting an activation code from the web service at https://android.X.com/activationCode

 

Intercepting the request and changing the phone number didn’t work, because the phone prefix is verified on the server side.

 

 

2.2 Editing shared preferences

 

The app uses the “Shared Preferences” Android service to store its minimal configuration. The configuration can be easily modified in a rooted phone by editing the file

 

/data/data/com.X.mobile.android.X/shared_prefs/preferences.xml

 

Set the “activated” preference to “true” like this:

 

<?xml version=’1.0′ encoding=’utf-8′ standalone=’yes’ ?>

<map>
<boolean name=”welcome_screen_viewed ” value=”true” />
<string name=”msisdn”>09999996666</string>
<boolean name=”user_notified” value=”true” />
<boolean name=”activated ” value=”true” />
<string name=”guid” value=”” />
<boolean name=”passcode_set” value=”true” />
<int name=”version_code” value=”202″ />
</map>

 

2.3 Starting the SetPasscode activity

 

The Android design allows the user to bypass the normal startup and directly start activities exported by applications. The decompiled code shows that the SetPasscodeactivity can be started after the activation code is verified. Start the SetPasscode activity using the “am” tool as follows:

 

From the adb root shell:

 

#am start -a android.intent.action.MAIN -n com.X.mobile.android.X/.activity.registration.SetPasscodeActivity

 

3. Intercepting HTTPS requests

 

To read and modify the traffic between the app and the server, perform a SSL/TLS MiTM attack. We weren’t able to create a CA certificate and install it using the Android’s user interface with the Android version we used for testing. Android ignores CA certificates added by the user. Instead, we located and then modified the app’s http client code to make it accept any certificate. Then we installed the modified APK file on the phone. Using iptables on the device, we could redirect all the HTTPS traffic to an MiTM proxy to intercept and modify requests sent by the application.

 

4. Data storage

 

The app doesn’t store any data on external storage (SD card), and it doesn’t use the SQLlite database. Preferences are stored on the “Shared Preferences” XML file. Access to the preferences is restricted to the application. During a review of the decompiled code, we didn’t find any evidence of sensitive information being stored in the shared preferences.

 

 

5. Attack scenario: Device compromised while the app is running.

 

The X android application doesn’t store sensitive information on the device. In the event of theft, loss or remote penetration, the auto lockout mechanism reduces the risk of unauthorized use of the running application. When the app is not being used or is running in background, the screen is locked and the passcode must be entered to initiate a new session. The HTTPS session cookie expires after 300 seconds. The current session cookie is removed from memory when the application is locked.

 

5.1 Attacker with root privileges

 
An attacker with root access to the device can obtain the GUID and phone number  from the unencrypted XML configuration file; but without the clear-text or encrypted passcode, mobile banking web services cannot be accessed. We have discovered a way to “unlock” the application using the Android framework to start the AccountsFragmentActivity activity, but if the web session has already expired, the app limits the attacker to a read-only access. The most profitable path for the attacker at this point is the running process memory dump, as we explain in the next section.

5.2 Memory dump analysis.

An attacker who gets root access can acquire the memory of a running Android application in several different ways. “Acquisition and Analysis of Volatile Memory from Android Devices,” published in the Digital Investigation Journal, describes some of the different methods.

 

We used the ddms (Dalvik Debug Monitor Services) tool included with the Android SDK to acquire the memory dump. The Eclipse Memory Analyzer tool with Object Query Language support is one of the most powerful ways to explore the application memory. The application passcodes are short numeric strings; a simple search using regular expressions returns too many occurrences. The attacker can’t try every occurrence of numeric strings in the process memory as a passcode for the app web services because the account is blocked after a few attempts. The HTTPS session cookies are longer strings and easier to find.

 

By searching for the prefix “JSESSION,” the attacker can easily locate the cookies when the application is running and active. However, the cookies are removed from memory after a timeout. The ActivityTimeoutTracker function calls the method clear() of the HashMap used to store the cookies. The cookie HashMap is accessed through the singleton class com.X.a.a.e.b.

 

 

Reviewing the decompiled code, we located a variable where the passcode is stored before being encrypted to perform the session initiation request. The field String f of the class com.X.a.a.d.a contains the passcode, and it is never overwritten or released. The references to the instance prevent the garbage collection of the string. Executing the OQL query “SELECT toString(object.f) FROM com.X.a.a.d.a object” inside the Eclipse Memory Analyzer is sufficient to reliably locate the passcode in the application memory dump.

 

Although developers tried to remove information from the memory to prevent this type of attack, they left the most important piece of information unprotected.

 

 

 

 

6. Attack scenario: Perform MiTM using a compromised CA

 

The banking application validates certificates against all the CA certificates that ship with Android. Any single compromised CA in the system key store can potentially compromise communication between the app and the backend. An active network attacker can hijack the connection between the mobile app and the server to impersonate the user.

 

Mobile apps making SSL/TLS connections to a service controlled by the vendor don’t need to trust Certificate Authorities signatures. The app could therefore implement certificate “pinning” or distribute a signing certificate created by the vendor.

 

The authentication protocol is vulnerable to MiTM attacks. The app’s authentication protocol uses the RSA and 3DES algorithms to encrypt the passcode before sending it to the server. After the user types the passcode and presses the “login” button, the client retrieves an RSA public key from the server without having to undergo any authenticity check, which allows for an MiTM attack. We were able to implement an attack and capture the passcodes from the app in our testing environment. Although the authentication protocol implemented by the app is insecure, attacks are prevented by the requirement of SSL/TLS for every request. Once someone bypasses the SSL/TLS certificate verification, though, the encryption of the passcode doesn’t provide extra protection.

 

 

7. Attack scenario: Enumerate users

 

The web service API allows user enumeration. With a simple JSON request, attackers can determine if a given phone number is using the service, and then use this information to guess passwords or mount social engineering attacks.

 

  

 

About Juliano

 

Juliano Rizzo has been involved in computer security for more than 12 years, working on vulnerability research, reverse engineering, and development of high quality exploits for bugs of all classes. As a researcher he has published papers, security advisories, and tools. His recent work includes the ASP.NET “padding oracle” exploit, the BEAST attack, and the CRIME attack. Twitter: @julianor

 

 

INSIGHTS | June 6, 2012

Summercon 2012

Hi Everyone,
Chris Valasek guest blogging here at IOActive. I just wanted to tell everyone a little bit about my involvement with Summercon and what to expect at the conference. Although I’m one of the current organizers (along with Mark Trumpbour @mtrumpbour), I’m obviously not the originator, as it started many years back (1987, I believe) as detailed in the most recent Phrack magazine (http://www.phrack.com/issues.html?issue=68&id=18#article).


 I started attending in 2000 when it was in Atlanta, GA and had a fantastic time. Over the years, the conference has changed and organizational efforts have varied, as running a conference is quite subjective and provides little utility (at times). Around 2006, the changing of the guard happened once again, leaving Mark and me the new organizers of the con. Like others that came before us, we put our own touch on the conference and have probably strayed further from the original than any before us.

 

While the talks are still the main attraction, the ability to meet people and have a good time is really what we want it to be all about. Many of us live in a world without much social interaction. The purpose of Summercon, in my opinion, is to provide an event that promotes social interaction of people with similar but varying backgrounds. If you really want to learn about the material being presented on, then you will take the time to review the content and figure out its purpose after the presentation. The ability to talk to others about your ideas and thoughts, regardless of their relevance to computer security, is the main benefit of gathering in a centralized location.

 

With that being said, I really do think we have a fantastic line-up of speakers this year that will promote stimulating conversation throughout the weekend (http://www.summercon.org/schedule.html). Whether you’re interested in Android hacking, instrumentation, or reverse engineering, I think you’ll be happy with the speakers this year (and every year for that matter!).

 

Lastly, I’d like to talk a bit about sponsorship. Although we feel that we had to ‘sell-out’ a bit by acquiring sponsors, it does facilitate having many more people attend and present at Summercon. I want to remind everyone that we’re not out to make a profit, but to throw the best party we can. By having sponsors, such as IOActive, we can ensure that speakers don’t have to pay their own way and attendees can have a blast learning something while making new friends.

 

        cv
P.S. We have big plans for next year, so follow @SummerC0n on twitter for more information.