RSS

Author Archives: satishb3

About satishb3

Over 6 years of experience as a web application penetration tester. Crazy about iPhone hacking. Passionate about hacking and sharing knowledge. Contributor to OWASP and NULL Hyderabad chapters. You can reach me on : securitylearn.wordpress@gmail.com satishb3@hotmail.com satishb3@securitylearn.net

Win A Free Copy of Packt’s Practical Mobile Forensics

We are pleased to announce that Packt publishing is organizing a giveaway especially for you. All you need to do is just comment below the post and win a free e-copy of Practical Mobile Forensics. Two lucky winners stand a chance to win an e-copy of the book. Keep reading to find out how you can be one of the Lucky One.

Practical Mobile Forensics cover

Overview of Practical Mobile Forensics

  • Clear and concise explanations for forensic examinations of mobile devices
  • Master the art of extracting data, recovering deleted data, bypassing screen locks, and much more
  • The first and only guide covering practical mobile forensics on multiple platforms

How to Enter ?

Simply post your expectations from this book in comments section below. You could be one of the 2 lucky participants to win the copy.

DeadLine:

The contest will close on 09/25/2014. Winners will be contacted by email, so be sure to use your real email address when you comment!

Update – 09/26/2014 : The contest is over. Will announce the winners shortly.

Update – 09/28/2014 : Lucky winners are listed below. Congrats.

Simon Lang
Pralhad

 

Posted by on September 17, 2014 in Android, iPhone

22 Comments

Tags:

LaunchKey Mobile Vulnerabilities : Bug Bounty Experience

Below are the vulnerabilities which I have found in the LaunchKey iPhone application.

Insecure Storage – passcode & auth token are stored in clear text

LaunchKey app allows its users to set a passcode to protect their information. This passcode is stored in clear text in the keychain, which can be obtained using keychain_dumper tool.

launchkey pin in plaintext

The app also stores the authentication token in clear text in the keychain.LaunchKey Auth Token in cleartext

Passcode Lock Bypass

Once a passcode lock is set, whenever the app is relaunched it prompts for the passcode. This passcode lock can be bypassed by manipulating the iOS runtime with cycript. Before manipulating the runtime, I have decrypted the app using clutch and obtained the class information using class-dump-z.

Steps followed to bypass the passcode lock:
1. Connected to the iPhone over SSH.
2. Launched the app and noticed that it prompts for a passcode.
LaunchKey pin lock
3. Attached LaunchKey process to cycript and obtained the view controller instance of current displaying screen. 
$cycript -p LaunchKey
>v=UIApp.keyWindow.rootViewController.visibleViewController
>v
<LKPinViewController: 0x1f5d5d00>
4. Looked at the class dump for LKPinViewController interface and didn’t find any interesting methods/variables.
@interface LKPinViewController : LKLockViewController <UITextFieldDelegate> {
	NSString* pinNumber;
	BOOL creation;
	NSString* firstPin;
	int tries;
	UITextField* pinDigitOneTextField;
	UITextField* pinDigitTwoTextField;
	UITextField* pinDigitThreeTextField;
	UITextField* pinDigitFourTextField;
	UIView* pinView;
	UIImageView* background;
	UIButton* cancelButton;
	UILabel* pinLabel;
	UINavigationBar* navigationBar;
	UIImageView* lkNavLogo;
	UILabel* notMatchLabel;
	UITextField* pinField;
}
@property(retain, nonatomic) UITextField* pinField;
@property(assign, nonatomic) __weak UILabel* notMatchLabel;
@property(assign, nonatomic) __weak UIImageView* lkNavLogo;
@property(assign, nonatomic) __weak UINavigationBar* navigationBar;
@property(assign, nonatomic) __weak UIView* pinView;
@property(assign, nonatomic) __weak UIImageView* background;
@property(assign, nonatomic) __weak UITextField* pinDigitFourTextField;
@property(assign, nonatomic) __weak UITextField* pinDigitThreeTextField;
@property(assign, nonatomic) __weak UITextField* pinDigitTwoTextField;
@property(assign, nonatomic) __weak UITextField* pinDigitOneTextField;
@property(assign, nonatomic) __weak UIButton* cancelButton;
@property(assign, nonatomic) __weak UILabel* pinLabel;
-(void).cxx_destruct;
-(void)viewDidUnload;
-(void)didReceiveMemoryWarning;
-(void)dealloc;
-(void)cancelButtonTouched:(id)touched;
-(void)shakeTheView;
-(void)viewDidLoad;
-(void)animationDidStop:(id)animation finished:(BOOL)finished;
-(void)showConfirmFields;
-(void)savePinToKeychain:(id)keychain;
-(BOOL)textField:(id)field shouldChangeCharactersInRange:(NSRange)range replacementString:(id)string;
-(id)initWithLocking;
-(id)initWithVerification;
-(id)initWithRemoval;
-(id)initWithCreation;
-(id)initWithNibName:(id)nibName bundle:(id)bundle;
@end

LKPinViewController inherits LKLockViewControllerHence, methods in the parent class (LKLockViewControllerclass) can be invoked from the child class (LKPinViewControllerinstance. So looked at the class dump for LKLockViewController interface and noticed an interesting method pinIsValid.

@interface LKLockViewController : GAITrackedViewController {
	NSNumber* AppId;
	BOOL removing;
	MBProgressHUD* hud;
	BOOL verifying;
	int yOffset;
}
@property(retain) MBProgressHUD* hud;
@property(assign) int yOffset;
@property(assign) BOOL verifying;
@property(assign) BOOL removing;
@property(retain, nonatomic) NSNumber* AppId;
-(void).cxx_destruct;
-(void)pinIsValid;
-(void)showTemporaryError:(id)error;
-(void)unpairDevice;
-(void)updateWaitingAPN:(id)apn;
-(void)didReceiveMemoryWarning;
-(void)viewDidLoad;
-(id)init;
-(id)initAsCombo;
-(id)initAsPin;
-(id)initWithNibName:(id)nibName bundle:(id)bundle;
@end

5. Invoking the pinIsValid method directly from the the cycript prompt, logged me into the app without entering the passcode.

&nbsp;&gt; [v pinIsValid]
launchkey pin bypass

 

Combination Lock Bypass

LaunchKey app allows its users to set a combination lock as an alternative to the passcode lock. Once a combo lock is set, whenever the app is relaunched it prompts the user to enter combo code to unlock. This combo lock can be  bypassed by manipulating the iOS runtime with cycript.

Steps followed to bypass the combo lock:
1. Connected to the iPhone over SSH.
2. Launched the app and noticed that it displays the combo lock.
LaunchKey combo lock
3. Attached LaunchKey process to cycript and obtained the view controller instance of currently displaying screen. 
$cycript -p LaunchKey
> UIApp.keyWindow.rootViewController.visibleViewController
> l=_
<LKComboLockViewController: 0x1e1c9680>

4. Looked at the class dump for LKComboLockViewController interface and noticed an interesting method comboDismissed.

@interface LKComboLockViewController : LKLockViewController {
	BOOL creation;
	int tries;
	UIImageView* background;
	UINavigationBar* navigationBar;
	UIImageView* lkNavLogo;
	UILabel* combinationLabel;
	UIButton* cancelButton;
	UILabel* detailsLabel;
	LKCombinationLock* combo;
}
@property(retain, nonatomic) LKCombinationLock* combo;
@property(assign, nonatomic) __weak UILabel* detailsLabel;
@property(assign, nonatomic) __weak UIButton* cancelButton;
@property(assign, nonatomic) __weak UILabel* combinationLabel;
@property(assign, nonatomic) __weak UIImageView* lkNavLogo;
@property(assign, nonatomic) __weak UINavigationBar* navigationBar;
@property(assign, nonatomic) __weak UIImageView* background;
-(void).cxx_destruct;
-(void)didReceiveMemoryWarning;
-(void)comboValid;
-(void)shakeTheView;
-(void)invalidComboTry;
-(void)invalidComboSet;
-(void)cancelButtonTouched:(id)touched;
-(void)comboDismissed;
-(void)comboUnlocked;
-(void)comboSetAndDismissed;
-(void)comboSet;
-(void)firstComboSet;
-(void)combosDoNotMatch;
-(id)initWithVerification;
-(id)initWithLocking;
-(id)initWithRemoval;
-(id)initWithCreation;
-(void)viewDidLoad;
-(id)initWithNibName:(id)nibName bundle:(id)bundle;
@end

5. Invoking the comboDismissed method directly from the the cycript prompt, logged me into the app without entering the combo lock code.

> [l comboDismissed]
launchkey combolock bypass

 

Passcode bruteforce limit bypass

When a passcode lock is set, LaunchKey app provides an option to unpair the device after 10 failed passcode attempts. The app is keeping track of the number of attempts in a variable. This bruteforce restriction can be bypassed by changing the variable value in runtime using cycript.
LaunchKey unpair after10

 

Steps followed to bypass the bruteforce limit:
1. Connected to the iPhone over SSH.
2. Turned on PIN lock and selected unpair after 10 option.
3. Closed and reopened the app. It prompted for a passcode.
4. Entered wrong passcode for 9 times.
5. Attached LaunchKey process to cycript and obtained the view controller of currently displaying screen.
$cycript -p LaunchKey
> UIApp.keyWindow.rootViewController
> n=_
> n.visibleViewController
> v=_
 <LKPinViewController: 0x1f5d5d00>
6. Looked at the class dump for LKPinViewController interface and noticed an interesting variable tries.
@interface LKPinViewController : LKLockViewController <UITextFieldDelegate> {
	NSString* pinNumber;
	BOOL creation;
	NSString* firstPin;
	int tries;
	UITextField* pinDigitOneTextField;
	UITextField* pinDigitTwoTextField;
	UITextField* pinDigitThreeTextField;
	UITextField* pinDigitFourTextField;
	UIView* pinView;
	UIImageView* background;
	UIButton* cancelButton;
	UILabel* pinLabel;
	UINavigationBar* navigationBar;
	UIImageView* lkNavLogo;
	UILabel* notMatchLabel;
	UITextField* pinField;
7. Printed the value stored in tries variable and confirmed that it is the variable keeping track of passcode failed attempts.
&gt; v.tries
 &nbsp;9
8. Changed the value to 0.
> v.tries=0
Now you can try another 9 attempts. This would allow to bruteforce the passcode without unpairing the device.


LaunchKey security team is very friendly and they fixed all the vulnerabilities within short time.  I have received 800$ in total for all the vulnerabilities as a bounty. Happy Hunting 🙂

 

Posted by on May 28, 2014 in iPhone

7 Comments

Tags: , ,

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

Disable ASLR on iOS applications

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 removePIE.zip 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. 

References:
1. http://www.peterfillmore.com/2013/01/removepie-tool-for-disabling-aslr-on.html
2. iOS 4 security evaluation white paper by Dai Zovi

 

Posted by on May 23, 2013 in iPhone

5 Comments

Tags: , , ,

Penetration testing of iPhone Applications – Part 4

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.
3. 
On Windows, download the iPhone configuration utility – Download link.
4. 
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.
2. 
On windows workstation, download Putty.
3. 
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.
5. 
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/CardInfo.app 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.

Cookies.binarycookies

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 BinaryCookieReader.py 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 & BinaryCookieReader.py.
2. 
Connect the iPhone and the workstation to the same Wi-Fi network.
3. 
Run WinScp and SSH into the iPhone by typing the iPhone IP address, root as username and alpine as password.
4. 
Navigate to the Library/Cookies folder in the application’s home directory.
5.
Copy the Cookies.binarycookies file to the windows machine by dragging it.

Cookies-Binarycookies-File

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

Python BinaryCookieReader.py [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.
3. 
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.
4. 
On the iPhone, open CardInfo application and login (works for any username and password).
5. 
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.

References:

1. Debunking NSLog Misconceptions
http://blog.gdssecurity.com/labs/2012/3/28/debunking-nslog-misconceptions.html
2. What’s in your iOS Image Cache ?
http://software-security.sans.org/blog/2011/01/14/whats-in-your-ios-image-cache-backgrounding-snapshot
3. Hacking and Securing iOS Applications by Jonathan Zdziarski

 

Posted by on April 15, 2013 in iPhone

2 Comments

Tags: , , , , , , ,