frida--hook记录
from __future__ import print_function
from frida.core import Session
import frida
import time
device = frida.get_usb_device() # 通过USB连接设备
# frida.get_device_manager().add_remote_device('192.168.50.96:6666')
pid = device.spawn(["com.android.settings"]) # spawn方式注入进程
device.resume(pid)
time.sleep(1)
session = device.attach(pid)
script = session.create_script("""
rpc.exports = {
hello: function () {
return 'Hello';
},
failPlease: function () {
return 'oops';
}
};
""")
script.load() # 加载脚本
api = script.exports # 获取rpc导出函数
print("api.hello() =>", api.hello()) # 执行导出函数
print("api.fail_please() =>", api.fail_please()) # 执行导出函数
想要在Python中调用 JavaScript中的函数,首先需要在JavaScript中将相应函数写到rpc.exports 这个字典中,在编写完成后,如果想要在Python中进行调用,只需先通 过script.exports获取相应的导出函数字典,再通过相应的字典键值进行 调用即可。
frida在命令行中的使用方式:
frida -U -f 包名 -l *.js 启动应用并注入脚本
frida-U "程序名" -l *.js 可以先启动程序,再注入脚本
常规hook:
function hook(){
console.log("Inside java perform function")
let MainActivity = Java.use("com.ad2001.frida0x1.MainActivity");
MainActivity["check"].implementation = function (i, i2) {
console.log(`MainActivity.check is called: i=${i}, i2=${i2}`);
i=2;
i2=8;
this["check"](i, i2);
}
}
function main(){
console.log("Script loaded successfully")
Java.perform(function(){
hook();
})
}
setImmediate(main)
调用类中静态(static)方法:
function hook(){
console.log("hook open!!!")
var MainActivity = Java.use("com.ad2001.frida0x2.MainActivity");
MainActivity.get_flag(4919); #需要调用的静态方法
}
function main(){
console.log("java hook begin")
Java.perform(function(){
hook();
})
}
setImmediate(main,2000);
修改静态变量:
function hook(){
console.log("hook open!!!")
var checker = Java.use("com.ad2001.frida0x3.Checker");
checker.code.value=512; #修改Checker类中的code静态变量
}
function main(){
Java.perform(function(){
hook();
})
}
setImmediate(main)
调用非MainActivity,其他的类中的静态方法:
function hook(){
console.log("java hook open!!!");
var obj = Java.use("com.ad2001.frida0x4.Check");
var check = obj.$new(); #需要new出这个类
var string=check.get_flag(1337); #调用get_flag这个静态方法
console.log(string);
}
function main(){
Java.perform(function(){
hook();
})
}
setImmediate(main)
调用MainActivity中的非静态方法:
function hook(){
Java.choose('com.ad2001.frida0x5.MainActivity',{ #需要使用choose这个api
onMatch:function (MainActivity){ #onMatch回调函数在Java.choose操作期间找到指定类的每个实例时执行。这个回调函数接收当前实例作为它的参数。您可以在onMatch回调中定义自定义操作,以在每个实例上执行
MainActivity.flag(1337); #调用flag方法
console.log("Hook Success!");
},onComplete:function (){ #onComplete回调在Java.choose操作完成后执行操作或清理任务。此块是可选的,如果您在搜索完成后不需要执行任何特定操作,则可以选择将其留空。
}
})
}
function main(){
Java.perform(function (){
hook();
})
}
setImmediate(main);
调用MainActivity中的非静态方法,且参数是需要new的实例
function hook(){
Java.choose("com.ad2001.frida0x6.MainActivity",
{
onMatch: function(instance){
console.log("success!!!")
var checker = Java.use("com.ad2001.frida0x6.Checker");
var checker_obj = checker.$new();
checker_obj.num1.value = 1234; // num1
checker_obj.num2.value = 4321; // num2
instance.get_flag(checker_obj);
},
onComplete: function() {}
});
}
function main(){
Java.perform(function(){
hook();
})
}
setImmediate(main)
Objection(Objection可以将 Frida运行时所需要的frida-gadget.so重打包进App中,从而完成 Frida的无root调试):
objection -g com.roysue.httpurlconnectiondemo(包名) explore
jobs命令:作业系统很好用,用于查看和管理当前所执行Hook的任务
查看当前hook任务: jobs list
终止hook任务: jobs kill id
内存漫游相关命令:
列出当前内存中所有类:android hooking list classes
搜索内存中包含关键字的类: android hooking search class 关键字
搜索内存中包含关键字的方法: android hooking search methods 关键字
列出指定类中的所有方法: android hooking list class_methods 类完整路径
列出当前APP四大组件: android hooking list activities|services|receivers|providers
Hook相关命令:
Hook指定的方法: android hooking watch class_method 方法名称 --dump-args --dump-backtrace --dump-return
Hook某个类的所有方法: android hooking watch class 类名
android heap search instances <classname> 对实例的搜索,打印出对应的Handle和toString()的结果
android heap execute <Handle> <methodname> 在Objection中调用实例
android intent launch_activity 类名 启动某个类
frida HttpURLConnection 自吐:
假设demo源码如下:
package com.example.demo_http;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
@Override
public void run() {
while (true){
try {
URL url = new URL("https://www.baidu.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("token","r0ysue666");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
connection.connect(); // 开始连接
InputStream in = connection.getInputStream();
//if(in.available() > 0){
// 每次写入1024字节
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
StringBuffer sb = new StringBuffer();
while ((in.read(buffer)) != -1) {
sb.append(new String(buffer));
}
Log.d("r0ysue666", sb.toString());
connection.disconnect();
// }
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(10*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
hookhttp.js脚本如下:
function hook(){
var URL=Java.use("com.android.okhttp.internal.huc.HttpURLConnectionImpl") //通过objection就行定位出来
URL.setRequestProperty.implementation = function(key,value){
var result = this.setRequestProperty(key,value)
console.log("setRequestProperty = >>>",key,":",value) //打印出token信息
return result
}
}
function main(){
Java.perform(function(){
hook();
})
}
setImmediate(main)
终极"自吐"脚本,socket层hook:
function jhexdump(array) {
var ptr = Memory.alloc(array.length);
for(var i = 0; i < array.length; ++i)
Memory.writeS8(ptr.add(i), array[i]);
//console.log(hexdump(ptr, { offset: off, length: len, header: false, ansi: false }));
console.log(hexdump(ptr, { offset: 0, length: array.length, header: false, ansi: false }));
}
function hookAddress(){
Java.perform(function(){
// java.net.InetSocketAddress.InetSocketAddress(java.net.InetAddress, int)
Java.use('java.net.InetSocketAddress').$init.overload('java.net.InetAddress', 'int').implementation = function(addr,port){
var result = this.$init(addr,port)
//console.log('addr,port =>',addr.toString(),port)
if(addr.isSiteLocalAddress()){
console.log('Local address =>',addr.toString(),', port is ',port)
}else{
console.log('Server address =>',addr.toString(),', port is ',port)
}
return result
}
})
}
function hookSocket() {
Java.perform(function () {
// java.net.SocketOutputStream.write
// java.net.SocketOutputStream.socketWrite
Java.use('java.net.SocketOutputStream').socketWrite.overload('[B', 'int', 'int').implementation = function (bytearray1, int1, int2) {
var result = this.socketWrite(bytearray1, int1, int2)
console.log('socketWrite result,bytearray1,int1,int2=>', result, bytearray1, int1, int2)
var ByteString = Java.use("com.android.okhttp.okio.ByteString");
// console.log('contents: => ', ByteString.of(bytearray1).hex())
jhexdump(bytearray1)
return result
}
// java.net.SocketInputStream.read
// java.net.SocketInputStream.socketRead0
Java.use('java.net.SocketInputStream').read.overload('[B', 'int', 'int').implementation = function (bytearray1, int1, int2) {
var result = this.read(bytearray1, int1, int2)
console.log('read result,bytearray1,int1,int2=>', result, bytearray1, int1, int2)
var ByteString = Java.use("com.android.okhttp.okio.ByteString");
//console.log('contents: => ', ByteString.of(bytearray1).hex())
jhexdump(bytearray1)
return result
}
})
}
function hookSSLSocketAndroid8(){
Java.perform(function () {
// com.android.org.conscrypt.ConscryptFileDescriptorSocket$SSLOutputStream.write
Java.use('com.android.org.conscrypt.ConscryptFileDescriptorSocket$SSLOutputStream').write.overload('[B', 'int', 'int').implementation = function (bytearray1, int1, int2) {
var result = this.write(bytearray1, int1, int2)
console.log('write result,bytearray1,int1,int2=>', result, bytearray1, int1, int2)
var ByteString = Java.use("com.android.okhttp.okio.ByteString");
console.log('contents: => ', ByteString.of(bytearray1).hex())
return result
}
// com.android.org.conscrypt.ConscryptFileDescriptorSocket$SSLInputStream.read
Java.use('com.android.org.conscrypt.ConscryptFileDescriptorSocket$SSLInputStream').read.overload('[B', 'int', 'int').implementation = function (bytearray1, int1, int2) {
var result = this.read(bytearray1, int1, int2)
console.log('read result,bytearray1,int1,int2=>', result, bytearray1, int1, int2)
var ByteString = Java.use("com.android.okhttp.okio.ByteString");
//console.log('contents: => ', ByteString.of(bytearray1).hex())
jhexdump(bytearray1)
return result
}
})
}
function main(){
hookAddress()
hookSocket()
hookSSLSocketAndroid8()
}
setImmediate(main)
frida辅助抓包:
objection -g cn.ticktick.task explore -s "android sslpinning disable" 加了-s参数,可以在程序打开时hook掉证书检验的函数
应对多数网络框架的hook脚本:WooyunDota/DroidSSLUnpinning: Android certificate pinning disable tools (github.com)
Java.perform(function() {
/*
hook list:
1.SSLcontext
2.okhttp
3.webview
4.XUtils
5.httpclientandroidlib
6.JSSE
7.network\_security\_config (android 7.0+)
8.Apache Http client (support partly)
9.OpenSSLSocketImpl
10.TrustKit
11.Cronet
*/
// Attempts to bypass SSL pinning implementations in a number of
// ways. These include implementing a new TrustManager that will
// accept any SSL certificate, overriding OkHTTP v3 check()
// method etc.
var X509TrustManager = Java.use('javax.net.ssl.X509TrustManager');
var HostnameVerifier = Java.use('javax.net.ssl.HostnameVerifier');
var SSLContext = Java.use('javax.net.ssl.SSLContext');
var quiet_output = false;
// Helper method to honor the quiet flag.
function quiet_send(data) {
if (quiet_output) {
return;
}
send(data)
}
// Implement a new TrustManager
// ref: https://gist.github.com/oleavr/3ca67a173ff7d207c6b8c3b0ca65a9d8
// Java.registerClass() is only supported on ART for now(201803). 所以android 4.4以下不兼容,4.4要切换成ART使用.
/*
06-07 16:15:38.541 27021-27073/mi.sslpinningdemo W/System.err: java.lang.IllegalArgumentException: Required method checkServerTrusted(X509Certificate[], String, String, String) missing
06-07 16:15:38.542 27021-27073/mi.sslpinningdemo W/System.err: at android.net.http.X509TrustManagerExtensions.<init>(X509TrustManagerExtensions.java:73)
at mi.ssl.MiPinningTrustManger.<init>(MiPinningTrustManger.java:61)
06-07 16:15:38.543 27021-27073/mi.sslpinningdemo W/System.err: at mi.sslpinningdemo.OkHttpUtil.getSecPinningClient(OkHttpUtil.java:112)
at mi.sslpinningdemo.OkHttpUtil.get(OkHttpUtil.java:62)
at mi.sslpinningdemo.MainActivity$1$1.run(MainActivity.java:36)
*/
var X509Certificate = Java.use("java.security.cert.X509Certificate");
var TrustManager;
try {
TrustManager = Java.registerClass({
name: 'org.wooyun.TrustManager',
implements: [X509TrustManager],
methods: {
checkClientTrusted: function(chain, authType) {},
checkServerTrusted: function(chain, authType) {},
getAcceptedIssuers: function() {
// var certs = [X509Certificate.$new()];
// return certs;
return [];
}
}
});
} catch (e) {
quiet_send("registerClass from X509TrustManager >>>>>>>> " + e.message);
}
// Prepare the TrustManagers array to pass to SSLContext.init()
var TrustManagers = [TrustManager.$new()];
try {
// Prepare a Empty SSLFactory
var TLS_SSLContext = SSLContext.getInstance("TLS");
TLS_SSLContext.init(null, TrustManagers, null);
var EmptySSLFactory = TLS_SSLContext.getSocketFactory();
} catch (e) {
quiet_send(e.message);
}
send('Custom, Empty TrustManager ready');
// Get a handle on the init() on the SSLContext class
var SSLContext_init = SSLContext.init.overload(
'[Ljavax.net.ssl.KeyManager;', '[Ljavax.net.ssl.TrustManager;', 'java.security.SecureRandom');
// Override the init method, specifying our new TrustManager
SSLContext_init.implementation = function(keyManager, trustManager, secureRandom) {
quiet_send('Overriding SSLContext.init() with the custom TrustManager');
SSLContext_init.call(this, null, TrustManagers, null);
};
/*** okhttp3.x unpinning ***/
// Wrap the logic in a try/catch as not all applications will have
// okhttp as part of the app.
try {
var CertificatePinner = Java.use('okhttp3.CertificatePinner');
quiet_send('OkHTTP 3.x Found');
CertificatePinner.check.overload('java.lang.String', 'java.util.List').implementation = function() {
quiet_send('OkHTTP 3.x check() called. Not throwing an exception.');
}
} catch (err) {
// If we dont have a ClassNotFoundException exception, raise the
// problem encountered.
if (err.message.indexOf('ClassNotFoundException') === 0) {
throw new Error(err);
}
}
// Appcelerator Titanium PinningTrustManager
// Wrap the logic in a try/catch as not all applications will have
// appcelerator as part of the app.
try {
var PinningTrustManager = Java.use('appcelerator.https.PinningTrustManager');
send('Appcelerator Titanium Found');
PinningTrustManager.checkServerTrusted.implementation = function() {
quiet_send('Appcelerator checkServerTrusted() called. Not throwing an exception.');
}
} catch (err) {
// If we dont have a ClassNotFoundException exception, raise the
// problem encountered.
if (err.message.indexOf('ClassNotFoundException') === 0) {
throw new Error(err);
}
}
/*** okhttp unpinning ***/
try {
var OkHttpClient = Java.use("com.squareup.okhttp.OkHttpClient");
OkHttpClient.setCertificatePinner.implementation = function(certificatePinner) {
// do nothing
quiet_send("OkHttpClient.setCertificatePinner Called!");
return this;
};
// Invalidate the certificate pinnet checks (if "setCertificatePinner" was called before the previous invalidation)
var CertificatePinner = Java.use("com.squareup.okhttp.CertificatePinner");
CertificatePinner.check.overload('java.lang.String', '[Ljava.security.cert.Certificate;').implementation = function(p0, p1) {
// do nothing
quiet_send("okhttp Called! [Certificate]");
return;
};
CertificatePinner.check.overload('java.lang.String', 'java.util.List').implementation = function(p0, p1) {
// do nothing
quiet_send("okhttp Called! [List]");
return;
};
} catch (e) {
quiet_send("com.squareup.okhttp not found");
}
/*** WebView Hooks ***/
/* frameworks/base/core/java/android/webkit/WebViewClient.java */
/* public void onReceivedSslError(Webview, SslErrorHandler, SslError) */
var WebViewClient = Java.use("android.webkit.WebViewClient");
WebViewClient.onReceivedSslError.implementation = function(webView, sslErrorHandler, sslError) {
quiet_send("WebViewClient onReceivedSslError invoke");
//执行proceed方法
sslErrorHandler.proceed();
return;
};
WebViewClient.onReceivedError.overload('android.webkit.WebView', 'int', 'java.lang.String', 'java.lang.String').implementation = function(a, b, c, d) {
quiet_send("WebViewClient onReceivedError invoked");
return;
};
WebViewClient.onReceivedError.overload('android.webkit.WebView', 'android.webkit.WebResourceRequest', 'android.webkit.WebResourceError').implementation = function() {
quiet_send("WebViewClient onReceivedError invoked");
return;
};
/*** JSSE Hooks ***/
/* libcore/luni/src/main/java/javax/net/ssl/TrustManagerFactory.java */
/* public final TrustManager[] getTrustManager() */
/* TrustManagerFactory.getTrustManagers maybe cause X509TrustManagerExtensions error */
// var TrustManagerFactory = Java.use("javax.net.ssl.TrustManagerFactory");
// TrustManagerFactory.getTrustManagers.implementation = function(){
// quiet_send("TrustManagerFactory getTrustManagers invoked");
// return TrustManagers;
// }
var HttpsURLConnection = Java.use("javax.net.ssl.HttpsURLConnection");
/* libcore/luni/src/main/java/javax/net/ssl/HttpsURLConnection.java */
/* public void setDefaultHostnameVerifier(HostnameVerifier) */
HttpsURLConnection.setDefaultHostnameVerifier.implementation = function(hostnameVerifier) {
quiet_send("HttpsURLConnection.setDefaultHostnameVerifier invoked");
return null;
};
/* libcore/luni/src/main/java/javax/net/ssl/HttpsURLConnection.java */
/* public void setSSLSocketFactory(SSLSocketFactory) */
HttpsURLConnection.setSSLSocketFactory.implementation = function(SSLSocketFactory) {
quiet_send("HttpsURLConnection.setSSLSocketFactory invoked");
return null;
};
/* libcore/luni/src/main/java/javax/net/ssl/HttpsURLConnection.java */
/* public void setHostnameVerifier(HostnameVerifier) */
HttpsURLConnection.setHostnameVerifier.implementation = function(hostnameVerifier) {
quiet_send("HttpsURLConnection.setHostnameVerifier invoked");
return null;
};
/*** Xutils3.x hooks ***/
//Implement a new HostnameVerifier
var TrustHostnameVerifier;
try {
TrustHostnameVerifier = Java.registerClass({
name: 'org.wooyun.TrustHostnameVerifier',
implements: [HostnameVerifier],
method: {
verify: function(hostname, session) {
return true;
}
}
});
} catch (e) {
//java.lang.ClassNotFoundException: Didn't find class "org.wooyun.TrustHostnameVerifier"
quiet_send("registerClass from hostnameVerifier >>>>>>>> " + e.message);
}
try {
var RequestParams = Java.use('org.xutils.http.RequestParams');
RequestParams.setSslSocketFactory.implementation = function(sslSocketFactory) {
sslSocketFactory = EmptySSLFactory;
return null;
}
RequestParams.setHostnameVerifier.implementation = function(hostnameVerifier) {
hostnameVerifier = TrustHostnameVerifier.$new();
return null;
}
} catch (e) {
quiet_send("Xutils hooks not Found");
}
/*** httpclientandroidlib Hooks ***/
try {
var AbstractVerifier = Java.use("ch.boye.httpclientandroidlib.conn.ssl.AbstractVerifier");
AbstractVerifier.verify.overload('java.lang.String', '[Ljava.lang.String', '[Ljava.lang.String', 'boolean').implementation = function() {
quiet_send("httpclientandroidlib Hooks");
return null;
}
} catch (e) {
quiet_send("httpclientandroidlib Hooks not found");
}
/***
android 7.0+ network_security_config TrustManagerImpl hook
apache httpclient partly
***/
var TrustManagerImpl = Java.use("com.android.org.conscrypt.TrustManagerImpl");
// try {
// var Arrays = Java.use("java.util.Arrays");
// //apache http client pinning maybe baypass
// //https://github.com/google/conscrypt/blob/c88f9f55a523f128f0e4dace76a34724bfa1e88c/platform/src/main/java/org/conscrypt/TrustManagerImpl.java#471
// TrustManagerImpl.checkTrusted.implementation = function (chain, authType, session, parameters, authType) {
// quiet_send("TrustManagerImpl checkTrusted called");
// //Generics currently result in java.lang.Object
// return Arrays.asList(chain);
// }
//
// } catch (e) {
// quiet_send("TrustManagerImpl checkTrusted nout found");
// }
try {
// Android 7+ TrustManagerImpl
TrustManagerImpl.verifyChain.implementation = function(untrustedChain, trustAnchorChain, host, clientAuth, ocspData, tlsSctData) {
quiet_send("TrustManagerImpl verifyChain called");
// Skip all the logic and just return the chain again :P
//https://www.nccgroup.trust/uk/about-us/newsroom-and-events/blogs/2017/november/bypassing-androids-network-security-configuration/
// https://github.com/google/conscrypt/blob/c88f9f55a523f128f0e4dace76a34724bfa1e88c/platform/src/main/java/org/conscrypt/TrustManagerImpl.java#L650
return untrustedChain;
}
} catch (e) {
quiet_send("TrustManagerImpl verifyChain nout found below 7.0");
}
// OpenSSLSocketImpl
try {
var OpenSSLSocketImpl = Java.use('com.android.org.conscrypt.OpenSSLSocketImpl');
OpenSSLSocketImpl.verifyCertificateChain.implementation = function(certRefs, authMethod) {
quiet_send('OpenSSLSocketImpl.verifyCertificateChain');
}
quiet_send('OpenSSLSocketImpl pinning')
} catch (err) {
quiet_send('OpenSSLSocketImpl pinner not found');
}
// Trustkit
try {
var Activity = Java.use("com.datatheorem.android.trustkit.pinning.OkHostnameVerifier");
Activity.verify.overload('java.lang.String', 'javax.net.ssl.SSLSession').implementation = function(str) {
quiet_send('Trustkit.verify1: ' + str);
return true;
};
Activity.verify.overload('java.lang.String', 'java.security.cert.X509Certificate').implementation = function(str) {
quiet_send('Trustkit.verify2: ' + str);
return true;
};
quiet_send('Trustkit pinning')
} catch (err) {
quiet_send('Trustkit pinner not found')
}
try {
//cronet pinner hook
//weibo don't invoke
var netBuilder = Java.use("org.chromium.net.CronetEngine$Builder");
//https://developer.android.com/guide/topics/connectivity/cronet/reference/org/chromium/net/CronetEngine.Builder.html#enablePublicKeyPinningBypassForLocalTrustAnchors(boolean)
netBuilder.enablePublicKeyPinningBypassForLocalTrustAnchors.implementation = function(arg) {
//weibo not invoke
console.log("Enables or disables public key pinning bypass for local trust anchors = " + arg);
//true to enable the bypass, false to disable.
var ret = netBuilder.enablePublicKeyPinningBypassForLocalTrustAnchors.call(this, true);
return ret;
};
netBuilder.addPublicKeyPins.implementation = function(hostName, pinsSha256, includeSubdomains, expirationDate) {
console.log("cronet addPublicKeyPins hostName = " + hostName);
//var ret = netBuilder.addPublicKeyPins.call(this,hostName, pinsSha256,includeSubdomains, expirationDate);
//this 是调用 addPublicKeyPins 前的对象吗? Yes,CronetEngine.Builder
return this;
};
} catch (err) {
console.log('[-] Cronet pinner not found')
}
});
hook控件脚本:
var jclazz = null;
var jobj = null;
function getObjClassName(obj) {
if (!jclazz) {
var jclazz = Java.use("java.lang.Class");
}
if (!jobj) {
var jobj = Java.use("java.lang.Object");
}
return jclazz.getName.call(jobj.getClass.call(obj));
}
function watch(obj, mtdName) {
var listener_name = getObjClassName(obj);
var target = Java.use(listener_name);
if (!target || !mtdName in target) {
return;
}
// send("[WatchEvent] hooking " + mtdName + ": " + listener_name);
target[mtdName].overloads.forEach(function (overload) {
overload.implementation = function () {
//send("[WatchEvent] " + mtdName + ": " + getObjClassName(this));
console.log("[WatchEvent] " + mtdName + ": " + getObjClassName(this))
return this[mtdName].apply(this, arguments);
};
})
}
function OnClickListener() {
Java.perform(function () {
//以spawn启动进程的模式来attach的话
Java.use("android.view.View").setOnClickListener.implementation = function (listener) {
if (listener != null) {
watch(listener, 'onClick');
}
return this.setOnClickListener(listener);
};
//如果frida以attach的模式进行attch的话
Java.choose("android.view.View$ListenerInfo", {
onMatch: function (instance) {
instance = instance.mOnClickListener.value;
if (instance) {
console.log("mOnClickListener name is :" + getObjClassName(instance));
watch(instance, 'onClick');
}
},
onComplete: function () {
}
})
})
}
function OnTouchListener() {
Java.perform(function () {
//以spawn启动进程的模式来attach的话
Java.use("android.view.View").setOnTouchListener.implementation = function (listener) {
if (listener != null) {
watch(listener, 'onTouch');
}
return this.setOnTouchListener(listener);
};
//如果frida以attach的模式进行attch的话
Java.choose("android.view.View$ListenerInfo", {
onMatch: function (instance) {
instance = instance.mOnTouchListener;
if (instance) {
console.log("mOnTouchListener name is :" + getObjClassName(instance));
watch(instance, 'onTouch');
}
},
onComplete: function () {
}
})
})
}
setImmediate(OnClickListener);
/**
* OnClickListener#onClick(View v)
* OnTouchListener#onTouch(View v, MotionEvent event)
* Activity onTouchEvent(MotionEvent event) Activity 触摸事件
* RecyclerView OnItemTouchListener#onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) RecyclerView条目触摸事件
* OnFlingListener#onFling(int x, int y)
或
OnScrollChangeListener#onScrollChange(View v, int x,int y, int oldX, int oldY)
或
OnScrollListener#onScrollStateChanged(RecyclerView recyclerView, int newState)
或
OnScrollListener#onScrolled(RecyclerView recyclerView,int dx, int dy) onScroll RecyclerView 滑动事件
* ListView OnItemClickListener#onItemClick(AdapterView parent,View view, int position, long id) - onViewItemClick - ListView - 条目点击事件
* OnScrollListener#onScrollStateChanged(AbsListView view, int scrollState) 或
OnScrollChangeListener#onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) onScroll ListView 滑动事件
*/
Native层hook:
memory list modules 查看加载的库文件
memory list exports libnative-lib.so 查看导出的库文件内容
demo--apk:
java层代码:
package com.example.demo_native;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.example.demo_native.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity {
// Used to load the 'demo_native' library on application startup.
static {
System.loadLibrary("demo_native");
}
private ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
// Example of a call to a native method
TextView tv = binding.sampleText;
tv.setText(stringFromJNI());
while(true){
try{
Thread.sleep(1000);
}catch (InterruptedException e){
e.printStackTrace();
}
Log.i("ggbomb",stringFromJNI());
}
}
/**
* A native method that is implemented by the 'demo_native' native library,
* which is packaged with this application.
*/
public native String stringFromJNI();
}
native层代码
#include <jni.h>
#include <string>
extern "C" JNIEXPORT jstring
JNICALL
Java_com_example_demo_1native_MainActivity_stringFromJNI(
JNIEnv *env,
jobject /* this */) {
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}
hook该demo脚本如下:
function hook_native(){
var addr=Module.getExportByName("libdemo_native.so","Java_com_example_demo_1native_MainActivity_stringFromJNI");
Interceptor.attach(addr,{
onEnter:function(args){
console.log("jnienv pointer =>",args[0]) //hook参数
console.log("jobj pointer =>",args[1])
},
onLeave:function(retval){ //hook返回值
console.log("retval is =>",Java.vm.getEnv().getStringUtfChars(retval,null).readCString())
console.log("================")
}
})
}
function main(){
hook_native()
}
setImmediate(main)
动态注册函数的hook:lasting-yang/frida_hook_libart: Frida hook some jni functions (github.com)
function find_RegisterNatives(params) {
let symbols = Module.enumerateSymbolsSync("libart.so");
let addrRegisterNatives = null;
for (let i = 0; i < symbols.length; i++) {
let symbol = symbols[i];
//_ZN3art3JNI15RegisterNativesEP7_JNIEnvP7_jclassPK15JNINativeMethodi
if (symbol.name.indexOf("art") >= 0 &&
symbol.name.indexOf("JNI") >= 0 &&
symbol.name.indexOf("RegisterNatives") >= 0 &&
symbol.name.indexOf("CheckJNI") < 0) {
addrRegisterNatives = symbol.address;
console.log("RegisterNatives is at ", symbol.address, symbol.name);
hook_RegisterNatives(addrRegisterNatives)
}
}
}
function hook_RegisterNatives(addrRegisterNatives) {
if (addrRegisterNatives != null) {
Interceptor.attach(addrRegisterNatives, {
onEnter: function (args) {
console.log("[RegisterNatives] method_count:", args[3]);
let java_class = args[1];
let class_name = Java.vm.tryGetEnv().getClassName(java_class);
//console.log(class_name);
let methods_ptr = ptr(args[2]);
let method_count = parseInt(args[3]);
for (let i = 0; i < method_count; i++) {
let name_ptr = Memory.readPointer(methods_ptr.add(i * Process.pointerSize * 3));
let sig_ptr = Memory.readPointer(methods_ptr.add(i * Process.pointerSize * 3 + Process.pointerSize));
let fnPtr_ptr = Memory.readPointer(methods_ptr.add(i * Process.pointerSize * 3 + Process.pointerSize * 2));
let name = Memory.readCString(name_ptr);
let sig = Memory.readCString(sig_ptr);
let symbol = DebugSymbol.fromAddress(fnPtr_ptr)
console.log("[RegisterNatives] java_class:", class_name, "name:", name, "sig:", sig, "fnPtr:", fnPtr_ptr, " fnOffset:", symbol, " callee:", DebugSymbol.fromAddress(this.returnAddress));
}
}
});
}
}
setImmediate(find_RegisterNatives);
frida检测绕过:
一把梭脚本,实测b站可以绕过:
function replace_str() {
var pt_strstr = Module.findExportByName("libc.so", 'strstr');
var pt_strcmp = Module.findExportByName("libc.so", 'strcmp');
Interceptor.attach(pt_strstr, {
onEnter: function (args) {
var str1 = args[0].readCString();
var str2 = args[1].readCString();
if (
str2.indexOf("REJECT") !== -1 ||
str2.indexOf("tmp") !== -1 ||
str2.indexOf("frida") !== -1 ||
str2.indexOf("gum-js-loop") !== -1 ||
str2.indexOf("gmain") !== -1 ||
str2.indexOf("linjector") !== -1
) {
console.log("strstr-->", str1, str2);
this.hook = true;
}
}, onLeave: function (retval) {
if (this.hook) {
retval.replace(0);
}
}
});
Interceptor.attach(pt_strcmp, {
onEnter: function (args) {
var str1 = args[0].readCString();
var str2 = args[1].readCString();
if (
str2.indexOf("REJECT") !== -1 ||
str2.indexOf("tmp") !== -1 ||
str2.indexOf("frida") !== -1 ||
str2.indexOf("gum-js-loop") !== -1 ||
str2.indexOf("gmain") !== -1 ||
str2.indexOf("linjector") !== -1
) {
//console.log("strcmp-->", str1, str2);
this.hook = true;
}
}, onLeave: function (retval) {
if (this.hook) {
retval.replace(0);
}
}
})
}
function main(){
Java.perform(function(){
replace_str()
})
}
setImmediate(main)
用于检测那个so在检测frida:[原创]绕过bilibili frida反调试-Android安全-看雪-安全社区|安全招聘|kanxue.com
function hook_dlopen() {
Interceptor.attach(Module.findExportByName(null, "android_dlopen_ext"),
{
onEnter: function (args) {
var pathptr = args[0];
if (pathptr !== undefined && pathptr != null) {
var path = ptr(pathptr).readCString();
console.log("load " + path);
}
}
}
);
}
function main(){
Java.perform(function(){
hook_dlopen()
})
}
setImmediate(main)