首页 > 其他分享 >frida--hook记录

frida--hook记录

时间:2024-03-31 16:35:26浏览次数:23  
标签:function Java java -- hook var frida android

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);

 

标签:function,Java,java,--,hook,var,frida,android
From: https://www.cnblogs.com/GGbomb/p/18099770

相关文章

  • 周报
    周报两场天梯训练赛进行了补题200及以上;另自己训练了一套天梯赛;整理了一下二叉搜索树模板,以及学习了点dijkstra进阶知识;SMU2024spring天梯赛2-Ke_scholar-博客园(cnblogs.com)SMU2024spring天梯赛3-Ke_scholar-博客园(cnblogs.com)SMU2024spring天梯......
  • 3.31 联考
    3.31补题A\(5pts\)\(n=2\)时,\(\fracn2=1\),即为nim游戏。\(30pts\)对于\((a_1,a_2,a_3,a_4,a_5,a_6)\)这样的六元组,至多有\(10^6\)个。记忆化搜索他们的SG值即可。可能需要若干剪枝,因为复杂度其实是\(10^6\times6^3\)的。\(100pts\)首先观察样例2,合理猜测......
  • 【每周例题】力扣 C++ 搜索插入位置
    搜索插入位置题目搜索插入位置 题目分析1.第一个想法肯定是暴力遍历,找到了就输出下标,找不到就对比前后两个数字,寻找合适的位置插入。2.需要注意一点,我们需要再一开始就对比target与数组最后一个数的大小,如果比数组最后一个数大,直接返回数组长度3.第二个想法就是缩短寻找的......
  • LeetCode Hot100-哈希-两数之和
    题目描述:给定一个整数数组nums和一个整数目标值target,请你在该数组中找出和为目标值target的两个整数,并返回它们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。你可以按任意顺序返回答案。示例1:输入:nums=[2,7,1......
  • 目前国内全地形能力最强的双足机器人 —— 逐际动力 —— 提出迭代式预训练(Iterative
    相关:https://weibo.com/1255595687/O5k4Aj8l2该公司对其产品的强化学习训练算法给出了较少的描述:提出迭代式预训练(IterativePre-training)方法,把通用机器人的基础运动能力划分为不同级别,进行循序渐进的预训练,这个过程让训练的结果更可控,从而高效地产出和收集有效数据,训练......
  • AtCoder Beginner Contest 347 A-F 题解
    A-DivisibleQuesiton给你正整数\(N\)和\(K\),以及长度为\(N\)的序列\(A\)。提取\(A\)中所有是\(K\)倍数的元素,除以\(K\),并打印商。Solution判断\(A_i\%K\)的值是否为\(0\),如果非\(0\)则表示可以整除Code#include<bits/stdc++.h>usingnamespacest......
  • useMemo和useCallback
    useMemo 和 useCallback 是React的两个高级Hooks,分别用于优化渲染性能和避免不必要的重新渲染,和vue中的计算属性computed相似(缓存)1.useMemouseMemo 用于避免在每次渲染时都执行高开销的计算。它会返回一个memoized(缓存)的值,这个值仅在其依赖项发生变化时才会重新计算......
  • react路径别名@配置
    首先下载包craconpmi-D @craco/craco1.路径解析在项目根目录下创建craco.config.js配置如下2.vscode识别配置在项目根目录下创建jsconfig.json,配置如下3. package.json将start和build的内容改成craco,重启项目 ......
  • C语言 05 变量与常量
    变量变量就像在数学中学习的x,y一样,可以直接声明一个变量,并利用这些变量进行基本的运算,声明变量的格式为:数据类型变量名称=初始值;(其中初始值可以不用在定义变量时设定)=是赋值操作,可以将等号后面的值赋值给前面的变量,等号后面可以直接写一个数字(常量)、变量名称、算式。比......
  • 自营小说3.0版推文新玩法、文字一键生成AI漫画视频、实时数据小白当天591.33?
    文字一键生成AI漫画视频、实时数据小白当天591.33?-1-项目简介小说推文是老项目,存在至今,不断有人再做,但是之前的玩法太老套,因为之前都是解压视频,文字需要转换成语音,然后需要去找解压素材,我们需要用剪映再去剪辑,这样一个作品需要30分钟,浪费时间,还不知道有没有效果今天给大......