如何将Frida Hook到的iOS NSDictionary转为JSON通过send发送至客户端?
Frida Hook中NSDictionary转标准格式发送至客户端的解决方案
问题场景
Hook iOS应用中接收NSDictionary参数的Objective-C方法时,无法直接通过Frida的send()发送原对象,而对象的字符串表示格式不标准,难以解析。需要将仅包含字符串、数字的NSDictionary转为JSON这类标准格式,以便客户端解码处理。现有代码如下:
Interceptor.attach(ObjC.classes.SomeClass['- someMethod:'].implementation, { onEnter: function (args) { let nsDictArg = new ObjC.Object(args[2]); // NSDictionary // console.log(nsDictArg); nsDictArg_converted = // How to convert NSDictionary so that it can be sent? send("mymessage", nsDictArg_converted); // directly sending nsDictArg does not work } });
两种可行解决方案
方案一:利用Frida内置API转JS对象(最简)
Frida提供ObjC.deepCopy()方法,可直接将Objective-C集合类(如NSDictionary)转为JavaScript原生对象,send()会自动将其序列化为标准JSON格式发送:
Interceptor.attach(ObjC.classes.SomeClass['- someMethod:'].implementation, { onEnter: function (args) { let nsDictArg = new ObjC.Object(args[2]); // 转为JS对象,send会自动序列化为JSON const jsObj = ObjC.deepCopy(nsDictArg); send("mymessage", jsObj); } });
客户端接收后,直接用JSON.parse()即可解析为本地对象,适用于仅包含基础类型(字符串、数字、布尔值、嵌套集合)的场景。
方案二:通过NSJSONSerialization生成标准JSON字符串
借助Objective-C原生的NSJSONSerialization类,将NSDictionary序列化为标准JSON字符串,确保格式完全符合JSON规范:
Interceptor.attach(ObjC.classes.SomeClass['- someMethod:'].implementation, { onEnter: function (args) { let nsDictArg = new ObjC.Object(args[2]); // 获取NSJSONSerialization类 const NSJSONSerialization = ObjC.classes.NSJSONSerialization; // 序列化NSDictionary为NSData(options传0表示不格式化) const jsonData = NSJSONSerialization.dataWithJSONObject_options_error_(nsDictArg, 0, NULL); // 将NSData转为UTF-8编码的NSString(4对应NSUTF8StringEncoding) const jsonString = ObjC.classes.NSString.alloc().initWithData_encoding_(jsonData, 4); // 转为JS字符串发送 send("mymessage", jsonString.toString()); } });
客户端接收后,直接解析该字符串即可得到标准JSON对象,此方法兼容性更强,适合需要严格控制JSON格式的场景。
内容的提问来源于stack exchange,提问作者Robert
相关产品推荐
相关产品推荐

