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

Tip

学习并实践 AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
学习并实践 GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE)
学习并实践 Az Hacking: HackTricks Training Azure Red Team Expert (AzRTE) 浏览用于评估路线的 完整 HackTricks Training 目录ARTA/GRTA/AzRTA)以及 Linux Hacking Expert (LHE)

支持 HackTricks

本页提供一个实用流程,用于在 Android 应用检测/阻止 instrumentation 或强制 TLS pinning 时恢复动态分析。重点是快速分诊、常见检测方法,以及可复制粘贴的 hooks/策略,以在可能的情况下绕过它们而无需重新打包。

检测面(应用会检查的内容)

  • Root 检测:su binary、Magisk paths、getprop values、常见 root packages
  • Frida/debugger 检测(Java):Debug.isDebuggerConnected(), ActivityManager.getRunningAppProcesses(), getRunningServices(), scanning /proc, classpath, loaded libs
  • Native anti‑debug:ptrace(), syscalls, anti‑attach, breakpoints, inline hooks
  • 早期初始化检测:Application.onCreate() 或在进程启动时的 hooks,如果检测到 instrumentation 会导致崩溃
  • TLS pinning:custom TrustManager/HostnameVerifier、OkHttp CertificatePinner、Conscrypt pinning、native pins

绕过 Anti-Frida 检测 / 隐蔽 Frida 服务器

phantom-frida 从源代码重建 Frida 并应用约 90 个补丁,使常见的 Frida 指纹消失,同时保持 stock Frida 协议兼容(frida-tools 仍可连接)。目标:针对那些 grep /proc(cmdline、maps、task comm、fd readlink)、D-Bus 服务名、默认端口或导出符号的应用。

阶段:

  • Source patches: 全局重命名 frida 标识符(server/agent/helper),并重建 helper DEX,使用重命名的 Java 包。
  • Targeted build/runtime patches: meson 调整,memfd 标签改为 jit-cache,SELinux 标签(例如 frida_file)被重命名,禁用 libc 在 exit/signal 上的 hooks 以避免 hook‑detectors。
  • Post-build rename: 导出符号 frida_agent_main 在第一次编译后被重命名(Vala 会发出该符号),因此需要第二次增量构建。
  • Binary hex patches: 线程名(gmaingdbuspool-spawner)被替换;可选的清理会移除残留的 frida/Frida 字符串。

覆盖的检测向量:

  • Base (1–8): 进程名 frida-server、映射的 libfrida-agent.so、线程名、memfd 标签、导出符号 frida_agent_main、SELinux 标签、libc hook 的副作用,以及 D-Bus 服务 re.frida.server 被重命名/中和。
  • Extended (9–16): 更改监听端口(--port)、重命名 D-Bus 接口/内部 C 符号/GType 名称、临时路径如 .frida/frida-、清理二进制字符串、重命名构建时的定义和资源路径(libdir/frida)。作为 wire 协议一部分的 D-Bus 接口名称在 base 模式下保持不变,以避免破坏 stock clients。

构建/使用(Android arm64 示例):

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.

步骤 1 — 快速手段:使用 Magisk DenyList 隐藏 root

  • 在 Magisk 中启用 Zygisk
  • 启用 DenyList,并添加目标包
  • 重启并重新测试

许多应用只检测明显的指示器 (su/Magisk paths/getprop)。DenyList 常能中和简单的检查。

参考:

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

Play Integrity / Zygisk 检测(post‑SafetyNet)

较新的银行/ID 应用将运行时检查与 Google Play Integrity(SafetyNet 的替代)绑定,如果检测到 Zygisk 本身也可能导致崩溃。快速分诊提示:

  • 临时禁用 Zygisk(切换为关闭 + 重启)后重试;有些应用在 Zygote 注入加载后就会崩溃。
  • 如果 attestation 阻止登录,使用 PlayIntegrityFix/Fork + TrickyStore 对 Google Play Services 进行补丁,或仅在测试时使用 ReZygisk/Zygisk‑Next。将目标保持在 DenyList 中,并避免使用会 leak props 的 LSPosed 模块。
  • 对于一次性运行,使用 KernelSU/APatch(无 Zygote 注入)以避开 Zygisk 的启发式检测,然后附加 Frida。

步骤 2 — 30 秒 Frida Codeshare 测试

在深入之前先尝试常见的可直接替换脚本:

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

示例:

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

这些通常会对 Java 的 root/debug 检查、process/service 扫描和本地 ptrace() 进行存根。适用于防护较弱的应用;针对防护更强的目标可能需要定制化 hooks。

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

使用 Medusa 自动化(Frida framework)

Medusa 提供 90+ 现成模块,用于 SSL unpinning、root/emulator detection bypass、HTTP comms logging、crypto key interception 等等。

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 结合使用。

使用 Auto-Frida 自动化(spawn-mode + consolidated hooks)

Auto-Frida 是一个 Frida 自动化工具包,侧重于可重复的设置以及对防护的 auto-detectionconsolidated bypass script generation。当应用很早就执行检查,或多个 bypass modules 可能会对同一 API 造成重复 hook 时,它非常有用。

关键自动化思路:

  • Spawn-mode analysis:在 Application.onCreate() 之前安装 hooks,以便捕获早期的 SSL pinning、root、emulator 或 anti-Frida 检查。
  • Protection detection + auto-bypass:检测结果会驱动生成一个单一的 consolidated script,该脚本对每个 Java method/native symbol 只 hook 一次,从而减少因重叠 hooks 导致的崩溃。
  • Frida server lifecycle checks:在下载/重启前验证服务器健康(进程 + 端口 27042 + frida-ps 握手),以保持运行稳定。

快速开始:

git clone https://github.com/ommirkute/Auto-Frida.git
cd Auto-Frida
pip install -r requirements.txt
python auto_frida.py

注意事项

  • Auto-Frida 可以在缺失时自动安装 frida/frida-tools,并支持 multi-device selection。
  • Generated scripts 可以在分析后立即执行,或与自定义 hooks 合并。

第3步 — 通过延迟附加绕过初始化时的检测器

许多检测仅在 process spawn/onCreate() 期间运行。Spawn‑time injection (-f) 或 gadgets 会被捕获;在 UI 加载后再附加可以避开这些检测。

# 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");
}

常见需要 review/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步 — 在运行时使用 Frida 进行 stubbing(Java)

覆盖自定义 guards 以在不进行 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 检测 stub 示例(根据目标 package/class 名称调整):

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 contexts:

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 扩展:根据需要 hook okhttp3.CertificatePinner 和 HostnameVerifier,或从 CodeShare 使用通用 unpinning 脚本。
  • 运行示例: frida -U -f com.target.app -l ssl-bypass.js --no-pause

OkHttp4 / gRPC / Cronet pinning (2024+)

现代栈会在较新的 API 中进行 pin(OkHttp4+、gRPC over Cronet/BoringSSL)。当基本的 SSLContext hook 失效时,添加这些 hooks:

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 仍然失败,则降到 native 并 patch BoringSSL verification entry points(由 Cronet/gRPC 使用):

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 entry points 来定位 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

示例:禁用 ptrace 以 绕过 libc 中的简单 anti‑debug:

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;请根据官方指南确保使用最新版本以避免构建问题: https://apktool.org/docs/install
  • Gadget injection enables instrumentation without root but can still be caught by stronger init‑time checks.

可选地,添加 LSPosed 模块和 Shamiko 以在 Zygisk 环境中增强 root 隐藏,并对 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

步骤 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
  • 关于 network config CA‑trust 技巧(以及 Android 7+ 的 user CA trust),参见:

Make APK Accept CA Certificate

Install Burp Certificate

LSPosed/Xposed Hooking Abuse (Telephony/SMS)

在已 root 的设备上,LSPosed/Xposed 模块可以在运行时 hook Java 的 telephony/SMS API,保持磁盘上的 APK 未被修改,同时完全控制应用看到的内容。攻击者常利用这一点绕过依赖本地 telephony API 或本地 SMS provider 状态的 SIM‑binding 流程。

Key primitives

  • Suppress outgoing verification SMS 同时通过在 beforeHookedMethod 中短路 SmsManager.sendTextMessage 来外泄令牌。
  • Spoof MSISDN/line number 通过强制 TelephonyManager.getLine1Number()SubscriptionInfo.getNumber() 返回攻击者控制的值。
  • Plant a fake “Sent” record 在 SMS provider 中伪造记录,使检查本地 SMS 历史的应用看到发送成功,即使运营商从未收到该短信。

Example: block SMS dispatch and capture content

XposedHelpers.findAndHookMethod(
"android.telephony.SmsManager",
lpparam.classLoader,
"sendTextMessage",
String.class, String.class, String.class, PendingIntent.class, PendingIntent.class,
new XC_MethodHook() {
protected void beforeHookedMethod(MethodHookParam param) {
String body = (String) param.args[2];
// exfiltrate body to operator channel
param.setResult(null); // suppress real SMS send
}
}
);

示例:伪造设备电话号码

XposedHelpers.findAndHookMethod(
"android.telephony.TelephonyManager",
lpparam.classLoader,
"getLine1Number",
new XC_MethodHook() {
protected void afterHookedMethod(MethodHookParam param) {
param.setResult(spoofedMsisdn);
}
}
);
XposedHelpers.findAndHookMethod(
"android.telephony.SubscriptionInfo",
lpparam.classLoader,
"getNumber",
new XC_MethodHook() {
protected void afterHookedMethod(MethodHookParam param) {
param.setResult(spoofedMsisdn);
}
}
);

示例:注入一个假的“Sent” SMS 记录

ContentValues v = new ContentValues();
v.put("address", dest);
v.put("body", body);
v.put("type", 2);   // sent
v.put("status", 0); // success
context.getContentResolver().insert(Uri.parse("content://sms/sent"), v);

实用命令速查表

# 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

通用代理强制 + TLS unpinning (HTTP Toolkit Frida hooks)

现代应用常常忽略系统代理并在多个层面实施 pinning(Java + native),即使安装了用户/系统 CA,也会使流量捕获变得很困难。一个实用的方法是结合通用 TLS unpinning 与通过现成的 Frida hooks 强制代理,然后将所有流量通过 mitmproxy/Burp 转发。

Workflow

  • 在你的主机上运行 mitmproxy(或 Burp)。确保设备可以访问主机的 IP/端口。
  • 加载 HTTP Toolkit 整合的 Frida hooks,以在常见栈(OkHttp/OkHttp3、HttpsURLConnection、Conscrypt、WebView 等)中同时解除 TLS pinning 并强制使用代理。这样可以绕过 CertificatePinner/TrustManager 检查并覆盖代理选择器, 即使应用显式禁用代理,流量也始终通过你的代理发送。
  • 使用 Frida 和 hook 脚本启动目标应用,并在 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> 将其与系统级代理结合使用。Frida hooks 将强制使用代理,即使应用绕过全局设置。
  • 当你需要对移动设备到 IoT 的 onboarding 接入流程进行 MITM(pinning/proxy 回避常见)时,此技术最为理想。
  • Hooks: https://github.com/httptoolkit/frida-interception-and-unpinning

参考资料

Tip

学习并实践 AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
学习并实践 GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE)
学习并实践 Az Hacking: HackTricks Training Azure Red Team Expert (AzRTE) 浏览用于评估路线的 完整 HackTricks Training 目录ARTA/GRTA/AzRTA)以及 Linux Hacking Expert (LHE)

支持 HackTricks