Red October Malware for Android

Blue Coat Systems recently released a paper about the Inception APT (also dubbed Cloud Atlas, it may be connected to the Red October APT). One component of this APT is an Android trojan, masquerading as a Whatsapp update package. It is able to record audio calls, as well as gather, encrypt and exfiltrate user information.

The 4 strings partially written in Hindi that have been speculated on are those:

redoctober-android-img1

redoctober-android-img2

redoctober-android-img3

For researchers wanting to have a peak inside the APK, we are providing JEB decompiled Java code for one such sample.

Download is here: cloudatlas-android-malware-decompiled.zip

FinFisher FinSpy Mobile app for Android decompiled

The fully decompiled code and assets of 421and.apk can be found here: FinSpyMobileAndroid-decompiled.zip (no password).

This particular APK, although not the latest, is not obfuscated and easily reveals most capabilities of the malware:

  • Location tracker
  • Information stealer (calendar, contact list, text messages, Whatsapp databases, etc.)
  • Remotely controlled through encrypted communication over SMS and data

A great recap of the full story can be read on Netzpolitik. Real time updates are on Twitter.

JEB Jar Plugins

Maintenance release 1.5.201408040 introduces support for Java Archive (Jar) plugins. Unlike Java scripts/plugins, running JEB using a JDK is not required, as the Jar plugin already contains compiled code.

Jar plugins allow for complex, multi-class plugins, and referencing external libraries is easy via Manifest entries.

The plugins/ sub-directory of your JEB installation directory contains a sample JAR plugin (SamplePluginJar.jar) as well as the associated source code (SamplePluginJar-src.zip). You can use this plugin’s source code as a template for your own Jar plugins. The build.xml file is a simple Apache Ant build file used to compile source files (located in src/) and package the generated *.class files into a single Jar, with appropriate JEB-specific Manifest entries set up.

About JEB-specific Manifest entries: unlike single source (Python, Java source) plugins, that define plugin metadata with a special comment line (#? for Python, //? for Java), Jar plugins use Manifest entries prefixed by JebPlugin- to define those entries:

  • JebPlugin-entryclass: (mandatory) set to the class that contains the plugin entry-point
  • JebPlugin-name: (optional) plugin name (as it will appear in “Action / Custom Actions…” menu)
  • Jeb-Plugin-shortcut: (optional) keyboard shortcut
  • JebPlugin-help: (optional) help information
  • JebPlugin-author: (optional) plugin’s author information

The above values can be set up by customizing the build.xml Ant file. Also, just like stand-alone Jar files loaded by the Java VM executable, the Manifest entry Class-Path can be set to reference external Jar files or repository of *.class files. Those entries will be added to the class path when JEB loads the plugin.

Please let us know on the forum if you have any question.

Using the AST Tagging API

JEB version 1.5.201404100 introduces new methods to the AST IElement objects, attachTag() and retrieveTag(). These methods allow an API user to tag elements of Abstract Syntax Trees. When a tagged tree is rendered (that is, when decompiled Java code is being generated), tags are processed and provided to the user alongside the decompiled code, with associated text coordinates (line, column). Within the API documentation, a “located tag” is referred to as a mark.

One example use case: Tagging nodes of an AST can be useful if the yielded source code is of specific interest, and potentially require follow-up human analysis.

The example below shows how one can navigate a Class tree, looking for specific calls to findViewById:

def processTree(e):
  if isinstance(e, Call) and e.getMethod().getName() == 'findViewById' and ... :
    print 'Tagging Call element:', e #e.getMethod().getName()
    e.attachTag('testTag', 'Calling interesting findViewById')
  if e:
    # recursively process sub-elements
    for e1 in e.getSubElements():
      processTree(e1)

sig = ...
ast = self.jeb.getDecompiledClassTree(sig)  # assume the class was decompiled
processTree(e)

The Class tree can be rendered by calling the newly introduced overloaded decompile(sig, is_class, regenerate, marks) method:

marks = []
decompiled_class = self.jeb.decompile(sig, True, False, marks)
print marks

Remember to set regenerate to False since you want to avoid re-decompilation (doing so would generate a new, tag-less AST).

The marks array will contain the precise locations (lines and columns) of each tag within the decompiled_class text buffer.

Hopefully, this simplistic example showed you how to use the new AST tagging methods. Happy reversing and code analysis.

Developing JEB plugins in Java with Eclipse

This tutorial explains how to configure an Eclipse IDE project to develop JEB plugins efficiently.

1 – Create a regular Java project. In this example, the project is named JEBPlugin.

2 – Add jeb.jar to the Build path. Edit the project Build path (right-click, Build Path, Configure Build Path…).

Select “Add External JARs…“, add select jeb.jar located in your JEB/bin installation folder.

3 – Attach the API docs to the JEB jar file. Unfold the newly added “jeb.jar” entry, click Javadoc location, then Edit.

Point to either the online Java doc at https://www.pnfsoftware.com/jeb1/apidoc or use an offline Javadoc archive, either present in your JEB installation folder (typically, doc/apidoc.zip), or downloaded from https://www.pnfsoftware.com/jeb1/downloads.

4 – You’re done! You can now develop native Java JEB plugins. Remember that the main plugin class must be in the default package (ie, no package), and implement jeb.api.IScript. This blog contains several How-to’s on plugin development. You will find even more examples on our Download section on the main website.

Decompiled Java code for Android MisoSMS

Yesterday was eventful on the Android malware front. After Mouabad reported by Lookout, FireEye reported MisoSMS. It might also have been reported by Sophos at roughly the same time.

The malicious application is used in several campaigns to steal SMS and send them to China, according to FireEye’s blog post.

Many of you would like to examine and study its code, that’s why I uploaded an archive with the source code decompiled by JEB 1.4, as well as a cleaned-up manifest. Link: MisoSMS_JEB_decomp_20131217

misosms_mainact

Decompiling Android Mouabad

Lookout has an interesting article about Android Mouabad. Yet another Korean SMS malware!

The APK fully decompiled by JEB 1.4 can be found here: mouabad_JEB_decomp_20131217.zip. I haven’t refactored or commented the code, these are raw decompiled classes.

mouabad_sms_receiver

Sample MD5 68DF97CD5FB2A54B135B5A5071AE11CF is available on Contagio.

Decompiled Java Code Manipulation using JEB API – Part 3: Defeating Reflection

This is the third and final part of our series of blogs showing how to use JEB’s API to manipulate decompiled Java syntax trees. (See Part 1, Part 2.)

Today, we will show how to leverage the API to defeat the main obfuscation scheme used to protect the infamous OBad trojan: generalized reflection.

Want a visual TL;DR? Have a look at the following demo video.

Download the scripts: 1, 2, 3
Demo video

Reflection is a powerful feature used by interpreted languages to query information about what is currently loaded and executed by the virtual machine. Using reflection, a program can find references to classes and items within classes, and act on those items, for example, execute methods.

Example:

java.lang.System.exit(3);

can be rewritten to:

java.lang.Class.forName("java.lang.System")
        .getMethod("exit", Integer.TYPE).invoke(null, 3);

Combined with string encryption, reflection can seriously bloat and obscure a program, slowing down the reverse-engineering process.

Based on the above code example, it appears that a solution to remove reflection code automatically or semi-automatically is both useful and realistic. Let’s see how we can to achieve this goal using JEB’s AST API.

As said in the introduction, consider the Android trojan OBad. The video shows the use of a preliminary script to decrypt the scripts. Refer to the script ObadDecrypt.py linked above; we won’t cover the details of string decryption here, as they have been covered in a previous blog.

After string decryption, OclIIOlC.onCreate looks like the following piece of Java code:

    protected void onCreate(Bundle arg9) {
        Object v1_2;
        Object v9;
        super.onCreate(arg9);
        if(Class.forName("android.os.Build").getField("MODEL").get(null).equals(new String(CIOIIolc.IoOoOIOI(CIOIIolc.cOIcOOo(IoOoOIOI.cOIcOOo("cmA4"), CIOIIolc.cOIcOOo("ÞÜëÇØÚâØÞÜÄØåØÞÜéê×èêÉÛè".getBytes())))))) {
            System.exit(0);
        }

        Context v0 = OcooIclc.cOIcOOo;
        Class v2 = MainService.class;
        try {
            v9 = Class.forName("android.content.Intent").getDeclaredConstructor(Class.forName("android.content.Context"), Class.class).newInstance(v0, v2);
        }
        catch(Throwable v0_1) {
            throw v0_1.getCause();
        }

        try {
            Class.forName("android.content.Intent").getMethod("addFlags", Integer.TYPE).invoke(v9, Integer.valueOf(268435456));
        }
        catch(Throwable v0_1) {
            throw v0_1.getCause();
        }

        Context v1_1 = OcooIclc.cOIcOOo;
        try {
            Class.forName("android.content.Context").getMethod("startService", Class.forName("android.content.Intent")).invoke(v1_1, v9);
        }
        catch(Throwable v0_1) {
            throw v0_1.getCause();
        }

        v1_1 = this.getApplicationContext();
        try {
            v1_2 = Class.forName("android.content.Context").getMethod("getPackageManager", null).invoke(v1_1, null);
        }
        catch(Throwable v0_1) {
            throw v0_1.getCause();
        }

        ComponentName v0_2 = this.getComponentName();
        try {
            Class.forName("android.content.pm.PackageManager").getMethod("setComponentEnabledSetting", Class.forName("android.content.ComponentName"), Integer.TYPE, Integer.TYPE).invoke(v1_2, v0_2, Integer.valueOf(2), Integer.valueOf(1));
        }
        catch(Throwable v0_1) {
            throw v0_1.getCause();
        }

        this.finish();
    }

Let’s remove reflection. The steps are:

  1. Recursively walk the AST and check the statements
    Note: we could enumerate all elements instead, however, the script is intended as a demo, not an exhaustive solution to this problem
  2. Look for Call statements (eg, foo()), or Assignments whose right part is a Call (eg, r = bar())
  3. Check if the Call matches the following nested Call pattern:
    Class.forName(…).getMethod(…).invoke(…)
    Note: the script does not take care of class instantiation or field access through reflection, for the same reasons stated above.
  4. Extract the reflection information:
    1. Fully-qualified name of the class
    2. Method name and prototype
    3. Invocation arguments
  5. Create a new method, register it to the DEX object
  6. Create a Call element that accurately mirrors the reflection calls
    Note: There are limitations, especially considering the return type
  7. Finally, replace the reflection call by the direct method call

A deobfuscated / “unreflected” version of the source code above looks like:

    protected void onCreate(Bundle arg9) {
        // ...
        // ...

        try {
            v9.addFlags(Integer.valueOf(268435456));
        }
        catch(Throwable v0_1) {
            throw v0_1.getCause();
        }

        Context v1_1 = OcooIclc.cOIcOOo;
        try {
            v1_1.startService(v9);
        }
        catch(Throwable v0_1) {
            throw v0_1.getCause();
        }

        v1_1 = this.getApplicationContext();
        try {
            v1_2 = v1_1.getPackageManager();
        }
        catch(Throwable v0_1) {
            throw v0_1.getCause();
        }

        ComponentName v0_2 = this.getComponentName();
        try {
            v1_2.setComponentEnabledSetting(v0_2, Integer.valueOf(2),
                    Integer.valueOf(1));
        }
        catch(Throwable v0_1) {
            throw v0_1.getCause();
        }

        this.finish();
    }

We can now remove the try-catchall. This is what the third script is doing.

At this stage, the value and potential of the AST API package should have been clearly demonstrated. We encourage users of JEB to experiment with it, tweak our sample scripts, create their own, and eventually contribute by sending us their useful deobfuscation and/or optimization scripts. We will be happy to make them available to our user base through the Resources page.

Decompiled Java Code Manipulation using JEB API – Part 2: Decrypting Strings

This is part 2 of our series of blogs showing how to use JEB’s API to manipulate decompiled Java syntax trees. (Missed Part 1?)

Let’s see how the API can be leveraged to decrypt strings, and plug the decrypted strings back into the source code.

Download the script
Demo video

As shown in the video, we are going to focus on a protected version of Cyanide. The strings are encrypted, and that the decompiled Java code does not look pretty:

    ...
    protected void onCreate(Bundle arg5) {
        super.onCreate(arg5);
        this.setContentView(2130903040);
        if(new File(MainActivity.鷭(-387, -15, 608)).exists()) {
            MainActivity.鷭(MainActivity.鷭(-389, 52, 159));
            MainActivity.鷭(MainActivity.鷭(-333, 37, 17));
            MainActivity.鷭(MainActivity.鷭(-407, 53, 629),
                    MainActivity.鷭(-395, -15, 0), this);
            MainActivity.鷭(MainActivity.鷭(-398, 53, 92),
                    MainActivity.鷭(-386, -15, 586), this);
            MainActivity.鷭(MainActivity.鷭(-402, 52, 102),
                    MainActivity.鷭(-378, -15, 665), this);
            MainActivity.鷭(MainActivity.鷭(-368, 37, 119));
            MainActivity.鷭(this);
            return;
        }

        ...
        ...

MainActivity.鷭(x, y, z) is the decryptor method. The parameters indirectly reference a static array of bytes, that contains the encrypted strings for the class.

Our script is going to do the following:

  1. Search the encrypted byte array
    1. Enumerate the fields of the class
    2. Look for a byte[] field marked private static final
    3. Verify that this field is referenced in <clinit>, the static {…} initializer for the class
    4. The field should also be referenced in another method: the decryptor
  2. Check the structure of <clinit>
    1. It should look like: encrypted_strings = new byte[]{………}
    2. Retrieve the encrypted bytes
  3. The decryptor was analyzed in a previous blog post
    1. The decryptor constants need to be extracted manually (let’s keep the script simple)
  4. Then, for every method of the class, we will:
    1. Enumerate the statements and sub-elements of the AST recursively
    2. Look for Call elements
    3. If the Call matches the decryptor method, we extract the argument provided to the Call
    4. We use these arguments to decrypt the string
    5. Finally, we replace the Call by a newly created Constant element that represent the decrypted string

(Note: The JEB python script is just a little over 100 lines, and took less than 1 hour to write. It could be greatly improved, for instance, the decryptor constants could be found programmatically, but this added complexity is out of the scope of this introductory blog post.)

Here what the deobfuscated code snippet looks like:

    ...
    protected void onCreate(Bundle arg5) {
        super.onCreate(arg5);
        this.setContentView(2130903040);
        if(new File("/data/last_alog/onboot").exists()) {
            MainActivity.鷭("rm /data/last_alog/*");
            MainActivity.鷭("cat /system/etc/install-recovery.sh > /system/etc/install-recovery.sh.backup");
            MainActivity.鷭("su", "/system/etc/su", this);
            MainActivity.鷭("supersu.apk", "/system/etc/supersu.apk", this);
            MainActivity.鷭("root.sh", "/system/etc/install-recovery.sh", this);
            MainActivity.鷭("chmod 755 /system/etc/install-recovery.sh");
            MainActivity.鷭(this);
            return;
        }
        ...
        ...

In part 3, we will show how to defeat a complex obfuscation scheme used by many bytecode protectors: reflection.