deardaniel/secdata-raw huggingface dataset:
OWASP Mobile Application Security Testing Guide: MASTG KNOW 0110

---
masvs_category: MASVS-RESILIENCE
platform: generic
title: Code Injection
---

Code injection is a very powerful technique that allows you to explore and modify processes at runtime. Injection can be implemented in various ways, but you'll get by without knowing all the details thanks to freely available, well-documented tools that automate the process. These tools give you direct access to process memory and important structures such as live objects instantiated by the app. They come with many utility functions that are useful for resolving loaded libraries, hooking methods and native functions, and more. Process memory tampering is more difficult to detect than file patching, so it is the preferred method in most cases.

@MASTG-TOOL-0139, @MASTG-TOOL-0031, and @MASTG-TOOL-0027 are the most widely used hooking and code injection frameworks in the mobile industry. The three frameworks differ in design philosophy and implementation details: ElleKit and Xposed focus on code injection and/or hooking, while Frida aims to be a full-blown "dynamic instrumentation framework", incorporating code injection, language bindings, and an injectable JavaScript VM and console.

We recommend starting with Frida because it is the most versatile of the three (for this reason, we also include more Frida details and examples across the MASTG). Notably, Frida can inject a JavaScript VM into a process on both Android and iOS, while injection with ElleKit only works on iOS and Xposed only works on Android. Ultimately, however, you can of course achieve many of the same goals with either framework.
OWASP Mobile Application Security Testing Guide: MASTG KNOW 0114

---
masvs_category: MASVS-RESILIENCE
platform: generic
title: Debugging and Tracing
---

In the traditional sense, debugging is the process of identifying and isolating problems in a program as part of the software development life cycle. The same tools used for debugging are valuable to reverse engineers even when identifying bugs is not the primary goal. Debuggers enable program suspension at any point during runtime, inspection of the process' internal state, and even register and memory modification. These abilities simplify program inspection.

Tracing refers to passive logging of information about the app's execution (such as API calls). Tracing can be done in several ways, including debugging APIs, function hooks, and Kernel tracing facilities. See ["Anatomy of a code tracer"](https://medium.com/@oleavr/anatomy-of-a-code-tracer-b081aadb0df8) by Ole André Vadla Ravnås for more details.
OWASP Mobile Application Security Testing Guide: MASTG KNOW 0112

---
masvs_category: MASVS-RESILIENCE
platform: generic
title: Emulation-based Dynamic Analysis
---

Emulation is an imitation of a certain computer platform or program being executed in different platform or within another program. The software or hardware performing this imitation is called an _emulator_. Emulators provide a much cheaper alternative to an actual device, where a user can manipulate it without worrying about damaging the device. There are multiple emulators available for Android, but for iOS there are practically no viable emulators available. iOS only has a simulator, shipped within Xcode.

The difference between a simulator and an emulator often causes confusion and leads to use of the two terms interchangeably, but in reality they are different, specially for the iOS use case. An emulator mimics both the software and hardware environment of a targeted platform. On the other hand, a simulator only mimics the software environment.

QEMU based emulators for Android take into consideration the RAM, CPU, battery performance etc (hardware components) while running an application, but in an iOS simulator this hardware component behaviour is not taken into consideration at all. The iOS simulator even lacks the implementation of the iOS kernel, as a result if an application is using syscalls it cannot be executed in this simulator.

In simple words, an emulator is a much closer imitation of the targeted platform, while a simulator mimics only a part of it.

Running an app in the emulator gives you powerful ways to monitor and manipulate its environment. For some reverse engineering tasks, especially those that require low-level instruction tracing, emulation is the best (or only) choice. Unfortunately, this type of analysis is only viable for Android, because no free or open source emulator exists for iOS (the iOS simulator is not an emulator, and apps compiled for an iOS device don't run on it). The only iOS emulator available is a commercial SaaS solution - @MASTG-TOOL-0108.
OWASP Mobile Application Security Testing Guide: MASTG KNOW 0056

---
masvs_category: MASVS-AUTH
platform: ios
title: Local Authentication Framework
---

The [Local Authentication framework](https://developer.apple.com/documentation/localauthentication) provides facilities for requesting a passphrase or Touch ID authentication from users. Developers can display and utilize an authentication prompt by utilizing the function `evaluatePolicy` of the `LAContext` class.

Two available policies define acceptable forms of authentication:

- `deviceOwnerAuthentication`(Swift) or `LAPolicyDeviceOwnerAuthentication`(Objective-C): When available, the user is prompted to perform Touch ID authentication. If Touch ID is not activated, the device passcode is requested instead. If the device passcode is not enabled, policy evaluation fails.

- `deviceOwnerAuthenticationWithBiometrics` (Swift) or `LAPolicyDeviceOwnerAuthenticationWithBiometrics`(Objective-C): Authentication is restricted to biometrics where the user is prompted for Touch ID.

The `evaluatePolicy` function returns a boolean value indicating whether the user has authenticated successfully.

The Apple Developer website offers code samples for both [Swift](https://developer.apple.com/documentation/localauthentication "LocalAuthentication") and [Objective-C](https://developer.apple.com/documentation/localauthentication?language=objc "LocalAuthentication"). A typical implementation in Swift looks as follows.

```swift
let context = LAContext()
var error: NSError?

guard context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &error) else {
    // Could not evaluate policy; look at error and present an appropriate message to user
}

context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: "Please, pass authorization to enter this area") { success, evaluationError in
    guard success else {
        // User did not authenticate successfully, look at evaluationError and take appropriate action
    }

    // User authenticated successfully, take appropriate action
}
```
OWASP Mobile Application Security Testing Guide: MASTG KNOW 0095

---
masvs_category: MASVS-STORAGE
platform: ios
title: Firebase Real-time Databases
---

Firebase is a development platform with more than 15 products, and one of them is Firebase Real-time Database. 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.

A misconfigured Firebase instance can be identified by making the following network call:

`https://\<firebaseProjectName\>.firebaseio.com/.json`

The _firebaseProjectName_ can be retrieved from the property list(.plist) file. For example, `PROJECT_ID` key stores the corresponding Firebase project name in _GoogleService-Info.plist_ file.

Alternatively, the analysts can use [Firebase Scanner](https://github.com/shivsahni/FireBaseScanner "Firebase Scanner"), a python script that automates the task above as shown below:

```bash
python FirebaseScanner.py -f <commaSeparatedFirebaseProjectNames>
```
OWASP Mobile Application Security Testing Guide: MASTG KNOW 0101

---
masvs_category: MASVS-STORAGE
platform: ios
title: Logs
---

iOS developers can use various logging mechanisms to output runtime information for debugging and monitoring purposes. Traditional logging methods, such as `print` statements or `NSLog`, can inadvertently expose sensitive information in system logs, which may be accessible to attackers with device access.

A modern and secure approach to logging on iOS is to use [Apple's Unified Logging system](https://developer.apple.com/documentation/os/logging), which provides structured and privacy-aware logging capabilities. This system allows developers to categorize log messages by severity and apply privacy modifiers to protect sensitive data.

The relevant APIs include:

- [`Logger`](https://developer.apple.com/documentation/os/logger) (Swift)
- [`os_log`](https://developer.apple.com/documentation/os/os_log) (Objective-C)

Key concepts:

- **Privacy Modifiers**: These modifiers help control how data appears in logs. For example, `.private` redacts sensitive information in persistent logs, while `.public` allows non-sensitive data to be displayed openly.
- **Log Levels**: Unified logging supports multiple log levels (e.g., `debug`, `info`, `error`, `fault`) to help categorize messages based on their importance and severity.

Apart from using secure logging APIs, developers can also implement build configurations or preprocessor directives to disable or limit logging in production builds. This ensures that sensitive information is not exposed in live environments.
OWASP Mobile Application Security Testing Guide: MASTG KNOW 0098

---
masvs_category: MASVS-STORAGE
platform: ios
title: User Interface Components
---

Entering sensitive information when, for example, registering an account or making payments, is an essential part of using many apps. This data may be financial information such as credit card data or user account passwords. The data may be exposed if the app doesn't properly mask it while it is being typed.

In order to prevent disclosure and mitigate risks such as [shoulder surfing](https://en.wikipedia.org/wiki/Shoulder_surfing_%28computer_security%29) you should verify that no sensitive data is exposed via the user interface unless explicitly required (e.g. a password being entered). For the data required to be present it should be properly masked, typically by showing asterisks or dots instead of clear text.

Carefully review all UI components that either show such information or take it as input. Search for any traces of sensitive information and evaluate if it should be masked or completely removed.
OWASP Mobile Application Security Testing Guide: MASTG KNOW 0096

---
masvs_category: MASVS-STORAGE
platform: ios
title: Realm Databases
---

[Realm Objective-C](https://realm.io/docs/objc/latest/ "Realm Objective-C") and [Realm Swift](https://realm.io/docs/swift/latest/ "Realm Swift") aren't supplied by Apple, but they are still worth noting. They store everything unencrypted, unless the configuration has encryption enabled.

The following example demonstrates how to use encryption with a Realm database:

```swift
// 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)")
}
```

Access to the data depends on the encryption: unencrypted databases are easily accessible, while encrypted ones require investigation into how the key is managed - whether it's hardcoded or stored unencrypted in an insecure location such as shared preferences, or securely in the platform's KeyStore (which is best practice).
However, if an attacker has sufficient access to the device (e.g. jailbroken access) or can repackage the app, they can still retrieve encryption keys at runtime using tools like Frida. The following Frida script demonstrates how to intercept the Realm encryption key and access the contents of the encrypted database.

```javascript
function nsdataToHex(data) {
    var hexStr = '';
    for (var i = 0; i < data.length(); i++) {
        var byte = Memory.readU8(data.bytes().add(i));
        hexStr += ('0' + (byte & 0xFF).toString(16)).slice(-2);
    }
    return hexStr;
}

function HookRealm() {
    if (ObjC.available) {
        console.log("ObjC is available. Attempting to intercept Realm classes...");
        const RLMRealmConfiguration = ObjC.classes.RLMRealmConfiguration;
        Interceptor.attach(ObjC.classes.RLMRealmConfiguration['- setEncryptionKey:'].implementation, {
            onEnter: function(args) {
                var encryptionKeyData = new ObjC.Object(args[2]);
                console.log(`Encryption Key Length: ${encryptionKeyData.length()}`);
                // Hexdump the encryption key
                var encryptionKeyBytes = encryptionKeyData.bytes();
                console.log(hexdump(encryptionKeyBytes, {
                    offset: 0,
                    length: encryptionKeyData.length(),
                    header: true,
                    ansi: true
                }));

                // Convert the encryption key bytes to a hex string
                var encryptionKeyHex = nsdataToHex(encryptionKeyData);
                console.log(`Encryption Key Hex: ${encryptionKeyHex}`);
            },
            onLeave: function(retval) {
                console.log('Leaving RLMRealmConfiguration.- setEncryptionKey:');
            }
        });

    }

}
```
OWASP Mobile Application Security Testing Guide: MASTG KNOW 0094

---
masvs_category: MASVS-STORAGE
platform: ios
title: CoreData
---

[`Core Data`](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/nsfetchedresultscontroller.html#//apple_ref/doc/uid/TP40001075-CH8-SW1 "Core Data iOS") is a framework for managing the model layer of objects in your application. It provides general and automated solutions to common tasks associated with object life cycles and object graph management, including persistence. [Core Data can use SQLite as its persistent store](https://cocoacasts.com/what-is-the-difference-between-core-data-and-sqlite/ "What Is the Difference Between Core Data and SQLite"), but the framework itself is not a database.

CoreData does not encrypt its data by default. As part of a research project (iMAS) from the MITRE Corporation, that was focused on open source iOS security controls, an additional encryption layer can be added to CoreData. See the [GitHub Repo](https://github.com/project-imas/encrypted-core-data "Encrypted Core Data SQLite Store") for more details.
OWASP Mobile Application Security Testing Guide: MASTG KNOW 0092

---
masvs_category: MASVS-STORAGE
platform: ios
title: Binary Data Storage
---

`NSData` (static data objects) and `NSMutableData` (dynamic data objects) are typically used for data storage, but they are also useful for distributed objects applications, in which data contained in data objects can be copied or moved between applications.

When writing `NSData` objects using [`write(to:options:)`](https://developer.apple.com/documentation/Foundation/Data/write(to:options:)), you can specify [`WritingOptions`](https://developer.apple.com/documentation/foundation/nsdata/writingoptions) for file protection:

- `noFileProtection`: does not encrypt the file.
- `completeFileProtection`: ensures the file is encrypted and can only be accessed when the device is unlocked.
- `completeFileProtectionUnlessOpen`: ensures the file is encrypted and can only be accessed when the device is unlocked or the file is already open.
- `completeFileProtectionUntilFirstUserAuthentication`: ensures the file is encrypted and can only be accessed until the first user authentication after a reboot.
OWASP Mobile Application Security Testing Guide: MASTG KNOW 0104

---
masvs_category: MASVS-STORAGE
platform: ios
title: Inter-Process Communication (IPC) Mechanisms
---

[Inter Process Communication (IPC)](https://nshipster.com/inter-process-communication/ "IPC on iOS") allows processes to send each other messages and data. For processes that need to communicate with each other, there are different ways to implement IPC on iOS:

- **[XPC Services](https://developer.apple.com/library/content/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingXPCServices.html "XPC Services")**: XPC is a structured, asynchronous library that provides basic interprocess communication. It is managed by `launchd`. It is the most secure and flexible implementation of IPC on iOS and should be the preferred method. It runs in the most restricted environment possible: sandboxed with no root privilege escalation and minimal file system access and network access. Two different APIs are used with XPC Services:
    - NSXPCConnection API
    - XPC Services API
- **[Mach Ports](https://developer.apple.com/documentation/foundation/nsmachport "NSMachPort")**: All IPC communication ultimately relies on the Mach Kernel API. Mach Ports allow local communication (intra-device communication) only. They can be implemented either natively or via Core Foundation (CFMachPort) and Foundation (NSMachPort) wrappers.
- **NSFileCoordinator**: The class `NSFileCoordinator` can be used to manage and send data to and from apps via files that are available on the local file system to various processes. [NSFileCoordinator](https://www.atomicbird.com/blog/sharing-with-app-extensions "NSFileCoordinator") methods run synchronously, so your code will be blocked until they stop executing. That's convenient because you don't have to wait for an asynchronous block callback, but it also means that the methods block the running thread.
OWASP Mobile Application Security Testing Guide: MASTG KNOW 0099

---
masvs_category: MASVS-STORAGE
platform: ios
title: Screenshots
---

Manufacturers want to provide device users with an aesthetically pleasing effect when an application is started or exited, so they introduced the concept of saving a screenshot when the application goes into the background. This feature can pose a security risk because screenshots (which may display sensitive information such as an email or corporate documents) are written to local storage, where they can be recovered by a rogue application with a sandbox bypass exploit or someone who steals the device.

Screenshots are stored inside the app's container at
`/var/mobile/Containers/Data/Application/$APP_ID/Library/SplashBoard/Snapshots/sceneID:$APP_NAME-default/`. They are overwritten every time the app enters the background state.

The system takes the screenshot after [`applicationDidEnterBackground`](https://developer.apple.com/documentation/uikit/uiapplicationdelegate/applicationdidenterbackground(_:)) completes, so it's common to display an overlay over the content of the screen. When an app comes back to the foreground, [`applicationWillEnterForeground`](https://developer.apple.com/documentation/uikit/uiapplicationdelegate/applicationwillenterforeground(_:)) is called.

You can find more information in ["Prepare your UI for the app snapshot"](https://developer.apple.com/documentation/uikit/preparing-your-ui-to-run-in-the-background#Prepare-your-UI-for-the-app-snapshot).
OWASP Mobile Application Security Testing Guide: MASTG KNOW 0102

---
masvs_category: MASVS-STORAGE
platform: ios
title: Backups
---

iOS includes auto-backup features that create copies of the data stored on the device. You can make iOS backups from your host computer by using iTunes (till macOS Catalina) or Finder (from macOS Catalina onwards), or via the iCloud backup feature. In both cases, the backup includes nearly all data stored on the iOS device except highly sensitive data such as Apple Pay information and Touch ID settings.

Since iOS backs up installed apps and their data, an obvious concern is whether sensitive user data stored by the app might unintentionally leak through the backup. Another concern, though less obvious, is whether sensitive configuration settings used to protect data or restrict app functionality could be tampered to change app behavior after restoring a modified backup. Both concerns are valid and these vulnerabilities have proven to exist in a vast number of apps today.

## How the Keychain Is Backed Up

When users back up their iOS device, the Keychain data is backed up as well, but the secrets in the Keychain remain encrypted. The class keys necessary to decrypt the Keychain data aren't included in the backup. Restoring the Keychain data requires restoring the backup to a device and unlocking the device with the users passcode.

Keychain items for which the `kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly` attribute is set can be decrypted only if the backup is restored to the backed up device. Someone trying to extract this Keychain data from the backup couldn't decrypt it without access to the crypto hardware inside the originating device.

One caveat to using the Keychain, however, is that it was only designed to store small bits of user data or short notes (according to Apple's documentation on [Keychain Services](https://developer.apple.com/documentation/security/keychain_services "Keychain Services")). This means that apps with larger local secure storage needs (e.g., messaging apps, etc.) should encrypt the data within the app container, but use the Keychain to store key material. In cases where sensitive configuration settings (e.g., data loss prevention policies, password policies, compliance policies, etc) must remain unencrypted within the app container, you can consider storing a hash of the policies in the keychain for integrity checking. Without an integrity check, these settings could be modified within a backup and then restored back to the device to modify app behavior (e.g., change configured remote endpoints) or security settings (e.g., jailbreak detection, certificate pinning, maximum UI login attempts, etc.).

The takeaway: If sensitive data is handled as recommended earlier in this chapter (e.g., stored in the Keychain, with Keychain backed integrity checks, or encrypted with a key that's locked inside the Keychain), backups shouldn't be security issue.
OWASP Mobile Application Security Testing Guide: MASTG KNOW 0100

---
masvs_category: MASVS-STORAGE
platform: ios
title: Keyboard Cache
---

Several options, such as autocorrect and spell check, are available to users to simplify keyboard input and are cached by default in `.dat` files in `/private/var/mobile/Library/Keyboard/` and its subdirectories.

The [`UITextInputTraits` protocol](https://developer.apple.com/reference/uikit/uitextinputtraits "UITextInputTraits protocol") is used for keyboard caching. The `UITextField`, `UITextView`, and `UISearchBar` classes automatically support this protocol and it offers the following properties:

- `var autocorrectionType: UITextAutocorrectionType` determines whether autocorrection is enabled during typing. When autocorrection is enabled, the text object tracks unknown words and suggests suitable replacements, replacing the typed text automatically unless the user overrides the replacement. The default value of this property is `UITextAutocorrectionTypeDefault`, which for most input methods enables autocorrection.
- `var secureTextEntry: BOOL` determines whether text copying and text caching are disabled and hides the text being entered for `UITextField`. The default value of this property is `NO`.
OWASP Mobile Application Security Testing Guide: MASTG KNOW 0097

---
masvs_category: MASVS-STORAGE
platform: ios
title: Other Third-Party Databases
---

## SQLite3

The SQLite3 library must be added to an app if the app is to use SQLite. This library is a C++ wrapper that provides an API for the SQLite commands.

## Couchbase Lite

[Couchbase Lite](https://github.com/couchbase/couchbase-lite-ios "Couchbase Lite") is a lightweight, embedded, document-oriented (NoSQL) database engine that can be synced. It compiles natively for iOS and macOS.