Mobile app instrumentation

From brucesongs/kali-claw · View interactive version

Mobile app instrumentation is an AI agent skill from the GitHub repository brucesongs/kali-claw. Dynamic instrumentation of iOS/Android apps via Frida, Objection, r2frida, and Introspy; runtime SSL pinning bypass, jailbreak/root detection bypass, native library hooking, and runtime secrets extraction.

How to use this skill

Skill file

Skill: Mobile App Instrumentation — Runtime Exploitation of iOS/Android Applications

Supplementary Files:

- payloads.md — 18 instrumentation sections with 60+ Frida JS scripts, Objection CLI one-liners, r2frida bridges, and runtime manipulation recipes (SSL pinning bypass, jailbreak/root detection bypass, anti-debug bypass, keychain/keystore dumping, native lib instrumentation, crypto tracing, WebView manipulation, anti-Frida evasion, and blue-side detection patterns)

- test-cases.md — 12 structured test cases (TC-MI-001 .. TC-MI-012) covering environment bring-up, iOS/Android app acquisition, Frida SSL pinning bypass, Objection runtime exploration, keychain/keystore dumping, jailbreak detection bypass, anti-debug bypass, r2frida native lib analysis, crypto tracing, and anti-Frida detection bypass

- guides/mobile-app-instrumentation-playbook.md — End-to-end operational playbook (iOS/Android runtime model, instrumentation lab build-out on jailbroken iOS / Magisk-rooted Android, instrumentation workflow, real-world case studies of Instagram cookie hijack, Snapchat jailbreak detection history, Uber cert pinning evolution, TikTok keystore bypass, and defense patterns including Play Integrity API and iOS App Attest)

- guides/mobile-app-instrumentation-ios-android-deep.md — Advanced deep dive: iOS instrumentation internals (frida-server / frida-gadget / USBMUXD, SSL Kill Switch 3, BoringSSL bypass, Shadow / A-Bypass / Liberty / Choicy jailbreak detection defeat, Keychain dump, URL scheme hijack, App Attest bypass research, PAC on A12+, CoreTrust CVE-2023-41974 / kfd exploit chain), Android instrumentation (Frida gadget injection modes, Magisk + Zygisk + LSPosed, RASP bypass recipe for PGY / Promon / Arxan, Flutter reverse via reflutter + BoringSSL, React Native / Hermes via hbctool), high-value CVE targets (CVE-2024-0044 run-as sandbox escape, Play Integrity bypass via pif), the full SSL Pinning Bypass Catalog decision matrix (15+ libraries mapped to bypass technique), modern obfuscation defeat (OLLVM string deobfuscation, control-flow flattening via angr / HexRaysDeob / ghidra-emotet, radare2 native arm64 flow), and lab setup (Corellium, Android Studio Emulator + Frida, Genymotion, Objection tunneling)

Summary

Mobile app instrumentation is the runtime counterpart to static mobile-app analysis. Where mobile-security reads the Info.plist, the AndroidManifest.xml, the binary's strings, and the Smali bytecode to discover what the app could do, this skill attaches a live Frida/Objection/r2frida bridge to a running process and observes what the app actually does at execution time — then forces it to behave otherwise. The operator spins up a jailbroken iOS device (checkm8 on A7-A11 or newer arm64e on A12+ with appropriate exploits) or a Magisk-rooted Android device (Android 13/14/15), acquires the app binary (decrypted IPA on iOS via Clutch/iPAA/bfinject; APK pull on Android via adb shell pm path), performs static triage with jadx/apktool/radare2/ghidra to locate the classes and functions of interest, then attaches Frida to hook arbitrary Java/Kotlin methods, Objective-C/Swift methods, and native exported functions. With those hooks in place, the operator can dump the iOS keychain (ios keychain dump), enumerate and manipulate the Android Keystore (android keystore), bypass SSL pinning at runtime (Frida's bypass_ssl_pinning.js lineage or Objection's android sslpinning disable / ios sslpinning disable), defeat jailbreak/root detection by hooking the detection routines to return false, defeat anti-debug routines (ptrace, sysctl, debug-trace), trace cryptographic operations (CC/CryptoKit on iOS; javax.crypto.* on Android), exploit WebView JavaScript bridges by invoking private bridge methods at runtime, and extract secrets (tokens, OAuth refresh tokens, biometric-gated keys) that the app would otherwise never write to disk. The discipline maps to MITRE ATT&CK Mobile T1623 (Mobile Adware), T1518 (Software Discovery), T1406 (Defacement), and T1627.001 (Adversary-in-the-Mobile-Device). Real-world engagements include bypassing Instagram certificate pinning to hijack session cookies, defeating Snapchat's evolving jailbreak detection lineage, bypassing Uber's multi-layer certificate pinning, and extracting TikTok's Keystore-attested secrets. Reference implementations: Frida (~19.7k stars, industry-standard), Objection (SensePost), r2frida (radare2 + Frida bridge), Introspy (iOS/Android tracer), Cycript (legacy iOS), iPAA/Clutch/bfinject (iOS decryption), jtool2, radare2, ghidra, jadx, apktool.

Tools: Frida, Objection, r2frida, Introspy, Cycript, iPAA, Clutch, bfinject, jtool2, radare2, ghidra, jadx, apktool

Domain: mobile-deep

Mappings: MITRE ATT&CK Mobile T1623 (Mobile Adware), T1518 (Software Discovery), T1406 (Defacement), T1627.001 (Adversary-in-the-Mobile-Device — Device Administrator), T1437 (Application Layer Protocol — TLS interception); OWASP MASVS V6 (Cryptography), V7 (User Authentication), V8 (Network Communication), V9 (Platform Interaction); OWASP MA5 (Insecure Communication — pinning); OWASP MASTG MASVS-NETWORK-1, MASVS-RESILIENCE-1..13

Detection Methods

Mobile App Tampering

SIEM Detection Rules

Defense Evasion Techniques

Frida Stealth

Jailbreak Stealth

SSL Pinning Bypass Stealth

Differentiation

This skill is explicitly distinct from mobile-security. Both deal with iOS/Android application assessment, but the operating mode is completely different.

| Aspect | mobile-security (existing skill) | mobile-app-instrumentation (this skill) |

|------|--------------------------------------|--------------------------------------------|

| Operating mode | Static — reads config, manifest, bytecode | Runtime — attaches to live process |

| Primary inputs | Info.plist, AndroidManifest.xml, Smali, strings, entitlements | Live process memory, method invocations, native calls |

| Tooling | jadx, apktool, mob-sf, iGoat, static analyzers | frida, objection, r2frida, introspy |

| What it proves | What the app could do (potential weakness) | What the app actually does at runtime (live exploitation) |

| Typical finding | "Hardcoded API key in strings.xml" or "Cleartext traffic allowed" | "Bypassed SSL pinning and exfiltrated the session cookie in real time" |

| Device requirement | None — analysis is offline | Jailbroken iOS / rooted Android device |

| Defender signal | Build-time config / lint | Runtime self-checks, SafetyNet, App Attest |

| MITRE mapping | MASVS static violations | T1627.001 — Adversary-in-the-Mobile-Device |

Coexistence model: The two skills compose. A typical engagement starts with mobile-security static triage to identify candidates (which classes handle SSL pinning? which native lib implements anti-debug?), then transitions to this skill to actually bypass and exploit those candidates at runtime. Use mobile-security to scope; use this skill to demonstrate.

Difference from reverse-engineering: reverse-engineering covers the binary-reversing discipline in general (ELF, PE, Mach-O, JVM bytecode). This skill is the mobile-runtime specialization — we lean on jadx/ghidra/radare2 for static triage, but the deliverable here is a runtime finding produced by an instrumented hook, not a static disassembly.

Difference from network-sniffing-mitm: That skill intercepts wire traffic with mitmproxy/Burp as a network element. When the app implements certificate pinning, that interception fails — and that is precisely when you pivot to this skill: instrument the app to disable pinning at runtime, then network-sniffing-mitm resumes. The skills form the standard two-step attack chain against any pinned mobile backend.

Use Cases

Core Tools

| Tool | Purpose | Command / Usage |

|------|---------|-----------------|

| Frida | Industry-standard dynamic instrumentation toolkit (JavaScript bridge to a live process on iOS/Android/Windows/Linux/macOS). ~19.7k stars. | frida -U -f com.example.app -l hook.js --no-pause; frida-ps -Uai; frida-trace -U -i "open*" -f com.example.app |

| Objection (SensePost) | Runtime exploration toolkit on top of Frida — provides a REPL with high-level commands for SSL pinning, keychain, keystore, hooking, etc. | objection -g com.example.app explore; then android sslpinning disable, ios keychain dump, android hooking list activities, etc. |

| r2frida | radare2 ↔ Frida bridge — drive r2 commands against a live process; inspect and hook native code in-process. | r2 'frida://spawn/attach/com.example.app' then iE (exports), dc (continue), =!? (help) |

| Introspy (iSEC Partners) | iOS/Android black-box tracer — generates a Frida-based hook set that logs every crypto/IPC/keychain call and produces a database + visualizer. | introspy-cli -p com.example.app -o trace.db; introspy-ui trace.db (web viewer) |

| Cycript (saurik, legacy iOS) | Objective-C++ introspection runtime — injects into a process and lets you evaluate ObjC expressions live. Predates Frida on iOS; still useful on legacy iOS < 13. | cycript -p SpringBoard then UIApp.keyWindow.recursiveDescription().toString() |

| iPAA (iOS App Extractor) | iOS app decryption / IPA extraction — pulls the FairPlay-decrypted binary from memory on a jailbroken device. | iPAA (interactive on device) → select app → produces decrypted .app bundle |

| Clutch (Khelandros / NinjaRIP) | iOS app decryption — decrypts apps in-memory using PT_TRACE and produces a decrypted IPA suitable for class-dump and Frida. | Clutch -d com.example.app or Clutch -i (interactive) |

| bfinject (Barnacle Nguyen) | iOS tweak injection + app decryption — older but still cited; used for Cycript/Frida injection on iOS 11 era. | bfinject -p com.example.app -l frida-cycript |

| jtool2 (Stefan Esser / Oren) | Modern Mach-O analysis CLI — replaces otool and class-dump-z for iOS binary triage; reads LC segments, ObjC metadata, entitlements, codesign blobs. | jtool2 -L AppBinary; jtool2 -objc AppBinary; jtool2 --ent AppBinary |

| radare2 | Cross-platform reverse-engineering framework — disassembles iOS Mach-O and Android ELF (.so) binaries; combined with r2frida for live analysis. | r2 -A libNative.so; aaa; afl; s sym.Java_com_example_Native_doStuff; pdf |

| ghidra | NSA reverse-engineering suite — decompiler for large iOS/Android native binaries; produces readable C-like pseudocode for sub_XXXX routines. | ghidraRun → import binary → Auto-Analyze → open in CodeBrowser |

| jadx | Android Dex → Java decompiler — the de-facto starting point for any APK triage; reads multidex, smali, resources. | jadx -d out/ app.apk; jadx --show-bad-code app.apk |

| apktool | Android APK decode/rebuild — extracts AndroidManifest.xml, smali, and res/; used to patch apps pre-instrumentation (e.g., to add a debuggable=true flag). | apktool d app.apk -o out/; apktool b out/ -o patched.apk |

Methodology

Phase 1 — App Acquisition

Before any instrumentation, the operator needs the app binary on disk:

Phase 2 — Environment Preparation

Phase 3 — Static Triage

Run the binary through jadx (Android) or jtool2 / ghidra (iOS) to identify:

Triage output is a target list — not yet findings, but a hook candidate list.

Phase 4 — Instrumentation

Attach Frida (or Objection) and load the hook candidates:

Iterate over candidates: pinning, jailbreak, anti-debug, crypto, keychain. Each hook logs to a file (Frida send() + Python sink) for later replay and evidence capture.

Phase 5 — Runtime Manipulation

With hooks in place, manipulate the live process:

Document every step: hook script, log output, screenshot, and the downstream consequence (decrypted HTTPS, extracted token, bypassed gate). This evidence packet is the deliverable.

iOS Instrumentation Stack

The iOS instrumentation stack spans multiple layers — the operator must know which layer a given app uses to choose the right bypass. This stack is documented in detail in guides/mobile-app-instrumentation-ios-android-deep.md.

Android Instrumentation Stack

The Android stack has its own dynamics — gadget injection for non-rooted devices, Magisk + Zygisk + LSPosed as a Frida-invisible alternative, and a separate RASP-bypass discipline.

Gadget injection is the operator's default for non-rooted engagements (corporate-managed devices) and for stealth against RASP that detects frida-server.

1. Port-shift Frida: ./frida-server -l 0.0.0.0:13371 (defeats the 27042 port check).

2. Rename the binary (defeats /proc/<pid>/exe name check).

3. Scrub /proc/self/maps and /proc/self/status via fopen interceptor (defeats the frida-agent / libfrida maps scan).

4. Rename Frida threads via pthread_setname_np interceptor (defeats the gmain / gdbus / gum-js-loop thread-name scan).

5. Hook Debug.isDebuggerConnected to return false (defeats the debugger check).

SSL Pinning Bypass Catalog

Modern mobile apps pin TLS at multiple layers. The decision matrix below maps each pinning library to its bypass technique. Use it as the first lookup when triaging an app.

| Library / Mechanism | Platform | Detection Signature | Bypass Technique |

|---|---|---|---|

| OkHttp CertificatePinner | Android | okhttp3.CertificatePinner.check | Objection android sslpinning disable or hook check() to no-op |

| X509TrustManager (custom) | Android | Class implements javax.net.ssl.X509TrustManager | Replace with trust-all TrustManager via Java.registerClass |

| X509TrustManagerExtensions.checkServerTrusted | Android | android.net.http.X509TrustManagerExtensions | Hook checkServerTrusted to return empty list |

| Network Security Config (<pin-set>) | Android | network_security_config.xml | Hook Conscrypt's TrustManagerImpl.checkTrustedRecursive |

| Conscrypt (Play Services BoringSSL) | Android | com.google.android.gms.conscrypt / com.android.org.conscrypt.TrustManagerImpl | Hook TrustManagerImpl.checkTrustedRecursive |

| BoringSSL (Flutter libflutter.so) | Android/iOS | SSL_CTX_set_custom_verify / SSL_set_custom_verify in libflutter.so | Pattern-scan for the API and Interceptor.replace to disable verify |

| BoringSSL (cronet / grpc) | iOS/Android | Static-linked into native lib | Same Flutter pattern — pattern-scan + Interceptor.replace |

| AFSecurityPolicy (AFNetworking) | iOS | - setSSLPinningMode: / - evaluateServerTrust: | Hook evaluateServerTrust: to return YES |

| TrustKit (iOS) | iOS | TSKPinningValidator.validateTrust | Hook validateTrust to return success |

| NSURLSessionDelegate (custom) | iOS | - URLSession:didReceiveChallenge:completionHandler: | Hook delegate method to call completion with useCredential |

| URLSession (Swift async/await) | iOS 15+ | Swift wrapper over URLSessionDelegate | Same as NSURLSessionDelegate |

| Network.framework (nw_protocol_options) | iOS 14+ | nw_protocol_options_create_tls + sec_protocol_options_set_verify_block | Hook verify block to call handler(true) |

| SecureTransport (legacy iOS) | iOS < 13 | SSLHandshake / SSLSetSessionOption | SSL Kill Switch 3 covers system-wide |

| WebViewClient.onReceivedSslError | Android | Custom WebViewClient calls handler.cancel() | Hook to call handler.proceed() |

| WKWebView didReceiveServerTrustChallenge | iOS | - webView:didReceiveServerTrustChallenge:completionHandler: | Hook to call completion with useCredential |

| Custom pinning (in-house) | Both | Vendor-specific | Static triage (jadx / jtool2 -objc) → targeted Frida hook |

Operator workflow: identify the pinning library (search the disassembled app), match against the matrix, apply the bypass technique, verify via mitmproxy. Modern banking apps stack 2-4 pinning layers (HTTP client + OS + native SDK) — the operator must bypass all layers; bypass scripts compose without conflict. See guides/mobile-app-instrumentation-ios-android-deep.md Section 6 for the full decision matrix and the stacked-pinning case study.

Modern Obfuscation Defeat

Modern mobile native libraries (banking, gaming, DRM, anti-cheat) are protected by OLLVM (Obfuscator-LLVM) descendants. The same techniques that appear in desktop malware (Emotet, Conti, TrickBot) appear in mobile libNative.so / Native.dylib.

See guides/mobile-app-instrumentation-ios-android-deep.md Section 7 for full worked examples (Frida .bss dump script, angr CFF recovery, IDA Python dispatcher finder, radare2 JNI flow).

Practical Steps

Example 1 — Frida SSL Pinning Bypass (Generic Script)

Save as bypass_ssl_pinning.js:

// bypass_ssl_pinning.js
// Generic SSL pinning bypass covering common iOS and Android pinning APIs.
// Usage: frida -U -f com.example.app -l bypass_ssl_pinning.js --no-pause

setTimeout(function () {
  // ---- Android: OkHttp CertificatePinner ----
  if (Java.available) {
    Java.perform(function () {
      try {
        var CertificatePinner = Java.use('okhttp3.CertificatePinner');
        CertificatePinner.check.overload('java.lang.String', 'java.util.List').implementation = function () {
          console.log('[+] OkHttp CertificatePinner.check() bypassed');
          return;
        };
      } catch (e) { console.log('[-] OkHttp not present: ' + e); }

      // ---- Android: X509TrustManager ----
      try {
        var X509TrustManager = Java.use('javax.net.ssl.X509TrustManager');
        var SSLContext = Java.use('javax.net.ssl.SSLContext');
        var TrustManager = Java.registerClass({
          name: 'org.owasp.TrustAll',
          implements: [X509TrustManager],
          methods: {
            checkClientTrusted: function () {},
            checkServerTrusted: function () {},
            getAcceptedIssuers: function () { return []; }
          }
        });
        SSLContext.init.overload(
          '[Ljavax.net.ssl.KeyManager;',
          '[Ljavax.net.ssl.TrustManager;',
          'java.security.SecureRandom'
        ).implementation = function (km, tm, sr) {
          console.log('[+] SSLContext.init() replaced with trust-all');
          this.init(km, [TrustManager.$new()], sr);
        };
      } catch (e) { console.log('[-] X509TrustManager hook failed: ' + e); }
    });
  }

  // ---- iOS: SecTrustEvaluate ----
  if (ObjC.available) {
    var SecTrustEvaluate = Module.findExportByName('Security', 'SecTrustEvaluate');
    if (SecTrustEvaluate) {
      Interceptor.replace(SecTrustEvaluate, new NativeCallback(function (trust, result) {
        // Force kSecTrustResultProceed = 1
        Memory.writePointer(result, ptr(1));
        console.log('[+] SecTrustEvaluate() forced to proceed');
        return 0; // errSecSuccess
      }, 'int', ['pointer', 'pointer']));
    }
    // Also hook the Swift-level URLSessionDelegate if present (left as exercise).
  }
}, 0);

Run with frida -U -f com.example.app -l bypass_ssl_pinning.js --no-pause. All TLS errors should disappear — re-arm mitmproxy and the traffic flows decrypted.

Example 2 — Objection Runtime Exploration

# Spawn the target under objection's REPL
objection -g com.example.app explore

# Inside the REPL — explore the app surface:
android hooking list classes
android hooking search classes keyword
android hooking list activities
android hooking list services
android hooking watch class_method com.example.LoginManager.login --dump-args --dump-return

# Disable SSL pinning in-process
android sslpinning disable
ios sslpinning disable

# Dump secrets at rest
ios keychain dump
ios nsuserdefaults get
android keystore list
android root disable

# Bypass biometrics
android biometric disable

Objection is the fastest path from "I have the app" to "I have the runtime surface" — use it for triage, drop down to raw Frida for custom hooks.

Example 3 — r2frida Native Library Analysis

# Launch r2 against the live process
r2 'frida://spawn/com.example.app'

# Inside r2 — enumerate native modules:
[0x00000000]> iE~libnative
# Seek into the native lib and list exports:
[0x00000000]> s sym.Java_com_example_Native_nativeSign
[0xdeadbeef]> pdf   # disassemble
[0xdeadbeef]> =?/ip # inject a Frida hook for this export via the bridge

# Detach and resume:
[0x00000000]> dc

r2frida lets you do static and dynamic analysis in one session — invaluable for understanding a native routine before you commit to a Frida hook.

Example 4 — Android Keystore Hook for Crypto Tracing

// trace_keystore.js — log every Cipher.init + doFinal with key + plaintext
Java.perform(function () {
  var Cipher = Java.use('javax.crypto.Cipher');

  Cipher.init.overload('int', 'java.security.Key').implementation = function (mode, key) {
    console.log('[Cipher.init] mode=' + mode + ' key=' + key.getEncoded());
    return this.init(mode, key);
  };

  Cipher.doFinal.overload('[B').implementation = function (input) {
    var out = this.doFinal(input);
    console.log('[Cipher.doFinal] in=' + bytesToHex(input) + ' out=' + bytesToHex(out));
    return out;
  };

  function bytesToHex(arr) {
    var s = '';
    for (var i = 0; i < arr.length; i++) s += ('0' + (arr[i] & 0xff).toString(16)).slice(-2);
    return s;
  }
});

Defense Perspective

Defenders should assume any non-server-side check is bypassable with sufficient time. The mitigation strategy is layered runtime defenses and server-side attestation:

A thorough mobile-app red-team deliverable should be paired with a mitigation mapping table: each finding → corresponding MASVS-RESILIENCE control → recommended runtime defense. See guides/mobile-app-instrumentation-playbook.md Section "Defense Patterns" for the full mapping.

References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.