Manual For Mobile Security Dr.Li-Yang. Vivek Vijayan. Table of Contents Installation tutorial for Android SDK with Eclipse. Installation of JDK---------------------------------------------------------2. Installation of Eclipse------------------------------------------------------3. Installation of Android SDK for eclipse--------------------------------3. Threats of Lost or Stolen Mobile Devices. Backup ----------------------------------------------------------------------12. Encryption-------------------------------------------------------------------17 Remote Lock or Wipe------------------------------------------------------21. Unauthorized Mobile Resource Access. Authentication: Single Sign-on-------------------------------------------24. Authentication: Two Factor Authentication----------------------------26. Data, Location and Cryptography Privacy. Encryption/ Decryption on SMS-----------------------------------------35. Mobile Malware Detecting and removing malware via tool------------------------------63. Mobile Malware Attack : Trojan-----------------------------------------66. Mobile Malware Defense--------------------------------------------------73. Mobile Spyware Detecting and removing spyware by tool------------------------------76. “Penetration Test and Analysis” on Spyware Threat/Attack--------80. Defence: Reverse Engineering Analysis-------------------------------83. 1|Page Installation tutorial for Android SDK with Eclipse Download jdk from the site JDK: http://www.oracle.com/technetwork/java/javase/downloads/jdk-6u26download-400750.html (Here we download jdk for Windows x86) Here we download windows X86 for windows version . Download the version that supports your operating System 2|Page Downloading Eclipse Download Eclipse (Java EE Developers): http://www.eclipse.org/downloads/ Install the version that supports your operating system. Downloading Android SDK Download Android SDK: http://developer.android.com/sdk/index.html From the site Download the version that supports your operating system we can also download SDK for other platforms by selecting the option download for other platforms 3|Page Here we Download Windows 32 bit for Windows Download the file and extract the file to a particular location of your choice once extracted you will find two folders created - Eclipse - SDK Open Eclipse and start the SDK Manager on Eclipse SDK Manager can be found below the menu options search for the symbol below to run SDK Manager 4|Page Above screen shot shows how Andorid ADT for Eclipse looks like Below is a screen shot of how a SDK Manager looks like Install Android 2.3.3. Package as all the versions of android support Android 2.3.3 Package and download Google USB Drive Package from Extras. The default Andorid version selected is Andorid 4.2(API 17) which is the latest version of android for the android based phones. 5|Page We need to install Android 2.3.3 package and integrate the ADT eclipse with Android 2.3.3. Now go to Help Tab in eclipse ADT and click on install new software and paste the link in work with tab https://dl-ssl.google.com/android/eclipse/ . 6|Page Installation of ADT Plugin Follow the below steps to install ADT plugin for eclipse Start Eclipse, then select Help > Install New Software. Click Add, in the top-right corner. In the Add Repository dialog that appears, enter "ADT Plugin" for the Name and the following URL for the Location: https://dl-ssl.google.com/android/eclipse/ Click OK. If you have trouble acquiring the plugin, try using "http" in the Location URL, instead of "https" (https is preferred for security reasons). In the Available Software dialog, select the checkbox next to Developer Tools and click Next. In the next window, you'll see a list of the tools to be downloaded. Click Next. Read and accept the license agreements, then click Finish. If you get a security warning saying that the authenticity or validity of the software can't be established, click OK. When the installation completes, restart Eclipse. After completing the installation we need to follow the below steps for successful application of the Andorid 2.3.3 package for Eclipse. Go to Window options from the Eclipse Menu and click on Preferences from the drop down list . Check the SDK Location is same as the location that you have installed your <ADT Bundle> -<operating System>-<version>. If it is not the same then we need to correct it and see that the SDK location path is the same as the installation path. 7|Page Select Android 2.3.3 and click on apply. Running the Android Virtual Device Manager Android Virtual Device Manager is also called as the emulator. The Android SDK includes a mobile device emulator- a virtual mobile device that runs on your computer. The emulator lets you develop and test Android applications without using a physical device. Below Screen shot shows how an Android Virtual Device Manager looks like. 8|Page Now click on Edit button and select the options that best suits your requirement for an emulator. Once selected click on OK button and you should be able to see the below screenshot. Now we need to start the emulator. 9|Page Select the AVD Name and Click on Start . Once we click on start we see the following interface now click on Launch button. The Emulator takes time to start for the first time. 10 | P a g e Once started the following interface shows up in the emulator which looks the same as any android application interface. Closer Look at the emulator. 11 | P a g e Threats of Lost or Stolen Mobile Devices Backup-Protect mobile data before it is lost or stolen The following steps show how to install an application on an emulator and the remaining steps show how to download a security app on your device and use the app for mobile security. Installation of an android app in an emulator: These steps show how to download and install an android app in an emulator. We will do this by downloading and installing Mobile backup 2 app . Download Mobilebackup2.apk Rename the file if you like to and place it in platform tools folder of your installed SDK folder location eg: Here we have renamed the file to mob2.apk Now open command prompt and go to the location of app placed Now type the following command adb devices to see if the emulator is detected Now install the app by giving the command adb install mob2.apk (give the name of the app that you have downloaded with .apk extension ). 12 | P a g e Once you get the success message this indicates that the app has been successfully installed in the emulator. Click on the app Mobile backup II and we see that the app is up and running on the emulator. 13 | P a g e Downloading and installing the app on your mobile device : Download the app Mobile Backup 2 from googly play store. Click on the following link you can do this from your mobile device see that your mobile supports android applications. https://play.google.com/store/apps/details?id=mobilehome.backup&feature=search_re sult#?t=W251bGwsMSwxLDEsIm1vYmlsZWhvbWUuYmFja3VwIl0. Install the app to your mobile device. Once the app is downloaded and installed run the app Mobile Backup2 you can see the following screen. 14 | P a g e Click on SMS option to take back up of your SMS log. We have also taken the backup for contacts. In this manual we have taken the backups for SMS and Contacts. Once we take the backup we see the below screen. 15 | P a g e If we try to take Backup for SMS again then below screen pops up with two options - Overwrite Previous backup file: It overwrites the stored backup file that was previously saved. Append to Previous backup file: This option appends the data to previously stored backup file. To Restore Backed up data click on restore button. 16 | P a g e Encryption- Protect mobile data before it is lost or stolen Download BoxCryptor App from the google play store into your mobile device . After installing BoxCryptor , you can see the below screen on your phone. Box Cryptor allows you to use several tools to store your encrypted files. Such as Dropbox, GoogleDrive , Microsoft SkyDrive, WebDAV and also SD Card . We will use SD Card to store the data . Tap on “Connect to SD Card”. Once you tap on Connect to SD Card it shows you the list of folders available that contain files which can be encrypted. 17 | P a g e Tap on the Add a new folder icon. Once you tap you can see the below screen on your mobile device. Enter the name, password and the confirm tab and then tap on Advanced then you get to the sreen shown below. 18 | P a g e In Encryption Algorithm select AES-256. Once completed you get to the screen below. Now tap on the icon shown below on your mobile device. Once tapped it shows you the categories of folders that contain the files that you would like to encrypt. 19 | P a g e We have selected an Image File from the Gallery folder. Once we select the file it gets encrypted as shown in the below screen shot. To decrypt the file tap on the encrypted file and the file would get decrypted. 20 | P a g e Remote lock and wipe- Protect mobile device after it is lost or stolen Download Antivirus app from google play on your mobile device. Tap on Anti-theft option and you will be asked to register on the site. Once registered you will be notified as shown in the below screen shot. 21 | P a g e Browse for the site www.avgmobilation.com log in using your google account. You can try any of the options such as Shout, Locate, Lock, Unlock, Wipe, Scan. For the manual we have experimented on Locate and Lock. Once you click on Locate the app locates your mobile device and the location is displayed on a google map. 22 | P a g e By clicking on Lock Device you will be prompted to enter a password which can be later used to unlock the device. As you click on the Next option your mobile device gets locked the below Screen shot shows how the screen looks like when your mobile gets locked. 23 | P a g e To Unlock the device enter the password that was entered in the beginning. Unauthorized Mobile Resource Access This tutorial covers the following two lab activities - Authentication: Single Sign-on. - Authentication: Two Factor Authentication. Authentication : Single Sign-on Single Sign-on is a property of access control of multiple related, but independent software systems. With this property a user logs in once and gains access to all systems without being prompted to log in again at each of them. As different applications and resources support different authentication mechanisms, single sign-on has to internally translate to and store different credentials compared to what is used for initial authentication. The following steps guide us as to how one can apply this feature on an android device. In your Android device go to Settings -> Accounts and Sync as shown below. 24 | P a g e Touch Add Account on you android phone. Now touch the facebook logo on your android browser. The Next screen that appears is your facebook login screen enter your username and password. 25 | P a g e Once you login the next screen gives us three selections, Sync Contacts, Add all friends and Sync calendar. Finally touch Sync. Now the facebook account sync with your mobile phones, it means you needn’t sign up to the facebook by entering Email and Password when you use your mobile device. Authentication : Two factor authenticaiton Most security processes like Facebook or email providers like Hotmail and Yahoo! Only let user provide one factor like a Username and a Password. However, in Two Factor authentication, it requires user two factors in order to prove user’s identity. The other factor is typically a physical token, such as a mobile phone or a card. In this context, the two factors involved are something spoken of as something you have and something you know. It just like, when you go to a bank, you can’t get money only by providing your Username and Password. You must have the second Factor (a bank card). This can be a common example of Two Factor Authentication. How to enable Two Factor Authentication in Dropbox account In Online world, we use two factors authentication by our mobile devices. The second factor can be a mobile app which displays a number every 30 seconds. Go to Google Play store search and download Google Authenticator. 26 | P a g e Install the App on your mobile device. Once you download the app you she be able to see the screen below on your android device. 27 | P a g e Using your PC, go to Dropbox homepage (dropbox.com). If you already have a Dropbox account, sign in. If not, create and account. The homepage looks like the screen below. Once you register and login you should be able to see the below home page. 28 | P a g e Click on your name and go to Settings. You get the below page. On this page click on security tab. 29 | P a g e On the Securitry tap page you can see the two step verification option, initially it is Disabled now click on change. You get a new window as shown below now click on get started. 30 | P a g e You get another window that asks you for a password. The next window shows two methods to enable two-step verification, here we choose use a mobile app, click Next. 31 | P a g e Once clicked on next you will be a given a QR code which should be scanned using your mobile device. In this step we use our mobile device, touch to open Google Authenticator. Then touch Scan a barcode option. 32 | P a g e After scanning the barcode on your PC screen, it will give you a set of numbers. You must type these numbers before the time is over. If it is over, it will give you a new number. Type the correct numbers and click next. The next window asks for the security code generated by your mobile authenticator app make sure you enter the code before the clock runs out. 33 | P a g e Finally, it will give you a emergency backup code, if you ever lose your phone you can disable two-step verification and access your account by it. If everything is done, click Enable two-step verification. Once you click on Enable two-step verification you should see the below window. 34 | P a g e Now, you can sign in your Dropbox account again, you will find it requires the security code that is generated by your mobile authenticator app. Permission objective We will need to request some permissions for our projects, but how to use these permissions could be a big issue in few cases. This lab gives a general idea of SMS permission and internet permission. The test result is shown if the project moves the permission out Software Requirement Eclipse IDE Java JDK, JRE Android SDK Tutorial Create a new android project Project Name: Permission Target Name: Android 2.2.2 Package Name: Android. Permission Copy and paste the following code to Permission->res->layout->main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/interb" android:text="Internet"></Button> <Button android:layout_height="wrap_content" android:id="@+id/smsb" android:text="SMS" 35 | P a g e android:layout_width="74dp"></Button> </LinearLayout> Create new xml file in permission->res->layout, name it internet.xml then copy and paste following code <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <WebView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/webView"></WebView> </LinearLayout> Create a new xml file in Permission->res->layout, name it sms.xml, then copy and paste the following code <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:weightSum="1"> <LinearLayout android:id="@+id/linearLayout1" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:layout_width="wrap_content" android:id="@+id/textView1" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="To: "></TextView> <EditText android:layout_width="wrap_content" android:layout_weight="1" android:layout_height="wrap_content" android:inputType="phone" android:id="@+id/addr"> <requestFocus></requestFocus> </EditText> </LinearLayout> <TextView android:id="@+id/textView2" android:textAppearance="?android:attr/textAppearanceLarge" android:layout_width="match_parent" android:layout_height="11dp"></TextView> <MultiAutoCompleteTextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="0.59" android:id="@+id/Text"></MultiAutoCompleteTextView> <TextView android:id="@+id/textView4" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:layout_width="match_parent" android:layout_weight="0.06"></TextView> <LinearLayout android:id="@+id/linearLayout2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="0.16" android:weightSum="1"> 36 | P a g e <TextView android:id="@+id/textView3" android:textAppearance="?android:attr/textAppearanceLarge" android:layout_height="match_parent" android:layout_width="wrap_content" android:layout_weight="0.33"></TextView> <Button android:layout_width="wrap_content" android:layout_weight="0.29" android:layout_height="72dp" android:id="@+id/send" android:text="SEND"></Button> </LinearLayout> </LinearLayout> Go to Permission->src->Andorid.Permission, then create two file “IntentActivity.java” and “SMSActivity.java” .Copy and paste the following code in “PermissionAcitivity.java” package Android.Permission; import Android.Permission.R; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class PermissionActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { final Context context = this; super.onCreate(savedInstanceState); setContentView(R.layout.main); final Button interb=(Button)findViewById(R.id.interb); final Button smsb=(Button)findViewById(R.id.smsb); //Internet Button listener interb.setOnClickListener(new OnClickListener() { public void onClick(View v) { //Start Internet Activity Intent intent = new Intent(context, InternetActivity.class); startActivity(intent); } }); //SMS Button listener smsb.setOnClickListener(new OnClickListener() { public void onClick(View v) { //Start SMS Activity Intent intent = new Intent(context, SMSActivity.class); startActivity(intent); } }); } 37 | P a g e } Copy and paste the following code in “IntentActivity.java” package Android.Permission; import android.app.Activity; import android.os.Bundle; import android.webkit.WebView; public class InternetActivity extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.internet); final WebView webView = (WebView) findViewById(R.id.webView); webView.getSettings().setJavaScriptEnabled(true); webView.loadUrl("http://www.google.com"); } } Copy and paste the following code in “SMSActivity.java” package Android.Permission; import android.app.Activity; import android.app.PendingIntent; import android.content.Intent; import android.os.Bundle; import android.telephony.gsm.SmsManager; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; @SuppressWarnings("deprecation") public class SMSActivity extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sms); final Button send=(Button)findViewById(R.id.send); final EditText text=(EditText)findViewById(R.id.Text); final EditText addr=(EditText)findViewById(R.id.addr); send.setOnClickListener(new OnClickListener() { public void onClick(View v) { //get address and text String maddr=addr.getText().toString(); String mtext=text.getText().toString(); SmsManager smsmanager=SmsManager.getDefault(); // send message if(maddr.trim().length()!=0&&mtext.trim().length()!=0) 38 | P a g e { try{ PendingIntent pintent=PendingIntent.getBroadcast(SMSActivity.this, 0, new Intent(), 0); smsmanager.sendTextMessage(maddr, null, mtext, pintent, null); } catch (Exception e) { e.printStackTrace(); } Toast.makeText(SMSActivity.this, "sending success", Toast.LENGTH_LONG).show(); } else Toast.makeText(SMSActivity.this, "Enter Address and Message", Toast.LENGTH_SHORT).show(); }; }); } } Finally go to Permission-> AndoridManifest.xml, copy and paste following code to it. <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="Android.Permission" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="8" /> <application android:icon="@+drawable/icon" android:label="@string/app_name"> <activity android:name=".SMSActivity" android:theme="@android:style/Theme.NoTitleBar" /> <activity android:name=".InternetActivity" android:theme="@android:style/Theme.NoTitleBar" /> <activity android:name=".PermissionActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-permission android:name="android.permission.SEND_SMS"></usespermission> <uses-permission android:name="android.permission.INTERNET" /> </manifest> Save and run the project, and one can see the below result: 39 | P a g e When Internet button is clicked it will visit to google.com Back to the main interface, click the SMS button. Start the new emulator and send a message to it. 40 | P a g e Then 5554 emulator will receive the message Go back to Pernission-> AndroidManifest.xml, delete following permission code from this file. <uses-permission android:name="android.permission.SEND_SMS"></usespermission> <uses-permission android:name="android.permission.INTERNET" /> Then save again, run the project again. When click the internet button it cannot connect to the internet 41 | P a g e Data, Location and cryptography Privacy Encryption/Decryption on SMS This lab creates a secure SMS Android Application. The secure SMS application that is designed utilizes encryption and decryption, which means that if there is some malware threat in the middle and the threat tries to intercept or view our short message body it will get nothing but some random bytes (the so-called cypher text). Software requirement for this lab - Eclipse IDE. Android SDK. Tutorial Create a Project Name : EncDecSMS. Target Name : Andorid 2.2.2. Package Name : android.encdecsms. Copy the following XML code to layout -> main.xml : <?xml version="1.0" encoding="utf-8"?> 42 | P a g e <LinearLayout xmlns:android="http://schemas.android.com/apk/res/andro id" 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/textA ppearanceMedium" /> </LinearLayout> <EditText android:id="@+id/recNum" android:layout_width="match_parent" android:layout_height="wrap_content" 43 | P a g e 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/textAppea ranceMedium" /> <EditText android:id="@+id/secretKey" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPassword" /> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Message:" android:textAppearance="?android:attr/textAppea ranceMedium" /> 44 | P a g e <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" /> 45 | P a g e </LinearLayout> </LinearLayout> This following code will create a layout as shown in the below screen: Create another layout under the folder, name it as onreceive.xml 46 | P a g e Use the following code in onreceive.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/andro id" 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/textAppea ranceMedium" /> 47 | P a g e <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/textA ppearanceMedium" /> </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/textAppea ranceMedium" /> <EditText android:id="@+id/secretKey" android:layout_width="match_parent" 48 | P a g e android:layout_height="wrap_content" android:inputType="textPassword" > <requestFocus /> </EditText> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Received Encrypted Message:" android:textAppearance="?android:attr/textAppea ranceMedium" /> <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/textAppea ranceMedium" /> 49 | P a g e <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> 50 | P a g e </LinearLayout> The above code will create a layout as shown below: Create EncDecSMSActivity.java and use the following code in it : 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; 51 | P a g e 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 52 | P a g e 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) { // encrypt the message byte[] encryptedMsg = encryptSMS(secretKeyString, msgContentString); 53 | P a g e // 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 54 | P a g e 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(); } } // 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; 55 | P a g e } 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; 56 | P a g e } catch (Exception e) { e.printStackTrace(); byte[] returnArray = null; return returnArray; } } private static Key generateKey(String secretKeyString) throws Exception { // generate secret key from string Key key = new SecretKeySpec(secretKeyString.getBytes(), "AES"); return key; } } Now Create two new classes and name them as “DisplaySMSActivity.java” and “SMSBroadCastReceiver.java”. Use the below code for “DisplaySMSAcitivity.java” : package android.encdecsms; import java.security.Key; 57 | P a g e 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); 58 | P a g e setContentView(R.layout.onreceive); 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 { 59 | P a g e // 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 String secretKeyString = secretKey.getText().toString(); //key length should be 16 characters as defined by AES-128-bit 60 | P a g e 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!", 61 | P a g e 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); b2[n / 2] = (byte) Integer.parseInt(item, 16); } return b2; } // decryption function public static byte[] decryptSMS(String secretKeyString, byte[] encryptedMsg) throws Exception { 62 | P a g e // 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; } } 63 | P a g e Use the following code for “SmsBroadCastReceiver.java” : package android.encdecsms; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.telephony.SmsMessage; 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); 64 | P a g e 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 65 | P a g e in.putExtra("originNum", originNum); //fill the entire message body into Intent in.putExtra("msgContent", new String(sb)); //start the DisplaySMSActivity.java context.startActivity(in); } } Now go to AndroidManifest.xml and use the following code: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/andro id" package="android.encdecsms" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" /> <uses-permission android:name="android.permission.RECEIVE_SMS"></usespermission> <uses-permission android:name="android.permission.SEND_SMS" /> 66 | P a g e <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> 67 | P a g e </manifest> Now open two emulators on the eclipse and run the android project “EncDecSms” on both the emulators. The first emulator serves as a sender which sends encrypted short message to Emulator2. The emulator2 serves as a receiver which receives the short message from Emulator1 and decrypts the received cipher text message. The Emulator1 has information such as recipient, 16-character AES secret key and the message body. The AES secret key should be a 16-character input. This is because in the AES encryption algorithm we use a 128-bit block cipher which uses a 128-bit, 192-bit or a 256-bit secret key. In this tutorial we set it to accept a 16 character (128-bit) secret key and we use “1111111111111111” as secret key demonstration. On filling the following details we press the “Send” button where the message is sent to the “Emulator2” and the received message looks like the screen below: 68 | P a g e “On Emulator2” we see that the sender’s number and the received encrypted messages has been filled. Now enter the “16-character secret key” that was entered on the “Emulator1” and then click on “submit” button. Once you click on “Submit” button the encrypted message is decrypted and displayed in the “Decrypted Message” field as shown below: 69 | P a g e If the entered “16-character secret key” is not correct or if the received message is corrupted, the message will not be decrypted. Encyption RSA Pending Mobile Security Labware Detecting and removing malware via tool This lab introduces the detection of a real-world Android Malware with the use of off-the shelf Anti-malware Applications. We will install an anti-malware and a malware on the android phone and demonstrate the detection and removal of the malware. 70 | P a g e In the above screenshot we can see the downloaded mobileCare application on the emulator. http://contagiominidump.blogspot.com/2011/07/droidkungfu2.html Download droid kungfu2 from the above site and use the zip file password is infected. Install the Trojan.apk in emulator After the installation the malware is detected by advance mobile care app. 71 | P a g e Click on delete and then we get the below screen Once uninstalled we will get an confirmation as shown below 72 | P a g e Lab 2 Mobile Malware Attack : Trojan This lab discusses the functionality of the Android Trojan which is to send text messages to others using hacker’s commands. The user is unconscious of the Trojan activities as the Trojan deletes all the messaging history. Below is a workflow of the android Trojan. 73 | P a g e Developing the Android Trojan When victim activates the application, The Trojan sends a notification to the hacker which encodes the user’s IP address and a port number for malicious communication. After the communication is set, the Trojan and the hacker set up a TCP/IP communication channel through which the hacker can send commands to the Trojan on the victim’s device. When the Trojan receives a command from the hacker, the Trojan analyses the data packet and then abstracts the target users phone numbers and the content of the malicious message and sends the malicious messages to the target phone users. After sending the messages the Trojan then deletes the messaging history of the user. If the target phone users send complaint messages back to the user, The Trojan will stop the arriving of those complaint messages to user’s phone. For ethical issues the whole code has not been shown only part of it which is important is displayed. The below code is a fragment from the whole code which shows that the Trojan (which has been installed without user’s knowledge) uses the Java ServerSocket class to set up a connection to listen to the hacker’s commands, The Trojan extracts the victim’s phone number and the malicious messages through SMS. The Trojan, to intercept all the incoming short messages and to filter out complain messages from users who receive junk messages setups a SMS Receiver. The configuration of the intercepter in AndroidManifest.xml is shown as below: 74 | P a g e The next step is to design a code that would filter out complaint messages. The below code shows how to filter messages from specific users. To implement the above code the app must request for permission for Sending and Receiving SMS. The permission requests of the Trojan in AndroidManifest.xml are shown in the following. 75 | P a g e Demo First we need to run the hacker server. We need to open two emulators in our eclipse. The emulator 1 serves as the victim that has installed and run the Trojan. The emulator 2 serves as the target phone user. 76 | P a g e Next we open a windows command prompt on the server and enter the command (“telnet localhost 5554”) to connect to Emulator1. Next is to enter the command to setup port mapping. We now enter the client id in the Target field and enter a message in the Message field in the Hacker Server. 77 | P a g e We can see the following things in the emulator as shown below. 78 | P a g e The below screenshot shows the screen of emulator2, which shows the message sent by Emulator1. When the Emulator2 wants to send back a complain to Emulator1 the below screen appears as shown below. 79 | P a g e This has no effect on Emulator1. Lab 3 Mobile Malware Defenense This lab discusses a Trojan defense application from scratch which demonstrates the concept of mobile Malware Defense on Android platform. The main functionality of the defense application is that it sends notification to the user reminding him that few malicious applications installed on his mobile are sending text messages without his consciousness. Consider the flowchart shown below for better understanding. 80 | P a g e Consider the following steps: 1) The hacker sends the command to the Trojan installed in the mobile device. 2) The Trojan installed in the mobile device sends an SMS to a specific group of people according to the Hacker’s command and unknown to the users consciousness the sent messages are deleted from the history by the Trojan app. 3) The specific group of users who receive the malicious message send a complaint message back to the user, but the Trojan app deletes the history of the received messages which is unknown to the user. 4) Protectionism Mechanism: Is to send notification message to the user when sending or receiving a message. Notice The method discussed here is only used for demonstrating a general idea of Mobile Malware Defense. 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 https://sites.google.com/site/mobilesecuritylabware/7-mobile-shortmessaging/mobile-short-messaging-labs/lab-2-attack-secret-sms-attack/labactivity/ethical-hacking Please read them carefully. Code Fragements The below fragment code shows a “Content Observer” which listens to any actions on the internal database of Android. 81 | P a g e We then have to request permission for sending and receiving SMS in AndroidManifest.xml as shown below: Demo The developed program runs in the background to monitor any malicious actions of sending text messages. Whenever there is a text message being sent out, there will be a notification. A notification of the Trojan sending the application is shown below : 82 | P a g e Mobile Spyware Detecting and Removing spyware by tool In this lab we are introduced to detection and removal of Android spyware via the use of off-the-shelf protection tools. In this lab we first install a real-world Android “Spyware” and then install the anti-spyware to detect and remove the spyware. The first step is to install spyware such as SMS tracker on the device. We do this by installing the sms tracker agent.apk file on the emulator device. The app can be downloaded from http://android.downloadatoz.com/apps/com.gizmoquip.smstracker,68074.html The below screenshot shows how it is done. The second step is to install the anti-spyware such as Anti-spy mobile. We do so by installing the Anti spy mobile.apk on the emulator device. The apk can be downloaded from 83 | P a g e http://mobileapk.tk/anti-spy-mobile-pro-v1-9-1-apk/ Now we start the AntiSpy Mobile app which is installed on our emulator device. We get the following screen shot The above screenshot appears for the user who uses the app for the first time. The prompt will prompt a message as shown above. The next step the app scans for installed spyware we get the below screen as the app starts scanning for any installed spyware. 84 | P a g e Once the app searches for any installed spywares we get the below alert message as shown in the screenshot below In then shows the list of spyware applications that are needed to be unistalled as shown below. 85 | P a g e Now click on the corresponding icon to see the details of the spyware application. 86 | P a g e “Penetration Test and Analysis” on spyware Threat/Attack This lab discusses the use of a malicious Android Application to demonstrate and simulate a spyware (malware) on the android mobile device. The malicious Android application (spyware) can catch user’s contact list from the Android mobile phone, and sends a malicious message to the contacts without user’s conscious, Student can analyse this spyware in this lab. Notice The attack method discussed here is only used for demonstrating a general idea of spyware. Readers should perform gracefully based on hacking ethics and should not spread or utilize the code in the lab to harm other Android phones users to gain their own benefits. A more thorough specification of hacking ethics can be found here. Code Fragments Let us assume that the malicious application has been installed on a victim’s Android phone carelessly. When the user clicks the button the spyware can catch the user’s contact list. To utilize the contact list on the phone, the malicious code must request the permissions accordingly in AndroidManifest.xml as the following code fragment. The below fragment code shows how to get contact list information by code: Demo To test the Demo we open two emulators on the eclipse. Emulator1 The API serves as the victim which unknowingly installs and runs the malicious application. Emulator2 Hello world runs as one of the users on the victims contact list on the emulator1. 87 | P a g e The emulator1’s contact list screen is shown below: 88 | P a g e The spyware on emulator1 runs as shown below: When the user clicks the button on emultor1, the other side on Emulator 2 receives a message as shown below: 89 | P a g e Here is the Apk for this spyware. https://sites.google.com/site/mobilesecuritylabware/5-mobile-spyware/spywarereverse-engineering-lab/1-spyware-attact-lab/labactivity/Simple_Malware.apk?attredirects=0&d=1 Defence Reverse Engineering analysis Reverse engineering is the most popular malware analysis method specified in android development. This lab provides a malware application and teaches students how to analyse the application and how to protect the mobile device by using reverse engineering from the malware application. We first take a look at some general information about reverse engineering. Reverse engineering is a method to take apart an object to see how it works in order to duplicate or enhance the object, it is a practise taken from older industries, and is now frequently used on computer hardware and software. Software reverse engineering involves reversing a program’s machine code (string 0’s and 1’s that are sent to the logic processor) back into the source code that it was written in, using program language statements. There are many tools that implement reverse engineering in android development. It can fully decompile the apps thus making the code readable and understandable. XdaDeveloperBrut.all has been working on a decompiler for android apps for a while. He had found the first workaround for enabling google maps navigation outside US by decompiling Google maps for android. The tool is called APKTool and is opensource. Another called dex2jar, developed by a Chinese student will translate dex to jar file. The next step would be to use jd-gui, the source code is readable as dex2jar makes some optimizations. An alternative option is use to Smali (http://code.google.com/p/smali/), which provides BAKSMALI which is most excellent reverse-engineering tool for DEX files. The tool was developed by JesusFreke, who is famous for making popular ROMs for android. The next portion of this manual covers the lab which would give detail by using one of the above tools in reverse engineering. LAB ACTIVITY In this lab, a simple malware was given to the students to give a general idea (Reverse Engineering) of analysing this kind of spyware. This lab also gives a Auto-analysis method by checking the result of decompiling. Part1: Decompile APK to JavaCode 90 | P a g e This part of the lab requires to two tools to be downloaded dex2jar and JD_GUI Dex2jar is a tool to transit classes.dex by converting .apk extention into .jar file . JDGUI is a decompiler tool. The tools dex2jar and JD_GUI can be downloaded from the links below Dex2jar: http://laichao.googlecode.com/files/dex2jar-0.0.7-SNAPSHOT.zip JD_GUI: http://laichao.googlecode.com/files/jdgui.zip The first step in this part of the lab is to convert is to change the extension of the apk file from .apk to .zip, and unpack it, by doing which we get the classes.dex. Then unpack the dex2jar, and place the classes.dex into dex2jar folder. The next step is to run JD-GUI (jd-gui.exe), open classes.dex.dex2jar.jar, where we can see the code as shown below 91 | P a g e Part2: Decompile apkfile to get AndroidManifest.xml The apktool can be downloaded from the link given below: http://code.google.com/p/android-apktool/downloads/list download apktool 1.5.2.tar.bz2 and apktool-install-windows-r05-ibot.tar.bz2 The next step is to upack the two downloaded files, we then get the three following files: aapt.exe, apktool.bat, apktool.jar . Copy the apktool.jar into the folder containing aapt.exe and apktool.bat. Then using the command prompt go to the folder containing the above mentioned three files and run the following command to get the .xml file Apktool.bat d c:\*.apk c:\* The AndoridManifest.xml file gets generated 92 | P a g e Code The general working idea of the application was written as the following: The spyware has been analysed by a kind of rules, where every rule aims to one specific spyware (malware), in this lab we serve one of the rules, but the rule can be added for aiming to another spyware (malware). Code: /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package auto_reverse; import java.io.BufferedReader; import java.io.FileReader; //import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; 93 | P a g e /** * * @author zhengzhe */ public class Auto_Reverse { /** * @param args the command line arguments */ public static void main(String[] args) { try { int warninglevel=0;//0 is lowest, 2 is highest. FileReader fin=new FileReader("AndroidManifest.txt"); BufferedReader br = new BufferedReader(fin); String Line=br.readLine(); //the rule for (int i=0;Line !=null;i++){ if(Line.contains("android.permission.SEND_SMS")&&Line.contains("and roid.permission.READ_CONTACTS")){ FileReader fi=new FileReader("Code.txt"); BufferedReader b = new BufferedReader(fi); String l=b.readLine(); for (int j=0;l !=null;j++) { if(l.contains("sendTextMessage")) { warninglevel=1; FileReader f=new FileReader("Code.txt"); BufferedReader bu = new BufferedReader(f); String le=bu.readLine(); for (int h=0;le !=null;h++) { if(le.contains("EditText")) { warninglevel=2; break; } le=bu.readLine(); } bu.close(); f.close(); } l=b.readLine(); } 94 | P a g e b.close(); fi.close(); } Line= br.readLine(); } br.close(); fin.close(); System.out.println(warninglevel); } catch (IOException ex) { Logger.getLogger(Auto_Reverse.class.getName()).log(Level.SEVER E, null, ex); } } } The result of analysis of the spyware is as shown below: : 6. Secure Mobile App Development Lab1: Android coding Vulnerabilities lab This lab tries to help students to get familiar with coding vulnerabilities of android programming, which include buffer overflow, input validation, SQL injection etc with other programming languages and platforms. There are some unique coding vulnerability in android programming that we need to be aware of. Ignoring these coding vulnerabilities will cause disastrous security issues. Tips for android coding vulnerabilities 1) One must protect any data user input into their device with ones application, and not allow malware to access the application’s special permissions. 2) Intent recipients like Acitivies, Services and Broad Receivers need to handle potentially hostile callers, and an Intent Filter doesn’t filter a malicious intent. The intentFilters help the system to figure out the right handler for a particular intent, but does not constitute an input filtering system. The reason being the IntentFilters are not a security boundary, they cannot be associated with permissions. 95 | P a g e 3) When the intents are started or broadcasted, the intent Filter is used by the system to determine the recipients, one must remember to add as many categories as correctly to apply to the intent. The categories often requires promises about the safety of dispatching an intent, helping stop the intent from having unintended consequences. 4) Activities cannot rely on IntentFilters to stop callers from passing them badly configured Intents. Misunderstanding this is actually a relatively common source of bugs. 5) The Developer needs to be careful not just when implementing Activities but when starting them too. One must avoid putting data into Intents used to start Activities that would be of interest to an attacker. An Example where a Malware could register a higher priority IntentFilter and end up getting the user’s sensitive data sent to their Activity instead. 6) When starting an Activity if you know the component you intend to have started, you can specify that in the Intent by calling its setComponent() method. This prevents the system from starting some other Activity in response to your Intent. Even in this situation it is still unsafe to pass sensitive arguments in this Intent. You can think of the Intent used to start an Activity as being like the command line arguments of a program, which usually shouldn’t include secrets either. 7) As with Activities, a broadcast sender can send a receiver an Intent that would not pass its IntentFilter just by specifying the target receiver component explicitly. Receivers must be robust against unexpected Intents or bad data. As always in secure IPC programming, programs must carefully validate their input. 8) if you need to make sensitive calls into a Service, like storing passwords or private messages, you’ll need to validate the Service that you’re connected to is the correct one and not some hostile program that shouldn’t have access to the information you provide. Lab Activities The diagram below shows an intent object which contains sensitive information (username and password in this example) is passed from one activity to another in order to start an Activity. However, since a malware has higher priority level in the InterntFilter, It has intercepted the Intent, parsed the Intent object, and then obtain the secret information (username and password). So, in Android programming, we need to keep in mind that sensitive information cannot be passed through an Intent object (please refer to Tip 5). 96 | P a g e Fig Basic idea of intent Passing and interception This lab shows an implicit intent object passed from one activity object to another activity object with vulnerability. Source Code 1) Create a new Android project in eclipse. 2) Create two java source files “Android_intentActivity.java” and “IntentRecevier.java”, copy and paste the source code to the corresponding source files. 3) Modify the “AndroidManifest.xml” file accordingly. Android_intentActivity.java // Android_intentActivity.java: // passing an Intent to another Activity package android.androidintent; import android.app.Activity; import android.content.Intent; import android.os.Bundle; 97 | P a g e import android.view.View; import android.widget.EditText; public class Android_intentActivity extends Activity { EditText e1,e2; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); e1=(EditText)findViewById(R.id.editText1); e2=(EditText)findViewById(R.id.editText2); } public void on_submit(View v){ Intent intent=new Intent(); Bundle bun = new Bundle(); bun.putString("Username", e1.getText().toString()); bun.putString("Password", e2.getText().toString()); intent.setAction("android.androidintent.IntentReciever"); intent.putExtras(bun); Android_intentActivity.this.startActivity(intent); } } IntentRecevier.java // IntentReceiver.java: // Intent intercepted and sensitive information extracted package android.androidintent; 98 | P a g e import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.widget.TextView; public class IntentReciever extends Activity { /** Called when the activity is first created. */ TextView t1,t2; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main1); Bundle bun = getIntent().getExtras(); String result1 = bun.getString("Username"); String result2 = bun.getString("Password"); t1=(TextView)findViewById(R.id.textView1); t2=(TextView)findViewById(R.id.textView2); t1.setText("Username:"+result1); t2.setText("Password:"+result2); Log.d("Username",result1); Log.d("Password",result2); } } AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android=http://schemas.android.com/apk/res/android package="android.androidintent" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".Android_intentActivity" 99 | P a g e 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="android.androidintent.IntentReciever"> <intent-filter> <action android:name=" android.androidintent.IntentReciever " /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> </application> </manifest> Results Demo Activity1: Username/Password typed and intent object created 100 | P a g e Malware Activity: Intent Intercepted and Sensitive Information Extracted Solution This lab requires us to learn, how to safely pass data between different activity objects. You will need to design a mechanism, which can pass data safely between different activities, without having to wrapping sensitive data within an intent object. The goal being to avoid an intent object being intercepted by malicious activity. There are different ways to achieve this goal, such as SQLLite, intent object creation etc. Please design your own mechanism and implement your solution. Lab2: Android Activities with intent Security Concern In this lab, we will use a malicious Android application we wrote to demonstrate a kind of intent security problem on Android platform. The malicious Android application can get the intent information from “Intent app” if the Show Activity has same action name and other characters are also the same with hack activity in Intent Filters. At the same time, the main activity intents according to the action name and other characters in the intent filter. The following diagram shows the basic idea of this security problem. 101 | P a g e Fig Intent app has intent Filters in shown activity. This lab utilizes android attack application that we developed to give user a brief demonstration on how hackers get the data the activities sent in other applications. Special Notice The attack method discussed here is only used for demonstrating a general idea of Intent attacks. 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. Code Fragments The Android Manifest.xml of a common login application, may define an activity like this: 102 | P a g e The below activity is for getting the user information of username and password which the user inputs in the previous activity and presses the login button. The activity can be called using: Next we need to create a hack app with the following activity The code in the main activity java file of the hack app would have: If this hack app runs on an android phone together with the previous common app, after the user inputs the user name and password and presses button to active the intent function and try to login, the hack app will also get the information input by the user. 103 | P a g e Demo: First we input the username and password and click Login The correct login activity that we want is shown below The information shown in the hacker’s app is as shown in the below screen shot 104 | P a g e Defense In this lab, an android application is updated to defend the intent security problem on android platform. The malicious android application never gets the intent information from “Intent app”, even though the show activity has same action name and other characters are also the same with hack activity in intent filters. The main activity intents according to the class name and the package name. The below diagram shows the basic idea of this solution 105 | P a g e The lab utilizes android attack application that we developed to give user a brief demonstration on how to avoid attack hackers to get the data the activities sent in applications Code fragment We need to be aware of the below code lines created in the previous lab SetClassName() for explicit intent is used, instead of using setAction() to reach implicit intent As the explicit intent will go straight to the activity we want and ignore the intent filters, the hack app will never get the information sent in intent function. Version 1: Code: TestIntentActivity.java package android.testintent; import import import import import import import android.app.Activity; android.content.Intent; android.os.Bundle; android.view.View; android.view.View.OnClickListener; android.widget.Button; android.widget.EditText; 106 | P a g e public class TestIntentActivity extends Activity { /** Called when the activity is first created. */ String name; String password; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final Button logb=(Button)findViewById(R.id.logb); final EditText Uname=(EditText)findViewById(R.id.uname); final EditText Pword=(EditText)findViewById(R.id.pword); // final String name; // final String password; logb.setOnClickListener(new OnClickListener() { public void onClick(View v) { name=Uname.getText().toString(); password=Pword.getText().toString(); Intent intent = new Intent(); intent.putExtra("username", name); intent.putExtra("password", password); // intent.setAction("android.testintent.Login"); // intent.addCategory(Intent.CATEGORY_DEFAULT); intent.setClassName("android.testintent","android.testintent.Login"); startActivity(intent); } }); } } Login.java package android.testintent; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class Login extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.loginlayout); final TextView text=(TextView)findViewById(R.id.logindata); // text.setText("babo"); text.setText("UserName: "+getIntent().getStringExtra("username")+"\nPassword: 107 | P a g e "+getIntent().getStringExtra("password")); } } Andorid Manifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="android.testintent" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="8" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".Login" android:theme="@android:style/Theme.NoTitleBar" /> <activity android:name=".Login" android:label="Login" > <intent-filter> <action android:name="android.testintent.Login" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <activity android:name=".TestIntentActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Demo: The first step is to give username and password as input and click on login 108 | P a g e This is the login activity that we want and no information sent to the hack app. Android_intentactivity.java package android.androidintent; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; 109 | P a g e import android.widget.EditText; public class Android_intentActivity extends Activity { EditText e1,e2; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); e1=(EditText)findViewById(R.id.editText1); e2=(EditText)findViewById(R.id.editText2); } public void onClick(View v){ Intent intent = new Intent(this,Android_intentActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Bundle bun = new Bundle(); bun.putString("Username", e1.getText().toString()); bun.putString("Password", e2.getText().toString()); intent.setClass(this, IntentReciever.class); intent.putExtras(bun); Android_intentActivity.this.startActivity(intent); } } IntentReciever package android.androidintent; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.widget.TextView; public class IntentReciever extends Activity { /** Called when the activity is first created. */ TextView t1,t2; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main2); Bundle bun = getIntent().getExtras(); String result1 = bun.getString("Username"); String result2 = bun.getString("Password"); 110 | P a g e t1=(TextView)findViewById(R.id.textView1); t2=(TextView)findViewById(R.id.textView2); t1.setText("Username:"+result1); t2.setText("Password:"+result2); Log.d("Username",result1); Log.d("Password",result2); } } AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="android.androidintent" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".Android_intentActivity" 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="android.androidintent.IntentReciever" > </activity> </application> </manifest> 111 | P a g e 112 | P a g e 113 | P a g e 114 | P a g e 115 | P a g e