0% found this document useful (0 votes)
52 views13 pages

GreHack-2012-Paper-Mathieu Renard - Practical IOS Apps Hacking

The document discusses techniques for attacking iOS applications without jailbreaking a device. It describes using the Apple File Communication protocol and backups to retrieve application data. It also covers monitoring communication and extracting keychain data to retrieve credentials.

Uploaded by

Sheet Abdullah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views13 pages

GreHack-2012-Paper-Mathieu Renard - Practical IOS Apps Hacking

The document discusses techniques for attacking iOS applications without jailbreaking a device. It describes using the Apple File Communication protocol and backups to retrieve application data. It also covers monitoring communication and extracting keychain data to retrieve credentials.

Uploaded by

Sheet Abdullah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Mathieu Renard/ Practical iOS Apps hacking GreHack 2012, Grenoble, France

3 Accepted Papers
3.1 Mathieu Renard/ Practical iOS Apps hacking
3.1.1 Mathieu Renard
@GoToHack Mathieu Renard “GoToHack” is a Senior Penetration tester, working for a French company
(SOGETI-ESEC) where is leading the penetration test team. His research areas focus in Web Application
Security, Embedded Systems, Hardware hacking and recently Mobile device Security. Since last year, he has
focused is work (security assessments) and his research on professional iOS applications and their supporting
architecture where data security is paramount.
twitter: @GoToHack

3.1.2 Practical iOS Apps hacking


This talk demonstrates how professional applications like, Mobile Device Management (MDM) Client, Con-
fidential contents manager (Sandbox), professional media players and other applications handling sensitive
data are attacked and sometimes easily breached. This talk is designed to demonstrate many of the techniques
attackers use to manipulate iOS applications in order to extract confidential data from the device. In this talk,
the audience will see examples of the worst practices we are dealing with every day when pentesting iOS
applications and learn how to mitigate the risks and avoid common mistakes that leave applications exposed.
Attendees will gain a basic understanding of how these attacks are executed, and many examples and demon-
strations of how to code more securely in ways that won’t leave applications exposed to such attacks. This
talk will focus especially on the following features:
Secure Data Storage Secure Password Storage Secure communication Jailbreak detection Defensive
tricks

• Talk and paper can be downloaded from http://grehack.org

14 / 61 GreHack
Mathieu Renard/ Practical iOS Apps hacking GreHack 2012, Grenoble, France

Practical iOS Apps hacking


Can we trust vendors to secure our data?

Mathieu RENARD
Sogeti ESEC / GotoHack.org
Paris, FRANCE
mathieu.renard[-AT-]gotohack.org

This paper demonstrates how professional applications like, that can allow retrieving confidential information stored by
Mobile Device Management (MDM) Client, Confidential contents miss implemented iOS application.
manager (Sandbox), professional media players and other
applications handling sensitive data are attacked and sometimes 1) Using afc protocol to retrieve data stored on the device
easily breached. Apple File Communication Protocol (AFC) is a serial
Readers will gain a basic understanding of how these attacks are port protocol that uses a framework called
executed, and many examples of how to code more securely in MobileDevice that is installed by default with iTunes.
ways that will not leave applications exposed to such attacks. Since 2010 this protocol is implemented in the
libimobiledevice[8] open-sources project. The protocol
uses the USB Port and cable when it is connected to the
I. INTRODUCTION computer and is responsible for things such as copying
Gone are the days when employees only used a company- music and photos and installing firmware upgrades.
issued phone for work related matters. Today, employees AFC Clients like iTunes are allowed access to a
bring personal smart phones and tablets to the office and often “jailed” or limited area of the device memory.
have access to sensitive company information on these Actually, AFC clients can only access to certain files,
devices. namely those located in the Media and User installed
applications folders. In other words, using AFC client a
This paper is the result of one-year pentesting iOS application user/attacker can download the application resources
and is designed to demonstrate many of the techniques and data. Including the default preferences file where
attackers use to manipulate iOS applications in order to extract sometimes credentials are stored. The only requirement
confidential data from the device. is the device has to be unlocked. But this is definitively
not a problem because an evil maid cans backdoor any
Then, Jailbreak detection features are analyzed before
iDevice Dock Station.
discussing the results of tests launched on professional
applications like, Mobile Device Management (MDM) Client,
Confidential contents manager (Sandbox), professional media
players and other applications handling sensitive data.
Finally the author proposes mitigation techniques to
implement in order to avoid common mistakes that leave
applications exposed.

II. ATTACKING IOS APPLICATIONS


Most of the time attacking iOS application is synonym to
jailbreak an iDevice, decrypt the application and reverse the
binaries. Before developing these items there is some
interesting points to linger on, especially on regular devices.

A. What attackers can do without jailbreaking the device


Without having access to the file system it is impossible de
decrypt and reverse iOS applications installed from Apple Figure 1 iPown Dock: Malicious dock station.
App Store. Nevertheless, this section present attacks vectors

15 / 61 GreHack
Mathieu Renard/ Practical iOS Apps hacking GreHack 2012, Grenoble, France

2) Retrieving data from backups TABLE III. PROTECTION CLASSES FOR BUILT IN ITEM
The main function of the backup is to permit user to Application & Item type Protection class
restore personal data and settings to an iPhone during a WiFi Password Always
Restore (during which the content on the iPhone is IMAP/POP/SMTP accounts AfterFirstUnlock
typically erased). Exchange Accounts Always
VPN Always
When the iPhone is connected to a computer and LDAP/CalDAV/CardDAV Accounts Always
synced with iTunes, iTunes automatically creates a iTunes backup password WhenUnlocked
folder with device UDID (Unique device ID – 40 ThisDeviceOnly
hexadecimal characters long) as the name and copies Device Certificate & private Key AlwaysThisDeviceOnly
the device contents to the newly created folder. Most of
the time this process is automatic. If the automatic sync Using the iphonedataprotection[1] tools developed by
option is turned off in iTunes, the user has to manually Jean-Baptiste Bédrune and Jean Sigwald of Sogeti
initiate the backup process through the iTune interface. ESEC, it is possible to extract all data stored in the
keychain. Nonetheless, only data stored without the
TABLE I. BACKUPS FILE PATH ThisDeviceOnly protection class can be extracted
System Backup Path without requiring any jailbreak.
Windows 7 C:\Users\(username)\AppData\Roaming\Apple
Computer\MobileSync\Backup\ Notice: Extracting data stored with the ThisDeviceOnly
Mac OSX /Users/(username)/Library/Application protection class require to previously extracting the
Support/MobileSync/Backup/
0x835 key the attack is detailed in the next section.
Since the sync option is defined on the computer side, 3) Monitoring communication
no user interaction except unlocking the device is Monitoring communication can highlights lack of
required. This implementation allows malicious dock encryption allowing unsecured credential gathering.
station to initiate backups without user authorization. Starting iOS 5, apple added a remote virtual interface
Performing such attack an attacker may retrieve (RVI) facility that allows capturing traces from an iOS
personal and confidential data like copies of SMS, Call device. On Mac OSX the virtual interface can be
Logs, application data, default preferences and data enabled with the rvictl command.
stored in the keychain.

Keychain class keys define whether a keychain item $ rvictl -s


can be migrated to other device or not. List of 454b673c547582234decef5ef3abce6765506af45
protection classes available for the keychain items are Starting device
shown in the table bellow. 454b673c547582234decef5ef3abce6765506af45
[SUCCEEDED]

TABLE II. KEYCHAIN CLASS KEYS $ # network interface, rvi0, added by the
previous command.
Protection class Description $ ifconfig -l
Keychain item is accessible lo0 gif0 stf0 en0 en1 p2p0 fw0 ppp0 utun0 rvi0
kSecAttrAccessibleWhenUnlocked only after the device is
$ sudo tcpdump -i rvi0 -n
unlocked listening on rvi0, link-type RAW (Raw IP),
Keychain item is accessible capture size 65535 bytes
kSecAttrAccessibleAfterFirstUnlock only after the first unlock of …
the device to till reboot
Keychain item is accessible
kSecAttrAccessibleAlways Figure 2 Enabling iOS virtual interface on OSX.
even the device is locked
Keychain item is accessible
only after the device is
kSecAttrAccessibleWhenUnlocked On other system this can be done using the
unlocked and the item
ThisDeviceOnly
cannot be migrated between com.apple.pcapd service through the usbmux[8]
devices deamon.
Keychain item is accessible
kSecAttrAccessibleAfterFirstUnlock after the first unlock of the
ThisDeviceOnly device and the item cannot 4) Attacking secure communications to servers
be migrated Almost every application handling sensitive data will
Keychain item is accessible connect back to some server component. Developers
kSecAttrAccessibleAlways even the device is locked are, thus, faced with the challenge of having to protect
ThisDeviceOnly and the item cannot be
migrated sensitive data in transit as it traverses the Internet and
sometimes even insecure wireless media. This can be
done using encryption but must be implemented
correctly.

16 / 61 GreHack
Mathieu Renard/ Practical iOS Apps hacking GreHack 2012, Grenoble, France

This is why, developers must take care when using the Running critical application on a jailbroken device may
URL loading library. According to the security best allow attackers to retrieve data such as encryption keys
practices, the default state of operation for the URL and credentials even when stored in the Keychain.
loading library is to fail on an invalid server certificate. In the iPhoneDataProtection framework, Jean-Baptiste
However, during development it is often required to Bédrune and Jean Sigwald implemented a tool named
use an invalid certificate. Failure to use the libraries “KeychainViewer”[1] allowing browsing the keychain
properly can result in weak client to server content by directly accessing the keychain database.
communications that attackers may compromise by
setting a transparent proxy (for example on a fake Wi-
Fi access point). This is why, it is really important to
check this point before production launch.

Nevertheless, the default SSL Warning message can be


bypassed by installing a fake certificate authority in the
apple certificate store. On a regular device, this cannot
be done without user interaction. However, prior iOS6,
SMS applications only displayed the reply-to field.
This allows attackers to send fake configuration
message spoofing the reply-to field [28].

B. Installing the application on a jailbroken device


Apple designed the iPhone platform with the intent to control
all software that is executed on the device. Thus, the design
does not intend to give full system (or root) access to a user.
Moreover, only signed binaries can be executed. In others
words, the loader will not execute either unsigned binaries or
signed binary without a valid signature from Apple. This Figure 3 Browsing Keychain with KechainViewer.
ensures that only unmodified Apple-approved applications are
2) Retrieving the 0x835 Key
executed on the device.
Browsing the keychain content on a jailbroken is not
really difficult. On the opposite, extracting all data
The term jailbreaking refers to a technique where a flaw in the
including data stored within the ThisDeviceOnly
iOS operating system is exploited to unlock the device,
protection class form a backup require extracting the
thereby obtaining system-level (root) access. With such
0x835 key. The 0x835 key is generated by encrypting
elevated privileges, it is possible to modify the system loader
01010101010101010101010101010101 with the UID-
so that it accepts any signed binary, even if the signature is not
key (Hardware key). Hardware keys can only be
from Apple. In others words, the loader will accept to launch
accessed from kernel. Therefore, IOAESAccelerator
every signed binaries even if it is not signed with Apple
kernel service has to be patched in order to allow keys
certificate.
access from user land.
1) Retrieving user password & keychain content
Jailbreaking also allows malicious user to retrieve The iPhoneDataProtection framework embeds tools
application and data stored on the device. When a device allowing patching the kernel and retrieving the 0x835
is Jailbroken, the confidentiality of the data and key.
information returned by the systems call cannot be
trusted.
Moreover, jailbreaking allows users to install an SSH
service, which is often left in a de facto unsecure state.
Remember: Worm:iPhoneOS/Ikee the first worm which
was targeting the Apple Jailbroken iPhone: Figure 4 Patching IOESAccelerator.
‐ The first version most notable action involved
changing the background wallpaper on the
device.
‐ The second version the worm was accessing
user's computing device and changing their data
without permission.

17 / 61 GreHack
Mathieu Renard/ Practical iOS Apps hacking GreHack 2012, Grenoble, France

C. Reversing Objective-C Binaries Fortunately (from the auditor point of view), Stefan
iOS executables are ARM binaries and use the Mach-O binary Esser Aka i0nic, published a tool called:
file format. dumpdecrypted[3] producing a decrypted version of the
application to analyze when loaded with. Nevertheless,
1) Faiplay encryption in order to limit iOS application cracking, the tool does
The primary obstacle to overcome in reversing iOS not unset the cryptic after decryption. Which mean, that
binaries from the App Store is that all published the flag has do be unset manually after decryption. Since
applications are encrypted using Apple's binary this step is not mandatory for a security analysis it will
encryption scheme. When an application is synchronized not be discussed here.
onto the iDevice, iTunes extracts the application folder
from the archive (bundle) and stores it on the device. 2) Objective-C & Objc_msgSend
Furthermore, the decryption key for the application is Objective-C is the most prevalent programming language
added to the device’s secure keychain. This is required used to create applications for the iOS platform. In
because the application binaries are stored in encrypted Objective-C methods are not called but instead a so-
form (When an application is encrypted the cryptid is set called message is sent to a receiver object. These
to 1). messages are handled by the dynamic dispatch routine
called objc_msgSend.
Here the benefit of jailbreaking is that the user obtains
immediate access to many development tools ready to be This dispatch routine is responsible for identifying and
installed on iOS, such as: debugger and disassembler. invoking the implementation for the method that
corresponds to a message. The first argument is always a
This makes the decryption step quite straightforward: pointer to the called object. That is, the object on which
‐ The application is launched in the debugger. the method should get invoked (for example, an instance
‐ A breakpoint is set to the program entry point. of the class NSString). The second argument is a called
Once this breakpoint triggers, the attacker knows selector. The selector is a string representation of the
that the system loader has verrified the signature name of the method that should get invoked (for example
and performed the decryption. length). All remaining arguments are passed to the target
‐ The memory region that contains the now method once it is resolved.
decrypted code is dumped. To perform this resolution, the obj_msgSend function
‐ The binary encrypted part is replaced by the walks the class hierarchy starting at the receiver and
dumped one. searches for a method whose name corresponds to the
‐ The CryptID is redefined to 0. selector. If no match is found in the receiver class, its
superclasses are searched recursively. Once the
Tools like Crackulous[2] are making this task easier corresponding method is identified, objc_msgSend
since they allow decrypting / cracking iOS application in invokes the method and passes along the necessary
one click. Unfortunately Crackulous v1.0.0.5 does not arguments.
handle the decryption of thin binary (Binary file
compiled for one processor architecture only). 3) Retreiving classes headers
Since many applications for iOS are developed in
Objective-C, the Mach-O format supports specific
sections, organized in so-called commands, to store
additional meta-data about Objective-C programs.

The __objc_classlist section contains a list of all classes


for which there is an implementation in the binary. The
__objc_classref section, on the other hand, contains
references to all classes that are used by the application
including imported classes. It is the responsibility of the
dynamic linker to resolve the references in this section
when loading the corresponding library. Others sections
include information about categories, selectors, or
protocols used or referenced by the application.
Apple has been developing the Objective-C runtime as
an open-source project. Thus, the specific memory layout
Figure 5 Cracking application with crackulous. of the involved data structures can be found in the header
files of the Objective-C runtime.

18 / 61 GreHack
Mathieu Renard/ Practical iOS Apps hacking GreHack 2012, Grenoble, France

One can rebuilt basic information about the implemented 1) Introducing Mobile substrate
classes traversing these structures in the binary. Using MobileSubstrate[6] is a framework that allows
“class-dump”, the commercial version of IDA pro developers to provide run-time patches
(starting 6.2) or using the IDA plugins like (“MobileSubstrate extensions”) to system functions.
zynamics/objc-helper-plugin-ida[11] within the IDA free MobileSubstrate can easily install on jailbroken device
version it is trivial to retrieve these information. through Cydia[6]. The framework consists of three major
components:
‐ MobileHooker is used to replace system functions.
‐ MobileLoader is used to automatically load
Mobilesubstrate extension at application launch.
MobileLoader will first load itself into the run
application using DYLD_INSERT_LIBRARIES
environment variable. Then it looks for all
dynamic libraries in the directory
/Library/MobileSubstrate/DynamicLibraries/, and
dlopen them.
‐ Safe Mode: When a extension crashed the
Figure 6 Analyzing iOS binarie with classdump.
SpringBoard, MobileLoader will catch that and
put the device into safe mode menaing that all 3rd-
4) Where to start ? party extensions will be disabled.
To start the analysis in the right way we have to locate
the main class. The UIApplicationDelegate protocol In order to define a hook the developer can use two
declares methods that are implemented by the delegate of functions:
a UIApplication object. These methods provide ‐ MSHookMessageEx() will replace the
information about key events in an application’s implementation of the Objective-C message
execution such as when it finished launching, when it is by replacement, and return the original
about to be terminated, when memory is low, and when implementation. This dynamic replacement is in
important changes occur. Finding one of the following fact a feature of Objective-C, and can be done
methods: ApplicationDidFinishLaunching, using method_setImplementation.
ApplicationDidFinishLaunchingWithOptions, ‐ MSHookFunction() is like MSHookMessageEx()
Application*… is a good way to find out which view is but is for C/C++ functions. Conceptually,
launched first. MSHookFunction() will write instructions at
assembly level that jumps to the replacement
Regarding the views initialization, The function, and allocate some bytes on a custom
UIViewController class provides specific methods that memory location, which has the original cut-out
are called when specific events occur. When trying to instructions and a jump to the rest of the hooked
follow the execution patch the main event to focus our function. Since on the iPhoneOS by default a
intention is viewDidLoad that is called after views memory page cannot be simultaneously writable
initialization. and executable, a kernel patch is applied for
MSHookFunction() to work.
5) Where to look ?
The list of points to focus on when reversing iOS Using this Framework attacker can easily trace and
Application is related to the features of the application to dynamically patch the application at runtime. Here is an
be analyzed. Here is a list of object that may have an example of jailbreak detection bypass:
interest regarding security matters.

TABLE IV. INTERESTING OBJECTS, CLASSES & METHODS static int (*old_system)(char *) = NULL;
int st_system(char * cmd){
Use case Objects / Classes / Methods if (!cmd){
URL Handling NSURL* return nil;
Socket Handling CFSocket* }
return old_system(cmd);
Keychain ksecAttr*, SecKeychain* }
Files Handling NSFileManager* __attribute__((constructor)) static void
Crypto CCCrypt* initialize() {
MSHookFunction(system, st_system,&old_system);
}
D. Dynamic analysis
There are many different approaches to dynamic analysis. In
Figure 7 Bypassing Jailbreak detection.
this section we will focus on the MobileSubstrate[6]
framework.

19 / 61 GreHack
Mathieu Renard/ Practical iOS Apps hacking GreHack 2012, Grenoble, France

2) Attacking network communication Launching a simple “strings” on the application binary can
Hooking the NSURLConnection and setting a proxy on highlight this test. Nonetheless, sometimes developers use
the device it is possible to silently still the credentials and dynamic string generation and obfuscation tricks in order hide
all the data exchanged with the server even when checked files. Anyway, this test can be bypassed by hooking
transmitted through HTTPS. NSFileManager methods.

iOS SSL Kill Switch[5] is a MobileSubstrate[6] extension


B. Checking if system partition is writable
developed by iSECPartners. This extension allows
disabling certificate validation in order to facilitate black On a regular device the system partition is mounted with the
box testing of iOS Apps. Once installed on a jailbroken read only attribute. After jailbreaking a device with the public
device, the extension patches NSURLConnection to jailbreak tool Absinthe [4], the system partition remains
override and disable the system's default certificate writable. This changes are made by replacing the /etc/fstab file.
validation. The file is commonly 80 bytes for all iOS version, whereas the
copy of the file installed by the public jailbreak tool: Absinthe
3) Stealing cryptos keys is only 65 bytes.
Hooking the CCCrypt(3cc) API it is possible to silently
still the crypto keys used on native iOS application. This
+ (BOOL)doFstabSize {
CCCrypt(3cc) API provides access to a number of struct stat sb;
symmetric encryption algorithms. Most of the time the stat("/etc/fstab", &sb);
long long size = sb.st_size;
application are directly calling the CCCrypt() function. if (size == 80){
CCCrypt() is a stateless, one-shot encrypt or decrypt return NO;
return YES;
operation. }

CCCrypt(CCOperation op, CCAlgorithm alg, Figure 10 Checking /etc/fstab size.


CCOptions options, const void *key,
size_t keyLength, const void *iv, This test can easily be bypassed by hooking the stat system call
const void *dataIn, size_t dataInLength,
void *dataOut, size_t dataOutAvailable, within a mobile substrate extension.
size_t *dataOutMoved);

C. Checking for shell


Figure 8 CCCrypt API definition. By default no shell is available on regular device but it comes
with the public jailbreak. This is why this test aims to detect if
III. JAILBREAK DETECTION FEATURES [THE TRUTH]
a shell is available on the device by calling system(0). If the
Jailbreak detection features are implanted in order to detect value of command is NULL, system() returns nonzero if the
when an end user has compromised their device, or to detect shell is available, and zero if not.
whether an intruder has compromised a stolen device. For
example, all MDM application embeds jailbreak detection
features. + (BOOL)doShell {
if (system(0)) {
return YES;
The following sections present common and uncommon }
return NO;
jailbreak detection features highlighted during one year }
studying iOS application security.

Figure 11 Checking /etc/fstab size.


A. Checking for jailbreak files
This test can easily be bypassed with a mobile substrate
This is the most common check performed on the application
extension (See Figure 7).
we analyzed. Usually applications are checking for files like:
“/Applications/Cydia.app”, “/bin/apt”,“/usr/sbin/sshd”…

+ (BOOL)doCydia {
if ([[NSFileManager defaultManager]
fileExistsAtPath: @"/Applications/Cydia.app"]){
return YES;
}
return NO;
}

Figure 9 Checking for jailbreak files.

20 / 61 GreHack
Mathieu Renard/ Practical iOS Apps hacking GreHack 2012, Grenoble, France

D. Checking for signer identity (Another common test) IV. REAL WORLD APPS & SECURITY WORST PRACTICES
Most of the applications cracked with “Crackulous” [2] come This section present the worst practices highlighted during 1-
with a SignerIdentity key added in the Info.plist file bundled year pentesting iOS Application used in professional
with the application. environment.
A. Unsecure password storage
+ (BOOL)doSignerIdentity { Some applications are using the NSUserDefaults
NSBundle *bundle = [NSBundle mainBundle];
NSDictionary *info = [bundle infoDictionary];
standardUserDefaults method in order to user credentials. The
if ([info objectForKey: @"SignerIdentity"] != nil){ problem is that standardUserDefaults stores information in
NSLog(@"App have has been hacked"); plain text in a plist file that can be downloaded trough AFC
return YES;
} protocol.
return NO;
}

Figure 12 Checking for SignerIdentity.

This test is designed to overcome automated processes at best,


and will probably only defeating most tutorial-followers. An
attacker can hexedit the binary file and as such, could edit the
string @"SignerIdentity" to read @"siNGerIDentitY" or
something else which would return nil, and thus pass. This test Figure 13 Default plist file including clear text stored password
can also by bypassed by hooking objectForKey and return nil.
B. Authentication Bypass
E. Less commons Jailbreak checks Here the password defined by the user is stored on the file
Less commons jailbreak checks are using system calls: system in an encrypted database. The problem is that the
‐ Fork(): Documented in some books and blog posts: If the application has to decrypt the database before the user being
process can fork, the device is jailbroken. Except this authenticated in order to check the password validity. Since the
check producing a lot of logs in the console, and most database is decrypted before the user was authenticated it is
important does not work because the jailbreak does not possible for an attacker, having an access to an unlocked
patch this part of the sandbox. See the iPhone Wiki [12] jailbroken device to retrieve the password in the memory.
for details about jailbreak patchs.
‐ Open(): Trying to open a file in write mode in a not
writable path outside the sandbox: if no error the device C. Unsecure data storage
is not jailbroken. This example was highlighted during the analysis of a sandbox
like application. According to the documentation the
Like other jailbreak detection functions presented in this application is using "high grade encryption” to secure the
section system calls can easily being hooked in order to hide document.
the jailbreak.
iExplorer is an iPhone browser or iPad file explorer that runs
on Mac & PC. iExplorer lets users browse the files and folders
F. Conclusion: Jailbreak detection = Fail by design! on their iDevice as if it were a normal USB flash drive or pen
Despite this test are interesting and probably stops most of the drive (this application does not require any jailbreak). Using
script kiddies, tutorial follower and automating tools, skillful this tool it is possible to download all the application resources
attackers can bypass them. and data. The analysis of the data highlights the lack of
The thing is that Apple does not provide any API to launch encryption.
action either before or after the installation. As a result
attackers are able to decrypt and analyze applications before In this case, when the vendor says "high grade encryption” you
they could launch their jailbreak detection tests. Moreover after must read: All data are stored on the iPhone encrypted file
jailbreak the attackers have root access to the device, which system that provides high-grade encryption.
means to control everything on the device as the opposite of
iOS application.

Nevertheless, when well implemented, jailbreak detection


features can discourage most of script kiddies and tutorial
followers.

21 / 61 GreHack
Mathieu Renard/ Practical iOS Apps hacking GreHack 2012, Grenoble, France

D. Extraction data from log ‐ When encryption is employed, references to the


This application embeds a secure web browser, according to corresponding key files appear in the index file so that
the best practices; redirect all the network traffic through an the client can retrieve the keys for decryption.
SSL Tunnel (even HTTP traffic is redirected trough this ‐ When a key file is listed in the index file, the key file
tunnel). However, all the cookies used during the user contains a cipher key that must be used to decrypt
navigation are exported in the application logs. Application subsequent media files listed in the index file.
logs are available to any applications installed on the device. A ‐ Currently HTTP Live Streaming supports AES-128
malicious application could use these cookies in order to encryption using 16-bytes keys. The format of the key
impersonate user sessions and access/steal confidential data. file is a packed array of these 16 bytes in binary
format”.

E. Hardcoded encryption key – Common! All an attacker needs to play the video on another device is the
This application is secure media player allowing to play / view index file; the key and the encrypted video, which in this case
protected content. Here is the pseudo code of the images are stored in, clear text on the file system and can be retrieved
decryption routine. through AFC protocols.

Base64Key = (int)objc_msgSend( #EXTM3U


*classRef_NSString_Ptr, #EXT-X-TARGETDURATION:63
*selRef_stringWithFormat_Ptr, #EXT-X-VERSION:2
CFSTR("HiddenTreasures")); #EXT-X-MEDIA-SEQUENCE:0
NSData = &classRef_NSData; #EXTINF:63,
#EXT-X-KEY:METHOD=AES-
Key = objc_msgSend(&OBJC_CLASS___NSData, 128,URI="http://localhost:12345/crypt5.key",IV=0cd463
"dataFromBase64String:", 4ed46bbc1e8235e21b23dc6792e3
Base64Key);
http://localhost:12345/fileSequence5.ts
BundlePath = objc_msgSend(&OBJC_CLASS__NSBundle,
"mainBundle"); #EXT-X-ENDLIST

cpngPath = (int)objc_msgSend(BundlePath,
"pathForResource:ofType:"
filename, Figure 15 MPMoviePlayerControler index file
CFSTR("cpng"),
1063452672); This allows an attacker to develop its own movie player to
Data = *NSData; read the videos files extracted/dumped from the Ipad.
cpngFileContent = (int)objc_msgSend(Data,
dataWithContentsOfFile:",
cpngPath);

decyptedContent = (int)objc_msgSend(
&OBJC_CLASS___FBEncryptorAES, V. DEFENDING IOS APPLICATION
"decryptData:key:iv:",
cpngFileContent,
Key, In matter of security the iOS system is not perfect. Even if
0);
Apple increases the security level of its mobile operating
system, for each new release comes a new jailbreak.
Figure 14 Image decryption function pseudo code Jailbreaking is a process that allows users to gain the root
Here the Key/Password: “Hiddentreasures” is Base64 decoded access to the command line, decrypt, analyze and crack iOS
before being used as a key for the AES decryption algorithm. application.
Moreover the IV used by the AES crypto function is fixed to
“0”. With this information an attacker can easily be re- In this section we will present some defensives tricks, which
implement the algorithm and decrypt the data. can be use to the aim to slow down skilful attackers,
discourage script kiddies and defeat automatic tools.

F. Playing DRM video with MPMoviePlayerControler


A. Anti-analysis part 1
This application was using the apple
“MPMoviePlayerControler” API to play encrypted content It is possible to add an anti-debugging feature by sending a
stored on the device. In other words the application was localy non-standard ptrace value named PT_DENY_ATTACH.
streaming the files. Setting this value allows a process that is not currently being
traced to deny future traces by its parent. All others arguments
The “MPMoviePlayerControler” is a part of Apple API’s. are ignored. An attempt by the parent to trace a process, which
Apple developer’s documentation says: has set this flag, will result in a segmentation violation in the
‐ A movie player (of type MPMoviePlayerController) parent.
manages the playback of a movie from a file or a
network stream.

22 / 61 GreHack
Mathieu Renard/ Practical iOS Apps hacking GreHack 2012, Grenoble, France

this flag is set, the application knows that it was either started
#import <dlfcn.h> with a debugger, or a debugger was later attached to it.
#import <sys/types.h>
#define PT_DENY_ATTACH 31
When the application detect it is being debugged, the program
typedef int (*ptrace_ptr_t)(int _request, pid_t _pid,
caddr_t _addr, int _data); should silently wipe all confidential data and encryption keys
and then inform the user.
void disable_gdb() {
void* handle = dlopen(0, RTLD_GLOBAL | RTLD_NOW);
ptrace_ptr_t ptrace_ptr = dlsym(handle, "ptrace");
ptrace_ptr(PT_DENY_ATTACH, 0, 0, 0);
dlclose(handle); #include <unistd.h>
#include <sys/types.h>
}
#include <sys/sysctl.h>
#include <string.h>
#define P_TRACED 0x00000800
Figure 16 Disabling GDB with PTRACE_DENY_ATTACH
static int checkGDB() __attribute__((always_inline));
It is useful for defeating most tutorial-followers but this is no
int checkGDB()
guarantee that your application cannot be debugged, and in {
fact there are ways around this. An attacker, can set a size_t size = sizeof(struct kinfo_proc);
struct kinfo_proc info;
breakpoint within the application prior to issuing a run from memset(&info, 0, sizeof(struct kinfo_proc));
within a debugger, and specify that the debugger run any
int ret, name[4];
commands he wants when ptrace starts and before the name[0] = CTL_KERN;
application can shut down. name[1] = KERN_PROC;
name[2] = KERN_PROC_PID;
name[3] = getpid();
Here is an example of a GDB script to bypass
if (ret = (sysctl(name, 4, &info, &size, NULL, 0)))
PT_DENY_ATTACH system call: return ret;
return (info.kp_proc.p_flag & P_TRACED) ? 1 : 0;
}

break ptrace
commands 1
return Figure 19 Checking the P_TRACED flag
continue
end
This technique will only allow the application to detect when
gdb, or another debugger, is attached to the process, but will
Figure 17 Bypassing PTRACE_DENY_ATTACH not detect when malicious code is injected, or when other
It is useful for defeating most tutorial-followers but this is no tools that do not trace are attached to the process.
guarantee that your application cannot be debugged, and in Implementing this in your code will only force an attacker to
fact there are ways around this. either avoid using a debugger (which will further complicate
things for him), or to locate and patch the debugging checks.
Moreover a skillful attacker could also patch out the
Nevertheless, since the ptrace function is built inside the
invocation of sysctl itself. This is why simple’s sanity checks
kernel, the user space interface only performs syscall 26
should be done to ensure that sysctl can return other data, and
(ptrace). If the anti-debugging function is inlined like the
to ensure that the call does not fail. This will help further
example bellow the PT_DENY_ATTACH will be installed
complicate the attack and require the attacker to properly
and there is no way .
populate the kinfo_proc structure with valid information.

mov r0, #31 C. Preventing Hooking


mov r1, #0 Hooking allowing attackers to alter or augment the behaviour
mov r2, #0
mov r3, #0 of applications. By implementing the following defensives
mov ip, #26 measures allowing ensuring that called function are the ones
svc #0x80
implemented in the application.

Figure 18 Inline vesion of the PTRACE_DENY_ATTACH test 1) Validating Address Space


Anyway a dedicated and skillful attacker can patch the Any time malicious code is injected into an application, it
kernel/application. is loaded into the application address space. Validating
the address space for critical methods used by the
B. Anti-analysis 2 application force the attacker to find ways to inject his
code into the existing address space.
When an application is being debugged, the kernel sets the
P_TRACED flag for the process signifying that the process is
being traced. Applications can monitor the state of this flag. If

23 / 61 GreHack
Mathieu Renard/ Practical iOS Apps hacking GreHack 2012, Grenoble, France

The dynamic linker library includes a function named application every time it is called. This rise up attacks
dladdr. The function dladdr() takes a function pointer and complexity by forcing an attacker to hunt down every
tries to resolve name and file where it is located. occurrence of code and patch it.
Information is stored in the Dl_info structure.
To be inlined a function must be declared within the
attribute __attribute__((always_inline));
typedef struct {
const char *dli_fname; /* Pathname of shared
object that
contains address */ static int isPasswordValid(char * pwd)
void *dli_fbase; /* Shared object Address */ __attribute__((always_inline));
const char *dli_sname; /* Name of nearest int isPasswordValid(char * pwd) {
symbol with address //Function body
lower than addr */ }
void *dli_saddr; /* Exact address of
symbol named in
dli_sname */
} Dl_info;
Figure 22 Defining inline attribute

In addition of this attribute the following two


Figure 20 Dl_info structure compilations flags should be enabled:
-finline-functions
By providing the structure with the function pointer of a -Winline
class’s method implementation, its origins can be
verified. D. Others binary protection
iOS Applications are not exempt of overflow vulnerabilities
#include <dlfcn.h>
this is why the following mitigating technics should be
#include <objc/objc.h> implemented in every application.
#include <objc/runtime.h>
#include <stdio.h>
#include <string.h> 1) Stack smashing protection
static int checkAddressSpace
It is possible to activate stack-mashing protection at
__attribute__((always_inline)); compilation time. This can be achieved by specifying the
int checkAddressSpace(NString MyCriticalClass ,
–fstack-protector-all compiler flag.
NSString MyCriticalMethod){ When an application is compiled with this protection, a
Dl_info info; known value called “canary” is placed on the stack
IMP imp = class_getMethodImplementation(
objc_getClass(MyCriticalClass), before the local variables to protect the saved base
sel_registerName(MyCriticalMethod)); pointer, saved instruction pointer and function
if (dladdr(imp, &info)){ arguments. The value of the canary is verified upon the
/* Do some additional tests: function return to see if it has been overwritten.
Pathname of shared object … */
return 1;
} else { One can identify the presence of stack canaries
NSLog("Error: cannot find %@ symbol",
MyCriticalMethod); examining the symbol table of the binary, if stack-
return 0; smashing protection is compiled in to the application,
}
} two undefined symbols will be present:
‐ ___stack_chk_fail
‐ ___stack_chk_guard
Figure 21 Checking address space

2) Inlining
iOS offers a way to override functions in a shared library 2) Automatic Reference Counting
with DYLD_INSERT_LIBRARIES environment Automatic Reference Counting (ARC) was introduced in
variable (which is similar to LD_PRELOAD on Linux). iOS SDK version 5.0 to move the responsibility of
On a jailbroken device the MobileSubstrate framework memory management from the developer to the
simplify this task and allows developers to easily load compiler. Consequently, ARC also offers some security
libraries at application launch. benefits as it reduces the likelihood of developers
introducing memory corruption (specifically object use -
Inline functions are functions in which the compiler after-free and double free) vulnerabilities in to
expands a function body to be inserted within the code applications. ARC can be enabled in an application
every time it is called. In other words, there is no longer within XCode by setting the compiler option “Objective-
a function: the code gets pasted into the machine code C Automatic Reference Counting” to “yes”. This option
whenever it is called. Turning the critical functions into is automatically check statring XCode 4.3.
inline ones will cause it to be repeated throughout the

24 / 61 GreHack
Mathieu Renard/ Practical iOS Apps hacking GreHack 2012, Grenoble, France

3) Binary obfuscation ‐ Do not store encryption keys or other critical data


Main purpose of code obfuscation and other protections inside Objective-C instance variables, as they can be
applied to source code or resulting binaries is to prevent easily referenced. Instead, manually allocate memory
reverse engineering and cracking. Unfortunately, there for these. This will not stop an attacker from hooking
are no popular, well-known tools for Objective C code into your application with a debugger, but will up the
obfuscation. Objective C is a dynamic language, based ante for an attacker. Typically, if a device is
on message passing paradigm, where most of bindings compromised while the user is using it, the attack is
are resolved run time. Therefore it is always possible for automated malware rather than an active human.
attacker to track, intercept and reroute calls, even with
obfuscated names.
VI. CONCLUSION
Nevertheless, adding some obfuscation to the binaries
will slow down the analysis. Since no open source tool Regarding security most of iOS applications are not
exists to perform this task automatically the developer mature!
has to implement the obfuscation himself.
Symbol stripping and dynamic string generation should Developers should apply the following recommendation
be implemented. Especially if the application is checking in order to mitigate the risks.
for Jailbreak files and if it informs the user they're using ‐ Do not relay only on iOS security,
a cracked version. Actually, when strings are stored in ‐ Do not store credential using
plain text, the crackers can quickly track down where the standardUserDefaults method.
view is generated with strings and disable the check. ‐ Encrypt your data even when stored in the
keychain,
For example the dynamic strings generation can easily ‐ Do not store crypto keys on the device,
being implemented by using a crypto algorithm. In this ‐ Check your code, classes, functions, methods
case strings are decrypted on the fly just before being integrity,
used and cleared from memory after use. In addition of ‐ Detect the jailbreak,
these basic tricks it may be interesting to rename classes ‐ Properly implement cryptography in
and methods with random names. applications (simple implementation are the
Using basic blocks cloning technics and inserting opaque most secure),
predicate will also increase the binary obfuscation level. ‐ Remove all debug information from the final
Basic blocs’ cloning allows spreading the execution release,
across the cloned basic blocks. ‐ Minimize use of Objective-C for critical
Inserting opaque predicate add extra tests which cannot functions & security features.
be easily proved to conditionals.
Users and companies should not blindly thrust iOS
The obfuscation should be performed semi-automatic, application vendors when talking about security.
over source code copy, with tool custom developed for
such task. Obfuscated code is by definition hard to read REFERENCES
before compilation as same as after decompiling from
binaries. [1] iPhoneDataProtection - Jean-Baptiste Bédrune and Jean
Sigwald,
Anyway, it important to keep in mind that obfuscation [2] Crakulous - Angel, http://hackulo.us
wills only slowdown attackers performing static analysis [3] Dumpdecrypted – Stefan Esser – i0n1c,
only. It is only a matter of time before an attacker mixing https://github.com/stefanesser/dumpdecrypted
static and dynamic analysis will be able to reverse your [4] Absinthe - Chronic-Dev Team and iPhone Dev Teams (Jailbreak
application. Dream Team), http://greenpois0n.com
[5] iOS SSL Kill Switch – iSECPartners,
E. Security of running memory https://github.com/iSECPartners
The following guidelines can help to improve the security of [6] MobileSubstrate, Cydia – Sauric,
http://iphonedevwiki.net/index.php/MobileSubstrate,
running memory:
http://cydia.saurik.com/
[7] iExplorer - Macroplatant, http://www.macroplant.com/iexplorer/
‐ Never store anything in memory until the user has
authenticated and data has been decrypted. It should [8] libimobiledevice & usbmuxd - Nikias,
http://www.libimobiledevice.org/
not even be possible to store passwords, credentials, or
other information in memory before a user has entered [9] Gutmann method,
http://en.wikipedia.org/wiki/Gutmann_method
their passphrase; if it is, the application is not properly
implementing encryption.

25 / 61 GreHack
Mathieu Renard/ Practical iOS Apps hacking GreHack 2012, Grenoble, France

[10] iPhone security model & vulnerabilities : http://esec- [24] Corona Jailbreak for iOS 5.0.1 by Dream team:
lab.sogeti.com/dotclear/public/publications/10-hitbkl-iphone.pdf http://conference.hitb.org/hitbsecconf2012ams/materials/D2T2 –
[11] zynamics/objc-helper-plugin-ida - Jailbreak Dream Team – CoronaJailbreak for iOS 5.0.1.pdf
https://github.com/zynamics/objc-helper-plugin-ida [25] Absinthe Jailbreak for iOS 5.0.1 by Dream team:
[12] Sandbox patch, http://conference.hitb.org/hitbsecconf2012ams/materials/D2T2
http://theiphonewiki.com/wiki/index.php?title=Sandbox_Patch %20-%20Jailbreak%20Dream%20Team%20-
%20Absinthe%20Jailbreak%20for%20iOS%205.0.1.pdf
[13] Evolution of iOS Data Protection and iPhone Forensics: from
iPhone OS to iOS 5: https://media.blackhat.com/bh-ad- [26] iOS Application Security : http://www.exploit-db.com/wp-
11/Belenko/bh-ad-11-Belenko-iOS_Data_Protection.pdf content/themes/exploit/docs/18831.pdf
[14] Overcoming iOS data protection to re-enable iPhone Forensics: [27] Breaking iOS code signing: http://reverse.put.as/wp-
https://media.blackhat.com/bh-us- content/uploads/2011/06/syscan11_breaking_ios_code_signing.
11/Belenko/BH_US_11_Belenko_iOS_Forensics_Slides.pdf pdf
[15] Apple iOS Security Evaluation: [28] Never trust SMS: iOS text spoofing -
http://hakim.ws/BHUS2011/materials/DaiZovi/BH_US_11_Dai http://www.pod2g.org/2012/08/never-trust-sms-ios-text-
Zovi_iOS_Security_WP.pdf spoofing.html
[16] New age application attacks against Apple iOS and [29] Mobile certificate pinning (iOS SSL kill switch):
countermeasures: https://media.blackhat.com/bh-eu- http://cloud.github.com/downloads/iSECPartners/ios-ssl-kill-
11/Nitesh_Dhanjani/BlackHat_EU_2011_Dhanjani_Attacks_Ag switch/BH2012_MobileCertificatePinning_short.pdf
ainst_Apples_iOS-WP.pdf [30] Overview on Apple iOS Security :
[17] Hacking and Securing Next Generation iPhone and iPad Apps: http://www.trust.informatik.tu-
http://software-security.sans.org/downloads/appsec-2011- darmstadt.de/fileadmin/user_upload/Group_TRUST/LectureSlid
files/dhanjani-hacking-securing-next-gen.pdf es/ESS-SS2012/9_iOS_-_hand-out.pdf
[18] Secure Development on iOS – Advice for developers and
penetration testers:
http://www.isecpartners.com/storage/docs/presentations/iOS_Se FURTHER READING
cure_Development_SOURCE_Boston_2011.pdf [31] Hacking and Securing iOS Applications: Jonathan Zdziarski
[19] Pentesting iPhone & iPad Apps: [32] iOS Hacker's Handbook : Charlie Miller , Dion Blazakis , Dino
http://www.hackinparis.com/slides/hip2k11/07- Dai Zovi , Stefan Esser , Vincenzo Iozzo , Ralf-Phillip
Pentesting_iPhone_iPad.pdf Weinmann
[20] Penetration testing of iPhone/iPad applications: [33] iOS kernel exploitation IOKit edition: http://reverse.put.as/wp-
http://www.mcafee.com/us/resources/white- content/uploads/2011/06/SyScanTaipei2011_StefanEsser_iOS_
papers/foundstone/wp-pen-testing-iphone-ipad-apps.pdf Kernel_Exploitation_IOKit_Edition.pdf
[21] Practical Consideration of iOS Device Encryption Security: [34] iOS 5 – an exploitation night mare
http://sit.sit.fraunhofer.de/studies/en/sc-iphone-passwords.pdf http://antid0te.com/CSW2012_StefanEsser_iOS5_An_Exploitation_
[22] iPhone 3GS Forensics: Logical analysis using Apple iTunes Nightmare_FINAL.pdf
Backup Utility: [35] Evolution of iPhone Baseband and unlocks:
http://www.ssddfj.org/papers/SSDDFJ_V4_1_Bader_Bagilli.pdf http://conference.hitb.org/hitbsecconf2012ams/materials/D1T2 –
[23] iOS Security by Apple: MuscleNerd – Evolution of iPhone Baseband and Unlocks.pdf
http://images.apple.com/ipad/business/docs/iOS_Security_May1
2.pdf

26 / 61 GreHack

You might also like