Applications the user can access run as the **mobile** user while critical system processes run as **root**.
However, the sandbox allows better control over actions that processes and applications can perform.
For example, even if two processes run as the same user \(mobile\), they are **not allowed to access or modify each other's data**.
Each application is installed under **`private/var/mobile/Applications/{random ID}`**
Once installed, applications have limited read access to some system areas and functions \(SMS, phone call...\). If an application wants to access a **protected area,** a **pop-up requesting permission** appears.
When a **file is created** on the disk, a new **256-bit AES key is generated** with the help of secure enclave's hardware based random number generator. The **content of the file is then encrypted with the generated key**. And then, this **key is saved encrypted with a class key** along with **the class ID,** with **both data encrypted by the system's key,** inside the **metadata** of the file.
For decrypting the file, the **metadata is decrypted using the system's key**. Then u**sing the class ID** the **class key is retrieved****to decrypt the per-file key and decrypt the file.**
**Depending on the state of the device \(locked, unlocked\) certain class keys may or may not be available.**
**There are 4 types of data protection classes:**
* **NSFileProtectionNone:** This class key is only protected with the UID of the device. This is the default data protection class. This ensures that files are at least stored encrypted on the device and that an attacker would need physical access to the device to decrypt them.
* **NSFileProtectionCompleteUnlessOpen**: For cases when a file needs to be accessible even when the device is locked \(like background processes\). Then, if the application opens a file, it can read and write to the file, but once close, the device must be unlocked to access the file again.
* **NSFileProtectionCompleteUntilFirstUserAuthentication**:Once the device has been locked at least once, the file remains accessible irrespective of whether the device is locked or unlocked \(as the data kay remains unencrypted in memory\). This is the minimum protection available.
* **NSFileProtectionComplete**: This protects the class key using the device ID and the user's pass code. 10 seconds after locking the device the class key is discarded.
\*\*\*\*[**FileDP**](https://github.com/abjurato/FileDp-Source) is a program that you can upload and use inside the IPhone to **inspect the data protection class** of each file.
A **provisioning identity** is a collection of public and private keys that are associated an Apple developer account. In order to **sign apps** you need to pay **99$/year** to register in the **Apple Developer Program** to get your provisioning identity. Without this you won't be able to run applications from the source code in a physical device. Another option to do this is to use a **jailbroken device**.
Starting in Xcode 7.2 Apple has provided an option to create a **free iOS development provisioning profile** that allows to write and test your application on a real iPhone. Go to _Xcode_ -->_Preferences_ -->_Accounts_ -->_+_ \(Add new Appli ID you your credentials\) -->_Click on the Apple ID created_ -->_Manage Certificates_ -->_+_ \(Apple Development\) -->_Done_
Then, in order to run your application in your iPhone you need first to **indicate the iPhone to trust the computer.** Then, you can try to **run the application in the mobile from Xcode,** but and error will appear. So go to _Settings_ -->_General_ -->_Profiles and Device Management_ --> Select the untrusted profile and click "**Trust**".
Note that **applications signed by the same signing certificate can share resources on a secure manner, like keychain items**.
The provisioning profiles are stored inside the phone in **`/Library/MobileDevice/ProvisioningProfiles`**
All the tools required to build and support an iOS app are **only officially supported on Mac OS**.
Apple's de facto tool for creating/debugging/instrumenting iOS applications is **Xcode**. It can be used to download other components such as **simulators** and different **SDK****versions** required to build and **test** your app.
It's highly recommended to **download** Xcode from the **official app store**. Other versions may be carrying malware.
The simulator files can be found in `/Users/<username>/Library/Developer/CoreSimulator/Devices`
To open the simulator, run Xcode, then press in the _Xcode tab_ -->_Open Developer tools_ -->_Simulator_
In the following image clicking in "iPod touch \[...\]" you can select other device to test in:
Inside `/Users/<username>/Library/Developer/CoreSimulator/Devices` you may find all the **installed simulators**. If you want to access the files of an application created inside one of the emulators it might be difficult to know **in which one the app is installed**. A quick way to **find the correct UID** is to execute the app in the simulator and execute:
Once you know the UID the apps installed within it can be found in `/Users/<username>/Library/Developer/CoreSimulator/Devices/{UID}/data/Containers/Data/Application`
However, surprisingly you won't find the application here. You need to access `/Users/<username>/Library/Developer/Xcode/DerivedData/{Application}/Build/Products/Debug-iphonesimulator/`
And in this folder you can **find the package of the application.**
**Objecttive-C** has a **dynamic runtime**, so when an Objective-C program is executed in iOS, it calls libraries whose **address are resolved at runtime** by comparing the name of the function sent in the message against a list of all the function names available.
At the beginning, only apps created by Apple run the iPhones, so they had **access to everything** as they were **trusted**. However, when Apple **allowed****third party applications,** Apple just removed the headers files of the powerful functions to "hide" them to developers. However, developers found that "safe" functions needed a few of these undocumented functions and just creating a **custom header file with the names of the undocumented functions, it was possible to invoke this powerful hidden functions.** Actually, Apple, before allowing an app to be published, check if the app calls any of these prohibited functions.
Then, Swift appeared. As **Swift is statically bound** \(it doesn't resolve the address of the functions in runtime like Objective-C\), it can be checked more easily the calls a Swift program is going to make via static code analysis.
From iOS version 6, there is **built-in support for device management** capability with fine grain controls that allows an organisation to control the corporate apple devices.
The enrolment can be **initiated by the user installing an agent** in order to access the corporate apps. In this case the device usually belongs to the user.
Or the **company can indicate the serial numbers** of the bought devices or the purchase order ID and specify the MDM profile to install on those devices. Note that Apple **doesn't allow to enrol a particular device this way twice**. Once the first profile is deleted the user needs to give consent to install another one.
As these MDM policies are checking and limiting other applications, they are **running with more privileges**.
A MDM policy can **enforce****users** to have a **passcode** set with a **minimun** password **complexity**.
The profiles are tied to the deviceID, **signed** and **encrypted** by the MDM server and **tamper****proof**. They **cannot** be **removed** without **losing** all the **corporate****data**.
MDM profiles allow to **wipe** all the **data** if there are X **failed** password **attempts**. Also, the **admin** can **remote****wipe** the iPhone whenever via the MDM interface.
`.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.
* **Assets.car**: Another zipped archive that contains assets \(icons\).
* \*\*\*\*[**Core Data**](https://developer.apple.com/documentation/coredata): 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**](https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPRuntimeConfig/Articles/ConfigApplications.html): The `PkgInfo` 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.
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`**:
```bash
otool -Vh DVIA-v2 #Check some compilation attributes
However, the best options to disassemble the binary are: [**Hopper**](https://www.hopperapp.com/download.html?) and [**IDA**](https://www.hex-rays.com/products/ida/support/download_freeware/).
Starting in iOS version 8.4, Apple has **restricted the third-party managers to access to the application sandbox**, so tools like iFunbox and iExplorer no longer display/retrieve files from apps installed on the device if the device isn't jailbroken.
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
A keychain is an **encrypted****container** where every application can **store****sensitive** pieces of **information** and only the same app \(or authorised apps\) can retrieve the contents.
The iOS **generated its own password for the keychain** and **stores** an **encrypted** version of this key in the device. This password is encrypted with AES using an AES key created by a **PBKDF2** function of the **user's passcode + salt** \(the 256 bit device **UID****only****accessible** to the secure **enclave chipset** on the device\). Due to the use of this device UID as salt, a device won't be able to decrypt the keychain of a different device even knowing the users passcode.
The only ways to try to BF this password is dumping the encrypted key and BF the passcode + salt \(the **pbkdf2** function uses **at least 10000 iteration**s\). Or trying to **BF inside the device** to avoids BFing the salt, however, secure enclave ensures there is at least a **5s delay between 2 failed password attempts**.
When a backup process is initiated the keychain **data backed up remains encrypted and the keychain password isn't included in the backup**.
**In a jailbroken device the keychain isn't protected.**
#### **Attribute types for items saved in the keychain:**
* **kSecAttrAccessibleAlways:** These items will not be stored securely in the keychain and are available at all times, even when the device is blocked
* **kSecAttrAccessibleAfterFirstUnlock**: Items secure in the keychain until the device is first unlocked after a reboot. Then, the items are accessible even when the device is blocked.
* **kSecAttrAccessibleWhenUnlocked**: Items are secure at rest and when the device is locked. The items are only accessible when the device is unlocked.
* **kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly**: Like **kSecAttrAccessibleWhenUnlocked** but you a passcode must be set in the device. If the passcode is unset, these secrets are deleted from the device.
You can also select the "_**ThisDeviceOnly**_" on keychain objects to ensure that even the encrypted keychains objects **never leave the device during backups**.
The iPhone uses the **passcode introduced by the user unlocking the device to decrypt the secrets in the keychain**.
iOS uses the _**AppIdentifierPrefix**_ \(Team ID\) and the _**BundleIdentifier**_ \(provided by the dev\) to enforce **access control oven keychain items**. Then, the same team **can****configure****2 apps to share keychain items**.
Tools like [**Keychain-Dumper**](https://github.com/ptoomey3/Keychain-Dumper) can be used to dump the keychain \(the dive must be jailbroken\).
{% hint style="info" %}
In **iOS earlier than 10.3**, when an application is deleted from the device, iOS **doesn't clean up the keychain**. So on these devices you can **find secrets of deleted apps**.
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**](https://github.com/mdegrazia/Safari-Binary-Cookie-Parser).
### 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**.
### 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.**
### **Log Files**
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\).
To inspect the application logs, connect the iPhone to your computer and open _**Xcode**_>_**Devices**_>_**{Your device}**_ and you should see the live logs in the console. You can also **ssh** into the phone and run `idevicesyslog`.
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.
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 app**s 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.
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**](https://github.com/bang590/JSPatch)**.
This is a dangerous mechanism that could be abused by malicious third party SDKs.**
* 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/<APPID>/`**\) you can find some interesting files:
* **`iTunesArtwork`**: The icon used by the app
* **`iTunesMetadata.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.
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**:
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**](https://github.com/nabla-c0d3/ssl-kill-switch2) ****or install [**Burp Mobile Assistant**](https://portswigger.net/burp/documentation/desktop/tools/mobile-assistant/installing)\*\*\*\*