Skip to content

hypnguyen1209/offensive-claude / skills/mobile-pentest

mobile-pentest

Unverified

Use when pentesting an Android/iOS app — Frida 17 instrumentation, SSL-pinning & root/jailbreak bypass, Android 14/15 CA injection, exported-component/content-provider abuse, deep-link/WebView chains, biometric bypass, Flutter/React-Native RE

references/environment-interception.md

View on GitHub
# Environment, Instrumentation & TLS Interception

> **ATT&CK (Mobile):** T1635 (Install Insecure/Malicious Config), T1521.001 (SSL-pinning bypass), T1633.001 (root-detection bypass) · **CWE:** CWE-1188, CWE-295, CWE-693

Foundation cluster: build the lab, get Frida running (incl. the breaking Frida 17 changes),
trust your proxy CA on modern Android, and defeat SSL/cert pinning + root detection so every
later technique has a working dynamic-analysis surface.

---

## 1. Lab Build

### Android

- **Device options**: physical phone with **Magisk** systemless root + **Shamiko** (Magisk-Hide successor) to hide root from Play Integrity / RootBeer; or an emulator. For emulators prefer a **Google APIs / AOSP (not Play Store)** AVD image so `adb root` and `/system` remount work, or **Genymotion** for ARM-translation of ARM-only apps.
- **Hooking**: **Frida server** (arch-matched) + **objection** + optionally **LSPosed** for Xposed modules (e.g. system-wide pinning bypass with TrustMeAlready / JustTrustMe forks).
- **Proxy**: **Burp** or **mitmproxy** (`mitmweb --mode transparent`). Route via Wi-Fi proxy, or for proxy-unaware stacks (Flutter/Dart, some native HTTP) use transparent redirect: `adb shell su -c 'iptables -t nat -A OUTPUT -p tcp --dport 443 -j DNAT --to <PROXY_IP>:8080'`.
- **Static tooling**: `jadx`, `apktool`, `dex2jar`, `MobSF` (containerized), `nuclei` for the backend API.

### iOS

- Jailbroken device (tool matrix in `ios-offensive.md`): **palera1n** (checkm8, A8–A11/T2), **Dopamine** (A8–A16, iOS 15–16.6.1).
- **Frida** + **objection** + **Filza** + SSH over USB: `iproxy 2222 22` then `ssh -p 2222 root@127.0.0.1` (default `alpine`).
- Burp CA: install profile, then **Settings → General → About → Certificate Trust Settings** → enable full trust.

---

## 2. Frida 17 — what changed (May 2025) and how to not break your scripts

Frida 17.0.0 (released 2025-05-17) was the first major bump in ~3 years and **breaks custom tooling**:

- **Bundled runtime bridges removed.** `frida-java-bridge`, `frida-objc-bridge`, `frida-swift-bridge` are no longer baked into the GumJS runtime. The `Java`, `ObjC`, `Swift` globals are **still available when you use the CLI** (`frida`, `frida-trace`) because `frida-tools 14.x` bundles them — but **raw `session.create_script()` from the Python/C bindings no longer has them**.
- **Fix for custom scripts**: compile with `frida-compile`, pulling bridges via the new package manager `frida-pm`:
  ```bash
  pip install frida-tools          # 14.x ships the REPL bridges
  npm init -y
  npx frida-pm install frida-java-bridge frida-objc-bridge
  npx frida-compile agent.ts -o agent.js   # bundles ESM bridges
  frida -U -f com.target.app -l agent.js --no-pause
  ```
- **Module API reworked** (Gum 19): static `Module.findExportByName(null, 'open')` style calls changed. Modern form:
  ```js
  // OLD (pre-17):  Module.findExportByName('libssl.so', 'SSL_read')
  // NEW (17+):
  const m = Process.getModuleByName('libssl.so');   // or Module.load(...)
  const p = m.getExportByName('SSL_read');          // throws if missing; use .findExportByName for null-safe
  ```
- **CModule is NOT removed** (despite rumors) — still available for inline-C hooks.

> **Version matching is the #1 cause of "Frida won't attach".** Host `frida --version` must equal the on-device `frida-server` major.minor.patch. Download the arch-matched server from the official GitHub releases (`frida-server-<ver>-android-arm64.xz` → `xz -d`).

### Non-root / non-jailbreak: Gadget injection

When you cannot root, repackage the app with `frida-gadget`:

```bash
apktool d base.apk -o app
# drop the gadget .so matching the app's primary ABI
cp frida-gadget-17.x-android-arm64.so app/lib/arm64-v8a/libgadget.so
# force-load it from the main activity's smali (add at top of onCreate):
#   const-string v0, "gadget"
#   invoke-static {v0}, Ljava/lang/System;->loadLibrary(Ljava/lang/String;)V
# (or add <uses-native-library> / use objection patchapk which automates this)
objection patchapk -s base.apk            # automated: injects gadget, re-signs
apktool b app -o patched.apk
apksigner sign --ks debug.keystore patched.apk
```

---

## 3. Trusting your CA on Android 14/15 (Conscrypt-APEX)

**The change:** Since Android 14 the system trust store moved into the **Conscrypt Mainline APEX** at `/apex/com.android.conscrypt/cacerts`, which is **immutable** — `mount -o rw,remount` *fails* and tmpfs overlays are ignored. The legacy `/system/etc/security/cacerts/` still exists only as a **fallback** (APEX wins when present). Because Conscrypt is Mainline, even some Android 12/13 devices behave this way depending on Google Play System Update level.

**The working technique (HTTP Toolkit / NVISO method):** bind-mount a modified cert dir over the APEX path **inside the Zygote mount namespace**, so every newly-spawned app inherits it. `/apex` uses `PRIVATE` mount propagation, so you must enter Zygote's namespace explicitly and re-apply if Zygote restarts.

Cert must be named `<subject_hash_old>.0`:

```bash
# Compute the BoringSSL/OpenSSL hashed filename for your Burp/mitmproxy CA
openssl x509 -inform PEM -subject_hash_old -in cacert.pem | head -1   # e.g. 9a5ba575
cp cacert.pem 9a5ba575.0
```

Then run `scripts/android_ca_inject.sh` (full implementation in scripts/), which:
1. copies the existing APEX certs to a tmp dir, adds yours, sets `0644` + `u:object_r:system_file:s0` SELinux label;
2. `nsenter`s into the Zygote PID mount namespace and bind-mounts the dir over `/apex/com.android.conscrypt/cacerts`;
3. watches Zygote and re-injects on crash.

> Alternative for pre-A14 or as a Magisk module: **AlwaysTrustUserCerts** / **MagiskTrustUserCerts** / **ConscryptTrustUserCerts** promote the user store to system. App-targeted bypass: if the app sets a custom `networkSecurityConfig`, edit `res/xml/network_security_config.xml` to add `<certificates src="user"/>` and rebuild.

---

## 4. SSL / Certificate Pinning Bypass

### 4a. Universal Java-layer bypass (TrustManager + SSLContext)

Defeats default `X509TrustManager`, custom `SSLContext.init`, and many pinning libs in one shot. Full script: `scripts/universal_unpin.js` (also hooks OkHttp `CertificatePinner`, `okhttp3.internal`, Conscrypt `TrustManagerImpl.verifyChain`, Appcelerator/TrustKit, WebView `onReceivedSslError`, and `NetworkSecurityConfig`). Core idea:

```js
Java.perform(() => {
  // 1. Replace SSLContext TrustManager array with a do-nothing TM
  const X509TM = Java.use('javax.net.ssl.X509TrustManager');
  const SSLContext = Java.use('javax.net.ssl.SSLContext');
  const TM = Java.registerClass({
    name: 'org.pentest.TrustAll', implements: [X509TM],
    methods: {
      checkClientTrusted(c, a) {}, checkServerTrusted(c, a) {},
      getAcceptedIssuers() { return []; }
    }
  });
  const init = SSLContext.init.overload(
    '[Ljavax.net.ssl.KeyManager;', '[Ljavax.net.ssl.TrustManager;', 'java.security.SecureRandom');
  init.implementation = function (km, tm, sr) { init.call(this, km, [TM.$new()], sr); };

  // 2. OkHttp CertificatePinner
  try {
    const CP = Java.use('okhttp3.CertificatePinner');
    CP.check.overload('java.lang.String', 'java.util.List').implementation = () => {};
    CP.check.overload('java.lang.String', '[Ljava.security.cert.Certificate;').implementation = () => {};
  } catch (e) {}

  // 3. Conscrypt TrustManagerImpl.verifyChain (covers most modern apps)
  try {
    const TMI = Java.use('com.android.org.conscrypt.TrustManagerImpl');
    TMI.verifyChain.implementation = function (chain, ku, host, ce, ocsp, tlsSct) { return chain; };
  } catch (e) {}
});
```

### 4b. Native pinning (BoringSSL `libssl.so`)

Apps that pin in C/C++ (NDK, or Flutter — see `crossplatform-re-instrumentation.md`) verify in BoringSSL. Hook the verifier to always succeed:

```js
const ssl = Process.getModuleByName('libssl.so');
// SSL_CTX_set_custom_verify(ctx, mode, cb) -> force cb to return SSL_VERIFY_OK(0)
const setVerify = ssl.findExportByName('SSL_CTX_set_custom_verify');
if (setVerify) {
  Interceptor.attach(setVerify, { onEnter(args) {
    args[2] = new NativeCallback(() => 0, 'int', ['pointer', 'pointer']);  // 0 = ssl_verify_ok
  }});
}
```

### 4c. Objection one-liners

```bash
objection -g com.target.app explore
android sslpinning disable        # wraps a frida script similar to 4a
android root disable
```

---

## 5. Root-Detection Bypass

Covered by `scripts/universal_unpin.js`. Patterns hit:

```js
Java.perform(() => {
  // RootBeer
  try { Java.use('com.scottyab.rootbeer.RootBeer').isRooted.implementation = () => false; } catch (e) {}
  // File.exists() lying about su/magisk
  const File = Java.use('java.io.File');
  File.exists.implementation = function () {
    const p = this.getAbsolutePath();
    if (/su$|magisk|supersu|busybox|xposed|frida/i.test(p)) return false;
    return this.exists();
  };
  // Runtime.exec("which su") / "su"
  const RT = Java.use('java.lang.Runtime');
  RT.exec.overload('java.lang.String').implementation = function (cmd) {
    if (/su|magisk|which/i.test(cmd)) cmd = 'echo';   // neutralize
    return this.exec(cmd);
  };
  // getprop ro.debuggable / ro.secure
  const SP = Java.use('android.os.SystemProperties');
  SP.get.overload('java.lang.String').implementation = function (k) {
    if (k === 'ro.debuggable') return '0';
    if (k === 'ro.secure') return '1';
    return this.get(k);
  };
});
```

> **Limit:** these defeat *client-side* checks only. **Play Integrity** / **SafetyNet** attestation is verified server-side using a Google-signed token — hiding root locally (Shamiko/magisk-hide) influences the verdict but a *bypassed* client check does not change the attestation the backend receives. Note in the finding whether the control is client- or server-enforced.

---

## Detection

App-side and SOC telemetry that catches this cluster:

- **Frida**: app scanning `/proc/self/maps` and `/proc/self/task/*/stat` for `frida`, `gum-js-loop`, `gmain`; probing TCP `27042`/`27043`; checking for the `re.frida.server` D-Bus name. Renaming `frida-server`, custom port (`frida-server -l 127.0.0.1:1337`) and gadget mode reduce static IOCs.
- **CA injection**: a properly written app uses **Network Security Config** `<trust-anchors>` listing only `system` (excluding `user`) and/or certificate pinning, so even a trusted user/APEX cert is rejected — defeating §3 unless §4 also runs.
- **Pinning bypass**: pin-failure callbacks (`CertificatePinner` throws, `onReceivedSslError`) often log to the analytics SDK; the backend sees a Burp/mitm leaf cert and TLS-fingerprint mismatch (JA3/JA4).
- **Sigma (host/proxy egress)** — interception proxy fan-in:
  ```yaml
  title: Mobile App TLS Interception via Local Proxy
  logsource: { category: proxy }
  detection:
    sel:
      tls.server_cert.issuer|contains: ['PortSwigger', 'mitmproxy']
    condition: sel
  level: high
  ```

## OPSEC

- §3 bind-mount lives only inside the Zygote namespace and **disappears on Zygote restart / reboot** — nothing is written to `/system` or the APEX; cleanup is automatic. Re-inject if the app stops trusting your cert.
- Prefer **gadget mode** over a network-listening `frida-server` for stealth; if using a server, bind to localhost and a non-default port.
- Pinning bypass should hook **before the first network request** (use `frida -f ... --no-pause`, not late `attach`) to avoid a logged pin-failure.
- For proxy-aware detection, combine transparent `iptables` redirect with a CA the app trusts; avoid leaving system proxy set (some apps flag "proxy detected").

## References

- Frida 17.0.0 release notes — https://frida.re/news/2025/05/17/frida-17-0-0-released/ (bridge removal, frida-pm, ESM, Module API)
- HTTP Toolkit — "New ways to inject system CA certificates in Android 14" — https://httptoolkit.com/blog/android-14-install-system-ca-certificate/
- NVISO — "Intercepting traffic on Android with Mainline and Conscrypt" (2025-06) — https://blog.nviso.eu/2025/06/05/intercepting-traffic-on-android-with-mainline-and-conscrypt/
- Source.android.com — Conscrypt Mainline module — https://source.android.com/docs/core/ota/modular-system/conscrypt
- OWASP MASTG — Frida (MASTG-TOOL-0031) — https://mas.owasp.org/MASTG/tools/generic/MASTG-TOOL-0031/
- akabe1 frida-multiple-unpinning (CodeShare) — https://codeshare.frida.re/@akabe1/frida-multiple-unpinning/
rea-analysis-optimizationmorluto/reaOptimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
rea-ci-tests-auditmorluto/reaAudit REA CI and test suites for correctness, fixture drift, false passes, and measured performance; use for suite or workflow investigations and efficiency changes, rather than ordinary feature testing or a single test failure.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first.Stars: 194kUpdated Claude CodeCodexVerifiedInstall