kratos: discovering inconsistent security policy ...alfchen/roy_ndss16.pdf · kratos: discovering...

15
Kratos: Discovering Inconsistent Security Policy Enforcement in the Android Framework Yuru Shao, Jason Ott , Qi Alfred Chen, Zhiyun Qian , Z. Morley Mao University of Michigan, University of California, Riverside {yurushao, alfchen, zmao}@umich.edu, [email protected], [email protected] Abstract—The Android framework utilizes a permission-based security model, which is essentially a variation of the ACL-based access control mechanism. This security model provides con- trolled access to various system resources. Access control systems are known to be vulnerable to anomalies in security policies, such as inconsistency. In this work, we focus on inconsistent security enforcement within the Android framework, motivated by the recent work which discovered such vulnerabilities. They include stealthily taking pictures in the background and recording keystrokes without any permissions, posing security and privacy risks to Android users. Identifying such inconsistencies is gener- ally difficult, especially in complicated and large codebases such as the Android framework. Our work is the first to propose a methodology to system- atically uncover the inconsistency in security policy enforcement in Android. We do not assume Android’s security policies are known and focus only on inconsistent enforcement. We propose Kratos, a tool that leverages static analysis to build a precise call graph for identifying paths that allow third-party applications with insufficient privilege to access sensitive resources, violating security policies. Kratos is designed to analyze any Android sys- tem, including vendor-customized versions. Using Kratos, we have conservatively discovered at least fourteen inconsistent security enforcement cases that can lead to security check circumvention vulnerabilities across important and popular services such as the SMS service and the Wi-Fi service, incurring impact such as privilege escalation, denial of service, and soft reboot. Our findings also provide useful insights on how to proactively prevent such security enforcement inconsistency within Android. I. I NTRODUCTION Access control is a well-known approach to prevent activ- ities that could lead to security breach. It is widely used in all modern operating systems. Linux inherits the core UNIX security model — a form of Discretionary Access Control (DAC). To provide stronger security assurance, researchers developed Security-Enhanced Linux (SELinux) [37], which incorporates Mandatory Access Control (MAC) into the Linux kernel. The fundamental question that access control seeks to answer is philosophical in nature: “who” has “what kind of access” to “what resources.” It is from this single question that access control policies or security policies are derived. Android OS employs a permission-based security model, which is a derivative of the Access Control List (ACL) based access control mechanism [14]. In this model, an application (commonly known as an app) or a user may request access to a set of resources that are governed by a set of permissions, exposed by the system or other apps. Access control systems are known to be vulnerable to anomalies in security policies, such as inconsistency [36]. However, security policies can be inconsistent not only in their definitions, but also in the ways they are enforced [38]. A major challenge of supporting permission-based security models, as well as other access control systems, is to en- sure that all sensitive operations on all objects are correctly protected by proper security checks in a consistent manner. If the proper security check is missing before a sensitive operation, an attacker with insufficient privilege may then perform the security-sensitive operation, violating user privacy or causing damage to the user or the system. For example, on Linux, multiple such examples have been discovered, which lead to unauthorized user account access [10], permanent data loss [38], etc. More recently, on the Android platform, attacks caused by inconsistent policy enforcement have also been found, e.g., stealthily taking pictures in the background [18] and stealing user passwords by recording keystrokes without the necessary permissions [46]. Therefore, to ensure a safe and secure platform for users and developers, it is critical to develop a systematic approach to identify inconsistencies in security policy enforcement. To address this problem on MAC-based operating systems, Tan et al. present a method and tool, AutoISES [38], that can automatically infer security policies by statically analyzing source code and then directly using those policies to detect security violations. Its effectiveness has been demonstrated by experiments with the Linux kernel and the Xen hypervisor; however, AutoISES has several limitations that prevent it from being applied to the Android framework. First, it does not take into account inter-process communication (IPC) between different processes (or threads). In Android, remote method calls across process (or thread) boundaries are very common. Any static analysis that fails to consider this special feature would be hugely incomplete. Second, the Android framework consists of conflated layers: Java and C/C++, which is not currently supported by AutoISES. A fundamental limitation is that AutoISES assumes that a complete list of security check functions are given. While in Android, different types of security checks exist, making it extremely difficult to obtain a comprehensive list of them. In view of these challenges, we propose Kratos, a static Permission to freely reproduce all or part of this paper for noncommercial purposes is granted provided that copies bear this notice and the full citation on the first page. Reproduction for commercial purposes is strictly prohibited without the prior written consent of the Internet Society, the first-named author (for reproduction of an entire paper only), and the author’s employer if the paper was prepared within the scope of employment. NDSS ’16, 21-24 February 2016, San Diego, CA, USA Copyright 2016 Internet Society, ISBN 1-891562-41-X http://dx.doi.org/10.14722/ndss.2016.23046

Upload: others

Post on 28-May-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Kratos: Discovering Inconsistent Security Policy ...alfchen/roy_ndss16.pdf · Kratos: Discovering Inconsistent Security Policy Enforcement in the Android Framework Yuru Shao, Jason

Kratos: Discovering Inconsistent Security PolicyEnforcement in the Android Framework

Yuru Shao, Jason Ott†, Qi Alfred Chen, Zhiyun Qian†, Z. Morley MaoUniversity of Michigan, †University of California, Riverside

{yurushao, alfchen, zmao}@umich.edu, [email protected], [email protected]

Abstract—The Android framework utilizes a permission-basedsecurity model, which is essentially a variation of the ACL-basedaccess control mechanism. This security model provides con-trolled access to various system resources. Access control systemsare known to be vulnerable to anomalies in security policies,such as inconsistency. In this work, we focus on inconsistentsecurity enforcement within the Android framework, motivatedby the recent work which discovered such vulnerabilities. Theyinclude stealthily taking pictures in the background and recordingkeystrokes without any permissions, posing security and privacyrisks to Android users. Identifying such inconsistencies is gener-ally difficult, especially in complicated and large codebases suchas the Android framework.

Our work is the first to propose a methodology to system-atically uncover the inconsistency in security policy enforcementin Android. We do not assume Android’s security policies areknown and focus only on inconsistent enforcement. We proposeKratos, a tool that leverages static analysis to build a precise callgraph for identifying paths that allow third-party applicationswith insufficient privilege to access sensitive resources, violatingsecurity policies. Kratos is designed to analyze any Android sys-tem, including vendor-customized versions. Using Kratos, we haveconservatively discovered at least fourteen inconsistent securityenforcement cases that can lead to security check circumventionvulnerabilities across important and popular services such asthe SMS service and the Wi-Fi service, incurring impact suchas privilege escalation, denial of service, and soft reboot. Ourfindings also provide useful insights on how to proactively preventsuch security enforcement inconsistency within Android.

I. INTRODUCTION

Access control is a well-known approach to prevent activ-ities that could lead to security breach. It is widely used inall modern operating systems. Linux inherits the core UNIXsecurity model — a form of Discretionary Access Control(DAC). To provide stronger security assurance, researchersdeveloped Security-Enhanced Linux (SELinux) [37], whichincorporates Mandatory Access Control (MAC) into the Linuxkernel. The fundamental question that access control seeks toanswer is philosophical in nature: “who” has “what kind ofaccess” to “what resources.” It is from this single questionthat access control policies or security policies are derived.

Android OS employs a permission-based security model,which is a derivative of the Access Control List (ACL) basedaccess control mechanism [14]. In this model, an application(commonly known as an app) or a user may request access toa set of resources that are governed by a set of permissions,exposed by the system or other apps.

Access control systems are known to be vulnerable toanomalies in security policies, such as inconsistency [36].However, security policies can be inconsistent not only intheir definitions, but also in the ways they are enforced [38].A major challenge of supporting permission-based securitymodels, as well as other access control systems, is to en-sure that all sensitive operations on all objects are correctlyprotected by proper security checks in a consistent manner.If the proper security check is missing before a sensitiveoperation, an attacker with insufficient privilege may thenperform the security-sensitive operation, violating user privacyor causing damage to the user or the system. For example, onLinux, multiple such examples have been discovered, whichlead to unauthorized user account access [10], permanent dataloss [38], etc. More recently, on the Android platform, attackscaused by inconsistent policy enforcement have also beenfound, e.g., stealthily taking pictures in the background [18]and stealing user passwords by recording keystrokes withoutthe necessary permissions [46]. Therefore, to ensure a safeand secure platform for users and developers, it is critical todevelop a systematic approach to identify inconsistencies insecurity policy enforcement.

To address this problem on MAC-based operating systems,Tan et al. present a method and tool, AutoISES [38], that canautomatically infer security policies by statically analyzingsource code and then directly using those policies to detectsecurity violations. Its effectiveness has been demonstrated byexperiments with the Linux kernel and the Xen hypervisor;however, AutoISES has several limitations that prevent it frombeing applied to the Android framework. First, it does nottake into account inter-process communication (IPC) betweendifferent processes (or threads). In Android, remote methodcalls across process (or thread) boundaries are very common.Any static analysis that fails to consider this special featurewould be hugely incomplete. Second, the Android frameworkconsists of conflated layers: Java and C/C++, which is notcurrently supported by AutoISES. A fundamental limitationis that AutoISES assumes that a complete list of securitycheck functions are given. While in Android, different typesof security checks exist, making it extremely difficult to obtaina comprehensive list of them.

In view of these challenges, we propose Kratos, a static

Permission to freely reproduce all or part of this paper for noncommercialpurposes is granted provided that copies bear this notice and the full citationon the first page. Reproduction for commercial purposes is strictly prohibitedwithout the prior written consent of the Internet Society, the first-named author(for reproduction of an entire paper only), and the author’s employer if thepaper was prepared within the scope of employment.NDSS ’16, 21-24 February 2016, San Diego, CA, USACopyright 2016 Internet Society, ISBN 1-891562-41-Xhttp://dx.doi.org/10.14722/ndss.2016.23046

Page 2: Kratos: Discovering Inconsistent Security Policy ...alfchen/roy_ndss16.pdf · Kratos: Discovering Inconsistent Security Policy Enforcement in the Android Framework Yuru Shao, Jason

/** * Used by device administration to set the maximum screen off timeout. * * This method must only be called by the device administration policy manager. */@Override // Binder callpublic void setMaximumScreenOffTimeoutFromDeviceAdmin(int timeMs) { final long ident = Binder.clearCallingIdentity(); try { setMaximumScreenOffTimeoutFromDeviceAdminInternal(timeMs); } finally { Binder.restoreCallingIdentity(ident); }}

@Overridepublic boolean havePassword(int userId) throws RemoteException { // Do we need a permissions check here? return new File(getLockPasswordFilename(userId)).length() > 0;}

@Overridepublic boolean havePattern(int userId) throws RemoteException { // Do we need a permissions check here? return new File(getLockPatternFilename(userId)).length() > 0;}

They know the use of this method should be restricted but did not apply any security checks

Android framework developers lack knowledge of security policies that should be enforced

Fig. 1. Code snippets from PowerManagerService.java (left side) and LockSettingsService.java (right side) in AOSP 5.0.1. They show thateven Google engineers do not have accurate knowledge of security policies that should be enforced.

analysis tool for systematically detecting inconsistent securityenforcement in the Android framework. Kratos accepts Javaclass files and security enforcement checks as input, and out-puts a ranked list of inconsistencies. It first builds a precise callgraph for the codebase analyzed. This call graph comprises ofall the execution paths available to access sensitive resources.Each node of the call graph is then annotated with securityenforcement methods that are applied to that node. For a setof entry points, Kratos compares their sub-call graphs pairwiseto identify possible paths which can reach the same sensitivemethods but enforce different security checks (e.g., one withchecks and the other without). Kratos can be applied to boththe AOSP framework and vendor-specific frameworks.

Another thread of related work focuses on automatedauthorization hook placement to mediate all security-sensitiveoperations on shared resources. In work by Muthuku-maran et al. [34], there is an implicit assumption made bythe authors: they have perfect knowledge of which functions orpieces of code needs protection. They are able to automaticallyplace the policy enforcement based on metrics such as theminimum number of checks needed. Not only do we lackthis understanding, but also any understanding that might beinferred from the Android source code is further obfuscatedby uncertainties introduced by developers, as illustrated in thecode snippets in Figure 1.

Kratos makes no assumptions about or attempts to in-fer what resources or operations in Android framework aresecurity-sensitive and should be protected. Instead, Kratosonly identifies where existing security policy enforcementoccurs based on observed security checks, and accurately inferssecurity-sensitive operations by identifying inconsistency inthe policy enforcement across different execution paths.

To implement Kratos, we overcome several engineeringchallenges. First, to maximize the completeness of our analy-sis, we need to cover as many system services as possible.However, system services are scattered throughout the An-droid framework with some implemented as private classesnested inside outer classes, making it difficult to include allservice interfaces as analysis entry points. We address thisby generating code that calls service interfaces and handlesnested private services. Second, our analysis relies on a preciseAndroid framework call graph, which is non-trivial to build.We tackle this challenge by resolving virtual method callsusing Spark [28], a tool for performing Java points-to analysis,and applying IPC shortcuts. Third, due to the large size ofcode in Android framework, it is non-trivial to make the

analysis efficient and scalable. We achieve high efficiency andscalability by optimizing the implementation and adopting aset of heuristics.

We run Kratos on six different Android codebases, in-cluding 4 versions of Android frameworks, 4.4, 5.0, 5.1, andM preview, and two customized Android versions on AT&THTC One and T-Mobile Samsung Galaxy Note 3 devices.After verifying the tool output manually, we find that all sixcodebases fail to ensure consistent policy enforcement withat least 16 to 50 inconsistencies discovered. For one, thenumber of inconsistencies are as high as 102. From theseinconsistencies, we are able to uncover 14 highly-exploitablevulnerabilities spanning a wide range of distinct Androidservices on the 6 codebases; 12 of them are found to affect atleast 3 codebases at the same time; 6 vulnerabilities have beenpatched in the latest or earlier releases but never been revealedto the public previously. All these exploits can be carried outwith no permission or only low-privileged permissions (e.g.,the INTERNET permission), and lead to serious security andprivacy breaches such as crashing the entire Android runtime,terminating mDNS daemon to make file sharing and multi-player gaming unusable, and setting up a HTTP proxy tointercept all web traffic on the device.

We have reported all of these vulnerabilities to the An-droid Security Team. Among the 11 that we have receivedfeedback, all were confirmed as low severity vulnerabilities.This indicates the challenging nature of enforcing consistentpolicies in a complex system like Android, and the necessityof a systematic detection tool like Kratos. Due to the lackof an up-to-date Android malware dataset, we do not havestatistics on how many of these vulnerabilities have alreadybeen exploited by malicious apps in the wild. More detailsabout the inconsistencies reported by Kratos and the vul-nerabilities we identified are available at our results websitehttp://tinyurl.com/kratos15.

We summarize our key contributions as follows.

• Our work is the first to systematically uncover securityenforcement inconsistencies in the Android frameworkitself, compared to previous work focusing on per-mission use in Android apps. We design and imple-ment Kratos, a static analysis tool that can effectivelyidentify inconsistent security enforcement in both theAOSP and customized Android. We tackle several en-gineering challenges, including automated entry pointgeneration, IPC edges connection, and parallelization

2

Page 3: Kratos: Discovering Inconsistent Security Policy ...alfchen/roy_ndss16.pdf · Kratos: Discovering Inconsistent Security Policy Enforcement in the Android Framework Yuru Shao, Jason

to ensure accuracy and efficiency.

• We evaluate our tool on four versions of the Androidframework: 4.4, 5.0, 5.1, and M preview, as wellas two customized: AT&T HTC One and T-MobileSamsung Galaxy Note 3, and find that all codebasesfail to ensure consistent policy enforcement with up to102 inconsistencies in a single codebase. Among thediscovered inconsistencies, we are able to uncover 14highly-exploitable vulnerabilities, which can lead toserious security and privacy breaches such as crashingthe entire Android runtime, ending phone calls, andsetting up a HTTP proxy with no permissions or onlylow-privileged permissions.

• Our analysis covers all app-accessible interfaces ex-posed by system services implemented in Java code.Many system service interfaces are by default invisibleand undocumented for apps. Among the 14 vulnera-bilities we identified, 11 of them are hidden interfacesthat are rather difficult to detect. These findings sug-gest useful ways to proactively prevent such securityenforcement inconsistency include reducing serviceinterfaces and restricting the use of Java reflection (foraccessing hidden interfaces).

II. BACKGROUND AND MOTIVATION

In this section, we cover background on Android’s sys-tem services and the different types of security enforcementadopted by the Android framework. We also present a motivat-ing case that demonstrates inconsistent security enforcement inAndroid’s Wi-Fi service.

A. System Services

System services implement the fundamental features withinAndroid, including display and touch screen support, tele-phony, and network connectivity. The number of serviceshas slowly increased with each version: growing from 73in Android 4.4 to 94 for M Preview. Most system servicesare implemented in Java with certain foundational serviceswritten in native code. At runtime, system services are run-ning in several system processes, such as system_server,mediaserver. To provide functionality to other services andapps, each system service exposes a set of interfaces accessiblefrom other services and apps through remote procedure calls.For simplicity, we define users (either another service oran app) of a system service as its clients. From a client’sperspective, calling remote interfaces of a system service isequivalent to calling its local methods.

ServiceManager

WiFi Service

SMS Service

...

Client

WiFi ServiceProxy

Register

Register

RegisterLookup

Fig. 2. System services register themselves to Service Manager and clientscall their remote interfaces with proxies.

Fig. 2 depicts how system services are managed and used.When the Android runtime boots, system server registerssystem services to the Service Manager, which runs in an inde-pendent process servicemanager and governs all systemservices. When a client wants to call a system service, e.g., Wi-Fi Service in Fig. 2, it first queries the service index providedby Service Manager. If the service exists, Service Managerreturns a proxy object, Wi-Fi Service Proxy, through whichthe client invokes Wi-Fi Service methods. The “contract” thatboth the Wi-Fi Service and the proxy agree upon is definedby Android Interface Definition Language (AIDL). Fig. 3 usesthe Wi-Fi Service as an example and shows how the serviceand its proxy use the AIDL to define consistent interfaces.

During compiling, a class IWifiManager is automati-cally generated from the AIDL file, IWifiManager.aidl.It has two inner classes, i.e., IWifiManager$Stuband IWifiManager$Stub$Proxy. All interfaces definedin the AIDL file IWifiManager.aidl are also de-clared in IWifiManager, IWifiManager$Stub andIWifiManager$Stub$Proxy. The service extendingIWifiManager$Stub is responsible for implement meth-ods defined in IWifiManager.aidl. Clients who wish toaccess service functionality only need to obtain a referenceto IWifiManager and invoke IWifiManager’s method.As a result, the corresponding implementation in the servicewill be called. The intermediate procedure is handle by BinderIPC [1] and completely transparent to clients and services.

1 // Client.java2 public class Client {3 IWifiManager mgr = IWifiManager.Stub.asInterface(4 ServiceManager.getService("wifi"));5 mgr.removeNetwork(netId);6 mgr.disableNetwork(netId);7 ...8 }9

10 // WifiManager.aidl11 interface IWifiManager {12 boolean removeNetwork(int netId);13 boolean disableNetwork(int netId);14 void connect();15 void disconnect();16 ...17 }18

19 // Decompiled from IWifiManager.class20 public interface IWifiManager extends IInterface {21 boolean removeNetwork(int netId);22 boolean disableNetwork(int netId);23 void connect();24 void disconnect();25 ...26 }27

28 // WifiService.java29 public class WifiService extends IWifiManager.Stub {30 @override31 public boolean removeNetwork(int netId) {32 enforceChangePermission();33 ...34 }35 @override36 public boolean disableNetwork(int netId) {37 enforceChangePermission();38 ...39 }40 ...41 }

Fig. 3. Code snippet that demonstrates the usage of AIDL

3

Page 4: Kratos: Discovering Inconsistent Security Policy ...alfchen/roy_ndss16.pdf · Kratos: Discovering Inconsistent Security Policy Enforcement in the Android Framework Yuru Shao, Jason

In our analysis, we focus solely on system services. Morespecifically, we consider all remote interfaces exposed bysystem services as application-accessible interfaces. Note thatsome proxy interfaces are invisible to apps, either becausethe classes are excluded from the Android SDK or becausethe methods are labeled with the @hide or @SystemApijavadoc directive in the source code. However, they still existin the runtime and apps can access them using Java reflectiontechniques.

B. Motivating Example of Inconsistent Security Enforcement

For convenience, we use the terms security policy enforce-ment and security enforcement interchangeably in this paper.Security enforcement consists of a set of security checks.Security check refers to a specific action which verifies whetherthe caller satisfies particular security requirements, e.g., holdsa permission or has a specific UID. The Android frameworkemploys several types of security enforcement: permissioncheck, UID check, package name check, and thread statuscheck, all explained below.

Permission checking is the most fundamental and widelyused security enforcement in Android. Each app requestsa set of permissions during installation The user must al-low all permissions requested or choose not to install theapp. When an app calls a method exposed by a systemservice, the service verifies that the app holds the requiredpermission(s). If so, the app passes the permission checkand continues executing. Otherwise, the service immedi-ately throws a security exception; as a result, the app can-not access resources guarded by the service. As shownin Fig. 3 lines 31–34, removeNetwork(int) invokesenforceChangePermission() to check that the callingapp has the CHANGE_WIFI_STATE permission. Permissionchecks are performed immediately after the code enters theservice side. This is different from other systems such asSELinux, which places security checks right before accessingsensitive objects [32]. We believe these different approachespresent tradeoffs in balancing the performance overhead andaccess control granularity.

Despite the permission check placement, we haveobserved inconsistent enforcement of permissions within thesame service and between services with similar functionality.For example, in Fig. 4 we detail inconsistencies withina single service, i.e., the Wi-Fi Service. It exposestwo interfaces to clients: addOrUpdateNetwork()and getWifiStateMachineMessenger(). Bothof them can be leveraged by apps to update Wi-Fi configurations. Though they ultimately invokethe same underlying method WifiConfigStore.addOrUpdateNetworkNative(), the two paths they tra-verse are different. The method addOrUpdateNetwork()first calls sendMessageSynchronously(), throughwhich it sends a CMD_ADD_OR_UPDATE_NETWORK messageto the internal Wi-Fi state machine which is able to updateWi-Fi configurations according to current status. Meanwhile,apps can call getWifiStateMachineMessenger()to obtain the Wi-Fi state machine’s Messengerobject, with which they are able to directly send aSAVE_NETWORK message to the Wi-Fi state machine toupdate configurations. Surprisingly, permission checks differ

addOrUpdateNetwork()CHANGE_WIFI_STATE

CONNECTIVITY_INTERNAL

addOrUpdateNetwork()

handleMessage()

saveNetwork()

sendMessageSynchronously()CMD_ADD_OR_UPDATE_NETWORK

addOrUpdateNetworkNative()

WifiService

WifiStateMachine

WifiConfigStore

Application

Client

Service

getWifiStateMachineMessenger()CHANGE_WIFI_STATEACCESS_WIFI_STATE

Messenger

sendMessage()SAVE_NETWORK� �

Fig. 4. A motivating case showing inconsistent security enforcement inthe Wi-Fi Service of Android 4.4. An app can use either of the twointerfaces exposed by the Wi-Fi Service, addOrUpdateNetwork() (callchain connected by solid lines) getWifiStateMachineMessenger()(call chain connected by dashed lines), to update connection configurations toa Wi-Fi access point. However, they are enforcing different permissions. Notethat actual call chains have been simplified to better demonstrate the example,with method parameters omitted.

along these two paths. addOrUpdateNetwork() checksthree different permissions, i.e., ACCESS_WIFI_STATE,CHANGE_WIFI_STATE, and CONNECTIVITY_INTERNAL.However, only two of them are enforcedin getWifiStateMachineMessenger(),i.e., ACCESS_WIFI_STATE and CHANGE_WIFI_STATE.Considering that CONNECTIVITY_INTERNAL is a system-level permission, it is impossible for third-party apps toacquire it. Thus, addOrUpdateNetwork() is protectedfrom third-party app usage. Nevertheless, this enforcementcan be completely bypassed if an app developer, or malwareauthor, uses getWifiStateMachineMessenger()instead of addOrUpdateNetwork(). Similarly, TelephonyService and Telecom Service both provide methods to accesstelephony-related functionality. While these two services aredifferent, they do have some overlapping functionality — theyexpose different methods which provide similar underlyingfunctionality, see Section V for further discussion.

C. UID Check

Interfaces provided by a system service can be called byapps, as well as other system services. For some sensitive oper-ations the system service only allows internal uses by checkingthe caller’s UID. As aforementioned, service interfaces areinvoked through the Binder IPC mechanism. For each AIDLmethod call, the system keeps track of the original caller’sidentity in order to check it within the service side. Fig. 5shows a code snippet extracted from the Keyguard Service. ItscheckPermission() method has two steps: First, it getsUID of the caller using Binder.getCallingUid() andverifies that the UID is equal to SYSTEM_UID. If so, the calleris the system and no further check is required. Otherwise, thepermission check is performed.

4

Page 5: Kratos: Discovering Inconsistent Security Policy ...alfchen/roy_ndss16.pdf · Kratos: Discovering Inconsistent Security Policy Enforcement in the Android Framework Yuru Shao, Jason

1 void checkPermission() {2 if (Binder.getCallingUid() == Process.SYSTEM_UID)3 return;4 // Otherwise, explicitly check for caller permission5 if (checkCallingOrSelfPermission(PERMISSION)6 != PERMISSION_GRANTED) {7 ...8 }9 }

Fig. 5. Permission check is performed if the UID check fails.

D. Package Name Check

The package name check is another means to restrict thecapability of apps. For instance, in order to ensure that theclient can only delete widgets that belong to itself, the AppWidget Service checks whether the caller owns the givenpackage, by using package name check shown in Fig. 6.

1 public void enforceCallFromPackage(String packageName) {2 mAppOpsManager.checkPackage(3 Binder.getCallingUid(), packageName);4 }

Fig. 6. Check to verify the caller owns a given package.

E. Thread Status Check

Many malicious apps are reported to run in the backgroundand stealthily jeopardize the security and privacy of endusers. This is seen through the myriad of research: stealingsensitive photos [18], inferring keystrokes [44], discoveringweb browsing habits [29], understanding speech through thephones gyroscope [33], etc. To mitigate this, Android employsthread status checks, which are designed to ensure that certainsensitive operations cannot be performed by callers running inbackground. In this check, the system verifies that the caller isrunning in the foreground and visible to users, and considersonly the operations from the foreground as performed by theuser. One example of such checks in Android is implementedin the Bluetooth Manager Service. It ensures that only clientsrunning in the foreground are able to manipulate the Bluetoothdevice, by checking their running status using a dedicatedmethod named checkIfCallerIsForegroundUser().

III. METHODOLOGY

In this section, we present our design of Kratos. Wefirst give an overview of the design, followed by the keycomponents to achieve the design goals.

A. Overview

Kratos’ analysis flow consists of four phases, as shownin Fig. 7. In the first phase, we retrieve Java class files ofthe given Android framework, and process them to generateentry points of services for further analysis. Kratos is ableto analyze both AOSP and customized Android versions.Therefore, Kratos takes Java classes as input as opposed toJava source code, since customized Android frameworks areusually closed source. In the second phase, Kratos constructsa precise call graph from the entry points generated from theprevious phase. Third, we annotate the framework call graph

Preprocessing

Call Graph Annotation

Inconsistency Detection

Inconsistent Security

Enforcement

JavaClassFiles

Call Graph Construction

RelevantSecurity

Check Types

Fig. 7. Kratos analysis flow. There are four major phases: (1) Preprocessing,(2) Call Graph Construction, (3) Call Graph Annotation, and (4) InconsistencyDetection.

by considering different types of security checks of interest,e.g., permission check, UID check, package name check, andthread status check. Each node of the call graph is examined todetermine which, if any, security checks exist within it. Finally,Kratos detects inconsistencies and outputs a prioritized list ofsecurity enforcement inconsistencies.

As we have illustrated in Fig. 4, system service interfaceswith overlap in functionality may eventually invoke thesame lower-level method(s) to complete their work.For instance, both of addOrUpdateNetwork() andgetWifiStateMachineMessenger() exposed by theWi-Fi Service can be used to update the configuration ofthe currently connected Wi-Fi network. Both methods invokeWifiConfigStore.addOrUpdateNetworkNative(),i.e., invoke the same lower-level sensitive method. Suchbehaviors are expected — while it is common that similarhigh-level functionality are provided for convenience, it isnot necessary for the Android framework to implement theirunderlying functionality multiple times, hence the convergenceat the lower-level method. Based on this observation, usinga call graph to represent the execution path of a serviceinterface, we can identify where those sensitive, or lower-level, methods are invoked by any two services. This is whatwe refer to as an “overlap.” As a result, Kratos reducesthe problem of detecting security enforcement inconsistencyamong system service interfaces into call graph comparisons.

B. Preprocessing

The Preprocessing step collects important information forfurther phases. Our analysis emphasizes system services whoseimplementations are scattered throughout the Android frame-work codebase. We must first obtain a comprehensive list ofapp-accessible system services and their corresponding Javaclasses, from which we can retrieve all interfaces they exposethat could be invoked by apps.

As we mentioned in Section II, Service Manager managesall system services. Clients are required to obtain a proxy of thesystem service from Service Manager in order to invoke thatservice’s interfaces remotely. System services that are visiblefor apps should be registered to Service Manager. In practice,besides a global service manager running in a dedicatedprocess (/system/bin/servicemanager), there exist a

5

Page 6: Kratos: Discovering Inconsistent Security Policy ...alfchen/roy_ndss16.pdf · Kratos: Discovering Inconsistent Security Policy Enforcement in the Android Framework Yuru Shao, Jason

few local service managers. System services registered to localservice managers are only accessible for other services runningwithin the same process. Therefore, we only care about systemservices registered to the global Service Manager since onlythese are accessible by apps. By looking into a service’simplementation and its corresponding AIDL definition, weeasily distinguish which public methods of the service arepublicly accessible AIDL methods. Although apps can invokesystem services directly via low-level Binder IPC mechanismwithout passing through the AIDL interfaces, those Binder IPCendpoints that can be reached directly are exactly the same asthose exported via the AIDL methods.

In addition to AIDL methods, we observe another typeof interface exposed by system services that could be calledby apps, i.e., unprotected broadcast receivers that are dy-namically registered. Normally, system services dynamicallyregister broadcast receivers in order to receive asynchronousmessages from within the system. To defend against broad-cast spoofing [19], either receivers should be protected byproper permissions or broadcast actions need to be protected.However, some broadcast receivers of system services arenot protected at all. That means apps can also send craftedbroadcasts to trigger certain method calls. Therefore, we alsoconsider unprotected broadcast receivers in system services asapp-accessible service interfaces.

Currently, we do not cover those system services whosemain logic and security checks are all performed in nativecode, e.g., Camera Service. These native services are smallin number: we manually checked the source code and onlyCamera Service, Media Player Service, Audio Policy Service,Audio Flinger and Sound Trigger Hardware Service werefound in the Android 5.1 source code. While this may intro-duce false negatives, we believe the impact is minimal becausemost system services are implemented in the Java code.

C. Call Graph Construction

A precise call graph is the foundation of discoveringinconsistent security policy enforcements in our approach.This phase computes the call graph for the entire Androidframework. We rely on a context-insensitive call graph [27]which is light-weight and easier to build compared to acontext-sensitive call graph, further discussion on the context-sensitivity may be found in Section VI.

To construct the call graph, we need to know, for eachcall-site, all of its possible targets. As is common for object-oriented languages, the target of a method call depends on thedynamic type of the receiving object. A polymorphic method,i.e., virtual method may have multiple implementations indescendant classes. The runtime has a dynamic dispatch mech-anism for identifying and invoking the correct implementation.Unfortunately, it is impossible for static analysis to collectruntime information and identify with 100% accuracy thecallees of a virtual method. To address this problem, we usea conservative way to compute possible methods that mightbe called at a call-site. In other words, it computes an over-estimation of the set of calls that may occur at runtime usingcontext information. Additionally, we connect IPC callers andcallees directly to improve the precision and conciseness ofthe call graph. This is necessary because IPCs would introduce

imprecision into our call graph. They use abstract methods tosend data across process boundaries and thus in that procedure,many levels of virtual method calls are involved.

We take advantage of the solution proposed by PScout [12]to resolve Binder IPC calls and Message Handler IPCs.However, PScout fails to take a few special cases intoaccount. For example, not all system services have anAIDL file that defines their remote interfaces. For in-stance, instead of using a stub class auto-generated fromAIDL file, Activity Manager Service relies on a manu-ally implemented class, ActivityManagerNative, to de-fine its remote interfaces. Activity Manager Service extendsActivityManagerNative and implements these remoteinterfaces. Therefore, system services like Activity ManagerService should be handled carefully with additional logic.

Moreover, PScout does not consider another important IPCthat is widely used by system services — Messengers andState Machines. System services expose AIDL methods thatallow callers to obtain Messenger objects of their internal statemachines. With an Messenger, an app or a system service cansend messages to the corresponding state machine. Althoughin essence the communication between Messengers and StateMachines is built on top of Message Handler IPCs, we findthat PScout is unable to deal with this. We identify and connectall such senders and receivers for messages sent throughMessenger objects.

Entry points. Like Java programs, the Android frameworkhas a main method SystemServer.main(), from whichsystem services are initialized and started. However, we cannotuse it as the entry point. All service interfaces are likely to becalled by a client app, but the construction and initializationprocedure of system services cannot cover all remote inter-faces. As a result, the framework call graph would be incom-plete if we use SystemServer.main() as our analysisentry point.

Preprocessing produces a list of app-accessible serviceinterfaces. Since we would like to include all of them in the callgraph, one possible approach is to build call graphs from eachof the interfaces, then combine these call graphs together toform the framework’s call graph. This is not efficient becausemany call-sites would be included and computed multipletimes. To cope with this problem, for each system service weconstruct a dummy main method, in which we construct theservice object and enumerate all its app-accessible interfaces.The implementation details are described in Section IV-A.

D. Call Graph Annotation

This phase annotates the framework call graph with se-curity check information. More specifically, given the typesof security checks that are of interest to Kratos, Kratosautomatically determines which security checks are performedby which call graph nodes, or methods, and annotates thenodes with security enforcement information, e.g., permissionsit enforces, UIDs it checks.

Identifying permission check methods. Android permissionsare represented as string constants in the framework sourcecode. When performing permission checks, a permissionstring is passed as an argument to a check method.

6

Page 7: Kratos: Discovering Inconsistent Security Policy ...alfchen/roy_ndss16.pdf · Kratos: Discovering Inconsistent Security Policy Enforcement in the Android Framework Yuru Shao, Jason

According to developer comments in the Android sourcecode, checkPermission in Activity Manager Serviceis the only public entry point for permission checking.Therefore, methods that eventually call checkPermissionare considered as performing permission checks. We also wantto know which particular permission is checked. To achievethis, we keep track of permission string constants passed topermission check methods. We observe that a few namingpatterns can indicate whether a method is a permissioncheck method, such as checkCallingPermission,enforceAccessPermission, andvalidatePermission. Their names start with “enforce”,“check” or ”validate”, and end with “Permission.” Essentially,they are just wrappers of checkPermission, but we canleverage such patterns to make permission check methodidentification faster.

Identifying other security enforcements. Apart from per-mission checks, Kratos can also identify three other types ofsecurity checks automatically. For UID checks, they alwaysget caller’s UID using Binder.getCallingUid() andcompare it with a constant integer. We use def-use analysis [39]to track which constant value the caller’s UID is comparedwith. The Android framework reserves a list of UIDs and theirvalues are defined in android_filesystem_config.h,from which we can identify the user that a given UID repre-sents. Package name checks are more complicated. Besidesthe method shown in Fig. 6 that uses a similar approachto permission checks, there also exist package name checksthat are conducted like UID checks. Similarly, we employdef-use analysis and examine if the package name returnedfrom Package Manager Service is compared with a string.In summary, to detect package name checks, we use bothapproaches for identifying permission checks and UID checks.Currently there are no explicit hints that can instruct us to finda good way to identify thread status checks. Fortunately, theirnumber is small, which allows us to identify them manually.

Annotating call graph nodes. After all security enforcementmethods are identified, Kratos iterates call graph nodes andannotates them with security checks (labels) that are performedwithin. Labels are propagated toward the root of each sub-callgraph with the union operator used to merge multiple labelsat a node. This annotated call graph is then used in the nextphase for detecting inconsistent security policy enforcement.

E. Inconsistency Detection

Inconsistency Detection consists of three phases. First, forevery service interface Kratos obtains its sub-call graph fromthe framework-wide call graph and does forward analysison it to determine which security checks must be passed toreach each node. Next, Kratos compares service interfaces’call graphs in a pairwise fashion. Those pairs invoking thesame method but with different security enforcements areconsidered as inconsistency candidates. Finally, Kratos appliesthree heuristics to rule out false positives.

With the annotated framework call graph, it is easy toobtain the sub-call graph of a service interface. For a sub-call graph, Kratos traverses all its nodes and summarizesthe set of security enforcements required to reach eachnode from the root, by accumulating security enforcements

along the path from root to that node. Note that in sys-tem services clearCallingIdentity() is frequentlyused to clear the original caller’s identity, or UID, andset caller identity to the system service temporarily. AsFig. 8 depicts, after certain operations, the caller’s identityis restored by calling restoreCallingIdentity(). Ifa method is called between clearCallingIdentity()and restoreCallingIdentity, all security checks aresuccessfully passed because it appears as being called bythe system service, which has elevated privileges. Thus, it isunnecessary for Kratos to perform any analysis between thetwo function calls.

Now we have annotated sub-call graphs for each serviceinterface. Next, we use pairwise comparisons starting fromtheir entry points to check if they ever invoke the samemethod, or converge on the same node. If such a convergencepoint exists for any two service interfaces, we believe theyoverlap in functionality and examine their paths that leadto the convergence point. Specifically, we compare securityenforcements along the two paths to see if they are consistent,i.e., one path has a security check while the other does not.

Reducing false positives. Not all methods are used to ac-cess system resources or perform sensitive operations. Ifwe use arbitrary convergence between call graphs to in-dicate they have similar functionality, there would be alarge number of false positives. For example, many meth-ods are frequently called, such as equal(), toString(),<init>(), <clinit>(), but they are not sensitive and donot reflect the caller’s functionality. To reduce the number offalse positives, we investigate service interface call graphs, aswell as the Android source, and design three heuristic rules.

We observed that sensitive, low-level methods reside withinthe service side and are not accessible to apps. The runtimedoes not load them into an app’s execution environment.Therefore, we can filter out methods that appear in an app’sruntime. To achieve this, we classify classes imported bysystem services into three categories: (1) classes only used bysystem services, (2) classes used by both services and apps,and (3) classes only used by apps. Methods from the last twocategories are believed to be insensitive and we discard them.

Second, we observe that many services havepaired “accessor” and “mutator” methods, whosefunctionality is obviously different. For example, inWindow Manager Service, getAppOrientation andsetAppOrientation are used to get and set theapp’s orientation, respectively. Similarly, there existother method pairs in which the two have oppositefunctionality, such as addGpsStatusListener andremoveGpsStatusListener, startBluetoothScoand stopBluetoothSco. If such methods are foundoverlapping, we are confident that it is a false positive.

Third, we prioritize service interface pairs by calculatingthe sub-call graph similarity score of each pair. We also grouptogether system services providing similar functionality, e.g.,the Telephony Service and the Telecom Service. Overlappingservice interfaces belong to the same group have higher priorityto be manually examined. The rationale behind this is thatif two services with no explicitly connection (e.g., the PowerManager Service and the SMS Service) are found overlapping,

7

Page 8: Kratos: Discovering Inconsistent Security Policy ...alfchen/roy_ndss16.pdf · Kratos: Discovering Inconsistent Security Policy Enforcement in the Android Framework Yuru Shao, Jason

WindowManagerService mService;...// AIDL methodpublic void closeSystemDialogs() { checkPermission();

clearCallingIdentity();

mService.closeSystemDialogs();

restoreCallingIdentity();}

...// AIDL method public void closeSystemDialogs() { doRealWork();}

Clear original caller's identity and set it to system

Restore original caller's identity

ActivityManagerService.java

WindowManagerService.java

Fig. 8. Activity Manager Service calls Window Manager Service to do the real work. Since both interfaces are accessible for apps, a third-partyapp without any permission can call WindowManagetService.closeSystemDialogs() to close system dialogs, bypassing security checks inActivityManagerService.closeSystemDialogs(). code has been simplified for brevity

it is highly likely a false positive.

IV. IMPLEMENTATION

We implement Kratos with around 15,000 lines of Java,Bash and Python. Based on the design described in Section III,in this section we elaborate our implementation choices ofKratos. To ensure efficiency and scalability, we make effort toparallelize the implementation.

Our implementation follows the logic shown in Fig. 7:(1) Preprocessing, (2) Call Graph Construction, (3) Call GraphAnnotation, and (4) Inconsistency Detection.

ODEX

Smali

DEX

AndroidSource Code

Stock Android

Translating

JavaClasses

Compiling

Fig. 9. Kratos can obtain Java class files from AOSP and customized Androidversions

A. Preprocessing

In the Preprocessing step, we obtain the necessary classfiles for the particular Android framework version. In the caseof analyzing AOSP, it is a matter of compiling the Androidoperating system from the source code and extracting the classfiles.

For a vendor specific version, it takes extra effort to obtainthe class files. Because we do not have access to the sourcecode of the customized framework, we must dump odex filesfrom the device image, and translate them into correspondingJava class files. Fig. 9 shows the three steps involved inthis process. We use baksmali [7] to convert odex into anintermediate format, smali. Then we employ smali [7] toassemble smali files into dex, and finally use dex2jar [8]

to get JAR files, i.e., Java classes. We notice that sinceAndroid 5.0 the Dalvik runtime has been replaced by theAndroid runtime (ART) [2], in which odex files are no longeravailable. To deal with that, Dextra [3] can be used to dumpdexs from ART’s oat files.

Once the class files are obtained, we utilize the Sootframework [40], a Java decompiler and analysis tool, to parseany given class and its member bodies in order to iden-tify which classes are app-accessible system services. Morespecifically, those services are identified by looking for invo-cations of publishBinderService and addService,two methods used for registering services to the globalservice manager. We exclude services registered by callingpublishLocalService, as they are only available forsystem use. That means they are not accessible for third-partyapps. We then distinguish app-accessible interfaces exposed bythese app-accessible system services. For AIDL methods welook for their AIDL definitions, either in aidl files or in apublic Java interface extending IInterface. Unprotectedbroadcast receivers can be identified by analyzing calls ofregisterReceiver and registerReceiverAsUser.If they do not have a broadcastPermission argument (orthe argument is null) and intent actions the broadcast receiverlistens to are not defined as protected-broadcast inthe framework’s AndroidManifest.xml, we consider thisreceiver as unprotected.

Once the identification of app-accessible system interfaceshas finished, we take one last important step. We build an artifi-cial single entry point for further analysis that uses Spark [28],a popular Java points-to analysis tool and call graph generator.It was designed to start at the program’s single entry point,look for method calls there, then take all found callees, lookat what callees call, and so on. This way, it builds a precisegraph of what method is potentially called and identifies themethods which are reachable over all [6]. While the Androidframework does have a static main() method in the SystemServer class, there is no guarantee that all methods will becalled from that point of origin, as that is only responsible forinstantiating system services. Thus, we must provide Spark asingle static entry point into the Android framework for eachclass analyzed.

We use method and class instrumentation data structuresprovided by Soot to dynamically build “wrapper” classes with

8

Page 9: Kratos: Discovering Inconsistent Security Policy ...alfchen/roy_ndss16.pdf · Kratos: Discovering Inconsistent Security Policy Enforcement in the Android Framework Yuru Shao, Jason

a static main method. These wrappers are a necessity to meetSpark’s requirement of static entry points for invoking methodcalls of a class. Kratos automatically builds the wrapper classesby inferring important attributes of service interfaces. Classaccess modifiers are one key piece of analysis. Once they areunderstood by Kratos, it decides how to build a wrapper. Inthe best case, the service is a public class; while in the worstcase, the service is a private inner class.

B. Call Graph Construction

In this phase we utilize Spark to generate a context-insensitive call graph that encompasses all app-accessibleservice interfaces. We use the dummy main method as thesingle entry point. For Spark to generate the call graph, it mustoperate on one thread; thus we are unable to parallelize thisphase. It is in this phase that Java virtual method resolutionoccurs, by leveraging “variable-type analysis” (VTA). We alsoenable the on-the-fly option, because it was reported that themost effective call graph construction method proceeds on-the-fly and builds the call graph at the same time as it computespoints-to set [30].

C. Inconsistency Detection

In order to discover inconsistencies within security en-forcements, we intelligently match two call graphs of differentservice interfaces in a pairwise fashion. Because this phase canrun, at worst, in O(n2) time, we use a set of heuristics in orderto reduce the total number of comparisons, which is outlined inSection III. Once two call graphs are paired, we look for a pointof convergence — a method whereby both paths will intersect.Once we find an intersection, we use backward analysis toidentify any other services that can reach the method. Thisallows Kratos to quickly identify additional services whichmay share that path in which security circumventions occur.

To prioritize the results for manual validation, we usefast belief propagation to measure node affinity, and thencalculate sub-call graph similarity score with the Matusitadistance. Denote the final affinity score matrix as S, we haveS = [I + ϵ2D − ϵA]−1 where I is the identity matrix, D isthe degree matrix, A is the adjacency matrix, and ϵ is a smallnumber which we take the value of 0.02. Matusita distanced is defined as d =

!"ni=1

"nj=1(

#S1,ij −

#S2,ij) where

S1,ij and S2,ij are entries of S for the subgraphs. And thesimilarity score sim = 1

1+d is then calculated.

V. RESULTS

In this section, we evaluate Kratos’ effectiveness, accu-racy, and efficiency by applying it to six different Androidframeworks. We also present vulnerabilities identified usingKratos and analyze some of them in detail. All our experimentsare conducted on a desktop machine with a 3.60GHz 8-coreIntel Core i7 CPU and 16GB memory, running 64-bit UbuntuLinux 14.04.

Codebases. We target both AOSP Android and customizedAndroid. Since the Android framework is evolving over time,in addition to inconsistencies within a particular Androidframework codebase, we also track inconsistencies acrossdifferent Android versions. Therefore, we choose four most

recent releases, i.e., Android 4.4, 5.0, 5.1, and 6.0. Vendorsand carriers often change existing or add new code to providea unique and differing experience. Previous work [43], [26]reported security threats brought by such customizations. Webelieve that they may also lead to more inconsistencies asdifferent parties are involved, and their engineers are likelyto have different understanding of the security policy. Specifi-cally, we analyze two customized Android frameworks, AT&THTC One and T-Mobile Samsung Galaxy Note 3, both basedon Android 4.4.2.

Table I summarizes the statistics of the six Android frame-work codebases in our evaluation. For the AOSP Android, thenumber of services increases dramatically from version 4.4 to5.0, then remains unchanged in 5.1 and M preview. However,as the second column shows, the number of AIDL methodsexposed by system services drops by 20 in M preview. It isobvious that Samsung and T-Mobile customize Android muchmore heavily than HTC and AT&T (mostly contributed bySamsung). Though both phones are based on the same versionof AOSP codebase, Galaxy Note 3 has 89 more system serviceswhile HTC One only has 9 more. Moreover, customization alsoincreases the number of service interfaces, as well as class files.

Tool Efficiency. We measure Kratos’s efficiency and sum-marize the results in Table II. The Preprocessing phase onlytakes a few minutes. Call Graph Construction and Call GraphAnnotation are very fast, each finishing within one minute.Even though Inconsistency Detection consumes the majorityof processing time, we can analyze a framework codebase inless than 20 minutes.

A. Tool Effectiveness

Table V summarizes our overall analysis and detectionresults on all six Android framework codebases. The first col-umn is the number of inconsistent security policy enforcementKratos discovered. To evaluate true positive (TP) and falsepositive (FP), we manually examine all cases of enforcementinconsistency. The numbers of true positives and false positivesare listed in column 2 and column 3, respectively. We alsomanually validate exploitable inconsistencies for each code-base, and show the results in the last column. We considerinconsistent enforcement cases which can be exploited by athird-party app as exploitable, as they are more likely to resultin real-world attacks.

For the four AOSP codebases, Kratos reports more incon-sistencies in newer versions. There are only 21 inconsistenciesin Android 4.4 framework. However, this number drasticallyincreases to 61 in the later version, Android 5.0. This is to beexpected, as shown in Table V, Android 5.0 introduces 19 moresystem services. More interestingly, many of the new systemservices seem to have similar functionality to existing ones.For example, the RTT (round trip time) Service introducedin Android 5.0 can be used to measure round trip time ofaccessible Wi-Fi access points nearby. Incidentally, the Wi-FiService also provides similar functionality. Another example isTelecom Service, whose functionality overlaps with TelephonyService. Meanwhile, the large number of system servicesadded by T-Mobile and Samsung undoubtedly introduce moreinconsistencies.

9

Page 10: Kratos: Discovering Inconsistent Security Policy ...alfchen/roy_ndss16.pdf · Kratos: Discovering Inconsistent Security Policy Enforcement in the Android Framework Yuru Shao, Jason

TABLE I. STATISTICS OF THE SIX CODEBASES IN OUR EVALUATION. WE ONLY CONSIDER SERVICES IMPLEMENTED IN JAVA.

Codebase # Services # Service Interfaces # Class Files# AIDL Methods # Broadcast ReceiversAndroid 4.4 70 1,010 26 14,901Android 5.0 89 1,483 28 33,110Android 5.1 89 1,510 31 33,433

Android M Preview 89 1,490 31 35,431AT&T HTC One (Android 4.4.2) 85 1,868 35 17,879T-Mobile Samsung Galaxy Note 3

(Android 4.4.2) 159 2,463 64 171,306

TABLE II. TIME CONSUMED IN EACH ANALYSIS STEP OF KRATOS (IN SECONDS)

Codebase Preprocessing CG Construction CG Annotation Inconsistency DetectionAndroid 4.4 95.4 23.4 8.6 470.3Android 5.0 137.1 25.0 10.53 496.4Android 5.1 209.0 22.2 14.6 445.9

Android M Preview 141.6 21.6 9.7 482.3AT&T HTC One (Android 4.4.2) 110.8 29.1 16.0 655.8T-Mobile Samsung Galaxy Note 3

(Android 4.4.2) 306.9 57.5 50.7 1273.7

TABLE III. OVERALL RESULTS OF KRATOS. THE NUMBERS OF EXPLOITABLE INCONSISTENCIES, TRUE POSITIVES AND FALSE POSITIVES ARECONCLUDED BY MANUAL ANALYSIS.

Codebase # Inconsistencies # TP # FP Precision # ExploitableAndroid 4.4 21 16 5 76.2% 8Android 5.0 61 50 11 82.0% 11Android 5.1 63 49 14 77.8% 10Android M 73 58 15 79.5% 8

AT&T HTC One (Android 4.4.2) 29 20 9 69.0% 8T-Mobile Samsung Galaxy Note 3

(Android 4.4.2) 128 102 26 79.7% 10

True positive and false positive. For all codebases exceptthe one from HTC One, Kratos can achieve more than 75%precision. We cannot measure false positive rate becausewe do not have other sources of data with ground truthof known inconsistencies. Therefore, it is not feasible forus to calculate the number of true negatives and false neg-atives. We further analyze false positive cases and try tounderstand why they occur. We find that most false positivesare caused by the three limitations of Kratos. First, twoservice interfaces are not equivalent in functionality, yet theyinvoke the same underlying sensitive method, which is invokedwith different arguments. Since Kratos uses path-insensitiveanalysis, it cannot discern the impact differing argumentshas on the execution path. For example, Account ManagerService has two public interfaces: getAccounts() andgetAccountsForPackage(). The former can list all ac-counts of any type registered on the device, while the latter re-turns the list of accounts that the calling packages is authorizedto use. They eventually call getAccountsAsUser() withdifferent arguments, and getAccountsForPackage()has one more security check — a UID check which ensuresthat the caller is an authorized user.

The second limitation is the inaccuracy of the overlappingservice interfaces reported by Kratos. As we have mentioned inSection III, the over-estimated call graph could introduce falsepositives. Spark utilizes point-to analysis, which makes everyeffort to resolve virtual method calls according to context.Nevertheless, it cannot resolve all virtual methods with 100%accuracy.

The third limitation also comes from service interfaceswith similar but not equivalent functionality. One mightbe more capable than the other one, and the service withmore capability is guarded by stricter security enforcement.

For example, deleteHost() and deleteAllHosts()from App Widget Service are able to delete host records.They both call deleteHostLocked(). The difference isdeleteHost() calls deleteHostLocked() only once,while deleteAllHosts() calls it multiple times in a loop.The latter appears to be more powerful, as it can delete allhost records while the former can only delete one record percall. Compared to deteleHost(), deleteAllHosts()checks a caller’s UID. Kratos is not able to recognize methodbody semantics in order to evaluate a service interface’scapability.

Not all inconsistencies are exploitable. Note that among alltrue inconsistency cases, only a small portion of them (18.3%)are exploitable by a third party. The reason is threefold. First,they may both require system-level permissions. Our attackmodel assumes that an attacker builds a third-party app andmanages to have it installed on a victim’s Android device.While it is possible for the methods to be invoked, system-levelpermissions are inaccessible by third-party apps. Two servicesin the “HTC One” code base provide telephony functionality,i.e., HtcTelephony Service and HtcTelephonyInternal Service.They both expose an interface setUserDataEnabled()for enabling and disabling cellular data connection, and bothinvoke Phone.setUserDataEanbled() to finish the re-quest. Kratos reports that permissions used in the enforcementare different. HtcTelephony only enforces APP_SHARED, butHtcTelephonyInternal enforces APP_SHARED together withCHANGE_PHONE_STATE. We cannot exploit this inconsis-tency, because APP_SHARED is a system-level permission.

The second reason that an identified inconsistencyis not exploitable stems from the difficulty to constructvalid arguments for calling a service interface withouta required permission, even though the interface has a

10

Page 11: Kratos: Discovering Inconsistent Security Policy ...alfchen/roy_ndss16.pdf · Kratos: Discovering Inconsistent Security Policy Enforcement in the Android Framework Yuru Shao, Jason

weaker security enforcement than another service interfaceproviding the same functionality. For instance, ConnectivityService exposes isActiveNetworkMetered()and Network Policy Management Service definesisNetworkMetered(NetworkState) to allowcallers to query if the active network is metered.Kratos reports that isActiveNetworkMetered()enforces a permission ACCESS_NETWORK_STATE,but isNetworkMetered(NetworkState) doesnot. This is a true inconsistency. However, to invokeisNetworkMetered(NetworkState), one must obtainor instantiate a NetworkState object, which requires theACCESS_NETWORK_STATE permission. In the end, thesame permission is required in order to successfully invokethese two interfaces.

Third, the existence of feature checking logics makes itdifficult to reach to particular methods. Some resources couldbe accessed only when a certain feature is satisfied. Sometimes,a security checking function is not directly called, and insteadan object (could either be a flag or instance of another class) isverified where the object itself will only be valid if a securitycheck is passed.

Characteristics of the vulnerabilities. Interestingly, we findmany vulnerabilities are discovered only when we analyzehidden interfaces. In fact, 11 of them are exploitable throughhidden interfaces that are not directly visible to apps. The-oretically, these hidden interfaces are not expected to beused by developers, but Android does not restrict apps toaccess them through Java reflection. This finding suggeststhat hidden interfaces are not carefully scrutinized. Perhapsdisabling reflection would be one way to reduce such attacksurface.

In addition, we find 3 vulnerabilities are discovered by ana-lyzing two different services which performed the same sensi-tive operation, which shows that functionalities are sometimesredundant across services. Besides, we find 4 vulnerabilitieswhere a system permission is bypassed, allowing a third-partyapp to perform operations that are absolutely disallowed byAndroid.

In summary, these results demonstrate that although humanefforts are indispensable, Kratos is effective at automaticallydetecting a variety of inconsistent security enforcement. Basedon the cases identified, Kratos is able to uncover previouslyunknown vulnerabilities.

B. Case Studies

By analyzing security enforcement inconsistencies reportedby Kratos, we have discovered 14 vulnerabilities, summarizedin Table IV. Items in Column 1 labeled with † indicatethe inconsistency occurs between two services. Permissionslabeled with ∗ are system permissions that cannot be usedby third-party apps. Specific UIDs that can be bypassed areparenthesized. N/A means the vulnerability only exists incustomized Android and does not affect other frameworks.

We have filed 8 security reports regarding these vulnera-bilities to the Android security team. All of the vulnerabilitieswe reported have been acknowledged and confirmed. Amongthem, the mDNS daemon vulnerability was originally classified

as a high severity vulnerability, but then rated as low severity.The ones in Wi-Fi Service and Power Manager Service hadbeen fixed before we reported it. Note that we are veryconservative about the results, which means those confirmedin code but have not been validated in real devices are notcounted.

In this section we select several vulnerabilities shown inTable IV and explain them in detail. Due to space constraints,we cannot provide code-level details, and refer to the reviewersto visit our anonymized result website http://tinyurl.com/kratos15 [4] for more information.

Starting/Terminating mDNS daemon (denial of service).The multicast Domain Name System (mDNS) provides theability to perform DNS-like operations on the local areanetwork in the absence of any conventional Unicast DNSserver [5]. Android starts an mDNS daemon mdnsd whenthe system boots up. This daemon is used and controlled bythe Network Service Discovery (NSD) service, which allowsan app to identify other devices on the local network thatsupport the services it requests [9]. It is useful for a varietyof peer-to-peer apps such as file sharing and multiplayergaming. NSD Service exposes an interface that is able tostart and terminate mdnsd. Considering the importance of themDNS daemon, that interface is protected by a system-levelpermission, CONNECTIVITY_INTERNAL, which cannot beacquired by third-party apps. Therefore, by design, all attemptsmade by third-party apps to start or terminate the mDNSdaemon is thwarted.

However, another interface exposed by the NSD Service,getMessenger(), could be used to achieve the exact samefunctionality. By calling getMessenger(), the caller ob-tains a reference of the Messenger object from NsdStateMa-chine that manages the communication with mdnsd, then cansend messages to it. Compared to the interface protected bythe CONNECTIVITY_INTERNAL permission, this interfaceonly checks the INTERNET permission, which is one of themost frequently requested permissions [42]. Considering thatthe INTERNET permission is so commonly used and low-privilege, apps that request it do not raise a user’s attention.NsdStateMachine distinguishes different types of incomingmessages by examining their what field. A malicious appwith only INTERNET permission can easily craft a message,set its what field to NsdManager.DISABLE, and send it toNsdStateMachine, to terminate the mDNS daemon. As a result,users can no longer use apps that rely on the NSD Service.

Ending phone calls (privilege escalation). BothTelephony Service and Telecom Service provide amethod endCall() that allows caller apps to rejectincoming phone calls and end ongoing phone calls.According to Android’s source code, their correspondingwrappers, TelephonyManager.endCall() andTelecomManager.endCall(), are annotated with@hide and @SystemApi, respectively. That means bothshould only be used by the system. In fact, TelecomService’s endCall() indeed enforces a system permission,MODIFY_PHONE_STATE, ensuring that only the system isable to use it. However, Telephony Service’s endCall()only checks the CALL_PHONE permission, which can beacquired by third-party apps. More interestingly, a componentof Telephony Service registers a broadcast receiver in which

11

Page 12: Kratos: Discovering Inconsistent Security Policy ...alfchen/roy_ndss16.pdf · Kratos: Discovering Inconsistent Security Policy Enforcement in the Android Framework Yuru Shao, Jason

TABLE IV. SUMMARY OF INCONSISTENT SECURITY ENFORCEMENT THAT CAN LEAD TO SECURITY POLICY VIOLATIONS.

Service Affected Framework Description SecurityImplication

Bypassed SecurityEnforcementAT&T

HTCT-MobileSamsung 4.4 5.0 5.1 M

Preview

SMS ✓ ✓ ✓ ✓ ✓ ✗Clear all SMS notificationsshowing in the status bar Privilege escalation Package Name (SMS)

Wi-Fi ✓ ✓ ✓ ✗ ✗ ✗Set up an HTTP proxy

that works in PAC mode Privilege escalation CONNECTIVITY INTERNAL*

NSD ✓ ✓ ✓ ✓ ✓ ✓Enable/Disable mDNS daemon

with only INTERNET permission DoS CONNECTIVITY INTERNAL*

RTT ✗ ✗ ✗ ✓ ✓ ✓ Crash the Android runtime Soft reboot ACCESS WIFI STATEWi-Fi Scanning ✗ ✗ ✗ ✓ ✓ ✓ Crash the Android runtime Soft reboot ACCESS WIFI STATE

GPS ✓ ✓ ✓ ✓ ✓ ✗(1) Send raw data to GPS’s native

interface (2) Crash the Android runtimePrivilege escalation,

Soft reboot ACCESS FINE LOCATION

GPS ✓ ✓ ✓ ✓ ✓ ✓Get GPS providers that

meet given criteria Privilege escalation ACCESS COARSE LOCATIONACCESS FINE LOCATION

Input MethodManagement ✓ ✓ ✓ ✓ ✓ ✓ Dismiss input method selection dialog DoS UID (SYSTEM)

Telephony/Telecom† ✗ ✗ ✗ ✓ ✓ ✓End phone calls

without any permissions Privilege escalation MODIFY PHONE STATE*CALL PHONE

Telecom ✗ ✗ ✗ ✓ ✓ ✓Get phone state

without any permissions Privilege escalation READ PHONE STATE

Activity Manager/Window Manager† ✓ ✓ ✓ ✓ ✓ ✓ Close system dialogs DoS UID (SYSTEM)

Power Manager/Persona Manager† ✓ ✓ ✓ ✓ ✗ ✗ Set maximum screen timeout Draining battery UID (ADMIN, SYSTEM)

Device Info N/A ✓ N/A N/A N/A N/A Save MMS to audit database Privilege escalation UID (PHONE)Phone Interface

Manager Ext N/A ✓ N/A N/A N/A N/A Send raw request to radiointerface layer (RIL) Not clear MODIFY PHONE STATE*

phone calls are ended when a specific broadcast comes in.Unfortunately, this broadcast receiver is not protected atall, making it possible for an app without any permissionsto end phone calls. This inconsistent security enforcementallows an attacker to create denial of service attacksagainst compromised devices. It could also be exploited byransomware to make victims’ phones unusable.

Dismissing all SMS notifications (privilege escalation).A MessagingNotification object instantiated in SMSService registers a broadcast receiver to listen to messagedeleting broadcast. If such broadcast is received, it clears allSMS notifications showing in the status bar. Kratos reportsthat this receiver is not protected by any permission, and ithas similar functionality to Notification Service. By design,notifications can only be dismissed by their owners or thesystem, enforced by package name check. However, we canbypass this enforcement by sending the broadcast to SMSService. This bug only affects Android 5.1 and earlier versionsbecause “the MMS app no longer ships with latest versions ofthe OS.”

Crashing the Android runtime (soft reboot). Wi-Fi ScanningService provides a way to scan the Wi-Fi universe aroundthe device. Similar functionality is provided by Wi-Fi Ser-vice as well. They both leverage the WifiNative classthat is responsible for communicating with the native bi-nary wpa_supplicant, from which Wi-Fi scanning resultscan be obtained. Kratos reports that Wi-Fi Service checksACCESS_WIFI_STATE permission, while Wi-Fi ScanningService has no permission enforcement. We attempt to exploitthis inconsistency to query Wi-Fi scanning reports withoutdeclaring any permissions. It turns out due to implementationissues of the Wi-Fi Scanning Service, it causes crash of theentire Android runtime.

We further analyze the source code and crash log.In fact, we could successfully trigger the invocation ofWifiNative.startScanNative. Since we have

to stop the scanning before reading the results, weattempt to call WifiNative.stopScanNative, inwhich a runtime exception is thrown out at line 65 ofart/runtime/check_jni.cc. The exception is nothandled, therefore the runtime crashes, causing a soft reboot.

Setting maximum screen timeout (draining battery).In T-Mobile’s Samsung Galaxy Note 3, Kratosuncovered two service interfaces with exactly the samename but different security enforcement for callingsetMaximumScreenOffTimeoutFromDeviceAdmin().One is exposed by Power Manager Service from the AOSPcodebase based on which customization was made; anotheris exposed by Persona Manager Service from customizedportion. These two methods implement the same functionalitybut their security enforcement is inconsistent. PowerManager Service does not apply any security checks on itssetMaximumScreenOffTimeoutFromDeviceAdmin(),however, Persona Manager Service checks the caller’s UID.

The name of the method implies that it should only be usedby the device administrator, but Kratos did not find any checks.We further analyze the AOSP source code and confirm that it isa real inconsistency in security enforcement. In the comments,the developer made it very clear that this method should onlybe called by a device administrator (as shown in left sideof Fig. 1). But surprisingly, they did not apply any securitychecks to secure it. By invoking Power Manager Service’ssetMaximumScreenOffTimeoutFromDeviceAdmin(),an app without the proper permissions can set the screentimeout to a very large value in order to drain the battery. Paststudies [45], [16], [35] have shown that display is a majorcontributor to the battery consumption of smartphone users.

In this case, the inconsistency occurs between two code-bases — the original AOSP code and customization code.This case also demonstrates that though customization is oftenblamed for introducing more security threats, it is also possiblethat customizations are more secure than AOSP.

12

Page 13: Kratos: Discovering Inconsistent Security Policy ...alfchen/roy_ndss16.pdf · Kratos: Discovering Inconsistent Security Policy Enforcement in the Android Framework Yuru Shao, Jason

Sending raw requests to RIL. We found two system servicesin the Samsung Galaxy Note 3 that provide very similartelephony-related functionality. These two services are im-plemented in two classes, PhoneInterfaceManager andPhoneInterfaceManagerExt. Kratos reports that theapp-accessible interface invokeOemRilRequestRaw()exposed by PhoneInterfaceManager and another interfacesendRequestRawToRIL() exposed by PhoneInterfaceM-anagerExt mirror in functionality. Specifically, they both in-voke Phone.invokeOemRilRequestRaw() to send rawrequests to radio link layer (RIL).

Nevertheless, their security enforcement is different.invokeOemRilRequestRaw() checks the CALL_PHONEpermission, while sendRequestRawToRIL() has no secu-rity checks. As a result, using sendRequestRawToRIL(),an attacker can send arbitrary data to RIL without requestingany permissions. Note that attackers can only control data, butcannot alter the request type. sendRequestRawToRIL()restricts request types to RIL_REQUEST_OEM_HOOK_RAW.We monitor all RIL requests sent by a test-phone and confirmthat this request type is used. We have not managed to craftmalicious data to take control of RIL or attack base stations,because of the difficulty involved in reverse engineering theprotocol. However, we believe this unprotected service inter-face can be exploited by sophisticated attackers who havemore knowledge of cellular networks, especially the use ofRIL_REQUEST_OEM_HOOK_RAW request.

Interestingly, our further analysis of AOSP Android 5.0source code reveals that invokeOemRilRequestRaw() isprotected by a system permission MODIFY_PHONE_STATE,which is higher-privileged than CALL_PHONE that this T-Mobile Samsung phone’s invokeOemRilRequestRaw()enforces. This implies that vendors/carries and Google engi-neers do have different understanding of how to protect certainsensitive operations.

VI. DISCUSSION AND LIMITATIONS

False negatives. Similar to previous static analysis work, ourapproach can miss security enforcement inconsistencies. First,Kratos is not able to deal with implicit control flow transitions,e.g., callbacks. To address this problem, we could implementsome principles found in EdgeMiner [15] and FlowDroid [11].Namely, their implicit control flow and context/flow/lifecycleanalysis principles, respectively. While this would help identifyanother security check present within the Android framework,it doesn’t completely solve our false negative problem.

Because we use heuristics to reduce computation time foridentifying security enforcement circumventions, there is thepotential that a heuristic may rule out a true positive. As withall heuristics, they come at a cost of introducing false negativesor false positives. This very tradeoff is one we work hard tobalance; keep the runtime fast and minimize the false positiveand false negatives. Moreover, vendors/carriers may introducenew means for enforcing their security policies besides thefour we have considered.

Kratos currently does not handle the native code (C/C++)that comprises the lower levels of Android and some smallportion of the service code base, leading to false negatives. Toaddress this, additional work is needed to build and analyze

a control flow graph at the native layer, which is part of ourfuture work.

Difficulty in verifying violations. Currently, Kratos is unableto automatically verify the presence of a circumvention. Todecide if a violation is exploitable, one needs to understandthe semantics of the code. In most cases, a review of the actualsource code is the only way to ascertain the semantics. Onemust know what operations are able to interact with untrustedspace and also design a feasible way to mount the attack. Thisis the most time consuming portion of Kratos.

Context-insensitive and path-insensitive analysis. Kratos de-pends on Spark to build a context-insensitive call graph, whichcould introduce false negatives or positives. It is understood,through work conducted by Lhotak and Hendren [31] , thata context-insensitive call graph may impact the call graphsaccuracy. However, Lhotak and Hendren go on to prove that theimprovements context-sensitivity provide to the accuracy areminimal. Through these findings, we justify our optimizationfor a context-insensitive call graph; the memory and com-putational overhead of a context-aware call graph analysisdoes not improve the accuracy enough relative to its costs.Path-insensitivity is not applicable here because we are notinterested in how branching affects a call chain. We are onlyinterested in security enforcement circumvention, which doesnot depend on branching. Thus, we are able to safely ignoreutilizing this analysis for our call graph.

Scalability. While we have made every effort to allow Kratosto be scalable at every facet, there is one specific place inwhich we cannot run a parallelized computation — our use ofSpark. Spark has significant limitations in scalability. Becauseof the reliance on Spark, the “Call Graph Construction” phaseis unable to be threaded. Even in spite of this limitation, theIV-B phase completes in minimal time (see results in Table II).Every other aspect of Kratos leverages threading in an effortto reduce run time.

Native System Interfaces. We also observe an interesting casewhere an app can get the MAC address of a network interfacecard (NIC) using three different ways, guarded by differentsecurity enforcement. The first approach is to call the Con-nectivity Service’s getLinkProperties(), which checksACCESS_NETWORK_STATE permission. Second, an app canrun the command line tool /system/bin/netcfg to obtaina list of available NICs and information, including MACaddresses. This requires the app owns INTERNET permission.However, the third approach, reading MAC address directlyfrom the file /sys/class/net/[nic]/address, doesnot require any permissions. This motivates our future im-provement of Kratos — to handle inconsistencies across dif-ferent layers of Android.

VII. RELATED WORK

Security policy violation detection and verification.Quite a few of program analysis and verification tools havebeen proposed to verify security properties or detect securityvulnerabilities caused by policy violation [13], [17], [20], [23],[38]. All of them, except AutoISES [38], require developersor users to provide code-level security policies. AutoISES [38]can automatically infer security specifications with the input

13

Page 14: Kratos: Discovering Inconsistent Security Policy ...alfchen/roy_ndss16.pdf · Kratos: Discovering Inconsistent Security Policy Enforcement in the Android Framework Yuru Shao, Jason

of a security check function list, and leverage inferred speci-fications to automatically detect security violations. Our toolalso supports security policy inference like AutoISES, freeingusers from providing specification manually. AutoISES workseffectively on Linux kernel and Xen, but compared to Kratos,its design may suffer from several limitations when appliedto code bases like Android. First, it assumes that securitychecks are placed just before accessing sensitive objects, whilein Android they are placed earlier. In our design, we solvethis by using function calls to represent sensitive operationsinstead of sensitive objects. Second, AutoISES needs a securitycheck function list as input, while in Android it is difficult toenumerate all possible ones due to the existence of differentsecurity check types. In contrast, in Kratos only security policytypes are needed as input. Last but not least, AutoISES cannothandle Android-specific features like conflated layers (Java andC/C++) and IPCs.

Android permission check circumvention. Felt et al. [21]propose the notion of permission re-delegation in the gener-alized contexts applicable for both web and smartphone apps.They identified vulnerabilities in Android applications that canbe exploited by malware to access privileged functionalitywithout having corresponding permissions. Wu et al. [43] alsostudy this problem but focus on vendor customized Android.Woodpecker [26] is a tool for systematically detecting capa-bility leaks in stock Android smartphones. Our work differsfrom them in two major aspects. First, we target Androidservices instead of applications. Second, we are detectingsecurity enforcement inconsistencies that can lead to directsecurity policy bypass without the need of another app (e.g.,a delegate).

Automated security policy enforcement. To date, a fewautomated solutions have been proposed to address inconsis-tencies in security policy enforcement. Ganapathy et al. [22]present a technique for automatic placement of authorizationhooks, and apply it to the Linux security modules (LSM)framework. Muthukumaran et al. [34] propose an automatedhook placement approach that is motivated by a novel observa-tion that the deliberate choices made by clients for objects fromserver collections and for processing those objects must allbe authorized. These solutions cannot be directly adopted byAndroid for distributing security enforcement as they requireperfect knowledge about the security policies that need to beenforced. In Android, this is unlikely the case as (1) Androidhas multiple layers and its policies are implemented in differentlayers using different code, e.g., Java and C/C++, and (2)multiple parties (e.g., vendors, carriers) are involved in thecustomization and each of them may have their own policies.Although automatic hook placement is promising and weshould encourage automatic hook placement, it is still highlydesirable to seek solutions like Kratos that can automaticallydetect security vulnerabilities from existing or legacy sourcecode.

Static analysis tools on Android. There has been signif-icant work in using static analysis techniques combined withcall graphs to map the Android framework, understand thepermission specification, understand how data is disseminatedwithin the Android framework, and enable the functionalityof gleaning information from avenues that are unassuming.PScout [12] uses static analysis tools to enumerate all per-

mission checks within the Android framework. They are ableto map all permission usages to their appropriate methodsand understand the utility of permission usage within theframework. While PScout identifies permissions, they don’tlook at paths through the framework which would allowthe invocation of the permissions they discover. Static taintanalysis tools such as FlowDroid [11], AndroidLeaks [24],DroidSafe [25], and Amandroid [41] work to understandhow, why, where, and what data travels through the Androidframework as a user uses an app in order to perform privacyleakage detection. They track this data from source to sink andwatch how and what uses the data they wish to observe. Theiruse of static analysis techniques and source/sink flow controlis an important concept in our work, but in comparison, weidentify how and where security enforcement occurs insteadof watching data flow. In our case, our sources are specificentry points in the AIDL services provided by Android andour sinks are the convergence point of two APIs.

VIII. CONCLUSION

In this work, we propose Kratos, a static analysis tool forsystematic discovering inconsistencies in security enforcementwhich can lead to security enforcement circumvention vulner-abilities within the Android framework. We have demonstratedthe effectiveness of our approach by applying our tool to fourversions of Android AOSP frameworks as well as two cus-tomized Android versions, conservatively uncovering at least14 highly-exploitable vulnerabilities that can lead to securityand privacy breaches such as crashing the entire Androidruntime, arbitrarily ending phone calls, and setting up a HTTPproxy with no permissions or only low-privileged permis-sions. Interestingly, many of these identified inconsistencies arecaused by the use of hidden interfaces of system services. Ourfindings suggest that some potentially promising directions toproactively prevent such security enforcement inconsistenciesinclude reducing service interfaces and restricting the use ofJava reflection (for accessing hidden interfaces).

We have shown that security enforcement circumventionis a systemic problem in Android. Our work demonstratesthe benefit of an automatic tool to systematically discoveranomalies for security enforcement in large codebases suchas Android. We expect Kratos to be useful for both Androiddevelopers as well as vendors who offer customized Androidcodebases.

ACKNOWLEDGMENTS

The authors would like to thank the anonymous reviewersfor their helpful feedback, as well as Shichang Xu and AshkanNikravesh for their proofreading efforts. This material is basedupon work supported in part by the National Science Foun-dation under grants CNS-1345226, CNS-1318306 and CNS-1526455, and by the Office of Naval Research under grantN00014-14-1-0440. Any opinions, findings, and conclusionsor recommendations expressed in this material are those of theauthors and do not necessarily reflect the views of the NationalScience Foundation and the Office of Naval Research.

REFERENCES

[1] Android Binder. https://www.nds.rub.de/media/attachments/files/2012/03/binder.pdf.

14

Page 15: Kratos: Discovering Inconsistent Security Policy ...alfchen/roy_ndss16.pdf · Kratos: Discovering Inconsistent Security Policy Enforcement in the Android Framework Yuru Shao, Jason

[2] ART and Dalvik. https://source.android.com/devices/tech/dalvik/.[3] Dextra - A tool for DEX and OAT dumping, decompilation. http://

newandroidbook.com/tools/dextra.html.[4] Kratos Results Website. http://tinyurl.com/kratos15.[5] Multicast DNS. https://tools.ietf.org/html/rfc6762.[6] Problem in Making Call Flow Graph from Class or Java files. https:

//mailman.cs.mcgill.ca/pipermail/soot-list/2014-May/006815.html.[7] Smali An assembler/disassembler for Android’s dex format. https://

code.google.com/p/smali/.[8] Tools to work with android .dex and java .class files. https://github.

com/pxb1988/dex2jar.[9] Using Network Service Discovery. http://developer.android.com/

training/connect-devices-wirelessly/nsd.html.[10] Vulnerability summary CVE-2006-1856. http://nvd.nist.gov/nvd.cfm?

cvename=CVE-2006-1856.[11] S. Arzt, S. Rasthofer, C. Fritz, E. Bodden, A. Bartel, J. Klein, Y. Le

Traon, D. Octeau, and P. McDaniel. Flowdroid: Precise context, flow,field, object-sensitive and lifecycle-aware taint analysis for androidapps. In Proc. of ACM PLDI, 2014.

[12] K. W. Y. Au, Y. F. Zhou, Z. Huang, and D. Lie. Pscout: analyzing theandroid permission specification. In Proc. of ACM CCS, 2012.

[13] T. Ball and S. K. Rajamani. The SLAM project: debugging systemsoftware via static analysis. In Proc. of ACM POPL, 2002.

[14] D. Barrera, H. G. Kayacik, P. C. van Oorschot, and A. Somayaji. Amethodology for empirical analysis of permission-based security modelsand its application to android. In Proc. of ACM CCS, 2010.

[15] Y. Cao, Y. Fratantonio, A. Bianchi, M. Egele, C. Kruegel, G. Vigna, andY. Chen. EdgeMiner: Automatically Detecting Implicit Control FlowTransitions through the Android Framework. In Proc. of ISOC NDSS,2015.

[16] A. Carroll and G. Heiser. An analysis of power consumption in asmartphone. In Proc. USENIX ATC, 2010.

[17] H. Chen and D. Wagner. MOPS: an infrastructure for examiningsecurity properties of software. In Proc. of ACM CCS, 2002.

[18] Q. A. Chen, Z. Qian, and Z. M. Mao. Peeking into your app withoutactually seeing it: Ui state inference and novel android attacks. In Proc.of USENIX Security, 2014.

[19] E. Chin, A. P. Felt, K. Greenwood, and D. Wagner. Analyzing inter-application communication in Android. In Proc. of ACM MobiSys,2011.

[20] A. Edwards, T. Jaeger, and X. Zhang. Runtime verification of autho-rization hook placement for the Linux security modules framework. InProc. of ACM CCS, 2002.

[21] A. P. Felt, H. J. Wang, A. Moshchuk, S. Hanna, and E. Chin. PermissionRe-Delegation: Attacks and Defenses. In Proc. of USENIX Security,2011.

[22] V. Ganapathy, T. Jaeger, and S. Jha. Automatic placement of authoriza-tion hooks in the Linux security modules framework. In Proc. of ACMCCS, 2005.

[23] V. Ganapathy, S. Jha, D. Chandler, D. Melski, and D. Vitek. Bufferoverrun detection using linear programming and static analysis. In Proc.of ACM CCS, 2003.

[24] C. Gibler, J. Crussell, J. Erickson, and H. Chen. AndroidLeaks: Au-tomatically Detecting Potential Privacy Leaks in Android Applicationson a Large Scale. In Proc. of TRUST, 2012.

[25] M. I. Gordon, D. Kim, J. Perkins, L. Gilham, N. Nguyen, and M. Rinard.

Information-flow Analysis of Android Applications in DroidSafe. InProc. of ISOC NDSS, 2015.

[26] M. C. Grace, Y. Zhou, Z. Wang, and X. Jiang. Systematic Detectionof Capability Leaks in Stock Android Smartphones. In Proc. of ISOCNDSS, 2012.

[27] D. Grove, G. DeFouw, J. Dean, and C. Chambers. Call graphconstruction in object-oriented languages. In Proc. of ACM OOPSLA,1997.

[28] L. Hendren. Scaling Java points-to analysis using Spark. In Proc. ofCompiler Construction, 12th International Conference, volume 2622 ofLNCS, 2003.

[29] S. Jana and V. Shmatikov. Memento: Learning secrets from processfootprints. In IEEE Symposium on Security and Privacy, 2012.

[30] P. Lam, E. Bodden, O. Lhotak, and L. Hendren. The Soot frameworkfor Java program analysis: a retrospective. In Cetus Users and CompilerInfastructure Workshop (CETUS 2011), 2011.

[31] O. Lhotak and L. Hendren. Context-sensitive points-to analysis: is itworth it? In Compiler Construction, pages 47–64. Springer, 2006.

[32] P. Loscocco. Integrating flexible support for security policies into theLinux operating system. In Proc. of the USENIX ATC, 2001.

[33] Y. Michalevsky, D. Boneh, and G. Nakibly. Gyrophone: Recognizingspeech from gyroscope signals. In USENIX Security Symposium, 2014.

[34] D. Muthukumaran, T. Jaeger, and V. Ganapathy. Leveraging ”choice” toautomate authorization hook placement. In Proc. of ACM CCS, 2012.

[35] A. Shye, B. Scholbrock, and G. Memik. Into the wild: studying real useractivity patterns to guide power optimizations for mobile architectures.In Proc. IEEE/ACM MICRO, 2009.

[36] K. Singh, A. Moshchuk, H. J. Wang, and W. Lee. On the incoherenciesin web browser access control policies. In Proc. of IEEE Symposiumon Security and Privacy, 2010.

[37] S. Smalley, C. Vance, and W. Salamon. Implementing SELinux as aLinux security module. NAI Labs Report, 1(43):139, 2001.

[38] L. Tan, X. Zhang, X. Ma, W. Xiong, and Y. Zhou. AutoISES:Automatically Inferring Security Specification and Detecting Violations.In Proc. of USENIX Security, 2008.

[39] A. V. Aho, R. Sethi, and J. D. Ullman. Compilers: Principles,Techniques, And Tools (2nd Edition). Addison Wesley, 2006.

[40] R. Vallee-Rai, P. Co, E. Gagnon, L. Hendren, P. Lam, and V. Sundare-san. Soot - a Java bytecode optimization framework. In Proceedingsof the 1999 conference of the Centre for Advanced Studies on Collab-orative research, page 13. IBM Press, 1999.

[41] F. Wei, S. Roy, X. Ou, et al. Amandroid: A precise and general inter-component data flow analysis framework for security vetting of androidapps. In Proc. of ACM CCS, 2014.

[42] P. Wijesekera, A. Baokar, A. Hosseini, S. Egelman, D. Wagner, andK. Beznosov. Android Permissions Remystified: A Field Study onContextual Integrity. In Proc. of USENIX Security, 2015.

[43] L. Wu, M. Grace, Y. Zhou, C. Wu, and X. Jiang. The impact of vendorcustomizations on android security. In Proc. of ACM CCS, 2013.

[44] Z. Xu, K. Bai, and S. Zhu. Taplogger: Inferring user inputs onsmartphone touchscreens using on-board motion sensors. In Proc. ofACM WiSec, 2012.

[45] L. Zhang, B. Tiwana, R. Dick, and Z. M. Mao. Accurate OnlinePower Estimation and Automatic Battery Behavior Based Power ModelGeneration for Smartphones. In Proc. of ACM CODES+ISSS, 2010.

[46] X. Zhou, Y. Lee, N. Zhang, M. Naveed, and X. Wang. The peril offragmentation: Security hazards in android device driver customizations.In Proc. of IEEE Symposium on Security and Privacy, 2014.

15