RSS

Tag Archives: penetration testing of iOS applications

Penetration testing of iPhone Applications – Part 6

In the First part of the article, we have discussed about the iPhone application traffic analysis. Second partThird part and Fourth part of the article covered in-depth analysis of insecure data storage locations on the iPhone. Part 5 covered runtime analysis basics with Cycript. In this part we will take a look at in-depth analysis of application runtime using cycript and GNU debugger.

Runtime analysis with Cycript:

With cycript we can hook into the application runtime, access & modify the instance variables, invoke the instance methods and override the existing methods. In the previous article we have discussed on how to access instance variables from the application runtime. In this article we will take a look at how to invoke & override the application instance methods. 

Invoking the instance methods with Cycript:

Cycript allows invoking the application instance methods directly from runtime. This helps in bypassing the validation mechanisms implemented in applications. For the demo, I am using a photovault application and you can download the IPA here. Photovault application will help to keep the photos securely by protecting with a passcode. When the application is launched for the first time, it prompts the user to set a passcode. Later on, the user has to enter the correct passcode to view the private photos. Below steps explains how to bypass the photovault passcode protection using cycript.

1. Launch the photovault application and it prompts for a passcode.

photovault login screen

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

photovault ps id

3. Hook into the application process using cycript –p [PID] command.

hook with cycript

4. On the cycript prompt, grab the application delegate instance using UIApp.delegate command.

photovault UIAppdelegate

5. Obtain the photovault class dump using class_dump_z. Search the class dump for AppDelegate & look for the @interface of it.

photovault classdump

6. Looking at the class dump reveals an interesting method called – pinLockControllerDidFinishUnlocking. The method does not take any arguments. So we can invoke it directly using [UIApp.delegate pinLockControllerDidFinishUnlocking] command. 

method invocation with cycript

7. Bingo!. It logs you into the application without entering the passcode and gives access to the private photos.

photovault passcode bypass

Overriding the instance methods with Cycript:

The objective-C runtime allows modification & replacement of the existing methods code dynamically. This technique is known as method swizzling. For this exercise, I have created a demo application called HackTest and you can download the IPA here. HackTest application prompts the user for a password and displays the welcome screen upon entering the correct password. Below steps explains how to bypass the HackTest password validation mechanism by overriding the existing methods using cycript.

1. Launch the HackTest application and it prompts for a password.

hacktest password

2. Enter any value (ex: abcd) and click on Enter button. It displays invalid passcode message.

hacktest invalid passcode

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

hacktest ps id

4. Hook into the application process using cycript –p [PID] command.

hacktest-hooke with cycript

5. On the cycript prompt, grab the application delegate instance using UIApp.delegate command.

hacktest UIAppdelegate

6. Obtain the HackTest class dump using class_dump_z. Looking at the class dump of HackTest application reveals an interesting method called validatePasscode. The method takes no arguments and returns a Boolean value. The application probably uses this method to check for a valid passcode and takes the authentication decision based on its return value. Now using the method swizzling technique we will modify the validatePasscode method to always return true.

hacktest classdump

7. validatePasscode method is declared in the ViewController interface and the ViewController instance is present in the AppDelegate interface. So grab the ViewController instance using UIApp.delegate.viewController command.

hacktest viewcontroller

8. To override the validatePasscode method, run the below command.

UIApp.delegate.viewController->isa.messages[‘validatePasscode’]=function (){return 1;}.

It overrides the function to always return 1. isa is a pointer to the class structure and gives access to the method implementation.

cycript metod override

9. Bingo!. It logs you into the application without entering the password and displays the welcome screen.

hacktest passcode bypass

The above examples shows how one can easily manipulate the runtime and circumvent the security checks implemented in iOS applications using cycript.

Runtime analysis with gdb:

Gdb – gnu debugger is a powerful tool to analyze and alter the runtime behaviour of iOS applications. Debugging is an interactive process and allows setting breakpoints in the application execution which in turn gives more control on the application. For this exercise, I am using a photovault application and you can download the IPA here. The photovault application keeps the private photos securely by protecting with a password. When the application is launched for the first time, it prompts the user to set a password. Later on, the user has to enter the correct password to access the private photos. Below steps explains how to grab the photovault password from runtime using gdb.

1. Launch the photovault application and it prompts for a password.

photovault-3 password

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

photovaut-3 ps id

3.  Attach gdb to the application process using gdb –p [pid] command.

photovault-3 gdb hook

gdb attaches to the process and reads the symbols for shared libraries.

photovault-3 gdb

4.  Obtain the photovault class dump using class_dump_z.  Looking at the class dump reveals an interesting method called btnLoginClicked. This method takes no arguments and probably gets invoked upon pressing the login button. Let’s inspect the method by setting a breakpoint.

photovault-3 classdump

5. Set a breakpoint for the btnLoginClicked method using b or break command. A breakpoint pauses the program execution whenever a certain point in the program is reached.

gdb breakpoint1

6. At this point the application gets freezed and does not accept any input. In order to continue the execution type c in the gdb prompt.

gdb continue execution 1

7. Enter some value in the photovault password and click on login button.

photovault-3 enter password

8. As expected it hits the breakpoint in gdb and the application execution is paused.

photovault-3 breakpoint

9. At this point, disassemble the btnLoginClicked method to look at the next executable instructions using disas or disassemble command. As iPhone binaries are compiled for ARM processors, gdb displays the ARM based assembly instructions.

gdb disassemble

10. In the disassembled code you will see a lot of dyld_stub_objc_msgSend instructions. Objective-c is based on the messaging framework, hence methods aren’t invoked or called, instead messages are passed between objects using objc_msgsend method. An attacker can tap into these messages and look for sensitive information. On gdb terminal, we can setup breakpoints for all the objc_msgsend calls and inspect for the important information. As there are too many objc_msgsend calls in the disassembly, it would be difficult & time taking process to inspect each and every call. In the btnLoginClicked disassembled code, dyld_stub_objc_msgSend located at 0x0000618a is followed by a cmp instruction (conditional execution) which probably means it checks for a login state. So let’s set a breakpoint at 0*0000618a and inspect the objc_msgsend call.

photovault-3 breakpoint2

11. Continue the application execution and it hits the breakpoint.

gdb continue execution2

We can inspect the breakpoint by looking at the register values. To see register values at the breakpoint use info reg command. iPhone uses ARM based processors which contain 15 general purpose registers (r0 – r14), program counter (r15) and current program status register (flags). The standard ARM calling conventions allocates the 16 ARM registers as:

r0 to r3 – holds argument values passed to a method (r0 is also used to store the return result from a method)
r4 to r11 – holds local variables
r12  ( ip) – Intra-Procedure-call scratch register
r13  ( sp) – stack pointer
r14  (lp) – link register
r15  (pc) – program counter

ios - gdb registers

objc_msgsend method contains 3 arguments –

Receiver (r0): A pointer to the called object. That is, the object on which the method should get invoked. x/a $r0 command is used to examine the address located at r0 and po $r0 command is used to print the object located at r0.

photovault-3 r0 reg

Selector (r1): String representation of the method that handles the message. x/s $r1 command is used to examine the string value stored in r1 register.

photovault-3 r1 reg

First argument passed to the objc_msgsend is stored in r2. Po $r2 command is used to print the r2 register value.

photovault-3 r2 reg

Looking at the register values explains that r0 contains the original password and the application is trying to compare it with the user entered value in r2. Bingo ! Now we know the password and can log into the application directly.

photovault-3 password bypass

The above example shows how one can easily manipulate the application runtime using gdb. The application security can be improved further by adding anti-debugging techniques which would prevent malicious users from using a debugger. Though they won’t provide 100% security, it works as an additional layer of security and delays the attacker attempts.

Penetration Testing For iPhone Applications is going to be covered in a series of articles. In the Part 7, we will take a look at push notifications, URL schemes and few automation tools.

 

Posted by on September 12, 2013 in iPhone

6 Comments

Tags: , , , ,

Penetration testing of iPhone Applications – Part 5

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.

Header:
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

Data:
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 http://www.securitylearn.net/wp-content/uploads/tools/iOS/class-dump-z.zip
unzip class-dump-z.zip
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 http://AppAddict.org/repo by navigating to Manage->Sources.
2. 
Download ClutchPatched, ZIP and IPA Installer from Cydia.
3.  
Connect to the iPhone over SSH and type the ‘Clutch’ command. It lists out all the applications installed on the iPhone.

clutch

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.

cycript

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).

References:

  1. Debunking NSLog Misconceptions
    http://oleb.net/blog/2011/06/app-launch-sequence-ios/
  2. Hacking and Securing iOS Applications by Jonathan Zdziarski
  3. “Apple iOS 4 Security Evaulation” by Dino Dai Zovi
 

Posted by on June 26, 2013 in iPhone

9 Comments

Tags: , , , ,

Hacking and Securing iOS Applications : Video

 

Posted by on December 13, 2012 in iPhone

Leave a comment

Tags: , , , ,

Hacking and Securing iOS Applications : Slides

A deck of slides which I have used for my presentation @ Clubhack 2012, India.

Abstract
iOS applications share common set of classes and highly depends on the operating system solutions for data communication, storage and encryption. Solely depending on the Apple implementation made them less complex but it affects security of the applications. Though iOS comes with a great set of security features like code signing, ASLR, DEP, sand boxing and Data Protection, all of them are subject to attack. Relying only on the iOS security could lead to demise the sensitive data stored within the application when the iOS is compromised. Application security can be improved by understanding the weaknesses in the current implementation and incorporating own code that work better.

The presentation illustrates several types of iOS application attacks like run time manipulation, custom code injection, SSL session hijacking and forensic data leakage. It gives an insight into the iOS Keychain & data protection API and explains the techniques to circumvent it. The presentation will provide guidelines and suggests best practices for secure iOS application development.

Slides

 

Demo Videos
I want to thank my friend TC for helping me in developing couple of apps for the demos.

 

 

 

 

 

Posted by on December 3, 2012 in iPhone

1 Comment

Tags: , , , ,

Penetration testing of iPhone Applications – Part 3

In the first part of this article, we have discussed about the iPhone application traffic analysis. Second part of the article covered the privacy issues and property list data storage. In this part, we will take a look at in-depth analysis of the keychain data storage. Apple has designed the keychain with many security measures in place to protect the user’s data, however it is broken at every level. So complete understanding to the keychain and its security & weaknesses will help penetration testers to provide proper remediation suggestions during iOS application security assessments.

Keychain storage: 

Keychain is an encrypted container (128 bit AES algorithm) and a centralized Sqlite database that holds identities & passwords for multiple applications and network services, with restricted access rights. On the iPhone, keychain Sqlite database is used to store the small amounts of sensitive data like usernames, passwords, encryption keys, certificates and private keys. In general, iOS applications store the user’s credentials in the keychain to provide transparent authentication and to not to prompt the user every time for login. iOS applications use the keychain service library/API (secItemAdd, secItemDelete, secItemCopyMatching & secItemUpdate methods) to read and write data to and from the keychain. Developers leverage the keychain services API to dictate the operating system to store sensitive data securely on their behalf, instead of storing them in a property list file or a plain text configuration file. On the iPhone, keychain Sqlite database file is located at – /private/var/Keychains/keychain-2.db.

Keychain contains a number of keychain items and each keychain item will have encrypted data and a set of unencrypted attributes that describes it. Attributes associated with a keychain item depends on the keychain item class (kSecClass). In iOS, keychain items are classified into 5 classes – generic passwords (kSecClassGenericPassword), internet passwords (kSecClassInternetPassword), certificates (kSecClassCertificate), keys (kSecClassKey) and digital identities (kSecClassIdentity, identity=certificate + key) . In iOS keychain, all the keychain items are stored in 4 tables – genp, inet, cert and keys . Genp table contains generic password keychain items, inet table contains internet password keychain items, and cert & keys tables contain certificates, keys and digital identity keychain items.

iPhone Keychain tables

Keychain Tables

Keychain database is encrypted with a hardware specific key which is unique per the device. Hardware key cannot be extracted from the device, so the data stored in the keychain can only be accessible on the device itself and cannot be moved to another device. Keychain database is tied to the device, so even if an attacker obtains access to the keychain through a physical access to the file system or in a remote attack, he cannot decrypt and view the file contents.

iPhone keychain file format

Keychain File Format

Keychain data is logically zoned and data stored by one application is not accessible to another application. Keychain data of an iOS application is stored outside the application’s sandbox. So operating system process securityd enforces the access control and regulates access to the keychain data in such a way that the applications with correct permissions can read their data. Keychain access permissions of an iOS application are defined in the code sign entitlements. Keychain Services uses these entitlements to grant permissions for the applications to access its own keychain items. Entitlements of an application define the properties that provide access to the iOS features such as push notifications, keychain access and iCloud communication, etc… Entitlements grant specific capabilities or security permissions to iOS applications. An entitlement file for a keychain data sharing application contains an application-identifier and may contain a set of keychain-access-groups constants. In iOS, each application ships with a unique application-identifier. The keychain service restricts the keychain data access based on this application identifier. By default, applications can only access data associated with their own application-identifier. Later, to share the keychain items with multiple applications, keychain-access-groups wereintroduced. Applications with the same keychain access group entitlement can access/share the keychain items. Entitlements of an application are embedded in the application binary and stored unencrypted. So, on a JailBroken iPhone, entitlements of an application can be extracted from the application binary using grep or sed commands (stream editor – sed can be downloaded from Cydia packages).

To list out the entitlements of an iOS application, connect to the iPhone over SSH, navigate to the application’s home directory (/var/mobile/Applications/[unique-id]/) and run the below command.

sed -n '/<dict>/,/<\/dict>/p'  [AppDirectory]/[ApplicationBinary]

Example: Below command list out the entitlements of Facebook iOS application.

> sed -n '/<dict>/,/<\/dict>/p'  Facebook.app/Facebook
<dict>
        <key>application-identifier</key>
        <string>T84QZS65DQ.com.facebook.Facebook</string>
        <key>aps-environment</key>
        <string>production</string>
        <key>keychain-access-groups</key>
        <array>
                <string>T84QZS65DQ.platformFamily</string>
        </array>
</dict>

* Facebook iOS application is a fat binary (built for ARM6 & ARM7 architectures), so the above command will print the entitlement details twice.

The above result indicates that the Facebook iOS application uses ‘T84QZS65DQ.platformFamily’ keychain-access-group while storing the entries in the keychain.

When an application adds an entry to the keychain, application identifier or keychain access group of the application also gets added to the keychain item agrp (access group)column. Later, when an application tries to access the keychain item, keychain service verifies the application identifier or keychain access group against the agrp value of corresponding keychain item to permit the access. Sample keychain-2.db file is shown in the Figure 3 and Facebook entitlements are highlighted.

Facebook keychain entitlements

Facebook keychain entries

*The above screen shot is captured by copying the keychain-2.db file from a JailBroken iPhone to a windows machine and opening it with a Sqlite browser.

Note:  Applications that are built for the simulator uses the same default keychain access group. So on the simulator, all the applications can access all the keychain items.

With the introduction of data protection mechanism in iOS, sensitive data stored in the keychain item is protected with another layer of encryption which is tied to the user’s passcode. Data protection encryption keys (protection class keys) are derived from a device hardware key and a key generated from the user’s passcode. So encryption offered by data protection API is as good as the strength of a user’s passcode. Data protection is designed to protect the user’s data in case a device is lost or stolen. Data protection for the keychain items can be enabled by supplying an accessibility constant value to the kSecAttrAccessible attribute of SecItemAdd or SecItemUpdate methods. Data protection accessibility constants determine when a keychain item should be readable by an application. It also determines whether a keychain item is allowed to migrate to other devices or not. During an iTunes backup, all the data stored in the iOS device is backed up to the computer including the keychain database. On the iTunes backups, keychain Sqlite database is stored as a Plist file (Keychain-backup.plist). Keychain items which are backed-up with the iTunes encrypted backup option can be moved/loaded to another device. However the keychain items which are protected with ThisDeviceOnly constants cannot be moved to other iOS devices.

Below is the list of keychain item accessibility constants –

  • kSecAttrAccessibleWhenUnlocked
    • Keychain item is accessible only after the device is unlocked
    • Data protection class keys required to decrypt the keychain items are loaded into memory only when the device is unlocked and the encryption keys are automatically purged in 10 seconds once the device is locked.
  • kSecAttrAccessibleAfterFirstUnlock
    • Keychain item is accessible only after the first unlock of the device to till reboot
    • Data protection class keys required to decrypt the keychain items are loaded into memory only when the user unlocks the device after a reboot and the keys remain in the memory till next reboot of the device.
  • kSecAttrAccessibleAlways
    • Keychain item is accessible even the device is locked
    • Data protection class keys required to decrypt the keychain items are always loaded into memory.
  • kSecAttrAccessibleWhenUnlockedThisDeviceOnly
    • Keychain item is accessible only after the device is unlocked and the item cannot be migrated between devices.
  • kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
    • Keychain item is accessible after the first unlock of the device and the item cannot be migrated between devices.
  • kSecAttrAccessibleAlwaysThisDeviceOnly
    • Keychain item is accessible even the device is locked and the item cannot be migrated between devices.

Data protection accessibility constants of a keychain item are mapped to pdmn (protection domain) column in the keychain tables – genp, inet… Mapping to the keychain data protection accessibility constants and pdmn values are shown in below table.

iPhone keychain pdmn values

Sample keychain-2.db file is shown in the Figure 4 and pdmn column is highlighted.

iOS Keychain data protection entries

*The above screen shot is captured by copying the keychain-2.db file from a JailBroken iPhone to an OS X machine and opening it with a Sqlite browser.

Third party applications usually store the plain text credentials in the keychain to not to prompt the user every time for login and to preserve the data across re-installation or up-gradation of the application. So while penetration testing, we have to look at the keychain items to see what kind of information is being stored by the applications in the keychain. But the keychain service does not allow viewing the keychain items of any application without proper entitlements. On a JailBroken device this restriction can be broken and it is possible to dump all the keychain items by signing an application with one of the below entitlements file.

  1. An entitlements file which has all the keychain access groups
    – Fetch all the keychain access groups from the keychain by running a SQL query: select agrp from genp and place them in the entitlements file.
  2. An entitlements file with wild card ‘*’ keychain access group
  3. An entitlements file with com.apple.keystore.access-keychain-keys keychain access group

Link identity editor – ldid (Cydia Package) can be used to the sign the application with the entitlement file: ldid –Sentitlements.xml [app-name]

Patrick Toomey has developed a keychain_dumper tool that can be used to dump all the keychain items on a JailBroken iOS device. Recent version of the keychain_dumper uses the wildcard ‘*’ keychain access group entitlement to access all the keychain items. Steps listed below explain the usage of keychain dumper tool on the iPhone.

keychain dumper usage:

1. Jailbreak the iPhone.
2. Install openssh from Cydia.
3. On Mac OS X, download keychain_dumper and cyberduck tools.
4. Connect the iPhone and the computer to the same WI-FI network.
5. On Mac OS X, run Cyberduck and connect to the iPhone by typing the iPhone IP address, username as root and password as alpine.

iPhone SSH cyberduck

6. Copy keychain_dumper executable to the iPhone root directory.Copy keychain dumper on iPhone

7. Run terminal and connect to the iPhone over SSH by typing the iPhone IP address, username as root and password as alpine.
8. On SSH terminal, type chmod 777 keychain_dumper and ./keychain_dumper commands. It will execute the keychain_dumper tool and displays all the keychain items from genp & inet tables.

iPhone keychain dumper

iPhone keychain dumper

9. ./keychain_dumper –c command dumps the keychain items from cert & keys tables.

iPhone keychain dumper - certificates

Note:keychain-dump & keychain viewer tools can also be used to dump all the keychain items. The tools are developed by Jean Sigwald and they use the com.apple.keystore.access-keychain-keyskeychain group entitlement to dump all the keychain items.

Third party applications also set data protection accessibility constants while adding the keychain items to make it available only after unlock. Data protection is designed to protect the data at rest by adding another layer of encryption. Data protection is tied to the user passcode and it secures the data only when a user sets a passcode as illustrated in the Figure.

iPhone passcode

Upon obtaining physical access to the device which is not protected with a passcode, an attacker can read all the keychain items by JailBreaking the device and running tools like keychain dumper. So even if third party applications use data protection API, data at rest is not protected without a user’s passcode and leaves the security to the end user.

Even if a user sets a simple passcode for the device, an attacker can still read all the keychain items by brute forcing the user’s passcode. A simple 4 digit passcode can be brute forced in less than 20 minutes by booting the device with a custom ram disk. More details about the iPhone passcode brute forcing are documented at iPhone Forensics article. Data protection is useful only when a user sets a complex passcode (minimum of 6 alpha numeric characters in length).

Note: Boot Rom level vulnerability is required to boot the device with a custom ram disk. At the time of writing this article, Boot Rom level vulnerability was not identified in A5 chips which are used in the iPhone 4s & iPad 2. So currently it is not possible to perform a passcode brute force attack on the iPhone 4s and iPad 2.

Techniques explained above concludes that the keychain items are secure only if a user sets a complex passcode for the device and the keychain item is protected with an accessibility constant which makes it available only after unlock.

Bottom Line: 

Though Apple has designed the iOS keychain with best security features in place, it is broken at every level. Techniques explained in the article demonstrate that, all the keychain items can be dumped upon gaining physical access to the device. It is also quite possible to design a remote application (targeting JailBroken devices) which can read all the keychain items and transmit the data to a remote server. In the recent versions of iOS (4 & 5), by default, the keychain items are stored using the kSecAttrAccessibleWhenUnlocked data protection accessibility constant. However the data protection is effective only with a device passcode, which implies that sensitive data stored in the keychain is secure only when a user sets a complex passcode for the device. But iOS applications cannot enforce the user to set a device passcode. So if iOS applications relies only on the Apple provided security they can be broken if iOS security is broken. iOS application security can be improved by understanding the shortcomings of the current implementation and writing an own implementation that works better. In case of the keychain, iOS application security can be improved by using the custom encryption (using built-in crypto API) along with the data protection API while adding the keychain entries. If custom encryption is implemented it is recommended to not to store the encryption key on the device.

Video:

 

References

  1. iPhone data protection tools
    http://code.google.com/p/iphone-dataprotection/
  2. iOS Keychain weaknesses FAQs
    http://sit.sit.fraunhofer.de/studies/en/sc-iphone-passwords-faq.pdf
  3. Keychain services concepts https://developer.apple.com/library/ios/#documentation/Security/Conceptual/keychainServConcepts/02concepts/concepts.html
  4. Ptoomey keychain dumper
    https://github.com/ptoomey3/Keychain-Dumper

 

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

Part 4Analysis of the  files stored in the application home directory, caching issues and error log analysis.
Part 5runtime analysis of iOS Applications.

 

Posted by on September 7, 2012 in iPhone

2 Comments

Tags: , , , , , , , , , , , , ,