RSS
 

Posts Tagged ‘iphone application security’

Penetration testing of iPhone Applications – Part 3

07 Sep

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.

 
2 Comments

Posted in iPhone

 

Penetration testing of iPhone Applications – Part 2

20 Apr

In the first part of this article, we have discussed about the iPhone application traffic analysis. In this part, we will take a look at the privacy issues and the application local data storage.

Privacy Issues:

Every iPhone has an associated unique device Identifier derived from a set of hardware attributes called UDID. UDID is burned into the device and one cannot remove or change it. However, it can be spoofed with the help of tools like UDID Faker.

UDID of a latest iPhone is computed with the formula given below –
UDID = SHA1(Serial Number + ECID + LOWERCASE (WiFi Address) + LOWERCASE(Bluetooth Address))

UDID is exposed to application developers through an API which would allow them to access the UDID of an iPhone without requiring the device owner’s permission. The code snippet shown below is used to collect the UDID of a device, later which can used to track the user’s behavior.

NSString *uniqueIdentifier = [device uniqueIdentifier]

Current research shows that, with the help of UDID, it is possible to observe the user’s browsing patterns and trace out the user’s geo location. As it is possible to locate the user’s exact location with the help of a device UDID, it became a big privacy concern. More possible attacks are documented in Eric Smith-iPhone application privacy issues whitepaper. Eric research shows that 68% of applications silently send UDIDs to the servers on the internet. Perfect example for a serious privacy security breach is social gaming network called Openfient. Openfient collected device UDID’s and misused them by linking it to a real world user identities (like email address, geo locations latitude & longitude, Facebook profile picture) and making them available for public access, resulting in a serious privacy breach. More details about this security breach are documented at this link.

While penetration testing, observe the network traffic for UDID transmission. UDID in the network traffic indicates that the application is collecting the device identifier or might be sending it to a third party analytic companies to track the user’s behaviour. In iOS 5, Apple has deprecated the API that gives access to the UDID and probably it will remove the API completely in future iOS releases. Development best practice is to not to use the API that collects the device UDIDs as it breaches the privacy of user’s. If the developers want to keep track of the user’s behaviour, create a unique identifier specific to the application instead of using UDID. The disadvantage with the application specific identifier is that it can only identifies an installation instance of the application and it does not identify the device.

Apart from UDID, applications may transmit personal identifiable information like age, name, address and location details to third party analytic companies. Transmitting personal identifiable information to third party companies without the user’s knowledge also violates the users privacy. So, during penetration testing carefully observe the network traffic for the transmission of any important data.

Ex: Pandora application was used to transmit user’s age and zip code to a third party analytic company (doubleclick.net) in clear text. For the applications which require the user’s geo location (ex: check-in services) to serve the content, it is always recommended to use the least degree of accuracy necessary. This can be achieved with the help of accuracy constants defined in core location framework (ex: CLLocationAccuracy kCLLocationAccuracyNearestTenMeters).

In iOS 6, Apple removed the API that gives access to UDID and introduced a new advertising identifier as an alternative of UDID to track the user’s behaviour.

Local data storage:

Mobile applications store the data locally on the device to maintain essential information across the application execution or for a better performance or for an offline access. Also, developers use the local device storage to store information such as user preferences and application configurations. As device theft is becoming the increasing concern, especially in the enterprise, insecure local storage is considered to be Top 1 risk in mobile application threats. Recent survey conducted by Viaforensics revealed that 76 percent of mobile applications are storing user’s information on the device. 10 percent of them are even storing the plain text passwords on the phone.

Sensitive information stored on the iPhone can be obtained by attackers in several ways. Few of them are listed below –

  • From Backups
    When an iPhone is connected to iTunes, iTunes automatically takes a backup of everything on the device. Upon backup, sensitive files will also end up on the workstation. So an attacker who gets access to the workstation can read the sensitive information from the stored backup files.
  • Physical access to the device
    People lose their phones and phones get stolen very easily. In both the cases, attacker will get physical access to the device and read the sensitive information stored on the phone. Passcode set to the device will not protect the information as it is possible to brute force the iPhone simple passcode within 20 minutes. To know more details about iPhone passcode bypass go through the iPhone Forensics article.
  • Malware
    Leveraging a security weakness in iOS may allow an attacker to design a malware which can steal the files on the iPhone remotely. Practical attacks are demonstrated by Eric Monti in his presentation on iPhone Rootkit? There’s an App for That! .

iPhone Application directory structure:

In iOS, applications are treated as a bundle represented within a directory. The bundle groups all the application resources, binaries and other related files into a directory. In iPhone, applications are executed within a jailed environment (sandbox or seatbelt) with mobile user privileges. Unlike Android UID based segregation, iOS applications runs as one user. Apple says The sandbox is a set of fine-grained controls limiting an application’s access to files, preferences, network resources, hardware, and so on. Each application has access to the contents of its own sandbox but cannot access other applications’ sandboxes. When an application is first installed on a device, the system creates the application’s home directory, sets up some key subdirectories, and sets up the security privileges for the sandbox. A sandbox is a restricted environment that prevents applications from accessing unauthorized resources however upon iPhone JailBreak sandbox protection gets disabled.

When an application is installed on the iPhone, it creates a directory with an unique identifier under /var/mobile/Applications directory. Everything that is required for an application to execute will be contained in the created home directory. Typical iPhone application home directory structure is listed below.

File structure of iPhone applications

In iPhone, applications might store the information in any of the locations listed below.

  • Plist files
  • Keychain
  • Application’s home directory
  • Cache
  • Logs

Plist files:

Property List is a structured binary formatted file which contains the essential configuration of a bundle executable in nested key value pairs. Plist files are used to store the user preferences and the configuration information of an application. For example, Gaming applications usually store game levels and game scores in the Plist files. In general, applications store the Plist files under [Application’s Home Directory]/documents/preferences folder. Plist can either be in XML format or in binary format. As XML files are not the most efficient means of storage, most of the applications use binary formatted Plist files. Binary formatted data stored in the Plist files can be easily viewed or modified using Plist editors (ex: plutil). Plist editors convert the binary formatted data into an XML formatted data, later it can be edited easily. Plist files are primarily designed to store the user preferences & application configuration, however the applications may use Plist files to store clear text usernames, passwords and session related information. So while penetration testing view all the Plist files available under application’s home directory and look for sensitive information like usernames, passwords, user’s personal information and session cookies, etc… Developers can assign any extension to the Plist files. A Plist file can be easily identified by looking at the file contents using cat command. The content of a Plist file starts with bplist’.

Along with the sensitive information storage, application may also take authentication & authorization decisions based on the values stored in Plist files. For example, if you notice a Plist entry like admin=0 during penetration testing, change the admin key value to 1 and open the application. If the application does not validate the user input properly and takes the authorization decision based on the Plist entry, you may log into the application as an administrator. Development best practice is to not to store any sensitive information in Plist files. Also do not take authentication & authorization decisions based on the information stored in Plist files. Plist files contain user controlled input and it should be validated properly like any other user input.

WordPress iPhone application used to store clear text username and password in a Plist file. The video below here demonstrates the WordPress vulnerability. This vulnerability was reported by SANS and WordPress fixed it immediately.

Plist files can be viewed and modified easily on both the JailBroken and non JailBroken iPhones. The examples listed below illustrate the various ways of editing Plist files on the both JailBroken and non JailBroken devices.

Tampering Plist files on a non JailBroken iPhone: 

On a non JailBroken iPhone, Plist files can be viewed & modified using tools like iExplorer and iBackupBot.

Modifying Plist entries with iExplorer
iExplorer (formerly iPhone Explorer) gives access to the iPhone in disk mode and allows browsing all the folders on the iPhone directly.

Stick Cricket iPhone game is used for the demo.

iPhone stick cricket game

Stick Cricket iPhone game stores the game score in a Plist file under application’s home directory. As the application is storing the game score locally in a Plist file, it can be altered by editing the Plist file.

Screenshot shown below displays the actual score before the Plist modification.

 StickCriket actual score before hacking the score

Steps shown below will demonstrate the usage of iExplorer tool to modify the game scores stored in the Plist file –

1. On your workstation download and install iExplorer.
2. Connect the iPhone to the workstation over USB.
3. In iExplorer, browse to Apps->com.sticksports.stickcricket folder.

iExplorer - Browse files on iPhone over USB

4. Navigate to stick cricket Library->Preferences folder.

 iExplorer - Explore iPhone over USB

5. Copy com.sticksports.stickcricket.Plist file to the workstation by dragging it to the desktop.
6. On the workstation open the Plist file using a Plist editor and modify the yourBest5Overs key value.

 iPhone stickcricket plist

For this demo, I have modified the value to 180 from 30 and saved the Plist file.

Modify iPhone game scores - changing stickcricket score in plist

7. From iExplorer, delete the com.sticksports.stickcricket.Plist on the iPhone and drag the newly saved file onto the iPhone.
8. In iPhone, terminate the Stick Cricket application and reopen it.  The Stick Cricket welcome screen now displays the modified score as shown in the screenshot below.

iPhone hack - modify stick cricket score

StrickCriket game score video is available at – Hacking iPhone Game Scores

Modifying Plist entries with iBackupBot
When the iPhone is connected to a computer, iTunes take a backup of everything on the phone including configuration files (Plist files). iBackupBot tool can be used to view and modify the Plist file entries on the iPhone backup and restore the modified backup onto the iPhone..

Steps shown below will demonstrate the use of iBackupBot tool to modify the game scores stored in the Plist file –

1. Connect the iPhone to the workstation over USB cable.
2. On Workstation, open iTunes and take a backup of the iPhone.
3. Close iTunes.
4. Open iBackupBot. It automatically identifies the existing backups and displays the files inside the backup to the user.
5. Click on Stick Cricket and open /Library/Preferences/com.sticksports.stickcricket.Plist file.

ibackupbot to read plist files from backups

6. Modify the score stored in the Plist file.
7. Click on Export icon to save the modified Plist file.
8. Click the restore icon in iBackupBot toolbar. It will restore the iPhone with the modified backup. Now on iPhone, reopening the Stick Cricket game will display the modified score.

Tampering Plist Files on a JailBroken iPhone:

On a JailBroken iPhone, Plist files can be viewed & modified using tools like plutil and iFile. Both these tools can be downloaded from Cydia (packages – com.eric.tool & iFile). iFile would allow to modify the Plist files directly on the iPhone.

The iPhone camera application is used for the demo. In iOS camera application, Apple has hidden the panorama mode feature and planned to include this feature in future iOS versions. Panorama mode basically allows the users to take continuous photos while panning the camera from left to right. Apple stored the panorama mode switch in a Plist file. iOS hackers Conard & Chpwn exposed the panorama mode in iOS 5 by modifying an entry in com.apple.mobileslideshow.Plist file.

Screenshot shown below displays the list of options available in the iPhone camera application.

iPhone camera toggle to turn off panorama

Steps shown below will demonstrate the usage of plutil tool to change the panorama switch stored in the Plist file –

1. SSH to the iPhone and login as a root user (password: alpine).
2. Navigate to /private/var/mobile/Library/Preferences/ directory.
3. View com.apple.mobileslideshow.Plist file content with the help of plutil tool.

> Plutil com.apple.mobileslideshow.plist

4. Add ‘EnableFirebreak’ key to the com.apple.mobileslideshow.plist file with the below command.

> Plutil –key EnableFirebreak –value yes com.apple.mobileslideshow.plist

 

iPhone modified Plist

5. It turns on the panorama feature in the iPhone camera application.

Screenshot below shows different options available in the iPhone camera after the modification-

 

Enable iPhone panorama

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

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

 
5 Comments

Posted in iPhone

 

Penetration testing of iPhone Applications – Part 1

12 Feb

This article focuses specifically on the techniques and tools that will help security professionals understand penetration testing methods for iPhone applications. It attempts to cover the entire application penetration testing methodology on a physical device (running with iOS 5) rather than a simulator.

Background:

Since the introduction of the iPhone, Apple has sold more than 110 million iPhones. The smartphone platform has created a new business and companies want to make their services available on mobile devices in order to reach out to the users very quickly and easily. As the iPhone has enough power and performance to do just about most of the stuff you can do on a  laptop, iPhone applications span a range of categories from education and productivity to games and entertainment.

iPhone provides developers with a platform to develop three types of applications.

  1. Web based applications – which uses JavaScript, CSS and HTML-5 technologies
  2. Native iOS applications- which are developed using Objective-C and Cocoa touch API
  3. Hybrid applications – Native applications with embedded web view

This article mainly covers the pen testing methodology of native iOS applications. However, some of the techniques explained here can also be used with web-based iOS applications.

Application Distribution model:

iOS developers use Apple Xcode developer tools and test their applications within the iOS simulator.  A simulator simulates an environment but it does not mimic many of the features and functionalities available on real devices. An iOS simulator compiles iOS applications to a local native code which is different from the Android emulator that compiles to ARM instructions. Though simulators allow basic development and testing, it is not sufficient for many applications which require the use of full hardware power, performance and features which are only available on real devices. To test these types of applications on real devices, developers have to subscribe to Apple’s iOS Developer Program because the iPhone is only allowed to run Apple signed applications. Mandatory Code Signing mechanism implemented in iOS requires that all the native code running on the device should be signed by a known or trusted certificate. Upon subscription to the iOS Developers Program, Apple issues a signed provisioning profile that configures the iOS device to permit the execution of code signed by a developer certificate. Developers can apply for this program as an individual, company or university.

Based on the provisioning profile, application distribution models are categorized as 5 types.

Single device distribution:
Development provisioning profiles issued by Apple are tied to a device’s UDID (Unique Device ID).  This provisioning profile allows running a developer’s application on the device.  As it is tied to a particular device, the provisioning profile does not work on other devices. This model is used during single device testing.

Ad Hoc distribution:
Ad Hoc provisioning profiles issued by Apple are tied to the UDID’s of up to 100 other devices, including the iPad, iPhone or iPod touch.  The developer has to supply the UDID of 100 devices during the subscription process. This model allows developers to test their application on a wide range of devices.

In-house distribution:
Enterprise provisioning profiles issued by Apple permit the installation of applications on devices without configuring their UDIDs. This distribution is generally used by enterprises to distribute applications internally to their employees.

Over the air (OTA) distribution:
This model is designed to allow enterprise developers to send applications to individual users in their organization through e-mail or by hosting the application on a web server. The main problem with this kind of distribution is if someone outside the organization gets access to the link then they too can also install the application.

App Store distribution:
This is a centralized mechanism for distributing Apple signed applications. Upon submitting the application to Apple, Apple verifies it against the App Store review guidelines and approves it if the application follows all the review guidelines. After the approval, Apple will re-sign the application with an Apple signing certificate and make it available for download in the App Store.

Penetration Testing

In this section we are going to focus on iOS applications rather than the iPhone operating system itself. Actually there is an overlap between the iPhone OS security and the iPhone application security. So understanding the iOS platform and its security technology will help penetration testers properly assess the security of iPhone applications.

The main areas of focus while assessing the security of iPhone applications are –

  • Application traffic analysis
  • Privacy Issues
  • Local Data Storage
  • Caching
  • Reverse Engineering
  • Unmanaged code
  • URL Schemes
  • Push Notifications

 

Setup:

A simulator does not provide the actual device environment, so all the penetration testing techniques explained in this article are specific to a physical device. iPhone 4 with iOS 5 will be used for the following demonstrations.

To perform pentesting we need to install a few tools on our device. These tools are not approved by Apple. Code signing restrictions in iOS do not allow us to install the required tools on the device. To bypass the code signing restrictions and run our tools we have to JailBreak the iPhone. JailBreaking gives us full access to the device and allows us to run code which is not signed by Apple.  After JailBreaking, the required unsigned applications can be downloaded from Cydia.

Cydia is a parallel App Store for unsigned applications. JailBreaking puts your phone at great risk to some security vulnerabilities because the device allows any application to run even if it is not approved by Apple. Though we can assess the security of an application on a non-JailBroken iPhone, it is not possible to give complete coverage. JailBreaking makes the pen tester’s work easier and helps to provide full coverage of an application.

Tools like Pwnage, readsn0w and greenposi0n can be used to JailBreak the iPhone.

Tools required for pentesting:

From Cydia, download and install the applications listed below.

  • OpenSSH – Allows us to connect to the iPhone remotely over SSH
  • Adv-cmds : Comes with a set of process commands like ps, kill, finger…
  • Sqlite3 : Sqlite database client
  • GNU Debugger: For run time analysis & reverse engineering
  • Syslogd : To view iPhone logs
  • Veency: Allows to view the phone on the workstation with the help of veency client
  • Tcpdump: To capture network traffic on phone
  • com.ericasadun.utlities: plutil to view property list files
  • Grep: For searching
  • Odcctools: otool – object file displaying tool
  • Crackulous: Decrypt iPhone apps
  • Hackulous: To install decrypted apps

iPhone does not give us a terminal to see inside directories. Upon OpenSSH installation on the device, we can connect to the SSH server on the phone from any SSH client (ex:Putty, CyberDuck, WinScp). This gives us flexibility to browse through folders and execute commands on the iPhone.  An iPhone has two users by default. One is mobile and the other is a root user. All the applications installed on the phone run with mobile user privileges. But using SSH we can log into the iPhone as a root user, which will give us full access to the device. The default password for both the user accounts (root, mobile) is alpine.

Note: Best practice is to change the default SSH passwords of your device.

If your phone and the workstation are connected to Wi-Fi, you can directly SSH to the iPhone by typing in the IP address and username/password.

SSH to iPhone over Wi-Fi-

ssh root@iPhoneIP
password: alpine

If your phone and the workstation are not on Wi-Fi, you can still do SSH via the USB cable with the help of an iPhone tunnel (which can be downloaded from – http://code.google.com/p/iphonetunnel-usbmuxconnectbyport/).

SSH to iPhone over USB cable –

./iphone_tunnel -lport 2222
ssh -p 2222 root@127.0.0.1
password : alpine

Once we have a SSH connection, we can run commands directly on the iPhone. As iOS is a trimmed version of Mac OS , many of the MAC OS commands will work on the iPhone.

Application traffic analysis 

Pen testing iPhone applications isn’t all that different because client-side applications still interact with the server-side components over a network using some protocols. So it also involves network pentesting and web application pentesting.  The primary goal in traffic analysis is to capture and analyze the network traffic to find vulnerabilities.

iPhone applications may transmit data to the server in any of these communication mechanisms:

  • Clear text transmission, such as http
  • Encrypted channel, such as https
  • Custom protocols or Low level streams

It’s 2012 and applications are still using clear text transmission protocols like http.  In general, mobile applications are more prone to MITM attacks because most people access them over WIFI. An attacker who has access to the same Wi-Fi can run tools like FireSheep and hijack user sessions. As plain text transport protocols are vulnerable to MITM attacks, applications which transmit sensitive data must use encrypted communication protocols like https.  During pen testing, observe whether the application is transmitting any sensitive data over the encrypted channel or not. Application traffic can be captured by configuring the proxy settings available in iPhone. Upon setting up a proxy, the iPhone routes its traffic through the configured proxy.

Configuring Proxy

The screenshots below illustrates the required settings in an iPhone workstation (IP-192.168.1.4) required to capture http application traffic.

1. Navigate to the Settings application

iPhone settings menu

2.Turn on Wi-Fi

iPhone-Turn on Wi-Fi

3. Choose a network and click on the blue arrow corresponding to it

View iPhone ip address

4. Choose ‘Manual’ and setup a proxy IP (ex: 192.168.1.4)

Proxy settings in iPhone

5. On your workstation, Open Burp Suite and navigate to Proxy->Options,
Edit proxy listeners – enter ‘port’ as 8080, disable ‘loopback only’ and select ‘support invisible’

Burp proxy to MITM iPhone applications

6. Now browsing any http website or http application in iPhone routes the traffic to your workstation and will display in Burp Suite.

Note: Charles proxy is also used instead of burp proxy.

The same proxy settings also work for https traffic as well. But capturing iPhone application https traffic is little tricky. In SSL communication, browser based applications automatically validate the server-side certificate; whereas in native iOS applications, the developer has to explicitly write the code to validate server certificates.  Coding mistakes at this point may lead the application to accept any server certificate. When an application fails to validate the server certificate, attackers can use any fake certificate and perform MITM attacks.

One common mistake that we see in iPhone application development is the use of allowanyhttpscertificateforhost (NSURLRequest) or continueWithoutCredentialForAuthenticationChallenge (NSURLConnection) function call. Applications which implement these functions accept any certificate even if it is not issued by the original server. Also the application users do not even get a certificate warning. While pentesting, check whether the application is validating the certificates properly or not. If the application validates server-side certificates properly, then it will display a certificate error message when it receives an invalid certificate. It also does not allow the user to use that application or proceed further with the invalid certificate.

To capture the SSL traffic of these applications during pen testing, first we have to add a proxy CA certificate to the iPhone trusted certificates list. Later if the application receives a proxy certificate it will not display any certificate error because we told our iPhone to trust that certificate.  This will allow us to capture the https traffic. The same technique is applicable to other protocols which work on certificates.

The video below demonstrates the MITM https application traffic.

Apart from http and https protocols iPhone applications may also use custom protocols or low level socket communication APIs (NSStreams, CFStreams). The MITM techniques explained above would not work to capture the network traffic of these applications. In order to capture the low level traffic of these applications download and install tcpdump from Cydia on iPhone. Upon installation of tcpdump, connect the iPhone over SSH and run the commands below to capture traffic and write it into a .pcap file.

ssh root@iphone-IP
password: alpine
tcpdump -w traffic.pcap

Connect to the phone using a GUI SSH client like Cyberduck. Browse to the folders and copy the recently created .pcap file to your workstation. Next, open the .pcap file using a traffic capture tool like Wireshark. Use your protocol analyzing skills and identify the custom protocol. The same techniques can be used for the applications which do not respect the iPhone proxy settings. In these cases, DNS spoofing techniques can be used to perform MITM and for traffic capture.

Once you capture the traffic, typical web application pen testing attacks are done on the application server. Now you can look for SQL injection, authentication, authorization, session management, cryptography weaknesses and many more web related vulnerabilities.

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

Part 2 : privacy issues and local data storage.
Part 3 keychain data storage and error log analysis.
Part 4Analysis of the  files stored in the application home directory, caching issues and error log analysis.
Part 5runtime analysis of iOS Applications.