Google Play Store on Android Emulator

31 Aug

Most of you must have noticed that the Google Play Store is not available in the Android Emulator. But having Play store on the emulator would be very handy when you want to access different applications and test them. So here are the steps to add Google Play Store to your android emulator.

  1. Download the 3 files  – GoogleLoginService.apk, GoogleServicesFramework.apk and Vending.apk.
  2. Launch your emulator.
  3. Remount the adb.
  4. Change the permission of file /system/app to read, write and execute (777).
  5. Push the files GoogleLoginService.apk, GoogleServicesFramework.apk and Vending.apk to /system/app location.
  6. Remove the directory /system/app/SdkSetup.*


If the above steps are properly done, play store will appear on your emulator. Give your Google account credentials to sign in and then it would ask about Google +, Back-up and restore options. After that it would show the below screen and click continue and you are done! Here is a screenshot for your reference that play store works on emulator.


With this you are done! Now you can download and run any application directly on the emulator. PlayWorking




Posted by rohit


Mobile Security Basic Challenges

21 Jul

Data stored on the device is worth more than the device


The above quote might well apply to desktops and laptops as well. But it’s highly probable that your mobile device might be used by someone or lost, compared to your laptop/desktop. This fact changes the entire scenario. With the advent of mobile phones and smart phones, the game has enormously changed in the last few years with respect to the ease with which tasks are accomplished. This article focuses on various security related aspects which are involved with increased use of mobiles. Before jumping into the security concerns here is a small introduction about how the mobile technology has slowly taken over the whole world.

The first hand-held mobile device was demonstrated by two Motorola employees in 1973. After 10 years i.e. in 1983, the first mobile was commercially made available. From 1990 to early 2000′s, mobile phones spread rapidly and people used it mainly for the purpose of communication. In the last 10 years, with the rapid increase in internet usage, mobiles started accommodating the features of personal computers and finally took a new shape with the introduction of ‘smart phones’. Today mobiles have penetrated into each and every corner of this world, serving variety of tasks including mobile applications, GPS navigation, storage, entertainment etc. In this article we will mainly focus on mobile applications and their security concerns.

Mobile applications:

Mobile phone applications extend the functionality of mobile phones.  Everything is readily available and the tasks which were previously accomplished in a desktop world are now available on mobile just with a single click. People now use mobile applications to assist them in several day to day activities and enterprises are in a mad rush to develop the mobile apps to reach out to the users in a better way.

What is a mobile app anyway?

Mobile app is a software application developed to run on mobiles. Each mobile operating system has a corresponding distribution platform from where these mobile apps can be downloaded. For example, Android app can be downloaded from Google Play and iPhone apps can be downloaded from Apple App Store.  So an individual or a company can develop a mobile application and upload it to the distribution platform and advertise it so that users can download and use the same. The general demand and the ease of development of these mobile apps have resulted in their enormous growth. So these days we have a mobile app for everything – for example mobile banking, online shopping, ticket purchases, games etc. The real question is how secure are these mobile apps which deal with sensitive information. So let’s have a look at general mobile security related issues which are common to all the platforms.

Mobile Security:

Mobile security is increasingly playing a crucial role as more sensitive and personal information is now stored in the mobile phones. Security is now considered as crucial and central aspect these days during the unveiling function of any Smartphone. Moreover with the corporate world embracing the mobiles in a big way the focus is very much on the security of these devices. Attacks which are seen on PC’s are now slowly making their way on to the mobiles. At a higher level mobile related attacks can be classified into below categories:

Attacks based on OS – Exploiting the loopholes present at OS level. So the concerned vendor has to release a patch to fix the issue.

Attacks based on Mobile apps – Exploiting the security holes present in mobile application which is a result of poor coding/development.

Attacks based on Communication networks – Attacks on GSM, Wi-Fi, Bluetooth etc.

Malware related attacks – Malware attacks on mobiles have been rising continuously. A successful attack can steal the photos on your mobile, hijack the camera click, hack the emails, and delete the files on the mobile.

Let’s now move on and talk a little bit more about the current issues related to mobile security. The following is a list of main issues in the field of mobile security. Please note that this is not the complete list and not in any particular order. Let’s have brief look into the security issues which revolve around the mobile devices currently.

Physical Security:

Physical security is one of the biggest challenges to the designers of mobile phones and their applications. Mobile phones are lost, stolen and borrowed (many times by others to make a call or view the photos). When a mobile device is lost, the real concern is not about the cost of the mobile but the amount of sensitive data that is present on that mobile. Imagine the personal phone which is provided by your employer for enterprise activities falls into the hands of wrong persons and he tweaks with the data present in it. Imagine a situation where your neighbor asks your mobile for a quick call and then downloads a malware on to that phone (by the way it just takes a few seconds to do that). These issues are rather less when you are dealing with a desktop world because it is unusual that you lose your desktop machine. So the bottom line is mobile applications & systems are to be designed assuming that untrusted parties would be granted access to the phone.

No such thing as ‘logging’ into mobile:

In a desktop world, each user supplies his username and password and logs into the system where he gets access to his environment. So each user has a different environment and thus the privileges and data that each user has are separated. This ensures that one account doesn’t have access to the data of other account. But this concept is not valid in a mobile world as there is nothing like logging into a mobile for each user. So sharing and accessing of data between applications is a big concern.

Secure storage of data on the phone:

In addition to the sensitive files present on your mobile (photos, contacts, documents etc.), mobile applications also store sensitive information like authentication tokens, password related files etc. It’s very important that these files are to be protected. One way is by storing them securely on the mobile so that they are not accessible or usable. For instance password files must be stored in encrypted fashion so that even after accessing those files they are of not much use.

Mobile Browsing Environment:

In a mobile browser, it is not possible to see the entire url or sometimes see any url at all. This paves the way for hackers to unleash the phishing related attacks. So the display space on a mobile device increases the possibility of phishing attacks by manifold. The fact that people are more inclined to follow links on mobile blindly adds to this problem. So in this mobile browsing environment it’s an impossible task to expect a normal user to verify every link before following it.

Isolating the applications:

The range of mobile applications that we install today are diverse – social applications to connect to family and friends, enterprise applications to manage your work, banking applications to transfer funds, gaming applications for entertainment and many more. So it’s very important that a social networking app does not gain access to your corporate app or a gaming app does not gain access to the banking app. In short, application isolation is crucial. This would depend on the factors like OS permissions in different platforms and how these permissions are granted. Exploiting the existing mechanisms to gain unauthorised access is one area where hackers are actively targeting.

Update Process:

Operating systems require patches/updates to resolve any security issues that are discovered. OS like Windows look continuously for updates and install them. But when it comes to mobile OS the patching process is not as simple as that. When a bug is reported in a particular OS, the OS vendor comes with a patch. He then publishes this information to all the carriers (like AT&T, Sprint, and Airtel etc.). Now these carriers will not be proactive in installing these updates because there is every chance that during patching processes other applications might break down. Hence if these carriers find such cases with the patching, they hold it on for some time without applying the patch/update immediately.

Proper Authentication:

Authentication process is very important in mobile phones because as explained earlier it just a matter of seconds before someone asks your phone and does something malicious and you have no idea about it. In the cases where a company offers extranet access to its corporate network through mobiles, there should be a means of Multifactor authentication because if that mobile falls into the hands of wrong guys it would expose the internal network of the company. Multifactor authentication needs to be implemented and improved in order to solve many issues.

Poor coding of mobile apps:

Poor coding or development practises of the developers could lead to severe consequences. For example: hard coding of sensitive data like passwords, transmission of information in unencrypted channel, weak server side controls, improper session handling etc. Many of the vulnerabilities that apply to web will apply to mobile applications as well.

Bluetooth & other Attacks:

Bluetooth and other drivers pose as a security threat to the overall security posture of the mobiles. We have seen in the past about the vulnerabilities reported on Bluetooth and other third party drivers. Since these have system access, by exploiting a critical vulnerability an attacker might even get access to everything on a mobile. So even if the underlying operating system has excellent built in mechanisms which does not easily grant system access, these vulnerable third party drivers would be a set back at any time.

Malware Attacks:

Many surveys point out that malware attacks on mobile phones is on the rise. If you are someone who browses through tech news every now and then you must have seen some news about android phones getting infected by malware in a big way. Malware is something which harms the system in which in resides. With new computing environment new class of threats in new forms arise. It is very important that these issues are addressed proactively leveraging from our experiences of 90’s. Reports have also been published which forecast the situation to be worse in the coming year and some quote 2013 will be the ‘year of mobile malware!’.

Jail breaking the phones:

Many users jailbreak the phone in order to run applications for free or to run applications which are not authorized by the vendor. Jail breaking a phone would remove the restrictions imposed on a device by its vendor. Hence jailbroken devices are more susceptible to computer viruses and malware. Downloading the apps from an unauthorised third party store would only put your mobile at risk.

New features like NFC pose a serious threat:

NFC – Near Field Communication is a technology that allows you to beam the content to nearby devices and lets you use your mobile as a wallet to purchase items. It has been demonstrated in Black hat conference that by brushing a tag with an embedded NFC chip over an android phone, it is possible to take over the control of the phone. So with increase in technology, you will need to address more complex attack scenarios. In future, many more advanced technologies like these are expected to come and they bring a whole lot of new issues to address.

User awareness:

User awareness is major factor in controlling many of the attacks and when it comes to mobiles it’s even more important. There are many things from the user end which he should be careful about – Having passcode for the device, look out for the permissions granted to application. A gaming application may not need access to dialling), not following the links sent by unknown persons.

As the time progresses, the industry has more challenges to face and answer. For instance new ideas pose a security threat like BYOD – Bring Your Own Device where employees bring their personally owned mobiles devices to their work place. Since there are huge number of devices out there, each having its own security issues, it’s a huge task for any organisation to guarantee corporate equivalent of privacy on these devices. These are some of the basic issues that are involved in current mobile security. If anyone of you has more points to make, I sincerely request you to comment and share with the community.


Posted by rohit


Penetration testing of iPhone Applications – Part 5

26 Jun

In the First part of the article, we have discussed about the iPhone application traffic analysis. Second part, Third part and Fourth part of the article covered in-depth analysis of insecure data storage locations on the iPhone. In this part we will take a look at runtime analysis of iOS applications. Runtime analysis allows an attacker to manipulate the application’s behaviour at runtime to bypass the security locks and access the sensitive information from memory. Before getting into runtime analysis first we will take a look at the iOS application architecture and its runtime protection features.

iOS Application Architecture:

iOS application is a zip archive with .ipa file extension. The zip file contains the executable binary and the iTunesArtwork which is used by the iTunes to manage the application. Typical structure of an iOS application is shown in the image below.

ios application arcitecture

The .app folder within the Payload directory contains the application binary, all the resources of the application like images & audio, provisioning profile that specifies application permissions and code signature.

iOS application binary is ARM compiled and uses Mach-O (mach object) file format. Mach-O format consists of 3 main regions – header, load commands and segments/sections. The picture below illustrates the Mach-O file basic structure.

mach-o file format

Mach-O structure of an iOS application can be viewed using otool on a jailbroken device. Otool is available in Darwin CC Tools package on Cydia.

It identifies the Mach-O file and contains basic file type information like target architecture and flags that affect the interpretation of rest of the file. To view the Mach-O header of an iOS application connect the iPhone over SSH and execute the below command.

otool –h ApplicationBinary

Below is the Mach-O header of Facebook iOS application.

ios app header

cputype and subtype values in the Mach-O header indicates the application’s target architecture. The above image shows that the Facebook application is built for ARM7 processor.

ARM7s (iPhone 5) = cputype 12/ subtype 11
ARM7 (iPhone 4 & 4S) = cputype 12/ subtype 9
ARM6 (iPhone 3GS) = cputype 12/ subtype 6

Applications that are built for multiple architectures contain more than one Mach-O file. These binaries are called fat binaries or universal binaries. To view the Mach-O header of a fat binary, run the below command on SSH terminal.

otool –arch all -h ApplicationBinary

fat binary header

The above image shows that CardInfo application is compiled for ARM7 and ARM7s processors.

Load commands:
Load commands specify the layout and linkage characteristics of the file. It includes initial layout of the file in virtual memory, location of symbol table, execution state of main thread of the program and shared library details. Load commands (LC_ENCRYPTION_INFO) also define whether the application binary is encrypted or not. To view the load commands of an application, run the below command on SSH terminal.

otool –Vl ApplicationBinary

Mach-O file contains the actual data in one or more segments. Each segment contains zero or more sections. Each section of a segment contains code or data of some particular type. The exact number and layout of segments and sections is specified by the load commands. 

iOS Application Runtime Protection Features:

The iOS platform provides a lot of runtime security features like ASLR, stack smashing protection and ARC. Understanding the runtime protection features is important for reversing & analyzing iOS applications.

Address Space Layout Randomization:

ASLR is an important exploit mitigation technique introduced in iOS 4.3. ASLR makes the remote exploitation of memory corruption vulnerabilities significantly more difficult by randomizing the application objects location in the memory. By default iOS applications uses limited ASLR and only randomizes part of the objects in the memory. In order to take full advantage of the ASLR the application has to compile with -fPIE -pie flag (“Generate Position-Dependent Code” build option in Xcode). In the latest version of the XCode this flag is automatically checked by default. The image below compares the different memory sections for partial and full ASLR applications.

ios partial vs full aslr

To find out whether the application is compiled with PIE flag or not, connect the iPhone over SSH and execute the below command.

otool –Vh ApplicaitonBinary

 ios PIE enabled binary

The above image shows PIE at the end of the output. It indicates that the Facebook application is compiled with PIE flag.

Stack Smashing Protection:

Stack smashing protection is an exploit mitigation technique that protects against stack overflow attacks by placing a random value known as stack canary before local variables on stack. The stack canary is checked upon return of the function. Incase of an overflow the canary is corrupted, and the application is able to detect and protect against the overflow. In order to take advantage of the stack smashing protection the application has to compile with –fstack-protector-all flag.

iOS applications which are using the stack canaries will contain _stack_chk_fail and _stack_chk_guard symbols in the binary. To find out whether the application is protected with stack smashing protection or not, connect the iPhone over SSH and execute the below command.

otool –I –v ApplicationBinary | grep stack

iOS app stack smashing protectionResult shown in the above image indicates that the Facebook application is using the stack smashing protection.

Automatic Reference Counting:

ARC is another exploit mitigation technique introduced in iOS 5. It protects the applications from memory corruption vulnerabilities by moving the responsibility of memory management from the developer to the compiler. ARC can be enabled in an application within XCode by setting the compiler option “Objective-C Automatic Reference Counting” to “yes”. By default it is marked as “yes”.

iOS applications with ARC enabled will contain _objc_release symbols in the binary. To find out whether the application is using ARC or not, execute the below command on SSH terminal.

otool –I –v ApplicationBinary | grep _objc_release

iOS - ARC enabled binary

Result shown in the above image indicates that the Facebook application is compiled with ARC flag.

Runtime protection features add an additional layer of security to the application. So during a pentest it’s always a best practice to recommend the application to implement the runtime protection features.

Reversing iOS Applications:

Objective-C is the primary language used to develop native iOS applications. Objective-C is a dynamic language based on the principles of message passing. As it is a dynamic language, all the classes, methods and any other components are stored in the binary itself. This information can be extracted using the class-dump-z tool written by kennytm.

class-dump-z setup:

1. On a JailBroken iPhone, install wget and unzip from Cydia.
2. Connect to the iPhone over ssh and run the below commands.

wget -U Mozilla/5.0
mv class-dump-z /usr/bin

class dump z setup

3. To dump the class information from an iOS application navigate to the application’s .app folder and run the below command.

class-dump-z ApplicationBinary

Below image shows the class dump of Gmail iOS application. The class dump does not reveal any useful data as the Gmail binary is encrypted. Applications downloaded from the AppStore are encrypted using FairPlay DRM to protect the piracy.

class-dump-z encrypted iOS app

To find out whether the application is encrypted or not, run the below command on the SSH terminal.

otool –l ApplicationBinary | grep crypt

iOS app encryption

cryptid 1 indicates that the application is encrypted. For unencrypted applications cryptid value is 0.

So in case of reversing iOS applications often the first step includes removing the AppStore encryption. Removing this encryption allows an attacker to get a greater understanding of how the application binary works, the internal class structure and to get the binary in a suitable state for reverse engineering. The applications which are in-house distributed and self signed are not encrypted.

Decrypting iOS applications:

When an iOS application is launched, the loader decrypts it and loads it into memory.  So a pretty well established process exists to take advantage of this process and remove the FairPlay copy protection of an iOS application. iOS application decryption process includes the below steps-

  1. Finding the starting offset and the size of the encrypted data in the application binary.
  2. Finding the memory loading address of the application (changes every time if the app is compiled with PIE).
  3. Dumping the decrypted portion of the application from memory using a debugger (ex: gdb).
  4. Overwriting the applications encrypted area with the dumped binary data.
  5. Changing the cryptid value to 0.

The complete decryption process has been automated by Cydia applications namely Clutch and Rasticrac.

Decrypting the Gmail iOS applications with Clutch:

1. On a JailBroken iPhone, go to Cydia and add the repo by navigating to Manage->Sources.
Download ClutchPatched, ZIP and IPA Installer from Cydia.
Connect to the iPhone over SSH and type the ‘Clutch’ command. It lists out all the applications installed on the iPhone.


4. Supplying the application name to the Clutch will decrypt it and stores the decrypted ipa file under /var/root/Documents/Cracked/ folder. The below image shows that Clutch cracked the Gmail application and stored the decrypted file as /var/root/Documents/Cracked/Gmail-v2.2.0.8921.ipa.

decyrpting ios app with clutch

5. The cracked ipa file can be installed on the iPhone directly from SSH using the below command.

installipa –c [iPAPath]

install ipa from ssh

The below image shows the class dump of the decrypted Gmail application.

class-dump-z on decyrpted ios app

A full class dump of a decrypted application maps to the classes, methods and provides an insight into what’s going on inside an application. Once the class dump is obtained, we can look into it for interesting classes, methods, properties and perform a runtime analysis.

Runtime Analysis With Cycript:

Runtime analysis involves reversing and analyzing the application work flow to bypass security locks, performing authentication bypass attacks, access sensitive information from memory, breaking logical checks and accessing restricted areas of the application. As Objective C is a reflective language, it allows to modification of its own behaviour at runtime. On the iPhone, iOS application runtime can be modified easily using the CyCript. Cycript is available in Cydia packages.

Cycript is a programming language designed to blend the barrier between Objetive-C and Javascript. Cycript allows hooking into a process, thus giving access to all of the classes and instance variables & methods within the application.

Before getting into the runtime analysis, it is necessary to understand the execution flow of an iOS application.

ios app execution flow

Objective C is a superset of C, so its execution also begins with main() function. When a user touches the application icon on the springboard, it calls main() function. Main() function in turn invokes UIApplicationMain method. UIApplicationMain instantiates the UIApplication object, displays the GUI (windows, views), creates the application delegate and set up the events cycle. Application delegate monitors the high level actions/events in the application. With Cycript we can connect to the running process and get access to the UIApplication object. UIApplication is a singleton object that represents the application and acts as a central control. So gaining access to the UIApplication object in turn gives access to the application internals.

The power of the cycript is demonstrated in below examples. For demonstration, I’ve used an older version of photo vault application. Before hooking into the application process with cycript first grab the class dump of the application using class-dump-z.

Accessing the instance variables with Cycript:

The photo vault application keeps the private photos securely by protecting with a password. When we launch the photo vault application for the first time, it prompts the user to set a password. Later, the user has to enter the correct password in order to access the private photos. Below steps explains how to grab the password from runtime using cycript.

1. Launch the photo vault application and it prompts for password.

photovault login

2. Connect to the iPhone over SSH and grab the process id using ps ax command.

iPhone running process

3. Hook into the application process using cycript –p [PID] command.
Note: If you know the application name you can attach the cycript using cycript –p [ApplicationName] command.


4. On the cycript prompt, we can get the instance of the application either by invoking [UIApplication sharedApplication] method or using the UIApp variable.

cycript UIApp

5. To find out the application delegate run UIApp.delegate command.

cycript UIApp delegate

6. Search the class dump for the application delegate PhotoVaultAppDelegate and look for the @interface of it (class dump will have @interface & @protocol directives). An interface contains the declaration of all the methods and the properties. Whereas the protocol contains a group of related methods, which an object might call on its delegate.

class dump of photovault

7. Looking at the properties of the application delegate, shows an interesting property strPass. Access the value stored in the strPass using UIApp.delegate.strPass command. 

photovault password reveal

8. Bingo!. It reveals the password to unlock the private photos. Type the password in the application and you will get access to the users private photos.

photovault auth bypass

Cycript also allows to modify the instance variables, invoke instance methods and overwrite the existing methods directly from the runtime.

Penetration Testing For iPhone Applications is going to be covered in a series of articles. In the Part 6, we will take a look at method swizzling techniques with cycript and runtime analysis with GNU Debugger (gdb).


  1. Debunking NSLog Misconceptions
  2. Hacking and Securing iOS Applications by Jonathan Zdziarski
  3. “Apple iOS 4 Security Evaulation” by Dino Dai Zovi

Android Forensics

27 May

The article tries to cover various Android forensic techniques which can be helpful in a variety of situations. The techniques or discussions below can be either logical or physical however we will try to stick mostly to logical techniques. By word ‘logical’ I intend to say the technique would mostly involve accessing the file system etc. This article also assumes that the reader has basic knowledge about android programming and other concepts related to android. Primary steps involved in the Android forensics are passcode bypass and data extraction. Let’s proceed to learn more.

Bypassing the Android passcode:

Firstly it’s important to note that every technique comes with some limitation or the other. You will need to figure out which technique would help you depending on the circumstances. Circumventing the passcode may not be always possible. We will take a few scenarios and see how you can take advantage in each case.

There are currently 3 main types of pass codes supported by android devices – Pattern lock, PIN and alphanumeric code.

1. Smudge Attack:

This is not specific to any android device but used generally by forensic analysts where they can deduce the password of a touch screen mobile. The attack depends on the fact that smudges are left behind by the user’s fingers due to repeated swiping across same locations. The pattern lock or any pass code is something that the user will have to swipe every time that he wants to use his mobile. So we can infer that the smudges would be heaviest across the same locations and hence under proper lighting and high resolution pictures we can deduce the code. So during examining any device, forensic analysts usually take care to avoid hand contact with the screen so as to check for the smudge attack.

smudge attack

2.  If USB – debugging is enabled:

If USB debugging in android is enabled, then bypassing the lock code can be done in matter of seconds. Imagine an attacker wants to get access to his friend’s files and applications on his android mobile, you can first ask his handset for some false reason (ex to make a call) and turn on the USB debugging under Settings -> Developer Options ->USB debugging and hand over the mobile back to him. So later on any some convenient time, when you get access to the device you can exploit it using any of the following ways. Now adb (android debugging bridge) is primarily a command line tool that communicates with the device. ADB comes along with the android platform tools. To explain in simple terms, this is what happens when you deal with adb:

  • An adb daemon runs as a background process on each android device.
  • When you install android SDK on your machine, a client is run. The client can be invoked from shell by giving an adb command.
  • A server is also run in the background to communicate between the client and adb daemon running on the android device.

You can use any of the below methods to take advantage of the USB debugging to bypass the screen lock:

Using UnlockAndroid.apk:

Before going ahead with this process you can download the Unlockandroid.apk file from the below location.


1. Connect the device to the machine where Android SDK (including platform tools etc) is installed.
Open command prompt and type cd C:\android-sdk-windows\platform-tools>adb.exe devices.
The device must be identified by the adb if everything is going fine.
Now copy the above UnlockAndroid.apk file into C:\android-sdk-windows\platform-tools directory.
In command prompt type, C:\android-sdk-windows\platform-tools>adb.exe install UnlockAndroid.apk and observe that the application gets installed on the device.
Now to start the application just type: C:\android-sdk-windows\platform-tools>adb.exe shell am start -n com.rohit.unlock/com.rohit.unlock.MainActivity
7. Observe that the screenlock is bypassed now you can access all the application and folders in the mobile phone. Below is a screenshot of the process.

unlock android apk

Deleting the gesture.key file:

If the android device is using pattern lock and it it’s a rooted device then the below process can be tried which will bypass the screen lock.

1. Connect the device to the machine where Android SDK (including platform tools etc.) is installed.
2. Open command prompt and type cd C:\android-sdk-windows\platform-tools>adb.exe devices.
The device must be identified by the adb if everything is going fine.
Connect to adb shell by typing : adb.exe shell.
The terminal appears giving you access to shell. Now type rm /data/system/gesture.key. This is the file where pattern is stored.
Now after this, restart the phone and you will still observe that the device is asking for the pattern. However you can draw any random pattern and unlock the device.

Below is the screenshot of the process.

gesture key deletion

Updating the sqlite files:

If the phone is rooted, then by updating the sqlite files you can bypass the screen lock. Here are the details.

cd /data/data/
sqlite settings.db
update system set value=0 where name='lock_pattern_autolock';
update system set value=0 where name='lockscreen.lockedoutpermenantly';

Cracking the Android PIN:           

We have seen how to bypass the screen lock and how to completely delete or disable the lock screen. But what if we wanted to know the actual PIN so that you can lock/unlock at any time? In android, the PIN that user enters is stored in /data/system/password.key file. As you might expect, this key is not stored in plain text. It’s first salted using a random string, then the SHA1-hashsum and MD5-hashsum are calculated and concatinated and then the final result is stored. Seems very complicated but not to the modern computing power.

Below is the code for the same.

public byte[] passwordToHash(String password)
if (password == null)
   {      return null;   }
String algo = null;
byte[] hashed = null;
try {
      byte[] saltedPassword = (password + getSalt()).getBytes();
      byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword);
      byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword);   hashed = (toHex(sha1) + toHex(md5)).getBytes();
catch (NoSuchAlgorithmException e)
    {        Log.w(TAG, "Failed to encode string because of missing algorithm: " + algo);
return hashed;
}<span style="font-size: 13px; line-height: 19px;"> </span>

Since the hash is salted it’s not possible to use a regular dictionary attack to the get original text. Here are the steps you can follow to try to crack the PIN.

1. Pull out the salt using adb. Salt is stored in the ‘secure’ table from /data/data/
2. Get the password :  sha1+md5: (40+32) (stored at /data/system/password.key)

Ex:  0C4C24508F0D29CF54FFC4DBC5520C3C10496F43313B4D3ADDFF8ACDD5C8DC3CA69CE740

3. Once you have the md5 and the salt you can brute force using the tools available in market (Ex hashcat) to get password.

Data Extraction:

After having seen different ways to bypass the android screen lock, now let’s have a look at how to extract the data from an android phone. You can extract the data of all the files on the system or only those relevant files which you are interested in. But for any form of extraction it’s important that the device is unlocked or USB-debugging is previously enabled. There are 2 types of extractions.

Extracting through ADB: As explained earlier, adb is a protocol that helps you to connect to android device and perform some commands.

Boot Loader Extraction: This can be done when the device is in Boot Loader mode. This takes advantage of the fact that during boot loader mode the android OS will not be running.

Before extracting the data, it is important to know how the data is stored in android device so that we understand where to look for and which data to pull. Android stores the data mainly in the below 4 locations:

  1. Share Preferences: Data is stored in key-value pairs. Shared preference files are stored in application’s ‘data’ directory in the ‘shared_pref’ folder.
  2. Internal Storage: Stores data which is private in device’s internal memory (something like NAND flash).
  3. External Storage: Stores data which is public in device’s external memory which might not contain security mechanisms. This data is available under /sdcard directory.
  4. SQLite: This is a database which holds structural data. This data is available under /data/data/Package/database.

For example if you want to analyse the Facebook android application, here is how you do it. Download and install the Facebook application and sign in to it. Now as soon as you install any application in android, the corresponding application data is stored in /data/data folder. However due to the security restrictions, you cannot access or pull this data unless you have root privileges on the phone. By using adb let us see what the /data/data folder consists of. As shown in the below fig a quick ‘ls’ on the /data/data folder gives the below results.

data data folder

Whether its browser or gallery or contacts, everything is an app in android. They are the applications which come along with the phone. Application like games, social network apps etc. are the applications installed by the user. But the data belonging to any of these applications will be stored in /data/data folder. So the first step is to identify where your application is.

android app location

To see the contents of that application, ‘ls’ into that directory.

android app files

As you can see these are the folders created by the facebook application on your phone. For instance the cache folder may consist of images which are cached and stored for faster retrieval during normal browsing. The main area of focus would be the databases folder where the data related to the user would be stored. Here comes the concept of application security. If the application is secure enough, it would take proper steps not to store any of the sensitive data permanently in the databases folder. Let us see what kind of data Facebook stores the when you are currently logged in. For that you happen you can pull the android folder into your system using the below command.

C:\android-sdk-windows\platform-tools>adb.exe pull /data/data/com.facebook.katana C:\test

The databases folder must be now copied into the ‘test’ folder in your C drive.

copy fb db

In the ‘databases’ folder you see DB file types which are the sqlite files where the data is stored. To view the data present in them, you can use a browser such as Sqlite browser. Download and install SQlite browser. In the Sqlite browser, click on File à Open Database and select any of those DB files.



This shows you the database structure and helps you to browse the data stored in them. Now logout of the application and you might notice that the data present in those tables would be deleted by the application.

So to conclude, in this article we have seen how to bypass the android screen lock under different conditions and how to extract the application data from android phone.

No Comments

Posted by rohit


Disable ASLR on iOS applications

23 May

ASLR – Address Space Layout Randomization is an important exploit mitigation technique introduced in iOS 4.3. ASLR makes the remote exploitation of memory corruption vulnerabilities significantly more difficult by randomizing the application objects location in the memory. By default iOS applications uses limited ASLR and only randomizes part of the objects in the memory. The image compares the different memory sections for partial and full ASLR applications.

partial vs full ASLR - iOS

In order to take full advantage of the ASLR, the application has to compile with -fPIE -pie flag (“Generate Position-Dependent Code” build option in Xcode). This flag is automatically checked by default in the latest version of the XCode (from iOS 6). So, all the applications that are compiled in the latest SDK will automatically use full ASLR. To find out whether the application is compiled with PIE flag or not, connect the iPhone over SSH and execute the below command.

Otool –Vh ApplicaitonBinary

PIE enabled iOS app

The above image shows PIE at the end of the file header. It indicates that the Facebook application is compiled with PIE flag and uses the full ASLR.

During the pentest, ASLR might cause issues while reversing or decrypting the application. To overcome this problem, Peter Fillmore wrote an awesome tool removePIE that can be used to disable the ASLR of an iOS application. It disables the ASLR by flipping the PIE flag.

Steps to disable the ASLR of an iOS Application:

1. Download and extract it.
2. Copy removePIE to the iPhone using the below SCP command (password is alpine).

SCP removePIE root@iPhoneIP:/var/root

3. The SCP command copies the removePIE file into /var/root directory on the iPhone. This can be verified by connecting to the iPhone over SSH.

copy removePIE to iPhone

4. Copy removePIE to the corresponding application’s home directory.

removePIE to application directory

5. To disable ASLR of an application, run the removePIE command on the application binary.

./removePIE ApplicationBinary

disable ASLR of iOS app

The above command takes a backup of the application binary, then flips the PIE flag and disables the ASLR. This can be confirmed by running the otool -Vh ApplicationBinary command.

PIE disabled

The above image does not show PIE flag in the file header. It confirms that the Facebook application no more uses the full ASLR.

Note: removePIE does not accept the application path as an argument. Supplying the binary path to the program, ends up with segment fault:11 exception. 

2. iOS 4 security evaluation white paper by Dai Zovi


Penetration testing of iPhone Applications – Part 4

15 Apr

In the first part of the article, we have discussed about the iPhone application traffic analysis. Second part of the article covered the privacy issues and property list data storage. Third part covered in-depth analysis of the iOS keychain data storage. In this part we will take a look at different types of files stored/created in the application’s home directory and other insecure data storage locations.

Sqlite storage

Sqlite is a cross-platform C library that implements a self-contained, embeddable, zero-configuration SQL database engine. Sqlite database does not need a separate server process and the complete database with multiple tables, triggers, and views is contained in a single disk file. The Sqlite database offers all the standard SQL constructs, including Select, Insert, Update and Delete. As Sqlite is portable, reliable and  small, it is an excellent solution for persistent data storage on iOS devices.

Sqlite library that comes with iOS is a lightweight and powerful relational database engine that can be easily embedded into an application. The library provides fast access to the database records. As the complete database is operated as a single flat file, applications can create local database files and manage the tables & records very easily. In general, iOS applications use the Sqlite database to store large and complex data as it offers good memory usage and speed. Sqlite database that comes with iOS does not have a builtin support for encryption. So most of the iOS applications store lots of sensitive data in plain text format in Sqlite files. For example, to provide offline email access, Gmail iOS application stores all the emails in a Sqlite database file in plain text format.

Unencrypted sensitive information stored in a Sqlite file can be stolen easily upon gaining physical access to the device or from the device backup. Also, if an entry is deleted, Sqlite tags the record as deleted but not purge them. So in case if an application temporarily stores and removes the sensitive data from a Sqlite file, deleted data can be recovered easily by reading the Sqlite Write Ahead Log.

The Sqlite files can be created with or without any file extention. Most common extentions are .sqlitedb &.db. The below article explains, how to view Sqlite files and how to recover the deleted data from Sqlite files on the iPhone. For this exercise, I have created a demo application called CardInfoDemo. CardInfoDemo is a self signed application, so it can only be installed on a Jailbroken iPhone. The CardInfo demo application accepts any username & password, then collects the credit card details from the user and stores it in a Sqlite database. Database entries are deleted upon logout from the app.

Steps to install the CardInfo application:

1. Jailbreak the iPhone.
2. Download the CardInfoDemo,ipa file -  Download link.
On Windows, download the iPhone configuration utility – Download link.
Open the iPhone configuration utility and drag the CardInfoDemo.ipa file on to it.

iPhone configuration utility

5. Connect the iPhone to the windows machine using USB cable. Notice that the connected device is listed in the iPhone configuration utility. Select the device and navigate to Applications tab. It lists the already installed applications on the iPhone along with our CardInfo demo app. Cardinfo demo iOS app install

6. Click on Install button corresponding to the CardInfo application and it installs the CardInfo application on to the iPhone.

cardinfo ios demo app

Steps to view  CardInfo Sqlite files:

1. On the Jailbroken iPhone, install OpenSSH and Sqlite3 from Cydia.
On windows workstation, download Putty.
Connect the iPhone and the workstation to the same Wi-Fi network. Note: Wi-Fi is required to connect the iPhone over SSH. If the Wi-Fi connection is not available SSH into the iPhone over USB.
4Run Putty and SSH into the iPhone by typing the iPhone IP address, root as username and alpine as password.
Navigate to /var/mobile/Applications/ folder and identify the CardInfo application directory using ‘find . –name CardInfo’ command. On my iPhone CardInfo application is installed on the – /var/mobile/Application/B02A125C-B97E-4207-911B-C136B1A08687/ directory. 

cardinfo directory

6. Navigate to the /var/mobile/Application/B02A125C-B97E-4207-911B-C136B1A08687/ directory and notice CARDDATABASE.sqlite3 database file.

cardinfo sqlite file

7. Using sqlite3 command, view the CARDDATABASE.sqlite3 and notice that CARDINFO table is empty.

Note: Sqlite files can also be copied from the iPhone to a workstation over SSH and viewed using Sqlite data browser & Sqlite spy tools.

cardinfo sqlite before login

8. On the iPhone, open CardInfo application and login (works for any username and password).

cardinfo login

9.Enter credit card details and click on Save button. In the background, it saves the card details in the Sqlite database.

cardinfo - card details                    cardinfo - saved details

10. View CARDDATABASE.sqlite3 and notice that CARDINFO table contains the credit card details data.

cardinfo sqlite after save

11. Logout from the application on the iPhone. In the background, it deletes the data from the Sqlite database.

cardinfo logout

12. Now view CARDDATABASE.sqlite3 and notice that CARDINFO table is empty.

cardinfo sqlite after logout

Steps to recover the deleted data from CardInfo Sqlite file:

Sqlite database engine writes the data into Write Ahead Log before storing it in the actual database file, to recover from system failures. Upon every checkpoint or commit, the data in the WAL is written into the database file. So if an entry is deleted from the Sqlite database and there is no immediate commit query, we can easily recover the deleted data by reading the WAL. In case of iOS, strings command can be used to print the deleted data from a Sqlite file. In our case, running ‘strings CARDDATABASE.sqlite3’ command prints the deleted card details.

cardinfo sqlite recovered

In iOS, if an application uses the Sqlite database for temporary storage, there is always a possibility to recover the deleted temporary data from the database file.

For better security, use custom encryption while storing the sensitive data in Sqlite database. Also, before deleting a Sqlite record, overwrite that entry with junk data. So even if someone tries to recover the deleted data from the Sqlite file, they will not get the actual data. Use iOS data protection constants while creating the Sqlite files.


Most of the iOS applications do not want to prompt the user for login everytime. So they create persistent cookies and store them in cookies.binarycookies file on the application’s home directory.  During penetration test, investigate the cookies.binarycookies file for sensitive information and to find session mangement issues. Cookies.binarycookies is a binary file and the content is not in readable format. So I wrote a python script that can read the cookie file and display the content on the screen.

Steps to read the Cookies.binarycookies:

1. On Windows, download WinScp, Python &
Connect the iPhone and the workstation to the same Wi-Fi network.
Run WinScp and SSH into the iPhone by typing the iPhone IP address, root as username and alpine as password.
Navigate to the Library/Cookies folder in the application’s home directory.
Copy the Cookies.binarycookies file to the windows machine by dragging it.


6. On windows, open command prompt and run the below command to list the contents of cookies.binarycookies file.

Python [Cookies.binarycookies file path]

Below is the screenshot of cookies created by Facebook iOS Application.

facebook iOS cookie file

Keyboard Cache

In an effort to learn how user’s type, iOS devices utilize a feature called Auto Correction to populate a local keyboard cache on the device. The keyboard cache is designed to autocomplete the predictive common words. The problem with this feature is, it records everything that a user types in text fields. The cache keeps a list of approximately 600 words. The keyboard cache is located at Library/Keyboard/en_GB-dynamic-text.dat file. To view the Keyboard cache, copy the en_GB-dynamic-text.dat file to a computer over SSH and open the file using a Hex Editor. Below is the screenshot of a keyboard cache Hex view.

iOS keyboard cache

Keyboard Cache does not store the informtion typed in the fields which are marked as Secure. By default, passwords and strings with all digits (pins & credit cards) are marked as Secure. Hence the data typed in those fields does not store in the keyboard cache. But data typed in other text fields like username, security questions & answers might get stored in the keyboard cache. During a pentest clear the existing keyboard cache by navigating to iPhone Settings -> General -> Reset -> Reset Keyboard Dictionary (shown in the below image), then browse the application & enter data in text fields and anlyze whether the data is getting stored in the keyboard cache or not.

Clear iOS keyboard cache

During the application development, to disable auto complete for a text field, either mark it as secure (ex: mytextField.secureTextEntry = YES) or disable the autocomplete (mytextField.autocorrectionType = UITextAutocorrectionTypeNo;).

Along with the keyboard cache, when a user copies data from a textfield, iOS stores the data into a pasteboard (clipboard in other operating systems). The pasteboard is shared among all the application, so the information copied in one application can be accessed from other application by reading the pasteboard. If the application is dealing with senstive data, it is recommended to use private or application specific pasteboard.

Snapshot Storage

Pressing the iPhone home button shrinks the iOS application and moves it to the background with a nice effect. To create that shrinking effect, iOS takes a screenshot of the application and stores it in the Library/Caches/Snapshots folder in the respective application’s home directory. This might result in storing the user’s sensitive information on the device without user’s knowledge. Snapshots stored on the iPhone will automatically cleared after the device is rebooted.

Ex: Incase of Gmail iOS application, when a user press the iPhone home button after viewing the email, a snapshot of users’ email gets stored on the device without user’s knowledge. Below snapshot is captured after viewing a mail from the Citibank.

Gmail iOS App Snapshot Storage

During development, the application snapshot problem can be fixed in two ways.
1. Remove sensitive data or change the screen to blank before the applicationDidEnterBackground()
function returns.
2. Instead of hiding or removing sensitive data, application’s back grounding can be disabled altogether by setting the “Application does not run in background” property in the application’s Info.plist file.

File Cache

Along with plist files, sqlite files, binary cookies & snapshots, iOS applications can store other format files like pdf, xls, txt, etc. when viewed from the application. For example, in Yandex.Mail iPhone application, when a user views an attachment it gets stored on the device and remains on the device even after user logged out from the mail application. Applications which are storing temp files on the device, should clear those files upon logout/close for better security.  Below is the screenshot of Yandex.Mail attachement directory.

iOS Yandex Mail Attachement Storage

Error Logs

In general, iOS applications write data into logs for diagnostic and troubleshooting purpose. Also, during development, applictions developers commonly use NSLog for debugging purpose. These logs might include requests, responses, cookies, authentication tokens and other sensitive data. On the iPhone, data passed to the NSLog funciton is logged by Apple System Log (ASL) and the data remains on the log until the device is rebooted. Also, Error logs are not bounded by the application sandbox. Which means, error log generated by one application can read by other application. So if an application logs sensitive data, a malicious application can actively query for this data and send it to a remote server.

Error logs on the iPhone can be viewed directly using Console app. Console app is available in AppStore. Error logs can also be viewed using iPhone configuration utility or by syncing the device with iTunes and looking at CrashReporter folder.

For this exercise, I have created a demo application called CardInfoDemo. CardInfoDemo is a self signed application, so it can only be installed on a Jailbroken iPhone. The CardInfo demo application accepts any username & password, then collects the credit card details from the user and writes it into the error log.

Steps to view the error logs:

1. Install CardInfoDemo application on the iPhone.
2. On windows, install & open the iPhone Configuration Utility.
Connect the iPhone to the windows machine using USB cable. Notice that the connected device is listed in the iPhone configuration utility. Select the device and navigate to Console tab.
On the iPhone, open CardInfo application and login (works for any username and password).
Enter credit card details and click on Save button. In the background, it logs the card details.

CardInfoDemo iOS App

6. On the iPhone configuration utility console tab, you can notice the card details logged by the CardInfoDemo application.

iOS App Error log

For better security, do not log sensitive data. Also, remove debugging and troubleshooting logs from the application before publishing it.

Penetration Testing iPhone Applications is going to be covered in a series of articles. Below are the links for next articles. 

Part 5runtime analysis of iOS Applications.


1. Debunking NSLog Misconceptions
2. What’s in your iOS Image Cache ?
3. Hacking and Securing iOS Applications by Jonathan Zdziarski

Page 2 of 1312345...10...Last »