ISA 564, Laboratory 4 Android Exploitation Software Requirements: 1. Android Studio http://developer.android.com/sdk/index.html 2. Java JDK http://www.oracle.com/technetwork/java/javase/downloads/index.html 3. Android emulator http://developer.android.com/tools/devices/emulator.html 4. Android ADT plugin for Eclipse (if you use Eclipse instead of Android Studio) http://developer.android.com/sdk/installing/installing-adt.html Lab Exercise Steps: Android Application Repackaging In this lab you will learn how to repackage Android applications. This technique can be used for various purposes such as creating trojan applications, examining application behavior by performing dynamic analysis, and inserting an in-line reference monitor to enforce security policies. Repackaging applications and hosting them on third-party application marketplaces is a common way of disseminating malware and spyware. Social engineering can also be used to lure a user to install a trojan application. 1. Recommended reading The paper below introduces a framework named I-ARM-Droid to repackage Android applications to enforce security policies. http://web.cs.ucdavis.edu/~hchen/paper/most2012iarmdroid.pdf The link below is to an open-source project to repackage Android applications for dynamic analysis. https://github.com/pjlantz/droidbox 1
The open-source Soot project enables the user to convert Java or Dalvik bytecode to an intermediate representation which can be modified and converted back to Java or Dalvik bytecode. http://sable.github.io/soot/ Paper about detecting repackaged Android applications. http://www.cse.psu.edu/~sxz16/papers/trust2013.pdf 2. Resources baksmali and smali are open-source command line tools for disassembling and reassembling Dalvik bytecode to/from an intermediate representation called smali. This is the link to the source code: https://github.com/jesusfreke/smali. The smali format is a intermediate representation of the Dalvik bytecode and it is also the name or the reassembler. The baksmali.jar file disassembles the classes.dex file to a directory of smali files that are organized hierarchically according their package name. The classes.dex file contains the Dalvik bytecode. The smali files can be modified to remove and/or add in additional code into an application as long as it is consistent with the smali format. After the smali files have been modified, the smali.jar file can be used to convert the smali files back into a classes.dex file. Then additional steps are taken to repackage the application Please download the baksmali-2.1.0.jar and the smali-2.1.0.jar from this website: https://bitbucket.org/jesusfreke/smali/downloads The instructions in the Dalvik bytecode are explained in the links below. https://source.android.com/devices/tech/dalvik/dalvik-bytecode.html http://pallergabor.uw.hu/androidblog/dalvik_opcodes.html 3. Setting up the environment. Please have the Java Development Kit (JDK) installed on your computer so that can run Java executables and use the developer tools. When you install the JDK, this should also provide the jarsigner and keytool utilities. The latest JDK can be found at the following URL: http://www.oracle.com/technetwork/java/javase/downloads/index.html 2
Download Android Studio from the URL below, which includes the Android Software Development Kit (SDK) tools. You can alternatively use Eclipse if you also have the Android ADT plugin installed. http://developer.android.com/sdk/index.html You will need the Android SDK for the logcat and zipalign utilities and the Android emulator. If you do not have an Android device or do not want to use your Android device, then you can use the emulator. The instructions for creating and using the emulator are at the URL below. http://developer.android.com/tools/devices/emulator.html The directions for signing an APK are at the URL below. View the Signing Your App Manually to see how to generate an RSA key pair. It also has examples for how to use the jarsigner and zipalign utilities. http://developer.android.com/tools/publishing/app-signing.html 3
Laboratory Exercises Security Lab, ISA 564, R. Johnson, R. Murmuria, A. Stavrou Laboratory 4 Exercise 1. Create An Android application from source code The goal of this exercise is to familiarize you with Android development and get started with a simple Login application. The App will accept userid and password and send them to our remote server for verification. The following are the steps to build this app: Step 1: --------- Follow the instructions in the link: http://developer.android.com/training/basics/firstapp/creating-project.html You can choose any appropriate application and company name. For point #4, Minimum SDK, select API 19: Android 4.4 (Kitkat). For point #6 choose Login Activity. Once the app is created, launch the application by clicking on the play button in the menu. Choose any Android virtual device which supports API 19 or above. The default credentials that can be used to login is listed in a string array DUMMY_CREDENTIALS in the LoginActivity.java. If the app finishes (disappears), it signifies successful login. Step 2: --------- We will now update the source code to include a network query. First we will remove some unnecessary code from the LoginActivity.java. - Delete variables: REQUEST_READ_CONTACTS - Delete functions: populateautocomplete, mayrequestcontacts, onrequestpermissionresult, oncreateloader, onloadfinished, onloaderreset, ProfileQuery, addemailstoautocomplete - Delete line from oncreate function: populateautocomplete(); - Delete the interface "implements LoaderCallbacks<Cursor>" from LoginActivity class definition. Next, select Code-->"Optimize Imports" from the menu This will clean up the imports of this class to only include what is necessary. At this stage, run this App again to check if it is still functioning as intended. 4
Next, we will add the remote communication parts to LoginActivity.java. In attemptlogin() function, change the call: UserLoginTask(email, password) à UserLoginTask(this, email, password) Replace the class UserLoginTask with the following code: /** * Represents an asynchronous login/registration task used to authenticate * the user. */ public class UserLoginTask extends AsyncTask<Void, Void, String> { private Context mcontext; private final String memail; private final String mpassword; UserLoginTask(Context context, String email, String password) { mcontext = context; memail = email; mpassword = password; @Override protected String doinbackground(void... params) { String link; String data; BufferedReader bufferedreader; String result; try { data = "uid=" + URLEncoder.encode(mEmail, "UTF-8"); data += "&pass=" + URLEncoder.encode(mPassword, "UTF-8"); link = "http://main.kryptowire.com:8081/isa564signin.php"; URL url = new URL(link); HttpURLConnection con = (HttpURLConnection) url.openconnection(); con.setrequestmethod("post"); con.setrequestproperty("content-type", "application/x-www-formurlencoded"); con.setrequestproperty("content-length", "" + Integer.toString(data.getBytes().length)); con.setrequestproperty("content-language", "en-us"); con.setusecaches(false); con.setdoinput(true); con.setdooutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream ()); wr.writebytes(data); wr.flush(); wr.close(); bufferedreader = new BufferedReader(new 5
InputStreamReader(con.getInputStream())); result = bufferedreader.readline(); return result; catch (Exception e) { return new String("Exception: " + e.getmessage()); @Override protected void onpostexecute(final String result) { mauthtask = null; showprogress(false); if (result!= null) { try { JSONObject jsonobj = new JSONObject(result); String query_result = jsonobj.getstring("login_result"); if (query_result.equals("success")) { Toast.makeText(mContext, "Sign-in successfull.", Toast.LENGTH_SHORT).show(); else if (query_result.equals("failure")) { mpasswordview.seterror(getstring(r.string.error_incorrect_password)); mpasswordview.requestfocus(); else { Toast.makeText(mContext, "Couldn't connect to remote server.", Toast.LENGTH_SHORT).show(); catch (JSONException e) { e.printstacktrace(); Toast.makeText(mContext, "Error parsing response data from server.", Toast.LENGTH_SHORT).show(); else { Toast.makeText(mContext, "No response data received.", Toast.LENGTH_SHORT).show(); @Override protected void oncancelled() { mauthtask = null; showprogress(false); Finally, add the permission to make network connections in the AndroidManifest.xml file: <uses-permission android:name="android.permission.internet" /> Now, run the application again. Look for the toast message Sign-in Successful. If not, 6
troubleshoot the application. Security Lab, ISA 564, R. Johnson, R. Murmuria, A. Stavrou Laboratory 4 Submit a screenshot showing this successful sign-in message. Exercise 2. Repackage an application In this exercise, you will repackage an application without making any changes to the underlying code. 1. Find the location on your computer of the apk you created from step 1. Search for apk files on your computer if you are having difficulty finding it. Using Android Studio on my Mac, it was located at /Users/<username>/AndroidStudioProjects/<project name>/mobile/build/outputs/apk/mobile-debug.apk. If you are using Eclipse, it should be located at /Users/<username>/Documents/workspace/<project name>/bin/<project name>.apk. The apk file is actually a zip file to encapsulate the application code and its resources. Copy and unzip the apk file you created from exercise 1 to a directory of your choosing. Now use the cd command to move to the directory containing the contents of the zip file if needed. The current directory should contain a classes.dex file, an AndroidManifest.xml file, and additional files. unzip -d DoS DoS.apk cd DoS 2. Use the baksmali.jar file to convert the classes.dex file to a directory containing smali files that are organized hierarchically according to package name. This will create a directory named out in the current directory which contains the smali files if you do not provide an output directory. java -jar ~/Desktop/somedir/baksmali.jar classes.dex 3. Examine a few of the smali files to familiarize yourself with their format (https://source.android.com/devices/tech/dalvik/dalvik-bytecode.html). 4. Delete the current classes.dex file so you can create a new classes.dex file based on the smali files. rm classes.dex 5. Create a new classes.dex file from the directory of smali files using the smali.jar file. java -jar ~/Desktop/somedir/smali.jar -o classes.dex out 6. Delete the out directory since you have just created a new classes.dex file. 7
rm -r out 7. Delete the directory containing the previous signature of the application s files. rm -r META-INF 8. Zip the files in the current directory to a file name of your choosing to create a zip file of the application. zip -r DoS.zip * 9. Change the file extension of the zip file to apk if needed. mv DoS.zip DoS.apk 10. Use the instructions at the following URL (http://developer.android.com/tools/publishing/app-signing.html) to generate an RSA key pair and sign the apk file. jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-releasekey.keystore DoS.apk alias_name 11. Next you will need to align the application. There is an example of how to use the zipalign command line tool here: http://developer.android.com/tools/publishing/appsigning.html. If you are going to put the aligned application in the same directory as the unaligned application, then use a different file name for the aligned application. zipalign -v 4 DoS.apk DoSa.apk 12. You can delete the unaligned apk and rename the aligned apk to whatever you want. The aligned application is the final product. rm DoS.apk mv DoSa.apk DoS.apk 13. Now you can run the app by installing it via Android Debug Bridge (ADB). To use ADB, you will need to enable USB debugging on your Android device if you are not using the emulator. This is generally done by going to the Settings app. Locate and click on the About Device option. From there, click on the Build Number option multiple times until it says that you have become a developer. If this option does not work on your specific Android device, then you can search on the internet for how to enable USB debugging for your specific Android device. Then a new option called Developer options should appear 8
in the Settings menu. Enable USB debugging which will allow you to use ADB. The first time you connect a USB cable from your computer to the Android device, the Android device will ask you if you want to connect to the computer. In this dialog, select Always allow from this computer and select OK. You may also have to visit the security settings in the Settings app to enable installation of apps from unknown sources. If you are using your own Android device, you can undo these changes after you have finished the lab. The emulator should have ADB enabled by default. If not, you can use the same approach that was just given to enable USB debugging. You can then use ADB to install the app on your Android device or emulator by entering the adb install <appname>.apk command to install the app. This should install the app on your Android device or emulator. From here, you can click on the app icon in the launcher and run the app. Exercise 3. Repackage an application and modify its code. You will need to modify one smali file from the Login app to leak the username and password to the Android log. Please follow the instructions above for the repackaging operations as given in exercise 2. Any changes you make make to the smali file need to be in the correct format and syntax. If you use the correct format then, the modified smali files will be successfully converted into a classes.dex file. Locate the smali file where the login occurs. Then use the android.util.log.d(string, String) Android API call in smali format to write both the username and password to the log. This is a static Android API call so an android.utli.log object does not need to be explicitly prior to writing to the log. The username and password will be contained in a register that references a String. You can create a log tag to use as well. You can declare and initialize a String and select the register number for the log tag. Make sure that you select either a new register number or a previously used register number that is not used in the subsequent smali method which you are modifying. The first parameter to the android.util.log.d(string, String) Android API call is the log tag and the second parameter is the message to write to the log. You should be able to identify the register that contains the login and password and reference them in the smali. After modifying the smali and repackaging the app, it should write the username and password to the Android log when you log in. You can use adb logcat command to view the Android log and then redirect the output to a file just prior to running the repackaged application. Provide the file name and the entire smali method that contains your additions to write the login credentials to the log. Exercise 4. Repackage an application from Google Play Download the itriage Health app from Google Play at the following URL: https://play.google.com/store/apps/details?id=com.healthagen.itriage. Identify where the login and password data are being used to authenticate the user, then write them to the Android log by modifying a smali file. It may take a few tries to locate the smali file where the username and password will be visible in the Android log. You may want to copy the 9
directory containing the unzipped apk with the modified smali file(s) to another directory and build it from there so you can maintain previous modifications to the smali files over numerous builds of the repackaged application. The app will not allow you to successfully login after repackaging, but you should still be able to see the credentials in the Android log when you press the LOGIN button. Provide the file name and the smali method that contains your additions to write the login credentials to the Android log. Ensure that they are actually written to the Android log. Laboratory Submission - What to turn in Exercise 1: What does the server respond when you login successfully? Exercise 3: Turn in the file name and entire smali method that you modified to write the username and password to the log from the Login app. Exercise 4: Turn in the file name and entire smali method that you modified to write the username and password to the log from the itriage Health app. Extra credit: Why is the app not allowing you to properly login? Locate the smali file and the smali method that is performing an action that prevents the user from logging on successfully and explain what it is detecting. Hint: They are detecting that the app is repackaged. 10