Android Security

16
Android Security Mihaita Dulgheru University Politehnica of Bucharest SSA Email: [email protected]

description

Android Security

Transcript of Android Security

Page 1: Android Security

Android Security

Mihaita DulgheruUniversity Politehnica of Bucharest

SSAEmail: [email protected]

Page 2: Android Security

Abstract

Nowadays the usage of devices that are using Android as operating systemis in continuing increase and these devices must be secure and prevent dataleaking. The purpose of this paper will be to identify and explore the AndroidPlatform Security Architecture and study the form of Android spywareapplications that are developed using reverse engineering. The big problemof android applications is that most users do not check the permissions of theapplication loaded onto their mobile device and by using reverse engineeringthe application can have more rights than it should have. Knowing theandroid vulnerabilities this thesis will enounce useful methods to developapplications that are secured and keep the user information safe even throughthe communication protocol.

Page 3: Android Security

1 Introduction

Smartphones have gained tremendous popularity over the last few years. Inthis growing market of smartphones, Android, an open source platform ofGoogle has become one of the most popular Operating Systems. Androidis mainly used in smartphones and tablets??. Smartphones are acceptedand admired by many mainly because they are capable of providing servicessuch as banking, social networking, etc all on the go. They are equippedwith several features such as Wi-Fi, voice, data, GPS, etc. Android is anoperating system that is open-source, which is based on a modified version ofthe Linux kernel, initially developed by Android Inc., a firm purchased byGoogle in 2005. Google as a big company has understood that to be ableto had the same success as Apple (iPhone), they need to provide a way tousers to develop their own application, and as result the Android marketwill be rapidly populated with applications. This strategy was to providedevelopers an easy way to develop applications that extend the functionalityof the devices, using Android SDK and NDK (Native Development Kit).Because of Google Market rapidly was populated with applications, they havebeen forced to allow all users to develop and publish applications withouta rigorous control and approval, that led users to develop also maliciousapplication. Users can go on Android Market and download applicationsfrom there, but unlike some of the other platforms, Android does not restrictapplication distribution via application signing and long approval period.Even though an application has to be signed to be installed on a device, itis possible to use self-signed certificates. Furthermore, users can downloadapplications not only from Android Market, but also from third party ap-plication stores, such as slideme.org and androlib.com. Applications can begranted permissions, which are required to access critical phone resourcesor for inter-application communication. Those permissions are defined inadvance(in the AndroidManifest.xml file), by the developer who wrote theapplication and permissions are displayed to the user for approval beforethe application installation. For example,a developer might claim that hisapplication requires complete access to the settings of the phone, access toSMS/MMS reading and so on. So it is up to the user to check the validity ofthese permissions. There are many situations when an application may claimthat require complete access o protected files, or to access phone settings,send SMS/MSS. As result of this, is the obligation of user to check the validityof these permissions, and by granting these permissions is in total aware andaccept what application can or will do. This paper will show a new form ofspyware development using reverse engineering techniques. The studies hasshowed that most of the users are feeling confident about what they download

1

Page 4: Android Security

from Android Market, and this is because they are not checking applicationpermissions.

2 Android System Arhitecture

Android is a software stack for mobile devices that includes an operatingsystem, middleware and key applications. Android applications are mostoften written in Java using a dedicated SDK (Android Developers Guide-SDK, 11/2010), some applications such as game applications are developed inC/C++ using the Android NDK. Android includes a set of C/C++ librariesused by various components of the Android system. These capabilities areexposed to developers through theAndroid application framework, for examplethe Webkit library is used by the Browser application. As explained previously,most Android applications are written in the Java programming language.The compiled Java code, along with any data and resource files required bythe application, is bundled into an Android package (an archive file markedby an .apksuffix). This file is the vehicle for distributing the application andinstalling it on mobile devices (Android Developers Guide-Security, 11/2010).

Fig 1. Android Arhitecture

Each Android application is composed of several components that cancommunicate between each other using Intent messages(for inter and intraapplication communication).Here is alist of those components and a shortdescription of each one.

2

Page 5: Android Security

• Activity: An activity represents a visual interface that the user canuse to process actions. One application might be composed of severalactivities.

• Service: A service doesn’t have a visual user interface, but rather runsin the background for an indefinite period of time.

• Broadcast Receiver: A broadcast receiver does not display a userinterface but rather receives and may react to broadcast announcementsby starting an activity. For example when the phone receives an SMS,a broadcast message is sent by the system to inform that a message isavailable.

• Content Provider: A content provider is a kind of database where anapplication makes data available to other applications. More generallydata are stored in anSQLite database, for instance as shown below thebrowser application has a content provider to storebrowser history andbookmarks.

3 Android Security Model

Android is a multi-process system, in which each application (and parts ofthe system) runs in its own process. Most security between applications andthe system is enforced at the process level through standard Linux facilities,such as user and group IDs that are assigned to applications. Additional finer-grained security features are provided through a ”permission” mechanismthat enforces restrictions on the specific operations that a particular processcan perform, and per-URI permissions for granting ad-hoc access to specificpieces of data. (Android Developers Guide-Security, 11/2010)

Fig. 2: Android’Security’Model:’sandbox’and’permissions’mechanisms

3

Page 6: Android Security

In android there are three categories of data: personal information, sen-sitive input, and device metadata. The personal information refers to userinformation stored on phone such as contact list, photos, call log, messages,etc. The sensitive input refers to phone hardware which reveal informationabout the device such as GPS, microphone, audio system, accelerometer.Metadata is the most important data and represent uniquely identifier suchas IMEI, user system preferences, MSISN. To access sensitive data the appli-cation is asking for permissions to be granted by user at install time. Theuser is prompted with a screen asking whatever the application need to access.An example of such screen is shown in Fig.1. For example, an applicationmay request to access exact location of the phone by prompting the userto grant the ACCESS FINE LOCATION permission or internet by askingfor the INTERNET permission. The Android API provides developers witha list of over 100 default permissions to choose from. Developers are alsoallowed to define custom permissions for their applications which the useralso has to approve at install time. These custom permissions are usuallypermissions to access some specific bit of data or to mediate interactionsbetween applications.

Fig. 1: Permissions Access

4

Page 7: Android Security

4 Android Credentials

The Android framework provides two ways to handle credentials either usingthe Authentication Manager or the Shared Preferences. By using SharedPref-erences utility applications can user information like credentials and accountname.

Landroid/preference/PreferenceManager;>

getDefaultSharedPreferences(Landroid/content/Context;)

Landroid/content/SharedPreferences;

Fig 2. Shared Preferences

5 Android Reverse Engineering

5.1 Setting up the Ground

We need Android SDK, a target to test with and the necessary tools:

• Android SDK

• Deurus Android crackme 03

• Smali and baksmali

• Dex2jar

• Java decompiler

Download and install Android SDK, SDK platform(latest is 2.2 at thetime of writing), necessary Java packages and rest of the tools. Create avirtual device from SDK menu and start emulation. Within few minutes youcan see the emulator booting up and showing the phone screen.

5

Page 8: Android Security

5.2 Getting Started with the Game

Now we need to install the software(crackme, its legal!) to the emulator.For that you may have to get acquainted with Android debug bridge(adb).Installing a apk file is pretty simple, all you have to do is to run two commandsfrom Android SDK directory/tools.

Fig. 2: Installing apk using adb utility

Now run the crackme by clicking on it. If everything went as expected youwill see the crackme application on the screen. Pressing check button withno inputs pops a message ’Min 4 chars’, and with a proper name it pops up’Bad boy’. We have to remember these strings because we will be using themas our search keys when we disassemble the .dex files. Also note that we havetwo hardware ids and we need to find out what those exactly means.

6

Page 9: Android Security

5.3 Real Android Reversing

As our crackme is up and running in emulator, we now move onto reversingit. If you have read apk file format, you can visualize it as a extended JARfile which essentially is a zip file. Now you can change the crackme file namefrom Crackme03.apk to Crackme03.zip and decompress it to any folder.

Now the interesting file for us is classes.dex, which contains the compiled vmcodes. We are going to disassemble the dex file with baksmali. Commandsare pretty simple as you can see from screen shots.

If everything worked fine, we will have a folder structure similar to Javapackages. Interesting .smali files are located at /com/example/helloandroid.Open all the .smali files into your favorite text editor(I use Notepad++). Wehave just opened a disassembled dex file. Now, if you are thinking how onearth someone can find the correct location of checking function, I hope youremember those pop up strings I told earlier. Yeah, ’Min 4 chars’ and ’Badboy’. Now we will use those strings as our search keys. Searching ”Min 4chars” in all the opened .smali files, we will find a hit in HelloAndroid.smaliline 130.

7

Page 10: Android Security

Our aim is to understand the serial checking function and write a keygen forit. For that we have to know all the dalvik opcodes that are used here. Thealgorithm is pretty straight forward. It is using name and two hardware idsas input and doing some operations on them to make a serial. We can easilyrecode it in any programming language we prefer to make it as a keygen.

5.4 Decoding the Algorithm

A demonstrative serial calculation routine is given below:

Name: aaaaa HW ID1: 0000000000000000 HW ID2: 89014103211118510720

At first ’aaaaa’ will be converted to "9797979797", from which we will take first 5 letters and convert it into integer 97979, this will be xored with 0x6B016 resulting 511661 and this will be first part of serial.

For second part, we will take first 6 letters from HW ID1 and HW ID2, convert them to integer and xor, resulting 000000^890141 = 890141.

For third part we will use first 6 characters from HW ID1.

Formatting with the specified delimiter the serial will become "511661-890141-000000".

5.5 Final Verification of Reversing

Now we will put the same magic number into our Crackme application.

8

Page 11: Android Security

Bingo! everything worked as expected. Now, for all those who thinks itis pretty hard to read all those disassembled instructions and manuallyconverting them to higher language constructs, there are other options. Asdalvik is based on design of Java, it is also susceptible to decompilation.There is no decompiler available at this moment, but there is hope.

For now we can use another utility which converts dex files to jar files sothat we can use Java decompilers to see much more abstracted code. Fromstarting of this blog post you may have noticed the tool dex2jar. Use dex2jarto convert classes.dex to classes.dex.dex2jar.jar. Open it in a Java decompilerand you can see much better output than dalvik disassembly. Please notethat dex2jar is still in development phase and the output is meaningless atmany places. This should be used only to get a quick understanding of allthe functions.

6 Reverse Engineering - malware attack

Monkey patching refer to process of extending or modifying code at run-timewithout modifying the original source. Dynamic languages, such as java,make this particularly easy to accomplish.

As we all know in Android framework there are a lots of classes andmethods that are not available for the end user. Some of them not forexample explained in Android API, other are available only for the samepackage, these methods or classes are private or protected. The usually

9

Page 12: Android Security

available channels that are available for general uses are:

• HTTP requests

• SMS/MMS

• TCP connections

Because of that, the released application on the Android Market thatrequire READ PHONE STATE , INTERNET may contain services that have onbase a malware. This malware is hide and stealthy and may only interceptintent-based communications (register to specific event) or can transmit dataover the internet using encryption with cryptographic API.

These malware can be active remotely and can be awake by receiving anevent from a trigger. The known way to do that, are:

• Internet polling

• Short Messages (SMS)

• Class 0 Short Messages as a covert channel

To be able to develop such a silent malware, we will use java reflection.In order to understand what well need to do, first we must choose a targetsdk version that will act as main target. For this example our sdk version is7 and we will develop a way to automatically hang up or reject a call. Letstake a look on the following interface:

interface ITelephony {

void dial(String number);

/**

* Place a call to the specified number.

* @param number the number to be called.

*/

void call(String callingPackage, String number);

/**

* End call if there is a call in progress, otherwise does nothing.

*

* @return whether it hung up

10

Page 13: Android Security

*/

boolean endCall();

...

}

This interface define methods that are visible only in the same package.To solve this problem and to be able to reject an call we will use monkeypatching concept and the resulting interface will be:

interface ITelephony { ... public boolean endCall(); ... }

The malware should define in the AndroidManifest.xml file the following:

uses-permission android:name="android.permission.READ_PHONE_STATE"

uses-permission android:name="android.permission.MODIFY_PHONE_STATE"

uses-permission android:name="android.permission.CALL_PHONE"

Create a Receiver which accepts broadcasts with intent action android.intent.action.PHONESTATE, define following in the Manifest,

[receiver android:name=".PhoneCall"]

[intent-filter]

[action android:name="android.intent.action.PHONE_STATE"/]

[/intent-filter]

[/receiver]

Next we will override onReceive() method and using Java Reflection andtry to get the Instance of one of hidden class of Android Telephony Framework- com.android.internal.telephony.ITelephony .

private void stopCall() {

TelephonyManager tm = (TelephonyManager) context

.getSystemService(Context.TELEPHONY_SERVICE);

try {

// Java reflection to gain access to TelephonyManager’s

// ITelephony getter

Class c = Class.forName(tm.getClass().getName());

Method m = c.getDeclaredMethod("getITelephony");

m.setAccessible(true);

com.android.internal.telephony.ITelephony telephonyService = (ITelephony) m.invoke(tm);

telephonyService.endCall(); // will and the call

} catch (Exception e) {

11

Page 14: Android Security

e.printStackTrace();

Log.e(TAG,

"FATAL ERROR: could not connect to telephony subsystem (obtain an instance)");

Log.e(TAG, "Exception object: " + e);

}

}

Now by using telephonyService (which is an instance of com. android.internal. telephony. ITelephony) we can ”Accept”/”Reject” calls and manyother operations.

Another example of developing a malware is to extend the triggers touse Flash SMS (Class 0). This will make the malware silent and hard to bedetected. To do that the application require the permission to RECEIVESMS.

Android’s Telephony layer provides a SmsManager class that contains thesendTextMessage() method which can be used to send flash sms by exposingthe privat method called sendRawPdu().

Table 6.1: SMS PDU format

Offset Size Role

0 1 SMSC address

1 1 Message type

2 1 TP-Message Reference

... ... ...

Changing message type to use class 0 :

m2.setAccessible(true);

SmsMessage.SubmitPdu pdus = SmsMessage.getSubmitPdu(

null, PhoneNumber,message,false);

/* change class to Class 0 */

size = (int)pdus.encodedMessage[2];

size = (size/2) + (size%2);

pdus.encodedMessage[size+5] = 0xF0;

m2.invoke( sm,dus.encodedScAddress,pdus.encodedMessage,

Null,null );

12

Page 15: Android Security

This example show how application can exploit operating system vulnera-bility just using Reverse Engineering, and by overriding interfaces classes ofthe system and loading classes with Java Reflection an application can gainaccess to unlimited resources.

13

Page 16: Android Security

7 Bibliografie

1)http://developer.android.com/reference

2)http://www.moses.rutgers.edu

3)Android Malware Exposed, Grayson Milbourne & Armando Orozco,August 2012

4)B. Wissingh and T. Kruger ”Privacy Issues with the Android MarketRP1 Project Paper”

5)Android Reverse Engineering - A Kick Start

14