# encoding:utf-8
#1.window电脑(mac或者linux)上安装frida,安装步骤:
# 1)先安装python环境(可选安装npm环境,最好安装一下)
# 2)pip install frida-tools # CLI tools 地址:https://github.com/frida/frida
# pip install frida # Python bindings
# npm install frida # Node.js bindings
#2.android手机安装frida-server(手机一定要root,没有真机可以使用模拟器)
# 1)下载对应版本(arm/arm64/x86)的frida-server,地址:https://github.com/frida/frida/releases
# 2)adb push frida-server /data/local/tmp 将frida-server推送到手机/data/local/tmp目录下
# 3)adb shell 进去手机环境
# 4)su 获取root权限
# 5)cd /data/local/tmp 来到frida-server目录下
# 6)chmod 777 frida-server 给足够权限给frida-server
# 7)./frida-server 让frida服务跑起来,不要关闭此窗口
#3.转发adb端口
# 1)另外开一个cmd窗口
# 2)frida-ps -U 查看frida-server是否以及运行起来了
# 3)adb shell 进去手机环境,接着su切换到root环境,因为netstat需要
# 4)netstat -anp | grep "frida" 查看frida-server运行到端口,比如27042
# 5)再另外开一个cmd窗口
# 6)adb forward tcp:27042 tcp:27042 进行端口转发
# 7)frida-ps -Uai 可以查看手机上运行的所有进程对应的包名、pid等等
# 8)写一个测试app跑起来,app一定要跑起来先,不然hook的时候找不到进程
# 9)编写下面的脚本保存为test.py,然后执行python test.py,看到Hook Start Running即hook成功了

import frida, sys

def on_message(message, data):
if message['type'] == 'send':
print("[*] {0}".format(message['payload']))
else:
print(message)

jscode="""
Java.perform(function () {
var s = Java.use("com.suyf.fridahook.MainActivity");
s.stringFromJNI.implementation = function () {
var ss = this.stringFromJNI() + "_hook";
send(ss);
return ss;
};
s.testHook.implementation = function (str) {
this.testHook(str);
send(str + "_add_hook");
};

var sfj = Module.findExportByName("libnative-lib.so", "Java_com_suyf_fridahook_MainActivity_stringFromJNI");
Interceptor.attach(sfj, {
onEnter: function () {
send("sfj-onEnter-->"+arguments);
},
onLeave: function () {
send("sfj-onLeave-->"+arguments);
}
});

});
"""
#新版本要使用name,不能使用包名,可以使用frida-ps -Uai 查看包名
process = frida.get_usb_device().attach('FridaHook')
#pid = device.spawn(["com.android.chrome"])
#session = device.attach(pid)
#device.resume(pid)
script = process.create_script(jscode)
script.on('message', on_message)
print('[*] Hook Start Running')
script.load()
sys.stdin.read()