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
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.
Sample MD5 68DF97CD5FB2A54B135B5A5071AE11CF is available on Contagio.
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.
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:
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
Look for Call statements (eg, foo()), or Assignments whose right part is a Call (eg, r = bar())
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.
Extract the reflection information:
Fully-qualified name of the class
Method name and prototype
Invocation arguments
Create a new method, register it to the DEX object
Create a Call element that accurately mirrors the reflection calls Note: There are limitations, especially considering the return type
Finally, replace the reflection call by the direct method call
A deobfuscated / “unreflected” version of the source code above looks like:
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.
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:
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:
Search the encrypted byte array
Enumerate the fields of the class
Look for a byte[] field marked private static final
Verify that this field is referenced in <clinit>, the static {…} initializer for the class
The field should also be referenced in another method: the decryptor
Check the structure of <clinit>
It should look like: encrypted_strings = new byte[]{………}
Retrieve the encrypted bytes
The decryptor was analyzed in a previous blog post
The decryptor constants need to be extracted manually (let’s keep the script simple)
Then, for every method of the class, we will:
Enumerate the statements and sub-elements of the AST recursively
Look for Call elements
If the Call matches the decryptor method, we extract the argument provided to the Call
We use these arguments to decrypt the string
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:
This is the first post of a 3-part blogs series that will demonstrate the new features of JEB’s jeb.api.ast API package.
Classes of this package allow read and write access on the Abstract Syntax Trees (AST) of the decompiled Java code produced by JEB. In a nutshell, it allows power users to implement complex deobfuscation schemes or their own optimizations strategies.
JEB decompiles this Dalvik bytecode to the following Java code:
public TileView(Context arg5, AttributeSet arg6, int arg7) {
super(arg5, arg6, arg7);
label_3:
switch(1) {
case 0: {
goto label_3;
}
case 1: {
goto label_6;
}
}
while(true) {
switch(0) {
case 0: {
goto label_6;
}
case 1: {
goto label_3;
}
}
}
label_6:
this.b0431бб0431б0431 = new Paint();
label_8:
switch(0) {
case 0: {
goto label_11;
}
case 1: {
goto label_8;
}
}
while(true) {
switch(0) {
case 0: {
goto label_11;
}
case 1: {
goto label_8;
}
}
}
label_11:
TypedArray v0 = arg5.obtainStyledAttributes(arg6,
xkkxkk.b04310431б0431б0431);
int v1 = v0.getInt(0, 12);
label_15:
switch(0) {
case 0: {
goto label_18;
}
case 1: {
goto label_15;
}
}
while(true) {
switch(0) {
case 0: {
goto label_18;
}
case 1: {
goto label_15;
}
}
}
label_18:
switch(1) {
case 0: {
goto label_15;
}
case 1: {
goto label_21;
}
}
while(true) {
switch(1) {
case 0: {
goto label_15;
}
case 1: {
goto label_21;
}
}
}
label_21:
switch(0) {
case 0: {
goto label_24;
}
case 1: {
goto label_15;
}
}
while(true) {
switch(1) {
case 0: {
goto label_15;
}
case 1: {
goto label_24;
}
}
}
label_24:
TileView.bб0431ббб0431 = v1;
v0.recycle();
}
As one can see, dummy switches as well as pseudo-infinite loops have been inserted within the original Java code, in order to produce flow obfuscation. Using the AST API, we’re going to implement a JEB plugin that cleans the obfuscated code.
A dummy switch construct looks like the following:
switch(X) {
case X:
goto next;
case Y:
goto label_fake1:
case Z:
goto label_fake2:
}
...
next:
The above piece of code is equivalent to:
goto next;
...
next:
Which can be reduced to a single label:
next:
In order to find the dummy switches, the JEB script is going to do the following:
Recursively enumerate the statements of a method body, looking for SwitchStm elements
Check that the switch is a dummy switch:
The switched expression must be a Constant
The case block associated with that constant must start with a Goto statement
Replace the switch by the goto
Find the first Label that follows the (now replaced) switch
If a label is found, is at the same block level as the switch, and is the label pointed to by the goto that replaced the switch, then all the expressions between the goto and the label can be discarded
Finally, apply standard JEB optimizations that remove the remaining useless gotos and labels
This algorithm fits in a less than a 100-line Python script. Download the script, experiment with it, and get accustomed to the API.
The cleaned-up code is this very simple, more readable method:
public TileView(Context arg5, AttributeSet arg6, int arg7) {
super(arg5, arg6, arg7);
this.b0431бб0431б0431 = new Paint();
TypedArray v0 = arg5.obtainStyledAttributes(arg6,
xkkxkk.b04310431б0431б0431);
int v1 = v0.getInt(0, 12);
TileView.bб0431ббб0431 = v1;
v0.recycle();
}
In Part Deux, we will show how the AST API can be leveraged to decrypt encrypted strings of a protected piece of code.
The API that shipped with JEB 1.3 allows direct access to the Android Manifest. Here, we are just demonstrating how some of the new methods that shipped with the API. This plugin allows a user to jump from an Activity tag in the manifest to the corresponding code in the Assembly view:
#? name=Jump to an Activity, shortcut=Ctrl+Shift+J
from jeb.api import IScript
from jeb.api.ui import View
from jeb.api.ui import CodePosition
class JumpToActivity(IScript):
def run(self, jeb):
# basic requirements
ui = jeb.getUI()
if not ui:
return
if jeb.getApiVersion() < 2:
print 'Please upgrade to JEB 1.3'
return
ui.focusView(View.Type.MANIFEST)
v = ui.getView(View.Type.MANIFEST)
if not v:
print 'No Manifest'
return
# whole copy of the Manifest
text = v.getText()
# retrieve the package name
pname = ''
pos = text.find('package="')
if pos >= 0:
pos += 9
pos1 = text.find('"', pos)
if pos1 >= 0:
pname = text[pos:pos1]
# the Activity name should be the on-caret item
aname = v.getActiveItem()
if not aname:
print 'Please position the caret on the Activity name'
return
# absolute class classname
if aname.startswith('.'):
if not pname:
print 'Package name not found'
return
aname = pname + aname
ui.focusView(View.Type.ASSEMBLY)
a = ui.getView(View.Type.ASSEMBLY)
if not a:
print 'No Assembly view'
return
# internal class name
classname = 'L' + aname.replace('.', '/') + ';'
if not a.setCodePosition(CodePosition(classname)):
print 'Class not found: '+aname
ui.focusView(View.Type.MANIFEST)
Feel free to experiment with the script, and customize it to your needs. Leave a comment if you have any questions. More sample scripts will be posted in the next week to showcase more other capabilities of API v2.
JEB 1.3 ships with two plugins that allow users to create signatures for library code, and apply signatures onto DEX files. (Note: we are not talking about digital signatures here, but rather, binary strings that are used to identify a method or body of code.)
Combined with the new navigation bar, portions of a DEX file that contain third-party frameworks (such as those ubiquitous ad libraries) or already analyzed code, can be easily identified: such areas will be marked using a light-green color in the navigation bar.
Applying signatures
In practice, applying signatures is extremely easy:
1- Load the file in JEB: as can be seen below, the navigation bar is mostly blue, which means no library code has been spotted yet. (Note: The orange marks identify public constant fields – public static final.)
2- Fire up the Library Recognition plugin. (Menu: Action / Custom Action / Library Recognition.)
3- By default, the plugin looks for library signature files (*.sig extension) stored in the “sigs” sub-directory.
4- The signatures are applied where they can be applied, and the results are visible both in the navigation bar (the light-green portions) and the console window. Here, many Google AdMob routines were recognized; it appears they make up for more than half of the entire DEX file.
Close examination of the navigation bar shows that it is divided into two parts:
The upper half concerns methods and fields.
The lower half concerns classes as a whole.
Due to how the matching algorithm works, an entire class may be marked as library code, when not all corresponding methods and fields may be.
Creating signatures
JEB ships with library signatures for popular Google and Android frameworks. But it is also extremely easy to create your own library signatures.
Let’s take an example. That same APK file contains the Android Support classes; let’s sign them.
1- Execute the Signature Generator plugin. (Menu: Action / Custom Action / Signature Generator.) Note that the plugin may also be executed from the command line and take arguments from the command line, in Automation mode. This is particularly useful for bulk signature creation.
2- The plugin asks the user for two pieces of information:
The library name: it is recommended to use the format “<libraryname>-<version>”. Here, we will go for: android-support-13
The regular expression that identifies which methods should be signed. We want to sign all methods of the android.support.v4 package, so we will input: Landroid/support/v4/.* (Java internal name convention)
After proceeding, the plugin signs the target code. The signing results appears in the Console window:
3- The signature file is created in the “sigs” directory. Later on, when you apply signatures to other DEX files, the android-support signatures will be automatically checked and matched against those DEX files.
If you were to re-apply signatures to the currently examined APK file, the android-support methods and classes would obviously be matched, and the navigation bar would reveal that most of this APK is library code:
In a future blog post, we will spend some time describing how the signing and matching algorithms work. Keep in mind the library code signing/matching system is plugins-based, which means it can be customized or tweaked by JEB users. Just have a look at the ApplySigs.py and GenSig.py files in the plugins directory if you’re curious about that.
This threat was initially reported by Kaspersky and seems to have gathered quite some amount of attention lately.
I’m attaching the sources decompiled by JEB 1.2 to this post, for analysts who’d like to take a look at it. One particularity of OBad: it’s been protected by a well-known commercial obfuscator (which was briefly mentioned here and there). This protector employs generalized string encryption and calls methods through reflection, which makes raw source code a bit difficult to read – the sources have not been refactored and marked-up, the usefulness of it all is very limited: you be warned.
Jurriaan Bremer was kind enough to provide oboy.dex, a version of OBad with encrypted strings replaced by their decoded versions. JEB handles the file okay, despite the multiple string duplicates (which is one of the reasons why it could not be loaded on a phone.) I’ve attached the decompiled sources for his version below. (I also disabled the try-catch support for improved clarity.)
This Android malware was referenced in a recent blog post (http://www.xchg.info/?p=46) and I thought analysts would be interested in checking out the decompiled bytecode.
Java files for live.photo.savanna and com.androways.advsystem: BadNewsA_Src.zip