Home Security Mobile Device Exploitation Cookbook

Mobile Device Exploitation Cookbook

By Akshay Dixit
books-svg-icon Book
eBook $35.99 $24.99
Print $43.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $35.99 $24.99
Print $43.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Introduction to Mobile Security
About this book
Mobile attacks are on the rise. We are adapting ourselves to new and improved smartphones, gadgets, and their accessories, and with this network of smart things, come bigger risks. Threat exposure increases and the possibility of data losses increase. Exploitations of mobile devices are significant sources of such attacks. Mobile devices come with different platforms, such as Android and iOS. Each platform has its own feature-set, programming language, and a different set of tools. This means that each platform has different exploitation tricks, different malware, and requires a unique approach in regards to forensics or penetration testing. Device exploitation is a broad subject which is widely discussed, equally explored by both Whitehats and Blackhats. This cookbook recipes take you through a wide variety of exploitation techniques across popular mobile platforms. The journey starts with an introduction to basic exploits on mobile platforms and reverse engineering for Android and iOS platforms. Setup and use Android and iOS SDKs and the Pentesting environment. Understand more about basic malware attacks and learn how the malware are coded. Further, perform security testing of Android and iOS applications and audit mobile applications via static and dynamic analysis. Moving further, you'll get introduced to mobile device forensics. Attack mobile application traffic and overcome SSL, before moving on to penetration testing and exploitation. The book concludes with the basics of platforms and exploit tricks on BlackBerry and Windows Phone. By the end of the book, you will be able to use variety of exploitation techniques across popular mobile platforms with stress on Android and iOS.
Publication date:
June 2016
Publisher
Packt
Pages
230
ISBN
9781783558728

 

Chapter 1.  Introduction to Mobile Security

In this chapter, we will cover the following recipes:

  • Installing and configuring Android SDK and ADB

  • Creating a simple Android app and running it in an emulator

  • Analyzing the Android permission model using ADB

  • Bypassing Android lock screen protection

  • Setting up the iOS development environment - Xcode and iOS simulator

  • Creating a simple iOS app and running it in the simulator

  • Setting up the Android pentesting environment

  • Setting up the iOS pentesting environment

  • Introduction to rooting and jailbreaking

 

Introduction


Today, smartphone usage is a much talked about subject. The world is quickly moving towards smartphone ownership, rather than traditional feature phones. Various studies and surveys have predicted increasing future usage of smartphones and tablets. There are incentives to do so; a lot of things are doable with these smartphones.

With increasing mobility comes risk. Attackers or cyber criminals look at all possible ways to attack users in order to obtain their personal data, credit card details, passwords, and other secrets. There have been threat reports from various security vendors on the increase in mobile attacks that comes with increased usage. Today, corporations are worried about data confidentiality and the resultant financial and reputational losses.

In this book, we introduce readers to some mobile device exploitation recipes, to let everyone understand the kind of attacks that are possible. Once people understand this, they will be more aware of such attack vectors and be better prepared to deal with them and secure their stuff.

This chapter will give the reader an idea about the basic security models of the two most popular mobile device platforms, Android and iOS. We will cover an introduction to their development environments and basic security models. We will set up a penetration testing environment and will introduce you to rooting and jailbreaking. This chapter builds the foundation for what is to be covered in the upcoming chapters, and is a pre-requisite for exploitation.

 

Installing and configuring Android SDK and ADB


The very first step in Android development and security testing is to learn to install and configure the Android SDK and ADB. The software development kit (SDK) for Android comes in two installable versions; Android Studio and the standalone SDK tools. This recipe primarily uses Android Studio and later provides additional information about standalone SDK tools.

Android Debug Bridge (ADB) is a very useful tool, which can connect to Android devices and emulators and is used to perform debugging and security testing for mobile applications.

Note

Whenever we use the words "Android devices" in this book, this means Android smartphones and tablets.

Getting ready

Navigate to https://developer.android.com and download either Android Studio or standalone SDK tools. You will also require JDK v7 or newer.

How to do it...

Let's set up using the first method, Android Studio:

  1. Go to http://developer.android.com/sdk/index.html and download the latest Android Studio.

  2. Once you have downloaded the Android Studio installer file, the installer guides you through the next steps and you just have to follow the instructions.

Note

As of writing this, the installer file used is android-studio-bundle-135.1740770-windows.exe.

Android SDK and ABD are installed as part of the default installation. Unless you deselect these, they will be installed.

Note

AVD stands for Android Virtual Device, which in turn refers to the Android emulator. Emulators provide a virtualized setup to test, run, and debug Android applications. These are especially useful in cases where hardware devices are not available. Most development testing works using emulators. We will use an emulator in the next recipe.

Note the Android Studio and SDK installation paths. You will need them repeatedly in setup:

Once Android Studio is installed, run it. It will guide you through the next set of instructions. It downloads the Android SDK tools, which may take up to 4 hours depending upon the Internet speed.

How it works...

The development environment is ready. Take a moment to make yourself familiar with the SDK installation directory (the path shown in the preceding screenshot). There are a few quick things you must know:

  • SDK Manager: This is used to manage Android packages and can be used to install or uninstall newer/older versions as required.

  • AVD Manager: This is used to manage AVD. Use it to create a few emulators that we will use at the appropriate time.

    Now run one of the emulators to test whether the installed setup is working well. An emulator takes 2-3 minutes to start up, so be patient and if the installation has gone well, the emulator should be up and running. (Please refer to the next recipe if you want to look at the emulator screenshot now.)

  • platform-tools: This folder contains useful tools such as ADB, SQLite3, and so on. We will use these tools in various recipes throughout this book.

  • tools: This folder contains batch files and other executables. We will mostly use emulator.exe, as well as other .exe files in this folder.

There's more...

There is an alternative way to develop in Android, as many people prefer other IDEs. In such cases, the standalone SDK tools can be downloaded. This provides the SDK tools required for application development and these tools can be invoked from the command line.

These standalone tools are also useful for pentesters and black hats, for quick analysis of underlying, application-related stuff. A lot of the time, application development is not needed and there is a need to debug; in such cases, the standalone SDK tools can be used.

See also

  • Analyzing the Android permission model using ADB

 

Creating a simple Android app and running it in an emulator


Now that we are ready with the Android SDK, let's write our first Android application. A little bit of coding skill is needed to get started. However, don't worry if source code scares you. There is a lot of sample code available in the Internet communities for you to use to get started.

Getting ready

To get ready to code the Android application, you need the SDK to be working well. If you have followed the first recipe and know a little bit of Java programming, the rest is easy and you are all set to code your very first Android application.

How to do it...

Let's write a very simple program to add two numbers together. I used the Eclipse IDE and created an Android application project called Addition:

  1. Create the graphical layout. Drag and drop three text fields (one each for the first number and the second number, and the last one to print the sum of the first two numbers), two TextView boxes to display text so that the user knows to enter two numbers, and finally a button for the addition action.

    • The activity_main.xml file is autogenerated. Edit it to look like the following code:

    <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"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context=".MainActivity" >
    
        <TextView>
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="First Number"
    Text displayed to guide user to input first number
        </TextView>
    
        <EditText>
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=""
            android:id="@+id/e1"
    Variable e1 is declared to be referenced in java file.
            android:inputType="textPassword"
        </EditText>
    
        <TextView>
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Second Number"
        </TextView>
    
        <EditText>
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=""
            android:id="@+id/e2"
            android:inputType="textPassword"
        </EditText>
    
        <Button>
            android:id="@+id/add"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:layout_marginBottom="122dp"
            android:text="Add"
    
    • Add the declared button:

        </Button>   
        <EditText>
            android:text=""
            android:id="@+id/t3" 
    
    • Finally, the third variable, which will contain the sum of the two numbers, is declared:

            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="textPassword"
        </EditText>
    </RelativeLayout>
    
  2. Now we have to write Java code to input and add the numbers, and output the sum. At this point, don't worry if you do not know Activity, Intent, and so on. Just focus on getting the code error-free. Eclipse guides you at each step. We start our program with MainActivity, coded like this:

    package com.android.addition;
     
    import android.os.Bundle;
    import android.app.Activity;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Button;
    import android.view.View;
     
    public class MainActivity extends Activity {
        EditText e1;
        EditText e2;
        TextView t3;
        Button add;
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            add=(Button)findViewById(R.id.action_settings);
            add.setOnClickListener(new Button.OnClickListener()
                {
            public void onClick
            (View v){Sum();}});
        }
            private void Sum(){
              int s1=Integer.parseInt(e1.getText().toString());
              int s2=Integer.parseInt(e2.getText().toString());
              int s3=s1+s2;
              t3.setText(Integer.toString(s3));
             }
    }
     
    

    See how straightforward this program is; it just takes two numbers, adds them together, and provides the result.

  3. Debug and run the program. The emulator opens up and the program runs.

See also

  • Android In Action, Ableson, Sen, King, Manning Publications Co.

 

Analyzing the Android permission model using ADB


Having set up the development environment and coded your first Android application, now it's time to understand the underlying permission model of the Android operating system. The underlying operating system is Linux; the Android operating system is built using Linux as the basis. Applications in Linux run with a specific user ID and group ID. Android uses the same Linux model to set permissions for applications; this separates and protects Android applications from each other.

Getting ready

Make sure you have ADB installed. You also need an Android emulator or an Android device to connect to ADB.

A device or emulator that has been used frequently is best for this purpose (as a newly created emulator or device may not contain much data to view using ADB). Furthermore, for learning purposes, a rooted phone is preferred.

How to do it...

Follow the steps given here for analyzing the Android permission model using ADB:

  1. Enable USB debugging mode on your Android device and connect it via a data cable to a computer on which ADB is running. ADB is a very powerful tool and can be used to run various useful commands, which can help us with the following tasks:

    • Pushing data into the phone/emulator

    • Pulling data from the phone/emulator

    • Obtaining a shell in the phone/emulator

    • Installing and removing applications

    • Navigating the filesystem

    • Stealing key system files

    • Stealing application-related files such as preferences and SQLite files

    • Viewing device logs

  2. Use ADB to analyze the application permissions. To do this, we will have to first obtain the shell in the device using the adb shell command and then we will have to run the ps command to find the details of the process that is running.

The following screenshot depicts this process for a phone connected to the Linux machine on which ADB was run:

How it works...

Take a while to analyze the preceding screenshot. Make a note of the first, second, and last columns which show USER, PID, and application NAME respectively. Note that each application has a unique PID and is run from a specific user. Only a few privileged processes run with the user root. Other applications run via specific users. For example, the com.android.datapass application with PID 299 runs as user app_47. Also, com.svox.pico runs with user app_28.

Each application in Android runs in its own sandbox. A sandbox is a virtual environment where the application runs within its limited context and is not allowed access to, or to be accessed from, other applications. The permissions model in Android (applications running with specific users) helps create a sandbox, thereby restricting applications within their own context and allowing no or limited interaction (as chosen by the application developer) with other applications. This also secures applications against data theft or other attacks from rogue applications and malware.

There's more...

The Android permissions model and sandbox implementation attempts to build in security by design. This has been the target of attackers and evangelists. Android sandbox bypass attacks and attacks originating from insecure code implementation are a couple of the types of attack against this security feature. Nevertheless, security by design is implemented in the Android OS itself in the form of the permissions model.

See also

 

Bypassing Android lock screen protection


Android users are advised to protect their devices by setting up a password, pin, or lock screen (graphical pattern). When users talk about lock screen bypass, they usually mean they have locked their phone or forgotten their pattern, not how to bypass the screen and get into the device. We are approaching the topic in a more aggressive fashion, as this book is about mobile device exploitation. As an attacker, how could we bypass a victim's lock screen? Now, this topic is widely spoken about and there is already a wide range of tricks to do it; various exploits/methods may work in specific Android or device versions but may not work with others.

Getting ready

We are going to take a case where we reset the lock pattern in a phone via ADB. So for this recipe, you need ADB ready. We learned about ADB in the previous recipe. Let's now use that what we learnt, to hack. Apart from ADB, you need to obtain an Android device with USB debugging enabled, and has a that password needs to be reset.

How to do it...

Follow these steps to bypass the lock screen protection:

  1. Connect to the target Android device using ADB. If we have obtained a phone with USB debugging enabled and the phone is rooted, things are much easier. If the phone is not rooted, then there are hacks to do so as well. For this recipe, let's consider a rooted phone.

  2. Now that you are connected via ADB, type the following command:

    adb shell
    
  3. This gives you the shell in a connected Android device.

  4. Next, change the current working directory to /data/system, which is where keys are located. To do this, we have to type the following command to change the directory:

    cd /data/system
    
  5. Then finally you need to delete the relevant key. Simply run the remove command to delete it:

    rm *.key
    
  6. It can also be run as follows:

    rm <correct-filename>.key
    
  7. In case you are prompted for superuser permissions, you can run the su command. The preceding commands delete the key files containing lock screen information.

  8. Next, do a device reboot and the lock screen should have gone.

How it works...

This works because the key files in the /data/system folder contain system information, such as the lock screen's password information. If these key files are deleted, on reboot the device is not able to locate a lock screen setting, so effectively it allows access without a password.

Note

A device already in USB debugging mode, and rooted as well, allows this recipe to work quite easily.

There's more...

The key message is; this is not the only way to bypass the lock screen, nor is this method guaranteed to work in all cases. Hackers have come up with multiple ways to bypass Android lock screens. To further complicate matters, not all methods work for all Android versions. So you may have to spend a lot of effort in certain cases to figure out how to bypass the Android lock screen.

 

Setting up the iOS development environment - Xcode and iOS simulator


By now, you have got the hang of Android development. Now it's time to be introduced to the iOS development environment. Apple's iPhone and iPad run on the iOS operating system. Application development for iOS requires the Xcode IDE, which runs on Mac OS X. Xcode, together with iOS simulator, can be used to develop and test iOS applications.

Note

Note we say emulators when we talk about Android, and we say simulators when talk about iOS. These two are similar to each other, but with one major difference. An emulator can use some OS features to test specific applications.

For example, an Emulator can use a laptop's webcam to run an application that requires a camera, whereas such application testing will be limited in an iOS simulator. Emulators can also send an SMS to other emulators.

Some people say that emulators are smarter than simulators. However, generalizing that much may not be fair, as long as both serve the job they are designed for.

Getting ready

Xcode is the IDE for developing iOS applications. Xcode runs on Mac OS X, so a MacBook is required for iOS application development. So get a MacBook, install Xcode, install the iOS SDK, and start coding in iOS.

Note

Note that there are useful guidelines at https://developer.apple.com/programs/ios/gettingstarted/ to help you out with this.

How to do it...

Follow these steps for setting up Xcode and iOS simulator:

  1. Locate App Store on your MacBook. Now use App Store to download Xcode (this is just like any other App download on mobile phones). You will need an Apple ID to download from the App Store. Note that Xcode is free to download from Apple's App Store.

  2. Once Xcode is installed, you can explore the IDE. It can be used to develop Mac OS X applications. Xcode is a common IDE for both OS X applications and iOS application development. To be able to develop an iOS application, you also need to install the iOS SDK. The latest versions of Xcode include both OS X and the iOS SDK. Simulators and instruments are also part of Xcode now.

    • Thankfully this is not complicated and the installation of Xcode takes care of everything.

    • Once you have everything set up, create a new project. Note that if things are properly installed, you get the option to create an iOS and OS X application, as shown here:

How it works...

Let's make ourselves familiar with the Xcode IDE.

From the preceding screenshot, let's create a project. We will choose the Single View Application template for simplicity's sake. This action opens up the Choose options for your new project window. Provide a name for your project, which appends the organization identifier to create a bundle identifier.

Note we selected Swift, which is a new language introduced in iOS 8. There is another option, to choose traditional Objective-C.

Note

Swift is new programming language for iOS and OS X. It is interactive and is intended to make coding fun. Swift makes app development easier and can work alongside traditional Objective-C.

Some people say that emulators are smarter than simulators. However, generalizing that may not be fair, as long as both serve the job they are designed for.

Finally, it is also important that the appropriate device option is selected from iPhone, iPad, or Universal. We select iPhone, just for the sake of this demonstration.

Once you select Next and Create, we see our project window:

The left-hand pane is the project navigator. You can find all your project files in this area. The center part of the workspace is the editor area. Depending on the type of file, Xcode shows different interfaces in the editing area.

The right-hand pane is the utility area. This area displays the properties of files, and allows you to access Quick Help.

There's more...

Up to now we have written zero lines of code. Even so, we can run our app using the built-in simulator. In the toolbar, we can see the run button (top left, the one resembling the traditional play music icon):

When we hit the run button, Xcode automatically builds the app and runs it on the default iPhone 6 simulator. Of course, since we haven't programmed our app to do anything, it will just display a white screen with nothing inside:

The stop button next to the run button terminates the app.

See also

  • Setting up the iOS pentesting environment

 

Creating a simple iOS app and running it in the simulator


Having introduced you to Xcode and the simulator, now we will create our first iOS application.

Getting ready

To get ready to code the iOS application, you need Xcode and iOS Simulator in your MacBook and working. If you have followed the previous recipe, and know a little bit of Objective-C, you are all set to code your very first iOS application.

How to do it...

Now that we have a basic idea of Xcode, let's start by building the user interface:

  1. In the project navigator, select Main.storyboard. Xcode then brings up a visual editor for storyboards, called interface builder.

    A storyboard is used to lay out views and transition between different views. As we use a single-view application, the storyboard already includes a View Controller.

  2. Next, we will add a button to the view. The bottom part of the utility area shows the Object Library, as shown in the following screenshot:

  3. Drag the Button object from the Object Library to the view:

  4. Stop dragging and move the button to the area of your choice. Double-click on the button and rename it Click Me.

  5. Next we will add a few lines of code to display our message. In the project navigator, you should find the ViewController.swift file. We will be adding a method to the already present ViewController class. When this method is called, our code will tell iOS to display a certain message.

  6. Now let's code our method. This is what our method looks like:

    @IBAction func showMessage(){ 
    let alertController = UIAlertController(title: "My First App", message: "Hello World", preferredStyle: UIAlertControllerStyle.Alert) 
    alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:nil)) 
    self.presentViewController(alertController, animated: true, completion: nil) 
    } 
    
  7. This is what the finished work will look like:

  8. Now we need to connect our Click Me button in the storyboard to our showMessage method. This part is easy; we click on Main.storyboard, where we have displayed our screen.

  9. Press and hold the Ctrl key on your keyboard, click the Click Me button, and drag it to the View Controller icon.

  10. Release both buttons, and we see a pop-up message with the showMessage option. Select it to make a connection between the button and our function:

  11. That's it! If everything is correct, we can now run our app perfectly when we click on the run button:

How it works...

The @IBAction attribute, introduced in Swift, is used to connect storyboard actions to the code. Here, we wanted to connect the click of a button to a message being displayed. So, we defined the function showMessage as func.

Note

Starting from iOS 8, UIActionSheet and UIAlertView were replaced by the new UIAlertController.

In our function, we call UIAlertController and ask it to display an alert popup, with the title My First App and the message Hello World. We also add an action:

alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:nil)) 

This essentially means we add an option to close the popup when OK is clicked on.

When we dragged our button to the ViewController and selected our showMessage function, we essentially linked the clicking of the button to the calling of our function.

There's more...

You can experiment by trying different styles of button, or using table views, links, and so on. Add more functionality to experiment in ways of learning iOS app development.

A good starting place would be the documentation from the creators of iOS:

See also

 

Setting up the Android pentesting environment


By this time, you will be familiar with the Android development environment, ADB, and emulators. You have also coded your first application. Now let's get into penetration testing. Penetration testing for mobile applications can be broadly classified under four categories:

  • Mobile application traffic-related attacks

  • Mobile device storage-related attacks

  • Mobile application source code-related attacks

  • Attacks involving mobile OS features used by mobile applications

This is the most complicated category. There are various Android OS features that applications interact with, such as Bluetooth, NFC, intents, broadcast receivers, and so on. These also need to be covered in an offensive penetration test.

Getting ready

We have to set up a lab for Android pentesting, which should be sufficiently well equipped to be able to conduct testing for test cases that fall into the four categories listed previously.

To get going, we need the following:

  • The Android SDK, emulators, and ADB

  • Emulators with different Android versions configured

  • One or two Android handsets or tablets (rooted)

  • Proxy tools such as Charles, Burp Suite, and Fiddler

  • A Wi-Fi network

  • Tools such as SQLite browser, text editors, and XML viewers

  • A data cable

  • Tools such as a DEX to JAR convertor, jdgui, or Java decompilers

  • Tools such as DroidProxy or Autoproxy for Android

How to do it...

Let's look at each of these tools:

  • Android SDK, emulators, and ADB

    We already learned about these in previous recipes in this chapter.

  • Emulators with different Android versions configured

    Refer to the AVD Manager screenshot shown in a previous recipe. There, we used API level 21 and created an emulator for Android version 5.0.1. Using the new option there, we can create more emulators for different API levels and for different Android versions.

    These different versions will come in handy when applications to be pentested are developed for specific versions. They also come in handy when specific mobile application features are present in specific Android versions.

  • One or two Android handsets or tablets (rooted)

    It is optional to have physical devices, but they do come in handy. Sometimes we see that applications crash, emulators are slow, or proxy tools in combination with emulators are too slow/crash often, making it difficult to test the application with emulators. Having a physical mobile device comes in handy in such cases.

  • Proxy tools such as Charles, Burp Suite, and Fiddler

    Various proxy tools can be downloaded from their websites. These are quite straightforward and there are guides and help forums about them as well. The installation of such tools is outside the scope of this book, but we will cover their configuration for mobile applications.

    Here are some links to the most common proxy tools:

  • A Wi-Fi network

    We need a Wi-Fi network to intercept Wi-Fi traffic. We will later set up a proxy for a mobile device to a laptop running a proxy tool, both on the same Wi-Fi network.

    You can either use a Wi-Fi router to set up your personal Wi-Fi network, or you can use one of the free tools available to create a hotspot from your laptop. In our experience, it is sometimes difficult to work with the latter option, so we prefer using the former.

  • Tools such as SQLite browser, text editors, and XML viewers

    These are additional tools to read the data extracted from phones. Again, these are free downloads or you may already have them.

  • A data cable

    It is also important to own a data cable. Later we will use it to connect the phone in order to read its data and conduct attacks that originate via USB.

  • Tools such as a DEX to JAR convertor, jdgui, or Java decompilers

    It is also important that these tools are ready in our lab. These small tools help us in the decompilation of Android applications.

  • Tools such as DroidProxy or Autoproxy for Android

    Since previous versions of Android did not have a feature to direct the OS to set a proxy, we need such tools to be downloaded from Google Play Store.

How it works...

With the tools ready in our pentesting lab, let's see how we can link the penetration testing use cases to different categories while using the tools:

  • Mobile application traffic-related attacks: This is where Wi-Fi network and proxy tools are going to come in handy. A laptop with a Charles or Burp proxy installed is connected to Wi-Fi. A mobile device running the application is directed to the laptop proxy, using the proxy configuration on the device. Since both the laptop and the mobile device are on the same Wi-Fi network, application traffic gets routed via the Charles or Burp proxy tool. Use tools like DroidProxy or Autoproxy for Android devices to set a proxy if required.

    Effectively, this whole process makes application traffic readable and editable via proxy tools so we can conduct various attacks, which will be seen in another chapter.

    • Mobile device storage-related attacks: We have a data cable to connect the phone to the laptop. We have the emulator on the laptop. Both of them can run mobile applications. We also have a very powerful tool, ADB, with us; it can connect to, and steal data from, devices or emulators, as well as performing many other possible attacks.

  • Mobile application source code-related attacks: Decompiling the Android application can be broken into two steps: APK to DEX conversion and DEX to JAR conversion.

    APK is the Android application package. Once the Android application is developed and packed, the resulting file format is .apk. Mobile applications are named <filename>.apk.

    APK to DEX conversion is quite straightforward; it just involves renaming and unzipping the archived files.

    .dex to .jar conversion is achieved via tools such as DEX to JAR converters.

There's more...

  • Attacks involving mobile OS features used by mobile applications

 

Setting up the iOS pentesting environment


Now that you are well acquainted with the iOS development environment and simulators, and have coded your first application as well, it is time to learn about penetration testing for iOS applications. Penetration testing for mobile applications can be broadly classified into four categories, as we saw in the previous recipe:

  • Mobile application traffic-related attacks

  • Mobile device storage-related attacks

  • Mobile application source code-related attacks

  • Attacks involving mobile OS features used by mobile applications

Getting ready

We have to set up a lab for iOS pentesting, which should be sufficiently well equipped to be able to conduct testing for test cases that fall into the four categories listed previously.

To get going, we need a minimum of the following tools. The list is not very different from Android, but includes some specific tools:

  • iOS simulators

  • Xcode

  • iExplorer

  • One or two iPhones or iPads (jailbroken)

  • Proxy tools such as Charles, Burp Suite, and Fiddler

  • A Wi-Fi network

  • Tools such as SQLite browser, text editors, XML viewers, and plist editors

  • A data cable

  • Tools such as otool and classdump

How to do it...

Let's look at each of these tools:

  • iOS simulators

    We will use iOS Simulators to run iOS applications where we have the application code available to us. In such cases, testing can be conducted from just one MacBook with all the tools installed (no need for Wi-Fi or mobile handsets).

  • Xcode

    Xcode is the IDE for iOS applications. It is not only helpful for reviewing the source code of an iOS application, but also comes in handy in terms of viewing certain files, which open in Xcode only.

  • iExplorer

    iExplorer can be downloaded on a MacBook from the Apple App Store. A Windows version of this can also be downloaded when working with iPhones or iPads connected to a Windows machine via a data cable.

    iExplorer, like Windows Explorer, helps to navigate the filesystem. It can be used to explore, read files, and steal data from iOS devices.

  • One or two iPhones or iPads (jailbroken)

    A jailbroken iOS device comes in handy. The applications installed on these devices can be pentested from the device itself, eliminating the requirement for Simulators.

  • Proxy tools such as Charles, Burp Suite, and Fiddler

    Various proxy tools can be downloaded from their websites. These are quite straightforward and there are guides and help forums about them as well. The installation of such tools is outside the scope of this book, but we will cover the configuration of them for mobile applications.

    Here are links to the most common proxy tools:

  • A Wi-Fi network

    We need a Wi-Fi network to intercept Wi-Fi traffic. We will later set up a proxy for a mobile device to a laptop running a proxy tool, with both on the same Wi-Fi network.

    Either you can use a Wi-Fi router to set up your personal Wi-Fi network, or you can use one of the free tools available to create a hotspot from your laptop. In our experience, it is sometimes difficult to work with the latter option, so we prefer using the former.

  • Tools such as SQLite browser, text editors, XML viewers, and plist editors

    These are additional tools for reading the data extracted from phones. Again these are free to download, or you may already have them.

    plist files are used in iOS applications to store data, and plist editors are useful in reading such files.

  • A data cable

    It is also important to own a data cable. Later, we will use it to connect to the phone in order to read data and conduct attacks that originate via USB.

  • Tools such as otool and classdump

    These tools are decompilation tools for iOS applications.

How it works...

With the tools ready in our pentesting lab, let's see how we can link the penetration testing use cases to different categories while using these tools:

  • Mobile application traffic-related attacks: This is where a Wi-Fi network and proxy tools are going to come in handy. A laptop with a Charles or Burp proxy installed is connected to Wi-Fi. An iOS device running the application is directed to the laptop proxy, using the proxy configuration on the device. Since both the laptop and the mobile device are on the same Wi-Fi network, application traffic is routed via the Charles or Burp proxy tool. This setup does not require a MacBook (any other laptop will do), but an iOS device is needed.

    Another possibility is that we can use a MacBook but not an iOS device. In this case, we will run the application via Xcode and the Simulator. The proxy is set to localhost on the MacBook, where we are running a proxy tool such as Burp or Charles.

    Effectively, both approaches make application traffic readable and editable via proxy tools, and we can conduct various attacks, which will be seen in another chapter.

  • Mobile device storage-related attacks: We have a data cable to connect the iPhone or iPad to the laptop. We can use the iExplorer tool on the laptop to read and steal files and other data.

  • Mobile application source code-related attacks: We discussed the otool and classdump tools. Only a limited decompilation is possible in the case of iOS applications, and these tools can help only up to a certain point. This will be covered in detail in one of the later chapters.

There's more...

  • Attacks involving mobile OS features used by mobile applications

This is the most complicated category and becomes further complicated in the case of the iOS platform. There are various iOS features that applications interact with, such as screenshot backgrounding, Bluetooth, NFC, and so on. The interaction of these features with the application, along with the insecure implementation of these features in the application, results in vulnerabilities. A popular example is the screenshot backgrounding vulnerability in iOS applications.

 

Introduction to rooting and jailbreaking


Fundamentally, rooting is obtaining root access to the underlying Linux system, in order to perform operations such as mounting/unmounting filesystems; running SSH, HTTP, DHCP, DNS or proxy daemons; killing system processes; and so on.

Being able to run commands as the root user allows us to do anything on Linux and thus, by extension, on an Android system.

Jailbreaking is the process of privilege escalation, by which we can remove the hardware level restrictions imposed by Apple on iOS devices. Jailbreaking permits root access to the iOS filesystem and manager, allowing the downloading of additional applications, extensions, and themes that are unavailable through the official Apple App Store.

Getting ready

All that is needed to root an Android device is a USB cable; an unrooted Android device; and an exploit code to be run on the device, either through ADB, one-click-root programs/apps, or a modified ROM that can be flashed onto the device.

The requirements for an iOS jailbreak are a USB Cable, an iOS device, and a jailbreaking program.

How to do it...

Here we will go through two steps; rooting and jailbreaking.

Rooting

The actual rooting process itself should only take a single click. However, you'll need to do a few quick things first:

  1. Download and install the Java JDK and Android SDK on your computer before continuing. Java must be installed before the Android SDK.

  2. Enable USB debugging on your Android. On the device, go into the Settings screen, tap Applications, tap Development, and enable the USB debugging checkbox:

    After this, the rooting process essentially involves finding tested rooting methods for your specific device by searching the Internet. The rooting processes for most Android devices can be categorized into the following:

    • Using a rooting application: In this process you perform the following tasks:

      1. Install the rooting application on your machine

      2. Connect the Android device with USB debugging enabled

      3. Follow the simple instructions to root your device

    • Using rooting apps: In this process you perform the following tasks:

      1. Download the rooting APK

      2. Enable USB debugging mode and allow installation from unknown sources, from the development settings of the Android device

      3. Install the rooting APK using adb install /path/to/apk

      4. Follow the onscreen instructions to root the Android device

    • Flashing a custom ROM: In this process you perform the following tasks:

      1. Copy the modified ROM to the SD card of the Android device (as a .zip file)

      2. Reboot the device in recovery mode

      3. Head to the install or install zip from sdcard section of the recovery menu

      4. Navigate to the .zip file, and select it from the list to flash it

Jailbreaking

Before performing a jailbreak, you should back up your device. If for any reason the jailbreak fails, you can restore the backup.

The jailbreaking process involves downloading the program to a Mac/Windows machine, connecting our iOS device to our machine via a USB cable, and running the tool. One such tool is evasi0n:

The instructions are mentioned along with the tool, and should be followed methodically.

As a part of the jailbreaking process, the tool installs Cydia on the target iOS device.

Cydia is an alternative App store containing iOS apps other than ones provided and usually approved by Apple. Most of these apps are developed by the jailbreaking community, such as tools for using custom themes and widgets, changing default apps, and so on.

How it works...

Let's take a look at the details with reference to the processes individually.

Rooting

Being able to run commands as the root user allows us to do anything on Linux and thus, by extension, on an Android system.

The process for rooting an Android device typically involves two steps:

  1. Find an exploit that allows the execution of arbitrary code as root.

  2. Use the exploit to install su.

If the target device has an unlocked bootloader, the process is pretty easy. An unpackaged bootloader allows the flashing of arbitrary ROMs, so su can be added to a stock ROM and repackaged into a modified ROM. All the user needs to do is to reboot the device into flashing mode by pressing a combination of keys during bootup, and use the device's utilities to flash the modified ROM onto the device.

But, what about devices that have locked bootloaders? You can only interact with unprivileged programs on the system and they cannot help you execute any privileged code.

Many programs, such as system services, run as root on Android, to be able to access underlying hardware resources.

All one-click-root methods exploit vulnerabilities in one of these system processes running in privileged mode to execute a particular piece of code that mounts the system in read-write mode and installs the su binary on the system, thus gaining privileged access to the system.

Jailbreaking

The jailbreaking process differs from tool to tool, and different procedures are followed for different iOS versions. Here, we analyze the anatomy of one such tool, used to jailbreak an iPhone 5.

The jailbreaking program begins by running libimobiledevice to exploit a bug in iOS's mobile backup system in order to gain access to a normally restricted file containing the time zone settings.

Note

libimobiledevice is a cross-platform software library which "talks" the protocols that support iOS devices. It allows other software to easily access the device's filesystem; retrieve information about the device and its internals; back up and restore the device; manage installed applications; retrieve address books, calendars, notes and bookmarks; and synchronize music and video to the device.

More information can be found at http://www.libimobiledevice.org/.

It then inserts a "symbolic link" to a certain altered "socket," which allows programs to communicate with launchd, a master process which is loaded whenever an iOS device boots up and can launch applications that require "root" privileges.

So now, whenever an iOS mobile backup runs, all programs will automatically be granted access to the time zone file, and therefore access to launchd.

Pretty neat, huh?

iOS implements code-signing as a safeguard to prevent any "untrusted" application from gaining access to launchd.

So to defeat code signing, the jailbreaking tool launches a new, unsigned, seemingly benign app. But when the user is prompted to tap the app's icon, the app uses a technique called shebang to call up code from another signed application, which in this case was launchd.

A shebang is a character sequence consisting of the hash symbol and exclamation mark characters (that is, #!) at the beginning of a script.

In Unix, when a script with a shebang is run as a program, the program loader parses the rest of the script's initial line as an interpreter directive; the specified interpreter program is run instead, passing to it as an argument the path that was initially used when attempting to run the script.

For example, if a code has the path path/to/code, and it starts with #!/bin/sh, then the program loader is instructed to run the program /bin/sh instead, passing path/to/code as the first argument.

launchd is then used to run the remount command, which changes the memory settings of the read-only root file system to be writable.

To make the jailbreak "persistent", the launchd.conf file is called to alter the launchd configurations. The user now does not need to re-run the program on every reboot.

The jailbreaking tool then moves on to its last feat, removing restrictions at the kernel level. The iOS kernel uses Apple Mobile File Integrity Daemon (AMFID) to run unapproved apps from using a process. The jailbreaking program leverages launchd once again, to load a library of functions into AMFID in order to always approve all apps.

The second restriction posed by the kernel is Address Space Layout Randomization (ASLR), used to prevent the alteration of memory by randomizing or "hiding" the device's code every time it boots. This would prevent someone from write over a particular part of the code.

The jailbreaking tool then uses a neat trick to locate one particular area in memory; the ARM exception vector. This part handles app crashes, indicating the part of memory where the crash occurred.

A crash is simulated by the jailbreaking tool, checking the ARM exception vector to see where the crash occurred and collecting minimal information, enough to map out the rest of the kernel.

The tool, as its final step, uses a bug in iOS's USB interface that passes an address in the kernel's memory to a program and expects the program to return it untampered.

This allows the tool to write to the part of the kernel that restricts code changes, thus taking complete control, and fulfilling its purpose successfully!

About the Author
  • Akshay Dixit

    Akshay Dixit is an information security specialist, consultant, speaker, researcher, and entrepreneur. He has been providing consulting services in information security to various government and business establishments, specializing in mobile and web security. Akshay is an active researcher in the field of mobile security. He has developed various commercial and in-house tools and utilities for the security assessment of mobile devices and applications. His current research involves artificial intelligence and mobile device exploitation. He has been invited to several international conferences to give training, talks and workshops. He has written articles for various blogs and magazines on topics such as mobile security, social engineering, and web exploitation.

    Browse publications by this author
Latest Reviews (3 reviews total)
tego wlasnie mi potrzeba!
Mobile Device Exploitation Cookbook
Unlock this book and the full library FREE for 7 days
Start now