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)
평가 트랙 (ARTA/GRTA/AzRTA)과 Linux Hacking Expert (LHE)를 보려면 전체 HackTricks Training 카탈로그를 둘러보세요.
HackTricks 지원하기
- subscription plans를 확인하세요!
- 💬 Discord group, telegram group에 참여하고, X/Twitter에서 @hacktricks_live를 팔로우하거나, LinkedIn page와 YouTube channel을 확인하세요.
- HackTricks 및 HackTricks Cloud github repos에 PR을 제출해 hacking tricks를 공유하세요.
This page provides a practical workflow to regain dynamic analysis against Android apps that detect/root‑block instrumentation or enforce TLS pinning. It focuses on fast triage, common detections, and copy‑pasteable hooks/tactics to bypass them without repacking when possible.
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 rebuilds Frida from source and applies ~90 patches so common Frida fingerprints disappear while the stock Frida protocol remains compatible (frida-tools can still connect). Target: apps that grep /proc (cmdline, maps, task comm, fd readlink), D-Bus service names, default ports, or exported symbols.
Phases:
- Source patches: global rename of
fridaidentifiers (server/agent/helper) and rebuilt helper DEX with a renamed Java package. - Targeted build/runtime patches: meson tweaks, memfd label changed to
jit-cache, SELinux labels (e.g.,frida_file) renamed, libc hooks onexit/signaldisabled to avoid hook-detectors. - Post-build rename: exported symbol
frida_agent_mainrenamed after the first compile (Vala emits it), requiring a second incremental build. - Binary hex patches: thread names (
gmain,gdbus,pool-spawner) replaced; optional sweep removes leftoverfrida/Fridastrings.
Detection vectors covered:
- Base (1–8): process name
frida-server, mappedlibfrida-agent.so, thread names, memfd label, exportedfrida_agent_main, SELinux labels, libc hook side-effects, and D-Bus servicere.frida.serverare renamed/neutralized. - Extended (9–16): change listening port (
--port), rename D-Bus interfaces/internal C symbols/GType names, temp paths like.frida/frida-, sweep binary strings, rename build-time defines and asset paths (libdir/frida). D-Bus interface names that are part of the wire protocol stay unchanged in base mode to avoid breaking stock clients.
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
플래그: --skip-build (patch only), --skip-clone, --arch, --ndk-path, --temp-fixes; WSL 도우미: wsl -d Ubuntu bash build-wsl.sh.
Step 1 — 빠른 성공: Magisk DenyList로 루트 숨기기
- 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 비활성화(토글 off + 재부팅)하고 재시도하세요; 일부 앱은 Zygote injection이 로드되자마자 충돌합니다.
- attestation이 로그인 차단하면, Google Play Services를 PlayIntegrityFix/Fork + TrickyStore로 패치하거나 테스트할 때만 ReZygisk/Zygisk‑Next를 사용하세요. 대상 패키지는 DenyList에 유지하고 props를 leak하는 LSPosed 모듈은 피하세요.
- 일회성 실행의 경우 KernelSU/APatch (no Zygote injection)를 사용해 Zygisk 휴리스틱을 피한 뒤 Frida를 attach하세요.
Step 2 — 30초 Frida Codeshare 테스트
본격 분석 전에 일반적으로 쓰이는 drop‑in 스크립트를 먼저 시도하세요:
- 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 검사, 프로세스/서비스 스캔, 그리고 native ptrace()를 스텁 처리한다. 보호 수준이 낮은 앱에서 유용하지만, 보안이 강화된 대상에는 맞춤형 hooks가 필요할 수 있다.
- Codeshare: https://codeshare.frida.re/
Medusa로 자동화 (Frida 프레임워크)
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는 custom hooks를 작성하기 전에 빠른 성과를 얻기에 좋습니다. 또한 모듈을 골라 자신의 스크립트와 결합할 수 있습니다.
Auto-Frida로 자동화 (spawn-mode + consolidated hooks)
Auto-Frida는 반복 가능한 설정과 보호 기능의 자동 감지 및 통합된 bypass 스크립트 생성에 중점을 둔 Frida 자동화 툴킷입니다. 앱이 매우 초기에 검사를 수행하거나 여러 bypass 모듈이 동일한 API를 중복으로 hook하게 될 상황에서 유용합니다.
Key automation ideas:
- Spawn-mode analysis:
Application.onCreate()전에 hooks를 설치하여 초기 SSL pinning, root, emulator, 또는 anti-Frida 검사를 포착합니다. - Protection detection + auto-bypass: 탐지 결과가 각 Java 메서드/네이티브 심볼을 한 번만 hook하도록 단일 통합 스크립트 생성을 유도하여, 겹치는 hooks로 인한 충돌을 줄입니다.
- Frida server lifecycle checks: 다운로드/재시작 전에 서버 상태(process + port
27042+frida-pshandshake)를 검증하여 실행을 안정적으로 유지합니다.
빠른 시작:
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가 없으면 자동으로 설치할 수 있고 다중 장치 선택을 지원합니다. - 생성된 스크립트는 분석 후 즉시 실행하거나 커스텀 훅과 병합할 수 있습니다.
Step 3 — init-time 탐지기를 늦게 attach해서 우회하기
많은 탐지 로직은 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
이 방법이 통하면 세션을 안정적으로 유지한 뒤 map 및 stub 검사를 진행합니다.
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단계 — Frida (Java)로 런타임 스터빙
커스텀 가드를 재패키징 없이 오버라이드하여 안전한 값을 반환:
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를 hook하거나, CodeShare의 universal unpinning script를 사용하세요.
- 실행 예:
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가 여전히 실패하면 네이티브로 전환해 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
}
});
}
Step 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'
대화형/네이티브 reversing:
- Ghidra: https://ghidra-sre.org/
- r2frida: https://github.com/nowsecure/r2frida
예시: ptrace를 무력화하여 libc의 simple 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
참고:
- apktool이 필요합니다; 빌드 문제를 피하려면 공식 가이드에서 최신 버전을 확인하세요: https://apktool.org/docs/install
- Gadget injection은 root 없이도 instrumentation을 가능하게 하지만, 더 강력한 init‑time checks에 걸릴 수 있습니다.
선택적으로, Zygisk 환경에서 더 강력한 root 숨김을 위해 LSPosed 모듈과 Shamiko를 추가하고, DenyList를 자식 프로세스까지 포함하도록 관리하세요.
script-mode Gadget 설정 및 Frida 17+ agent를 APK에 번들링하는 전체 워크플로우는 다음을 참조하세요:
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+ user CA trust)은 다음을 참조:
Make APK Accept CA Certificate
LSPosed/Xposed Hooking Abuse (Telephony/SMS)
루팅된 기기에서는 LSPosed/Xposed 모듈이 런타임에 Java telephony/SMS API를 훅하여 디스크상의 APK를 수정하지 않고도 앱이 보는 내용을 완전히 제어할 수 있습니다. 이는 로컬 telephony API나 로컬 SMS provider 상태를 신뢰하는 SIM‑binding 흐름을 우회하는 데 흔히 악용됩니다.
핵심 프리미티브
- Suppress outgoing verification SMS:
beforeHookedMethod에서SmsManager.sendTextMessage를 단축(short‑circuit)하여 토큰을 유출하면서 발신 인증 SMS를 차단합니다. - Spoof MSISDN/line number:
TelephonyManager.getLine1Number()와SubscriptionInfo.getNumber()가 공격자가 제어하는 값을 반환하도록 강제합니다. - Plant a fake “Sent” record: SMS provider에 가짜 “Sent” 레코드를 심어, 앱이 로컬 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
}
}
);
예: spoof 기기 전화번호
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
Universal proxy forcing + TLS unpinning (HTTP Toolkit Frida hooks)
최신 앱들은 종종 system proxies를 무시하고 여러 층의 pinning (Java + native)을 적용하여, user/system CAs가 설치되어 있어도 트래픽 캡처가 어렵다. 실용적인 접근법은 ready-made Frida hooks를 이용해 universal TLS unpinning과 proxy forcing를 결합하고, 모든 트래픽을 mitmproxy/Burp로 라우팅하는 것이다.
Workflow
- 호스트에서 mitmproxy(또는 Burp)를 실행한다. 디바이스가 호스트의 IP/포트에 접근할 수 있는지 확인한다.
- HTTP Toolkit’s consolidated Frida hooks를 로드하여 common stacks(OkHttp/OkHttp3, HttpsURLConnection, Conscrypt, WebView, 등) 전반에서 TLS를 unpin하고 proxy 사용을 강제한다. 이는 CertificatePinner/TrustManager 검사를 우회하고 proxy selectors를 재정의하므로, 앱이 명시적으로 프록시를 비활성화하더라도 트래픽이 항상 당신의 프록시를 통해 전송된다.
- Frida와 hook script로 대상 앱을 시작하고 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
노트
- 가능한 경우 시스템 전체 proxy와 함께
adb shell settings put global http_proxy <host>:<port>를 결합하세요. Frida hooks는 앱이 global settings를 우회하더라도 proxy 사용을 강제합니다. - 이 기법은 pinning/proxy 회피가 흔한 모바일-to-IoT onboarding 흐름을 MITM해야 할 때 이상적입니다.
- Hooks: https://github.com/httptoolkit/frida-interception-and-unpinning
참고자료
- Reversing Android Apps: Bypassing Detection Like a Pro
- Frida Codeshare
- Objection
- apk-mitm
- Jadx
- Ghidra
- r2frida
- Apktool install guide
- Magisk
- Medusa (Android Frida framework)
- Auto-Frida (Android Frida automation toolkit)
- Build a Repeatable Android Bug Bounty Lab: Emulator vs Magisk, Burp, Frida, and Medusa
- phantom-frida (stealth Frida server builder)
- Frida OkHttp4 SSL pinning bypass script
- XDA guide to strong Play Integrity bypass (2025)
- Weaponizing LSPosed: Remote SMS Injection and Identity Spoofing in Modern Payment Ecosystems
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)
평가 트랙 (ARTA/GRTA/AzRTA)과 Linux Hacking Expert (LHE)를 보려면 전체 HackTricks Training 카탈로그를 둘러보세요.
HackTricks 지원하기
- subscription plans를 확인하세요!
- 💬 Discord group, telegram group에 참여하고, X/Twitter에서 @hacktricks_live를 팔로우하거나, LinkedIn page와 YouTube channel을 확인하세요.
- HackTricks 및 HackTricks Cloud github repos에 PR을 제출해 hacking tricks를 공유하세요.


