Android Anti-Instrumentation & SSL Pinning Bypass (Frida/Objection)

Tip

AWSハッキングを学び、実践する:HackTricks Training AWS Red Team Expert (ARTE)
GCPハッキングを学び、実践する:HackTricks Training GCP Red Team Expert (GRTE) Azureハッキングを学び、実践する:HackTricks Training Azure Red Team Expert (AzRTE)

HackTricksをサポートする

このページは、instrumentation を検出/root ブロックする、または TLS pinning を強制する Android アプリに対してダイナミック解析を取り戻すための実践的ワークフローを提供します。高速なトリアージ、一般的な検出方法、および可能な場合はリパック不要でコピペ可能なフック/戦術に焦点を当てています。

Detection Surface (what apps check)

  • Root checks: su binary, Magisk paths, getprop values, common root packages
  • Frida/debugger checks (Java): Debug.isDebuggerConnected(), ActivityManager.getRunningAppProcesses(), getRunningServices(), scanning /proc, classpath, loaded libs
  • Native anti‑debug: ptrace(), syscalls, anti‑attach, breakpoints, inline hooks
  • Early init checks: Application.onCreate() or process start hooks that crash if instrumentation is present
  • TLS pinning: custom TrustManager/HostnameVerifier, OkHttp CertificatePinner, Conscrypt pinning, native pins

Bypassing Anti-Frida Detection / Stealth Frida Servers

phantom-frida は Frida をソースからビルドし、一般的な Frida のフィンガープリントを消すために約90のパッチを適用しますが、stock Frida プロトコルとの互換性は維持されます(frida-tools は引き続き接続可能)。対象は /proc(cmdline, maps, task comm, fd readlink)をgrepするアプリ、D-Bus サービス名、デフォルトポート、エクスポートされたシンボルをチェックするアプリです。

フェーズ:

  • Source patches: frida 識別子(server/agent/helper)のグローバルリネームと、Java パッケージ名を変更した helper DEX の再ビルド。
  • Targeted build/runtime patches: meson の微調整、memfd ラベルを jit-cache に変更、SELinux ラベル(例: frida_file)のリネーム、libc の exit/signal フックを無効化してフック検出器を回避。
  • Post-build rename: エクスポートされたシンボル frida_agent_main を最初のコンパイル後にリネーム(Vala がこれを生成するため)、2回目のインクリメンタルビルドが必要。
  • Binary hex patches: スレッド名(gmain, gdbus, pool-spawner)を置換;オプションで残存する frida/Frida 文字列を掃除。

対応する検出ベクトル:

  • Base (1–8): process name frida-server, mapped libfrida-agent.so, thread names, memfd label, exported frida_agent_main, SELinux labels, libc hook の副作用、D-Bus service re.frida.server をリネーム/無効化。
  • Extended (9–16): リッスンポートの変更(--port)、D-Bus インターフェース/内部 C シンボル/GType 名のリネーム、.frida/frida- のような一時パスの変更、バイナリ文字列の掃き出し、ビルド時の define や asset パス(libdir/frida)のリネーム。ワイヤープロトコルの一部である D-Bus インターフェース名は、stock クライアントを壊さないよう base モードではそのままにしてあります。

Build/usage (Android arm64 example):

python3 build.py --version 17.7.2 --name myserver --port 27142 --extended --verify
adb push output/myserver-server-17.7.2-android-arm64 /data/local/tmp/myserver-server
adb shell chmod 755 /data/local/tmp/myserver-server
adb shell /data/local/tmp/myserver-server -D &
adb forward tcp:27142 tcp:27142
frida -H 127.0.0.1:27142 -f com.example.app

Flags: --skip-build (patch only), --skip-clone, --arch, --ndk-path, --temp-fixes; WSL helper: wsl -d Ubuntu bash build-wsl.sh.

Step 1 — 手っ取り早い対策: Magisk DenyListでrootを隠す

  • MagiskでZygiskを有効にする
  • DenyListを有効化し、対象のパッケージを追加する
  • 再起動して再試行する

多くのアプリは明らかな指標(su/Magisk paths/getprop)しか見ていません。DenyListは単純なチェックを無効化することがよくあります。

References:

  • Magisk (Zygisk & DenyList): https://github.com/topjohnwu/Magisk

Play Integrity / Zygisk 検出 (post‑SafetyNet)

新しい銀行系やIDアプリはランタイムチェックをGoogle Play Integrity(SafetyNetの代替)に結び付けており、Zygisk自体が存在するとクラッシュする場合があります。クイックトリアージのヒント:

  • 一時的にZygiskを無効にして(オフにして + 再起動)再試行する;Zygote injectionがロードされると即座にクラッシュするアプリもあります。
  • attestationがログインをブロックする場合は、Google Play ServicesをPlayIntegrityFix/Fork + TrickyStoreでパッチするか、テスト時のみReZygisk/Zygisk‑Nextを使用してください。対象はDenyListに入れ、propsをleakするLSPosedモジュールは避けてください。
  • 単発の実行にはKernelSU/APatch(Zygote injectionなし)を使ってZygiskのヒューリスティックを逃れ、その後Fridaをアタッチする、という手もあります。

Step 2 — 30秒のFrida Codeshareテスト

本格的に掘り下げる前に、一般的なドロップインスクリプトを試してください:

  • anti-root-bypass.js
  • anti-frida-detection.js
  • hide_frida_gum.js

Example:

frida -U -f com.example.app -l anti-frida-detection.js

これらは通常、Javaの root/debug checks、process/service scans、およびネイティブの ptrace() をスタブします。保護が緩いアプリでは有用ですが、ハード化されたターゲットではカスタムのフックが必要になる場合があります。

  • Codeshare: https://codeshare.frida.re/

Medusa (Frida framework) を使った自動化

Medusaは、SSL unpinning、root/emulator detection bypass、HTTP comms logging、crypto key interceptionなど、90以上の既成モジュールを提供します。

git clone https://github.com/Ch0pin/medusa
cd medusa
pip install -r requirements.txt
python medusa.py

# Example interactive workflow
show categories
use http_communications/multiple_unpinner
use root_detection/universal_root_detection_bypass
run com.target.app

ヒント: Medusaはカスタムhooksを書く前の短期的な成果を得るのに最適です。modulesを個別に選んで自分のscriptsと組み合わせることもできます。

Step 3 — 後からattachしてinit-time検出を回避する

多くの検出はprocess spawn/onCreate()の実行時にのみ動作します。Spawn‑time injection (-f) や gadgets は検出されやすく、UIがロードされた後にattachすることで回避できることがあります。

# Launch the app normally (launcher/adb), wait for UI, then attach
frida -U -n com.example.app
# Or with Objection to attach to running process
aobjection --gadget com.example.app explore  # if using gadget

これがうまくいったら、セッションを安定させたまま、マップとスタブのチェックに進んでください。

Step 4 — Jadxと文字列検索による検出ロジックのマッピング

Jadxでの静的トリアージキーワード:

  • “frida”, “gum”, “root”, “magisk”, “ptrace”, “su”, “getprop”, “debugger”

典型的なJavaパターン:

public boolean isFridaDetected() {
return getRunningServices().contains("frida");
}

確認・hook対象の一般的なAPI:

  • android.os.Debug.isDebuggerConnected
  • android.app.ActivityManager.getRunningAppProcesses / getRunningServices
  • java.lang.System.loadLibrary / System.load (native bridge)
  • java.lang.Runtime.exec / ProcessBuilder (probing commands)
  • android.os.SystemProperties.get (root/emulator heuristics)

ステップ5 — Runtime stubbing with Frida (Java)

repacking を行わずに、安全な値を返すようにカスタムガードをオーバーライドする:

Java.perform(() => {
const Checks = Java.use('com.example.security.Checks');
Checks.isFridaDetected.implementation = function () { return false; };

// Neutralize debugger checks
const Debug = Java.use('android.os.Debug');
Debug.isDebuggerConnected.implementation = function () { return false; };

// Example: kill ActivityManager scans
const AM = Java.use('android.app.ActivityManager');
AM.getRunningAppProcesses.implementation = function () { return java.util.Collections.emptyList(); };
});

早期のクラッシュをトリアージしていますか?クラッシュ直前にクラスをダンプして、検知の可能性が高いネームスペースを特定します:

Java.perform(() => {
Java.enumerateLoadedClasses({
onMatch: n => console.log(n),
onComplete: () => console.log('Done')
});
});

簡単な root detection stub の例(ターゲットの package/class names に合わせて調整してください):

Java.perform(() => {
try {
const RootChecker = Java.use('com.target.security.RootCheck');
RootChecker.isDeviceRooted.implementation = function () { return false; };
} catch (e) {}
});

実行フローを確認するために、疑わしいメソッドをログに記録し無効化する:

Java.perform(() => {
const Det = Java.use('com.example.security.DetectionManager');
Det.checkFrida.implementation = function () {
console.log('checkFrida() called');
return false;
};
});

Bypass emulator/VM detection (Java stubs)

一般的なヒューリスティック: Build.FINGERPRINT/MODEL/MANUFACTURER/HARDWARE が generic/goldfish/ranchu/sdk を含む; QEMU アーティファクト(/dev/qemu_pipe, /dev/socket/qemud など); デフォルト MAC 02:00:00:00:00:00; 10.0.2.x の NAT; telephony や sensors の欠如。

Build フィールドの簡易な偽装:

Java.perform(function(){
var Build = Java.use('android.os.Build');
Build.MODEL.value = 'Pixel 7 Pro';
Build.MANUFACTURER.value = 'Google';
Build.BRAND.value = 'google';
Build.FINGERPRINT.value = 'google/panther/panther:14/UP1A.231105.003/1234567:user/release-keys';
});

ファイル存在チェックや識別子(TelephonyManager.getDeviceId/SubscriberId, WifiInfo.getMacAddress, SensorManager.getSensorList)に対するスタブを追加し、現実的な値を返すようにしてください。

SSL pinning bypass quick hook (Java)

カスタム TrustManagers を無効化し、許容的な SSL コンテキストを強制します:

Java.perform(function(){
var X509TrustManager = Java.use('javax.net.ssl.X509TrustManager');
var SSLContext = Java.use('javax.net.ssl.SSLContext');

// No-op validations
X509TrustManager.checkClientTrusted.implementation = function(){ };
X509TrustManager.checkServerTrusted.implementation = function(){ };

// Force permissive TrustManagers
var TrustManagers = [ X509TrustManager.$new() ];
var SSLContextInit = SSLContext.init.overload('[Ljavax.net.ssl.KeyManager;','[Ljavax.net.ssl.TrustManager;','java.security.SecureRandom');
SSLContextInit.implementation = function(km, tm, sr){
return SSLContextInit.call(this, km, TrustManagers, sr);
};
});

注意

  • OkHttp 用に拡張: 必要に応じて okhttp3.CertificatePinner と HostnameVerifier をフックするか、CodeShare の汎用 unpinning スクリプトを使用する。
  • 実行例: frida -U -f com.target.app -l ssl-bypass.js --no-pause

OkHttp4 / gRPC / Cronet pinning (2024+)

最新のスタックでは、新しい API 内で pinning を行うことが多いです(OkHttp4+、gRPC over Cronet/BoringSSL)。基本的な SSLContext フックが効かない場合は、これらのフックを追加してください:

Java.perform(() => {
try {
const Pinner = Java.use('okhttp3.CertificatePinner');
Pinner.check.overload('java.lang.String', 'java.util.List').implementation = function(){};
Pinner.check$okhttp.implementation = function(){};
} catch (e) {}

try {
const CronetB = Java.use('org.chromium.net.CronetEngine$Builder');
CronetB.enablePublicKeyPinningBypassForLocalTrustAnchors.overload('boolean').implementation = function(){ return this; };
CronetB.setPublicKeyPins.overload('java.lang.String', 'java.util.Set', 'boolean').implementation = function(){ return this; };
} catch (e) {}
});

それでもTLSが失敗する場合は、ネイティブに降りて、Cronet/gRPCが使用するBoringSSLの検証エントリポイントをパッチしてください:

const customVerify = Module.findExportByName(null, 'SSL_CTX_set_custom_verify');
if (customVerify) {
Interceptor.attach(customVerify, {
onEnter(args){
// arg0 = SSL_CTX*, arg1 = mode, arg2 = callback
args[1] = ptr(0); // SSL_VERIFY_NONE
args[2] = NULL;  // disable callback
}
});
}

ステップ 6 — Java hooks が失敗した場合は JNI/native のトレイルを追う

JNI のエントリポイントをトレースして、native loaders と detection init の位置を特定する:

frida-trace -n com.example.app -i "JNI_OnLoad"

バンドルされた .so ファイルの簡易ネイティブトリアージ:

# List exported symbols & JNI
nm -D libfoo.so | head
objdump -T libfoo.so | grep Java_
strings -n 6 libfoo.so | egrep -i 'frida|ptrace|gum|magisk|su|root'

インタラクティブ/ネイティブ リバース:

  • Ghidra: https://ghidra-sre.org/
  • r2frida: https://github.com/nowsecure/r2frida

例: libc の単純な anti‑debug を回避するために ptrace を無効化する:

const ptrace = Module.findExportByName(null, 'ptrace');
if (ptrace) {
Interceptor.replace(ptrace, new NativeCallback(function () {
return -1; // pretend failure
}, 'int', ['int', 'int', 'pointer', 'pointer']));
}

参照: Reversing Native Libraries

ステップ7 — Objection patching (embed gadget / strip basics)

repacking を runtime hooks の代わりに使用したい場合は、次を試してください:

objection patchapk --source app.apk

注意:

  • Requires apktool; ensure a current version from the official guide to avoid build issues: https://apktool.org/docs/install
  • Gadget injection enables instrumentation without root but can still be caught by stronger init‑time checks.

必要に応じて、Zygisk 環境でのより強力な root hiding のために LSPosed モジュールと Shamiko を追加し、子プロセスをカバーするよう DenyList を調整してください。

For a complete workflow including script-mode Gadget configuration and bundling your Frida 17+ agent into the APK, see:

Frida Tutorial — Self-contained agent + Gadget embedding

参考:

  • Objection: https://github.com/sensepost/objection

Step 8 — フォールバック: TLS pinning をパッチしてネットワークの可視性を確保

instrumentation がブロックされている場合でも、pinning を静的に除去することでトラフィックを検査できます:

apk-mitm app.apk
# Then install the patched APK and proxy via Burp/mitmproxy
  • ツール: https://github.com/shroudedcode/apk-mitm
  • ネットワーク設定のCA‑trustトリック(およびAndroid 7+のユーザーCA信頼)については、次を参照してください:

Make APK Accept CA Certificate

Install Burp Certificate

便利なコマンド チートシート

# List processes and attach
frida-ps -Uai
frida -U -n com.example.app

# Spawn with a script (may trigger detectors)
frida -U -f com.example.app -l anti-frida-detection.js

# Trace native init
frida-trace -n com.example.app -i "JNI_OnLoad"

# Objection runtime
objection --gadget com.example.app explore

# Static TLS pinning removal
apk-mitm app.apk

Universal proxy forcing + TLS unpinning (HTTP Toolkit Frida hooks)

最近のアプリはしばしばシステムプロキシを無視し、複数レイヤーのピンニング(Java + native)を強制するため、ユーザー/システムCAをインストールしていてもトラフィックの捕捉が難しくなります。実用的な方法としては、既成の Frida hooks を使って universal TLS unpinning と proxy forcing を組み合わせ、すべてを mitmproxy/Burp 経由でルーティングすることです。

Workflow

  • ホスト上で mitmproxy(または Burp)を実行します。デバイスがホストの IP/ポートに到達できることを確認してください。
  • HTTP Toolkit の統合された Frida hooks を読み込み、一般的なスタック(OkHttp/OkHttp3、HttpsURLConnection、Conscrypt、WebView など)全体で TLS を unpin し、プロキシ使用を強制します。これにより CertificatePinner/TrustManager のチェックがバイパスされ、プロキシセレクタが上書きされるため、アプリが明示的にプロキシを無効にしていてもトラフィックは常にあなたのプロキシ経由で送信されます。
  • Frida とフックスクリプトで対象アプリを起動し、mitmproxy でリクエストをキャプチャします。

Example

# Device connected via ADB or over network (-U)
# See the repo for the exact script names & options
frida -U -f com.vendor.app \
-l ./android-unpinning-with-proxy.js \
--no-pause

# mitmproxy listening locally
mitmproxy -p 8080

注意

  • 可能なら adb shell settings put global http_proxy <host>:<port> を使って system-wide proxy と組み合わせてください。Frida hooks は、アプリがグローバル設定を回避しても proxy の使用を強制します。
  • この手法は、pinning や proxy 回避が一般的な mobile-to-IoT のオンボーディングフローを MITM する必要がある場合に最適です。
  • Hooks: https://github.com/httptoolkit/frida-interception-and-unpinning

参考資料

Tip

AWSハッキングを学び、実践する:HackTricks Training AWS Red Team Expert (ARTE)
GCPハッキングを学び、実践する:HackTricks Training GCP Red Team Expert (GRTE) Azureハッキングを学び、実践する:HackTricks Training Azure Red Team Expert (AzRTE)

HackTricksをサポートする