Binary Ninja Python插件中Frida拦截器JS脚本无输出问题排查
Binary Ninja插件Frida函数追踪日志输出问题
问题背景
我正在开发一款Binary Ninja插件,核心功能之一是用Frida实现函数追踪。插件基于Python 3.10开发,但Frida的核心逻辑采用JavaScript编写。我知道Frida自带JS虚拟机,因此尝试加载JS代码并通过Frida运行,但目前遇到了关键问题:JS模板trace_template中,Interceptor.attach的onEnter和onLeave回调里的console.log内容无法输出到Binary Ninja控制台。我已经确认模板内容本身能正常打印,但不确定问题出在模板逻辑还是frida.core.Session.create_script(formatted)方法上,而这些日志输出是后续开发必不可少的。
复现代码
import frida import binaryninja as bn # Frida JS追踪模板 trace_template = """ Interceptor.attach(ptr("%s"), { onEnter: function(args) { console.log("进入函数,地址: " + this.context.pc); }, onLeave: function(retval) { console.log("离开函数,返回值: " + retval); } }); """ def trace_selected_function(bv, function): # 附加到目标进程(此处假设通过USB设备连接移动端进程,可根据实际场景调整) device = frida.get_usb_device() session = device.attach(bv.file.filename) # 填充模板中的函数地址 formatted_script = trace_template % hex(function.start) # 打印模板内容确认格式无误 print(formatted_script) # 创建并加载Frida脚本 script = session.create_script(formatted_script) script.load() # 此处无法获取Frida回调中的console.log输出
排查与解决方法
- 绑定Frida消息回调:Frida脚本的
console.log输出默认不会直接流向Binary Ninja的Python控制台,需要手动绑定消息回调捕获输出:def handle_frida_message(message, data): if message['type'] == 'send': # 用Binary Ninja日志函数输出正常消息 bn.log_info(message['payload']) elif message['type'] == 'error': # 输出错误栈信息便于调试 bn.log_error(message['stack']) # 在script.load()前绑定回调 script.on('message', handle_frida_message) - 替换console.log为send():Frida的
send()方法会主动将消息推送到Python端回调,比console.log在插件环境下更可靠,修改JS模板:onEnter: function(args) { send("进入函数,地址: " + this.context.pc); }, onLeave: function(retval) { send("离开函数,返回值: " + retval); } - 验证函数地址正确性:确保
function.start转换后的地址与目标进程实际内存地址匹配,用hex(function.start)明确地址格式,避免ptr解析错误。 - 检查会话状态:确认
session.attach是否成功,script.load()是否抛出异常,排查目标进程权限(如移动端进程是否需要root,桌面进程是否有足够权限)。
内容的提问来源于stack exchange,提问作者GABRIEL R GARCIA-AVILES
相关产品推荐
相关产品推荐

