28 KiB
iOS Pentesting
iOS Basics
{% page-ref page="ios-basics.md" %}
Testing Environment
In this page you can find information about the iOS simulator, emulators and jailbreaking:
{% page-ref page="ios-testing-environment.md" %}
Initial Analysis
Listing Installed Apps
When targeting apps that are installed on the device, you'll first have to figure out the correct bundle identifier of the application you want to analyze. You can use frida-ps -Uai
to get all apps `-a`
currently installed `-i`
on the connected USB device `-U`
:
$ frida-ps -Uai
PID Name Identifier
---- ------------------- -----------------------------------------
6847 Calendar com.apple.mobilecal
6815 Mail com.apple.mobilemail
- App Store com.apple.AppStore
- Apple Store com.apple.store.Jolly
- Calculator com.apple.calculator
- Camera com.apple.camera
- iGoat-Swift OWASP.iGoat-Swift
IPA Structure
.ipa
files are zipped packages, so you can change the extension to .zip
and decompress them. A complete packaged app ready to be installed is commonly referred to as a Bundle.
After decompressing them you should see <NAME>.app
, a zipped archive that contains the rest of the resources.
Info.plist
: A file that contains some of the application specific configurations._CodeSignature/
contains a plist file with a signature over all files in the bundle.Assets.car
: Another zipped archive that contains assetsicons
.Frameworks/
contains the app native libraries as .dylib or .framework files.PlugIns/
may contain app extensions as .appex filesnot present in the example
.Core Data
: It is used to save your application’s permanent data for offline use, to cache temporary data, and to add undo functionality to your app on a single device. To sync data across multiple devices in a single iCloud account, Core Data automatically mirrors your schema to a CloudKit container.- ****
PkgInfo
: ThePkgInfo
file is an alternate way to specify the type and creator codes of your application or bundle. - en.lproj, fr.proj, Base.lproj: Are the language packs that contains resources for those specific languages, and a default resource in case a language isn' t supported.
There are multiple ways to define the UI in an iOS application: storyboard, nib or xib files.
Info.plist
The information property list or Info.plist
is the main source of information for an iOS app. It consists of a structured file containing key-value pairs describing essential configuration information about the app. Actually, all bundled executables app extensions, frameworks and apps
are expected to have an Info.plist
file. You can find all possible keys in the Apple Developer Documentation.
The file might be formatted in XML or binary (bplist). You can convert it to XML format with one simple command:
-
On macOS with
plutil
, which is a tool that comes natively with macOS 10.2 and above versionsno official online documentation is currently available
:$ plutil -convert xml1 Info.plist
-
On Linux:
$ apt install libplist-utils $ plistutil -i Info.plist -o Info_xml.plist
Here's a non-exhaustive list of some info and the corresponding keywords that you can easily search for in the Info.plist
file by just inspecting the file or by using grep -i <keyword> Info.plist
:
- App permissions Purpose Strings:
UsageDescription
- Custom URL schemes:
CFBundleURLTypes
- Exported/imported custom document types:
UTExportedTypeDeclarations
/UTImportedTypeDeclarations
- App Transport Security
ATS
configuration:NSAppTransportSecurity
Please refer to the mentioned chapters to learn more about how to test each of these points.
Data Paths
On iOS, system applications can be found in the /Applications
directory while user-installed apps are available under /private/var/containers/
. However, finding the right folder just by navigating the file system is not a trivial task as every app gets a random 128-bit UUID Universal Unique Identifier
assigned for its directory names.
In order to easily obtain the installation directory information for user-installed apps you can use objection's command env
will also show you all the directory information of the app:
OWASP.iGoat-Swift on (iPhone: 11.1.2) [usb] # env
Name Path
----------------- -------------------------------------------------------------------------------------------
BundlePath /var/containers/Bundle/Application/3ADAF47D-A734-49FA-B274-FBCA66589E67/iGoat-Swift.app
CachesDirectory /var/mobile/Containers/Data/Application/8C8E7EB0-BC9B-435B-8EF8-8F5560EB0693/Library/Caches
DocumentDirectory /var/mobile/Containers/Data/Application/8C8E7EB0-BC9B-435B-8EF8-8F5560EB0693/Documents
LibraryDirectory /var/mobile/Containers/Data/Application/8C8E7EB0-BC9B-435B-8EF8-8F5560EB0693/Library
As you can see, apps have two main locations:
- The Bundle directory
`/var/containers/Bundle/Application/3ADAF47D-A734-49FA-B274-FBCA66589E67/`
. - The Data directory
`/var/mobile/Containers/Data/Application/8C8E7EB0-BC9B-435B-8EF8-8F5560EB0693/`
.
These folders contain information that must be examined closely during application security assessments for example when analyzing the stored data for sensitive data
.
Bundle directory:
- AppName.app
- This is the Application Bundle as seen before in the IPA, it contains essential application data, static content as well as the application's compiled binary.
- This directory is visible to users, but users can't write to it.
- Content in this directory is not backed up.
- The contents of this folder are used to validate the code signature.
Data directory:
- Documents/
- Contains all the user-generated data. The application end user initiates the creation of this data.
- Visible to users and users can write to it.
- Content in this directory is backed up.
- The app can disable paths by setting
NSURLIsExcludedFromBackupKey
.
- Library/
- Contains all files that aren't user-specific, such as caches, preferences, cookies, and property list
plist
configuration files. - iOS apps usually use the
Application Support
andCaches
subdirectories, but the app can create custom subdirectories.
- Contains all files that aren't user-specific, such as caches, preferences, cookies, and property list
- Library/Caches/
- Contains semi-persistent cached files.
- Invisible to users and users can't write to it.
- Content in this directory is not backed up.
- The OS may delete this directory's files automatically when the app is not running and storage space is running low.
- Library/Application Support/
- Contains persistent files necessary for running the app.
- Invisible to users and users can't write to it.
- Content in this directory is backed up.
- The app can disable paths by setting
NSURLIsExcludedFromBackupKey
.
- Library/Preferences/
- Used for storing properties that can persist even after an application is restarted.
- Information is saved, unencrypted, inside the application sandbox in a plist file called [BUNDLE_ID].plist.
- All the key/value pairs stored using
NSUserDefaults
can be found in this file.
- tmp/
- Use this directory to write temporary files that do not need to persist between app launches.
- Contains non-persistent cached files.
- Invisible to users.
- Content in this directory is not backed up.
- The OS may delete this directory's files automatically when the app is not running and storage space is running low.
Let's take a closer look at iGoat-Swift's Application Bundle .app
directory inside the Bundle directory `/var/containers/Bundle/Application/3ADAF47D-A734-49FA-B274-FBCA66589E67/iGoat-Swift.app`
:
OWASP.iGoat-Swift on (iPhone: 11.1.2) [usb] # ls
NSFileType Perms NSFileProtection ... Name
------------ ------- ------------------ ... --------------------------------------
Regular 420 None ... rutger.html
Regular 420 None ... mansi.html
Regular 420 None ... splash.html
Regular 420 None ... about.html
Regular 420 None ... LICENSE.txt
Regular 420 None ... Sentinel.txt
Regular 420 None ... README.txt
Plist
plist files are structured XML files that contains key-value pairs. It's a way to store persistent data, so sometimes you may find sensitive information in these files. It's recommended to check these files after installing the app and after using intensively it to see if new data is written.
The most common way to persist data in plist files is through the usage of NSUserDefaults. This plist file is saved inside the app sandbox in Library/Preferences/<appBundleID>.plist
This data cannot be longer accessed directly via a trusted computer, but can be accessed performing a backup.
Binary Reversing
Inside the <application-name>.app
folder you will find a binary file called <application-name>
. This is the file that will be executed. You can perform a basic inspection of the binary with the tool otool
:
otool -Vh DVIA-v2 #Check some compilation attributes
magic cputype cpusubtype caps filetype ncmds sizeofcmds flags
MH_MAGIC_64 ARM64 ALL 0x00 EXECUTE 65 7112 NOUNDEFS DYLDLINK TWOLEVEL WEAK_DEFINES BINDS_TO_WEAK PIE
otool -L DVIA-v2 #Get third party libraries
DVIA-v2:
/usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 400.9.1)
/usr/lib/libsqlite3.dylib (compatibility version 9.0.0, current version 274.6.0)
/usr/lib/libz.1.dylib (compatibility version 1.0.0, current version 1.2.11)
@rpath/Bolts.framework/Bolts (compatibility version 1.0.0, current version 1.0.0)
[...]
Check if the app is encrypted
See if there is any output for:
otool -l <app-binary> | grep -A 4 LC_ENCRYPTION_INFO
Disassembling the binary
Disassemble the text section:
otool -tV DVIA-v2
DVIA-v2:
(__TEXT,__text) section
+[DDLog initialize]:
0000000100004ab8 sub sp, sp, #0x60
0000000100004abc stp x29, x30, [sp, #0x50] ; Latency: 6
0000000100004ac0 add x29, sp, #0x50
0000000100004ac4 sub x8, x29, #0x10
0000000100004ac8 mov x9, #0x0
0000000100004acc adrp x10, 1098 ; 0x10044e000
0000000100004ad0 add x10, x10, #0x268
To print the Objective-C segment of the sample application one can use:
otool -oV DVIA-v2
DVIA-v2:
Contents of (__DATA,__objc_classlist) section
00000001003dd5b8 0x1004423d0 _OBJC_CLASS_$_DDLog
isa 0x1004423a8 _OBJC_METACLASS_$_DDLog
superclass 0x0 _OBJC_CLASS_$_NSObject
cache 0x0 __objc_empty_cache
vtable 0x0
data 0x1003de748
flags 0x80
instanceStart 8
In order to obtain a more compact Objective-C code you can use class-dump:
class-dump some-app
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#pragma mark Named Structures
struct CGPoint {
double _field1;
double _field2;
};
struct CGRect {
struct CGPoint _field1;
struct CGSize _field2;
};
struct CGSize {
double _field1;
double _field2;
};
However, the best options to disassemble the binary are: Hopper and IDA.
Data Storage
To learn about how iOS stores data in the device read this page:
{% page-ref page="ios-basics.md" %}
{% hint style="warning" %}
The following places to store information should be checked right after installing the application, after checking all the functionalities of the application and even after login out from one user and login into a different one.
The goal is to find unprotected sensitive information of the application passwords, tokens
, of the current user and of previously logged users.
{% endhint %}
NSUserDefaults
The NSUserDefaults
class provides a programmatic interface for interacting with the default system. The default system allows an application to customize its behaviour according to user preferences. Data saved by NSUserDefaults
can be viewed in the application bundle. This class stores data in a plist file, but it's meant to be used with small amounts of data.
You can locate this plist file inside the application's folder: /private/var/mobile/Containers/Data/Application/A079DF84-726C-4AEA-A194-805B97B3684A/Library/Preferences/*.plist
Search sensitive information inside the file.
Core Data
Core Data
is a framework for managing the model layer of objects in your application. Core Data can use SQLite as its persistent store, but the framework itself is not a database.
CoreData does not encrypt it's data by default. However, an additional encryption layer can be added to CoreData. See the GitHub Repo for more details.
You can find the SQLite Core Data information of an application in the path /private/var/mobile/Containers/Data/Application/{APPID}/Library/Application Support
If you can open the SQLite and access sensitive information, then you found a miss-configuration.
{% code title="Code from iGoat" %}
-(void)storeDetails {
AppDelegate * appDelegate = (AppDelegate *)(UIApplication.sharedApplication.delegate);
NSManagedObjectContext *context =[appDelegate managedObjectContext];
User *user = [self fetchUser];
if (user) {
return;
}
user = [NSEntityDescription insertNewObjectForEntityForName:@"User"
inManagedObjectContext:context];
user.email = CoreDataEmail;
user.password = CoreDataPassword;
NSError *error;
if (![context save:&error]) {
NSLog(@"Error in saving data: %@", [error localizedDescription]);
}else{
NSLog(@"data stored in core data");
}
}
{% endcode %}
SQLite Databases
It's common for applications to create their own sqlite database. They may be storing sensitive data on them and leaving it unencrypted. Therefore, it's always interesting to check every database inside the applications directory. Therefore go to the application directory where the data is saved `/private/var/mobile/Containers/Data/Application/{APPID}`
find ./ -name "*.sqlite" -or -name "*.db"
Firebase Real-Time Databases
It can be leveraged by application developers to store and sync data with a NoSQL cloud-hosted database. The data is stored as JSON and is synchronized in real-time to every connected client and also remains available even when the application goes offline.
You can find how to check for misconfigured Firebase databases here:
{% page-ref page="../pentesting/pentesting-web/buckets/firebase-database.md" %}
Realm databases
Realm Objective-C and Realm Swift aren't supplied by Apple, but they are still worth noting. They store everything unencrypted, unless the configuration has encryption enabled.
You can find this databases in /private/var/mobile/Containers/Data/Application/{APPID}
iPhone:/private/var/mobile/Containers/Data/Application/A079DF84-726C-4AEA-A194-805B97B3684A/Documents root# ls
default.realm default.realm.lock default.realm.management/ default.realm.note|
You can use the tool Realm Studio to open this database files.
The following example demonstrates how to use encryption with a Realm database:
// Open the encrypted Realm file where getKey() is a method to obtain a key from the Keychain or a server
let config = Realm.Configuration(encryptionKey: getKey())
do {
let realm = try Realm(configuration: config)
// Use the Realm as normal
} catch let error as NSError {
// If the encryption key is wrong, `error` will say that it's an invalid database
fatalError("Error opening realm: \(error)")
}
Snapshots
Whenever you press the home button, iOS takes a snapshot of the current screen to be able to do the transition to the application on a much smoother way. However, if sensitive data is present in the current screen, it will be saved in the image which **persists** **across** **reboots**
. These are the snapshots that you can also access double tapping the home screen to switch between apps.
Unless the iPhone is jailbroken, the attacker needs to have access to the device unblocked to see these screenshots. By default the last snapshot is stored in the application's sandbox in /Library/Caches/Snapshots/
folder the trusted computers can' t access the filesystem from iOX 7.0
.
Once way to prevent this bad behaviour is to put a blank screen or remove the sensitive data before taking the snapshot using the ApplicationDidEnterBackground()
function.
Keychain
Tools like Keychain-Dumper can be used to dump the keychain the dive must be jailbroken
.
You can also use ios keychain dump
from Objection****
Cookies
iOS store the cookies of the apps in the Library/Cookies/cookies.binarycookies
inside each apps folder. However, developers sometimes decide to save them in the keychain as the mentioned cookie file can be accessed in backups.
To inspect the cookies file you can use this python script.
Custom Keyboards
From iOS 8.0 Apple allows to install custom extensions for iOS like custom keyboards.
The installed keyboards can be managed via Settings > General > Keyboard > Keyboards
Custom keyboards can be used to sniff the keystrokes and send them to the attacker server. However, note that custom keyboards requiring networking connectivity will be notified to the user.
Also, the user can switch to a different more trusted
keyboard for introducing the credentials.
Moreover, applications can prevent its users from using custom keyboards within the app or at least for sensitive parts of the app
.
Note that because of auto-correct and auto-suggestions, the default iOS keyboard will capture and store each non-standard word word in a cache file if the attribute securetTextEntry is not set to true or if autoCorrectionType is not set to UITextAutoCorrectionTypeNo.
By default the keyboards store this cache inside the applications sandbox in Library/Keyboard/{locale}-dynamic-text.dat
file. However, it might be saving the date elsewhere.
It's possible to reset the cache in Settings > General > Reset > Reset Keyboard Dictionary
Therefore, check always these files and search for possible sensitive information.
Intercepting the network traffic is another way to check if the custom keyboard is sending keystroked to a remote server.
Logs
The most common ways to debug code is using logging, and the application may print sensitive information inside the logs.
In iOS version 6 and below, logs were world readable a malicious app could read logs from other apps and extract sensitive information from there
. Nowadays, apps can only access their own logs.
However, an attacker with physical access to an unlocked device can connect it to a computer and read the logs note that the logs written to disk by an app aren't removed if the app ins uninstalled
.
It's recommended to navigate through all the screens of the app and interact with every UI element and functionality of and provide input text in all text fields and review the logs looking for sensitive information exposed.
Monitoring System Logs
Many apps log informative and potentially sensitive
messages to the console log. The log also contains crash reports and other useful information. You can collect console logs through the Xcode Devices window as follows:
- Launch Xcode.
- Connect your device to your host computer.
- Choose Window -> Devices and Simulators.
- Click on your connected iOS device in the left section of the Devices window.
- Reproduce the problem.
- Click on the Open Console button located in the upper right-hand area of the Devices window to view the console logs on a separate window.
You can also connect to the device shell as explained in Accessing the Device Shell, install socat via apt-get and run the following command:
iPhone:~ root# socat - UNIX-CONNECT:/var/run/lockdown/syslog.sock
========================
ASL is here to serve you
> watch
OK
Jun 7 13:42:14 iPhone chmod[9705] <Notice>: MS:Notice: Injecting: (null) [chmod] (1556.00)
Jun 7 13:42:14 iPhone readlink[9706] <Notice>: MS:Notice: Injecting: (null) [readlink] (1556.00)
Jun 7 13:42:14 iPhone rm[9707] <Notice>: MS:Notice: Injecting: (null) [rm] (1556.00)
Jun 7 13:42:14 iPhone touch[9708] <Notice>: MS:Notice: Injecting: (null) [touch] (1556.00)
...
Clipboard
Some applications may save sensitive information inside the clipboard, which is dangerous because then a different application may sniff the clipboard and steal the data.
Fortunately, apps signed by the same certificate can create private UIPasteboards. This way, unlike the global Pasteboard, only selected applications can share and view the content of the private pasteboard.
Then, it's important to check that sensitive information isn't being saved inside the global pasteboard.
It's also important to check that an application isn't using the global pasteboard data to perform actions, as malicious application could tamper this data.
An application can also prevent its users to copy sensitive data to the clipboard which is recommended
.
Custom URI Handlers / Deeplinks / Custom Schemes
A custom URI handler is used to invoke an application from an URI.
For example, the URI: myapp://hostname?data=123876123
will invoke the application mydata the one that has **register** the scheme `mydata`
to the action related to the hostname hostname
sending the parameter data
with value 123876123
You can find the schemes registered by an application in the app's Info.plist
file searching for CFBundleURLTypes
.
However, note that malicious applications can re-register URIs already registered by applications. So, if you are sending sensitive information via URIs myapp://hostname?password=123456
a malicious application can intercept the URI with the sensitive information.
Also, the input of these URIs should be checked and sanitised, as it can be coming from malicious origins trying to exploit SQLInjections, XSS, CSRF, Path Traversals, or other possible vulnerabilities.
Universal Links
Universal links allows to redirect users directly to the app without passing through safari for redirection.
Universal links are unique, so they can't be claimed by other apps because they use standard HTTP(S) links to the website where the owner has uploaded a file to make sure that the website and the app are related.
As these links uses HTTP(S) schemes, when the app isn't installed, safari will open the link redirecting the users to the page. These allows apps to communicate with the app even if it isn't installed.
To create universal links it's needed to create a JSON file called apple-app-site-association
with the details. Then this file needs to be hosted in the root directory of your webserver e.g. [https://google.com/apple-app-site-association](https://google.com/apple-app-site-association)
.
For the pentester this file is very interesting as it discloses paths. It can even be disclosing paths of releases that haven't been published yet.
Third Party SDKs
One problem of 3rd party SDKs is that there is no granular control over the features offered by the SDK. You could sue the SDK and have all features including diagnostic leaks and insecure HTTP connections
, or not use it. Also, usually it's no possible for the applications developers to patch a vulnerability on the SDK.
Moreover some SDKs start containing malware once they are very trusted by the community.
You can find the libraries used by an application by running otool
against the app and **running** it **against** **each** shared **library** to find more shared libraries used
.
Hot Patching
The developers can remotely patch all installations of their app instantly without having to resubmit the application to the App store and wait until it's approved.
For this purpose it's usually use JSPatch.
This is a dangerous mechanism that could be abused by malicious third party SDKs.
Misc
- In
/System/Library
you can find the frameworks installed in the phone used by system applications - The applications installed by the user from the App Store are located inside
/User/Applications
- And the
/User/Library
contains data saved by the user level applications - You can access
/User/Library/Notes/notes.sqlite
to read the notes saved inside the application. - Inside the folder of an installed application
**`/User/Applications/<APP ID>/`**
you can find some interesting files:iTunesArtwork
: The icon used by the appiTunesMetadata.plist
: Info of the app used in the App Store/Library/*
: Contains the preferences and cache. In/Library/Cache/Snapshots/*
you can find the snapshot performed to the application before sending it to the background.
Dynamic Analysis
Network Communication
It's important to check that no communication is occurring without encryption and also that the application is correctly validating the TLS certificate of the server.
To check these kind of issues you can use a proxy like Burp:
{% page-ref page="burp-configuration-for-ios.md" %}
Hostname check
One common issue validating the TLS certificate is to check that the certificate was signed by a trusted CA, but not check if the hostname of the certificate is the hostname being accessed.
In order to check this issue using Burp, after trusting Burp CA in the iPhone, you can create a new certificate with Burp for a different hostname and use it. If the application still works, then, something it's vulnerable.
Certificate Pinning
If an application is correctly using SSL Pinning, then the application will only works if the certificate is the once expected to be. When testing an application this might be a problem as Burp will serve it's own certificate.
In order to bypass this protection inside a jailbroken device, you can install the application SSL Kill Switch ****or install Burp Mobile Assistant****
Automatic Tools
****