deardaniel/secdata-raw huggingface dataset:
OWASP Mobile Application Security Testing Guide: MASTG TECH 0139

---
title: Attach to WKWebView
platform: ios
---

## Safari Web Inspector

Enabling the [Safari Web Inspector](https://developer.apple.com/library/archive/documentation/AppleApplications/Conceptual/Safari_Developer_Guide/GettingStarted/GettingStarted.html) on iOS allows you to remotely [inspect the contents of a WebView from a macOS device](https://developer.apple.com/documentation/safari-developer-tools/inspecting-ios). This is particularly useful in apps that expose native APIs using a JavaScript bridge, such as hybrid apps.

Starting with iOS 16.4, apps must explicitly opt in to inspection for `WKWebView` content by setting [`isInspectable`](https://developer.apple.com/documentation/webkit/wkwebview/isinspectable) to `true`:

```swift
let webView = WKWebView()
...
if #available(iOS 16.4, *) {
    webView.isInspectable = true
}
```

Apps installed from the App Store can still be inspected if the app enables `WKWebView.isInspectable = true`. On jailbroken devices, you can use @MASTG-TOOL-0137, to force enable WebView inspection for apps that do not opt in themselves. After installing it, Safari Web Inspector can attach to `WKWebView` (@MASTG-KNOW-0076) instances in those apps.

To activate web inspection, follow these steps:

1. On the iOS device, open the Settings app: go to **Safari** -> **Advanced** and toggle on **Web Inspector**.
2. On the macOS device, open Safari: in the menu bar, go to **Safari** -> **Settings** -> **Advanced** and enable **Show features for web developers**.
3. Connect your iOS device to the macOS device and unlock it: the iOS device name should appear in the **Develop** menu.
4. If needed, in macOS Safari go to **Develop** -> **'iOS device name'** -> **Use for Development** and trust the device.

To open Web Inspector and debug a WebView:

1. On iOS, open the app and navigate to any screen containing a WebView.
2. In macOS Safari, go to **Develop** -> **'iOS Device Name'**, and you should see the name of the WebView based context. Click it to open Web Inspector.

Now you're able to debug the WebView as you would with a regular web page in your desktop browser.

<img src="Images/Tools/TOOL-0137-safari-dev.png" width="400px"/>

If everything is set up correctly, you can attach to any WebView with Safari:

<img src="Images/Tools/TOOL-0137-attach-webview.png" width="400px"/>

<img src="Images/Tools/TOOL-0137-web-inspector.png" width="400px"/>
OWASP Mobile Application Security Testing Guide: MASTG TECH 0068

---
title: Disassembling Native Code
platform: ios
---

Because Objective-C and Swift are fundamentally different, the programming language used to write the app affects the feasibility of reverse engineering it. For example, Objective-C allows method invocations to be changed at runtime. This makes hooking into other app functions (a technique heavily used by [Cycript](http://www.cycript.org/ "Cycript") and other reverse engineering tools) easy. This "method swizzling" is implemented differently in Swift, which makes the technique harder to implement in Swift than in Objective-C.

On iOS, all the application code (both Swift and Objective-C) is compiled to machine code (e.g. ARM). Thus, to analyze iOS applications, a disassembler is needed.

If you want to disassemble an application from the App Store, remove the FairPlay DRM first. See @MASTG-TECH-0054 for more information.

In this context, the term "app binary" refers to the Mach-O file in the application bundle, which contains the compiled code and should not be confused with the application bundle - the IPA file. See @MASTG-TECH-0058 for more details on the composition of IPA files.

## Disassembling With IDA Pro

If you have a license for IDA Pro, you can also analyze the app binary with IDA Pro.

> The free version of IDA unfortunately does not support the ARM processor type.

To get started, open the app binary in IDA Pro.

<img src="Images/Chapters/0x06c/ida_macho_import.png" width="100%" />

Upon opening the file, IDA Pro will perform auto-analysis, which can take some time depending on the binary's size. Once the auto-analysis is completed, you can browse the disassembly in the **IDA View** (Disassembly) window and explore functions in the **Functions** window, both shown in the screenshot below.

<img src="Images/Chapters/0x06c/ida_main_window.png" width="100%" />

A regular IDA Pro license does not include a decompiler by default and requires an additional license for the Hex-Rays decompiler, which is expensive. In contrast, Ghidra consists of a highly capable, free built-in decompiler, making it a compelling alternative for reverse engineering.

If you have a regular IDA Pro license and do not want to buy the Hex-Rays decompiler, you can use Ghidra's decompiler by installing the [GhIDA plugin](https://github.com/Cisco-Talos/GhIDA/) for IDA Pro.
OWASP Mobile Application Security Testing Guide: MASTG TECH 0060

---
title: Monitoring System Logs
platform: ios
---

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 multiple methods:

## Using @MASTG-TOOL-0070

1. Launch Xcode.
2. Connect your device to your host computer.
3. Choose **Window** -> **Devices and Simulators**.
4. Click on your connected iOS device in the left section of the Devices window.
5. Reproduce the problem.
6. Click on the **Open Console** button located in the upper right-hand area of the Devices window to view the console logs in a separate window.

<img src="Images/Chapters/0x06b/open_device_console.png" width="100%" />

To save the console output to a text file, go to the top right side of the Console window and click on the **Save** button.

<img src="Images/Chapters/0x06b/device_console.png" width="100%" />

## Using @MASTG-TOOL-0126

1. Connect your device to your host computer.
2. Run `idevicesyslog | grep YOUR_APP_NAME` in your terminal. The output will include many device-specific logs for that app.

<img src="Images/Chapters/0x06b/idevicesyslog-screen.png" width="100%" />

!!! note
    The `idevicesyslog` might not log all types of logs. E.g [debug](https://developer.apple.com/documentation/os/oslogtype/debug) and [info](https://developer.apple.com/documentation/os/oslogtype/info) logs might not be logged.
OWASP Mobile Application Security Testing Guide: MASTG TECH 0071

---
title: Retrieving Strings
platform: ios
---

Strings are always a good starting point while analyzing a binary, as they provide context to the associated code. For instance, an error log string such as "Cryptogram generation failed" suggests that the adjoining code might be responsible for generating the cryptogram.

To extract strings from an iOS binary, you can use GUI tools such as Ghidra or [iaito](https://github.com/radareorg/iaito "iaito") or rely on CLI-based tools such as the _strings_ Unix utility (`strings <path_to_binary>`) or radare2's @MASTG-TOOL-0129 (`rabin2 -zz <path_to_binary>`). When using CLI-based tools, you can leverage other tools, such as grep (with regular expressions), to further filter and analyze the results.
OWASP Mobile Application Security Testing Guide: MASTG TECH 0072

---
title: Retrieving Cross References
platform: ios
---

@MASTG-TOOL-0033 can be used to analyze iOS binaries and retrieve cross-references by right-clicking the desired function and selecting **Show References to**.
OWASP Mobile Application Security Testing Guide: MASTG TECH 0132

---
title: Software Composition Analysis (SCA) of iOS Dependencies by Creating a SBOM
platform: ios
---

You can use @MASTG-TOOL-0134 to generate a Software Bill of Materials (SBOM) in the CycloneDX format when using SwiftPM. Currently, Carthage and CocoaPods are not supported. You can either ask the development team to provide the SBOM file or create it yourself. To do so, navigate to the root directory of the Xcode project you wish to scan, then execute the following command:

```bash
$ cdxgen -o sbom.json
```

The SBOM file needs to be Base64-encoded and uploaded to @MASTG-TOOL-0132 for analysis.

```bash
$ cat sbom.json | base64
$ curl -X "PUT" "http://localhost:8081/api/v1/bom" \
     -H 'Content-Type: application/json' \
     -H 'X-API-Key: <YOUR API KEY>>' \
     -d $'{
  "project": "<YOUR PROJECT ID>",
  "bom": "<BASE64-ENCODED SBOM>"
  }'
```

Also, check the [alternatives for uploading](https://docs.dependencytrack.org/usage/cicd/) the SBOM file if the generated JSON file is too large.

If you are using the default settings of the @MASTG-TOOL-0133 Docker container, go to the frontend of @MASTG-TOOL-0132, which is <http://localhost:8080>. Open the project you uploaded the SBOM to verify whether there are any vulnerable dependencies.

!!! note
    Transitive dependencies are not supported by @MASTG-TOOL-0134 for [SwiftPM](https://cdxgen.github.io/cdxgen/#/PROJECT_TYPES).
OWASP Mobile Application Security Testing Guide: MASTG TECH 0114

---
title: Demangling Symbols
platform: ios
---

To make some identifiers unique within the program, the compiler processes their symbol names. This process is called "name mangling" or simply "mangling". Often, the resulting symbols are complex for humans to interpret. Additionally, their format is specific to the input language and the compiler and may even be version-dependent.

You can use demangling tools to reverse the mangling process. For Swift, see @MASTG-TOOL-0067 and for C++ function names, @MASTG-TOOL-0122.

## swift-demangle

Pass the mangled symbol to @MASTG-TOOL-0067:

```bash
$ xcrun swift-demangle __T0So9WKWebViewCABSC6CGRectV5frame_So0aB13ConfigurationC13configurationtcfcTO
_T0So9WKWebViewCABSC6CGRectV5frame_So0aB13ConfigurationC13configurationtcfcTO ---> @nonobjc __C.WKWebView.init(frame: __C_Synthesized.CGRect, configuration: __C.WKWebViewConfiguration) -> __C.WKWebView
```

## c++filt

You can demangle C++ symbols with @MASTG-TOOL-0122:

```bash
c++filt _ZSt6vectorIiSaIiEE
std::vector<int, std::allocator<int>>
```
OWASP Mobile Application Security Testing Guide: MASTG TECH 0057

---
title: Listing Installed Apps
platform: ios
---

When targeting apps installed on the device, you'll first need to determine the correct bundle identifier for 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`):

```bash
$ frida-ps -Uai
 PID  Name                 Identifier
----  -------------------  -----------------------------------------
6853  iGoat-Swift          OWASP.iGoat-Swift
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
```

It also shows which of them are currently running (@MASTG-APP-0028, for example). Note the "Identifier" (bundle identifier: `OWASP.iGoat-Swift`) and the PID (`6853`) as you'll need them for further analysis.

You can also open @MASTG-TOOL-0061 directly and, after selecting your iOS device, you'll get the list of installed apps.

<img src="Images/Chapters/0x06b/grapefruit_installed_apps.png" width="400px" />
OWASP Mobile Application Security Testing Guide: MASTG TECH 0112

---
title: Obtaining the Code Signature Format Version
platform: ios
---

To extract the code signature format version from a signed binary, you can use @MASTG-TOOL-0114.

The version is obtained by calling `codesign -dv` and identifying the value of `v` in the `CodeDirectory` row:

```bash
$ codesign -dv MASTestApp.app
Executable=/Users/user/MASTestApp.app
Identifier=org.owasp.mastestapp.MASTestApp-iOS
Format=Mach-O universal (armv7 arm64)
CodeDirectory v=20400 size=404674 flags=0x0(none) hashes=12635+7 location=embedded
Signature size=4858
...
```

In this case, the version is 20400, since the output contains `v=20400`.
OWASP Mobile Application Security Testing Guide: MASTG TECH 0138

---
title: Convert Plist Files to JSON
platform: ios
---

You can convert Plist files, such as `Info.plist` or `PrivacyInfo.xcprivacy` (which is a Plist file despite the '.xcprivacy' extension), to JSON for easier readability and analysis.

## Using plutil

Use @MASTG-TOOL-0062 to convert any Plist files, such as `PrivacyInfo.xcprivacy`, to JSON format:

```console
plutil -convert json -o PrivacyInfo.xcprivacy.json SocialApp.app/PrivacyInfo.xcprivacy
```

## Using plistlib

Use Python's built-in @MASTG-TOOL-0136 module to convert any Plist files, such as `PrivacyInfo.xcprivacy`, to JSON format:

```python
import plistlib
import json

with open('SocialApp.app/PrivacyInfo.xcprivacy', 'rb') as fp:
    data = plistlib.load(fp)

with open('PrivacyInfo.json', 'w', encoding='utf-8') as fp:
    json.dump(data, fp, indent=2, ensure_ascii=False)
```

Which outputs:

```json
{
  "NSPrivacyAccessedAPITypes": [
    {
      "NSPrivacyAccessedAPIType": "NSPrivacyAccessedAPICategoryUserDefaults",
      "NSPrivacyAccessedAPITypeReasons": [
        "CA92.1",
        "1C8F.1",
        "C56D.1"
      ]
    },
    ...
  ],
  "NSPrivacyCollectedDataTypes": [
    {
      "NSPrivacyCollectedDataType": "NSPrivacyCollectedDataTypeName",
      "NSPrivacyCollectedDataTypeLinked": true,
      "NSPrivacyCollectedDataTypePurposes": [
        "NSPrivacyCollectedDataTypePurposeAppFunctionality",
        "NSPrivacyCollectedDataTypePurposeOther"
      ],
      "NSPrivacyCollectedDataTypeTracking": false
    },
    ...
  ],
  "NSPrivacyTracking": true,
  "NSPrivacyTrackingDomains": [
    "trk-v2.socialapp.com",
    "trk-v2.socialapp.us",
    ...
  ]
}
```

## Using IPSW

Use @MASTG-TOOL-0105 to convert any Plist files, such as `Info.plist`, to JSON format:

```bash
$ ipsw plist ./Info.plist
{
    "BuildMachineOSBuild": "23B74",
    "CFBundleDevelopmentRegion": "en",
    "CFBundleExecutable": "MASTestApp",
    "CFBundleIdentifier": "org.owasp.mastestapp.MASTestApp",
    "CFBundleInfoDictionaryVersion": "6.0",
    "CFBundleName": "MASTestApp",
    "CFBundlePackageType": "APPL",
    "CFBundleShortVersionString": "1.0",
    "CFBundleSupportedPlatforms": [
        "iPhoneOS"
    ],
    ...
}
```
OWASP Mobile Application Security Testing Guide: MASTG TECH 0081

---
title: Get Open Connections
platform: ios
---

The `lsof` command, when invoked with option `-i`, gives the list of open network ports for all active processes on the device. To get a list of open network ports for a specific process, the `lsof -i -a -p <pid>` command can be used, where the `-a` (AND) option is used for filtering. Below is a filtered output for PID 1.

```bash
iPhone:~ root# lsof -i -a -p 1
COMMAND PID USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
launchd   1 root   27u  IPv6 0x69c2ce210efdc023      0t0  TCP *:ssh (LISTEN)
launchd   1 root   28u  IPv6 0x69c2ce210efdc023      0t0  TCP *:ssh (LISTEN)
launchd   1 root   29u  IPv4 0x69c2ce210eeaef53      0t0  TCP *:ssh (LISTEN)
launchd   1 root   30u  IPv4 0x69c2ce210eeaef53      0t0  TCP *:ssh (LISTEN)
launchd   1 root   31u  IPv4 0x69c2ce211253b90b      0t0  TCP 192.168.1.12:ssh->192.168.1.8:62684 (ESTABLISHED)
launchd   1 root   42u  IPv4 0x69c2ce211253b90b      0t0  TCP 192.168.1.12:ssh->192.168.1.8:62684 (ESTABLISHED)
```
OWASP Mobile Application Security Testing Guide: MASTG TECH 0091

---
title: Injecting Libraries into an IPA Manually
platform: ios
---

This technique allows you to inject arbitrary libraries into an IPA file. After injecting the library, you'll have to install the modified IPA onto your device using @MASTG-TECH-0056.

This technique is appropriate when you want to add functionality or test capabilities to an application. For example, you can inject the Frida Gadget into an IPA file to enable dynamic instrumentation of the application.

We'll use the Frida Gadget (`FridaGadget.dylib`) as an example, but you can use this technique to inject any `.dylib` library you want.

## Obtaining the Library

In our example, the library is Frida Gadget, which can be downloaded from the Frida project's [GitHub release page](https://github.com/frida/frida/releases). Look for the latest release that matches your target platform and download the `frida-gadget-XX.YY.ZZ-ios-universal.dylib.xz` file.

Decompress the file using the `xz` tool and save it as `FridaGadget.dylib`:

```bash
xz -d <frida-gadget-XX.YY.ZZ-ios-universal.dylib.xz> -c > FridaGadget.dylib
```

## Adding the Library to the IPA

IPA files are ZIP archives, so you can use any ZIP tool to unpack the archive:

```bash
unzip UnCrackable-Level1.ipa
```

Next, copy the target library, in this case `FridaGadget.dylib`, into the `.app/Frameworks` directory (create the directory if it doesn't exist):

```bash
mkdir -p Payload/UnCrackable\ Level\ 1.app/Frameworks
cp FridaGadget.dylib Payload/UnCrackable\ Level\ 1.app/Frameworks/
```

Use @MASTG-TOOL-0059 to add a `load` command to the binary (`LC_LOAD_DYLIB`). The code below shows how this is done for the @MASTG-APP-0025:

```bash
optool install -c load -p "@executable_path/Frameworks/FridaGadget.dylib"  -t Payload/UnCrackable\ Level\ 1.app/UnCrackable\ Level\ 1

Found FAT Header
Found thin header...
Found thin header...
Inserting a LC_LOAD_DYLIB command for architecture: arm
Successfully inserted a LC_LOAD_DYLIB command for arm
Inserting a LC_LOAD_DYLIB command for architecture: arm64
Successfully inserted a LC_LOAD_DYLIB command for arm64
Writing executable to Payload/UnCrackable Level 1.app/UnCrackable Level 1...
```

After injecting the `load` command, you need to repackage the IPA:

```bash
zip -r patched.ipa Payload
```

To debug an iOS application obtained from the App Store, it must be re-signed with a development provisioning profile that includes the `get-task-allow` entitlement. See @MASTG-TECH-0147 for the complete workflow on patching an app to make it debuggable.
OWASP Mobile Application Security Testing Guide: MASTG TECH 0065

---
title: Reverse Engineering iOS Apps
platform: ios
---

iOS reverse engineering is a mixed bag. On the one hand, apps programmed in Objective-C and Swift can be disassembled nicely. In Objective-C, object methods are called via dynamic function pointers called "selectors", which are resolved by name during runtime. The advantage of runtime name resolution is that the names must remain intact in the final binary, making the disassembly more readable. Unfortunately, this also means that the disassembler provides no direct cross-references between methods, making it challenging to construct a flow graph.

## References

- [#miller] - Charlie Miller, Dino Dai Zovi. The iOS Hacker's Handbook. Wiley, 2012 - <https://www.wiley.com/en-us/iOS+Hacker%27s+Handbook-p[PII_REDACTED]122>
- [#levin] Jonathan Levin. Mac OS X and iOS Internals: To the Apple's Core. Wiley, 2013 - <http://newosxbook.com/MOXiI.pdf>
OWASP Mobile Application Security Testing Guide: MASTG TEST 0018

---
masvs_v1_id:
- MSTG-AUTH-8
masvs_v2_id:
- MASVS-AUTH-2
platform: android
title: Testing Biometric Authentication
masvs_v1_levels:
- L2
profiles: [L2]
status: deprecated
covered_by: [MASTG-TEST-0326, MASTG-TEST-0327, MASTG-TEST-0328, MASTG-TEST-0329, MASTG-TEST-0330]
deprecation_note: New version available in MASTG V2
---

## Overview

## Static Analysis

Note that there are quite some vendor/third party SDKs, which provide biometric support, but which have their own insecurities. Be very cautious when using third party SDKs to handle sensitive authentication logic.

## Dynamic Analysis

Please take a look at this detailed [blog article about the Android KeyStore and Biometric authentication](https://labs.withsecure.com/blog/how-secure-is-your-android-keystore-authentication "How Secure is your Android Keystore Authentication?"). This research includes two Frida scripts which can be used to test insecure implementations of biometric authentication and try to bypass them:

- [Fingerprint bypass](https://github.com/FSecureLABS/android-keystore-audit/blob/master/frida-scripts/fingerprint-bypass.js "Fingerprint Bypass"): This Frida script will bypass authentication when the `CryptoObject` is not used in the `authenticate` method of the `BiometricPrompt` class. The authentication implementation relies on the callback `onAuthenticationSucceded` being called.
- [Fingerprint bypass via exception handling](https://github.com/FSecureLABS/android-keystore-audit/blob/master/frida-scripts/fingerprint-bypass-via-exception-handling.js "Fingerprint bypass via exception handling"): This Frida script will attempt to bypass authentication when the `CryptoObject` is used, but used in an incorrect way. The detailed explanation can be found in the section "Crypto Object Exception Handling" in the blog post.
OWASP Mobile Application Security Testing Guide: MASTG TEST 0017

---
masvs_v1_id:
- MSTG-AUTH-1
- MSTG-STORAGE-11
masvs_v2_id:
- MASVS-AUTH-2
platform: android
title: Testing Confirm Credentials
masvs_v1_levels:
- L2
profiles: [L2]
status: deprecated
covered_by: ['MASTG-TEST-0327', 'MASTG-TEST-0330']
deprecation_note: New version available in MASTG V2
---

## Overview

## Static Analysis

Make sure that the unlocked key is used during the application flow. For example, the key may be used to decrypt local storage or a message received from a remote endpoint. If the application simply checks whether the user has unlocked the key or not, the application may be vulnerable to a local authentication bypass.

## Dynamic Analysis

Validate the duration of time (seconds) for which the key is authorized to be used after the user is successfully authenticated. This is only needed if `setUserAuthenticationRequired` is used.
OWASP Mobile Application Security Testing Guide: MASTG TEST 0005

---
masvs_v1_id:
- MSTG-STORAGE-4
masvs_v2_id:
- MASVS-STORAGE-2
platform: android
title: Determining Whether Sensitive Data Is Shared with Third Parties via Notifications
masvs_v1_levels:
- L1
- L2
profiles: [L1, L2]
status: deprecated
covered_by: [MASTG-TEST-0315]
deprecation_note: New version available in MASTG V2
---

## Overview

## Static Analysis

Search for any usage of the `NotificationManager` class which might be an indication of some form of notification management. If the class is being used, the next step would be to understand how the application is [generating the notifications](https://developer.android.com/training/notify-user/build-notification#SimpleNotification "Create a Notification") and which data ends up being shown.

## Dynamic Analysis

Run the application and start tracing all calls to functions related to the notifications creation, e.g. `setContentTitle` or `setContentText` from [`NotificationCompat.Builder`](https://developer.android.com/reference/androidx/core/app/NotificationCompat.Builder). Observe the trace in the end and evaluate if it contains any sensitive information which another app might have eavesdropped.