首页
社区
课程
招聘
一个Ida小插件
发表于: 2023-9-26 18:16 7938

一个Ida小插件

2023-9-26 18:16
7938

IosIdaFrida

写了个ida小插件,自动生成frida hook 脚本代码。代码大部分是抄其他大佬和chatgpt的:)

使用效果

源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import idaapi
import ida_kernwin
import idc
import re
from string import Template
from PyQt5.QtWidgets import QApplication
 
#ScriptGenerator
class SG():
    logTemplate = 'send("arg$index:"+args[$index]);\n'
 
    # 这里没有考虑ida分析出的参数个数与frida获取到的参数个数不一致问题
    objc_logTemplate = """
                var arg = args[$index]
                if (targetMethod.argumentTypes[$index] == "pointer"){
                        arg = ObjC.Object(arg)
                    }
                send("arg$index:"+ObjC.Object(arg));"""
     
     
 
    hook_c_fun_template = """
function hook_$functionName(){
    var hook_addr =  $hookAddr
    Interceptor.attach(hook_addr, {
        onEnter(args) {
            send("call $functionName");
            $args
        },
        onLeave(retval) {
            $result
            send("leave $functionName");
        }
    });
}
 
setImmediate(hook_$functionName)
"""
 
    hook_objc_fun_template = """
function hook_${className}_$functionName(){
    // 导入 Objective-C 框架
    if (ObjC.available) {
        try {
 
            // 找到目标方法
            const targetMethod = ObjC.classes['$className']['$methodHookName'];
 
            // 挂钩方法
            Interceptor.attach(targetMethod.implementation, {
            onEnter: function(args) {
                // 在方法进入时执行的代码
                send('call  $className:$functionName')
                $args
            },
            onLeave: function(retval) {
                $result
                send('leave  $className:$functionName')
            }
            });
        }catch(err) {
            send(`[!] hook $className:$functionName Exception2: ` + err.message);
        }
    }
}
 
setImmediate(hook_${className}_$functionName)
"""
    @classmethod
    def get_fun_hook_info(self,ea):
        # 获取当前光标处的函数名称
        func_name = idaapi.get_func_name(ea)
        f_type =  1 #0:object_c 函数  1: sub_xxxx 内部函数  2: 导入函数
        func_info = {}
        if func_name:
            # 判断函数类别的方法有点糙
            # 使用正则表达式检查函数名称是否匹配Objective-C方法的命名规则
            objc_ida_name_pattern = r'^[+-]\[.*\]'
            if re.match(objc_ida_name_pattern, func_name):
                f_type = 0
            elif '__stubs' == idc.get_segm_name(ea):
                f_type = 2
             
 
            # 获取当前光标所在的函数
            f = idaapi.get_func(idaapi.get_screen_ea())
            if f:
                base = idaapi.get_imagebase()
                func_info['module_name'] = idaapi.get_root_filename()
                func_info['func_offset'= hex(f.start_ea - base)
               
                # 判断是否为导入函数
                if f.end_ea - f.start_ea <= 8:
                    f_type = 2
                 
                func_info['func_type'= f_type
     
                # 获取函数的类型信息
                func_type = idaapi.tinfo_t()
                idaapi.get_tinfo(func_type, f.start_ea)
                # 获取返回类型
                func_ret_type_name = func_type.get_rettype().__str__()
                # # 打印返回类型
                # print("Return Type: {}".format(func_ret_type_name))
                 
                # 获取参数数量
                num_args = func_type.get_nargs()
                func_info['args_types'] = []
                # 遍历获取参数类型
                for i in range(num_args):
                    arg_type_name = func_type.get_nth_arg(i).__str__()
                    func_info['args_types'].append(arg_type_name)
                    # print("Argument {}: Type: {}".format(i + 1, arg_type, ))
                if f_type == 0:
                     
                    cls_method = func_name.split(' ')
                    pre = func_name[0:2].replace('[', ' ')
                    func_info['cls_name'] = cls_method[0][2:]
                    func_info['method_hook_name'] = pre + cls_method[1][:-1]
                    func_name = ''.join(re.findall(r'\w+', func_info['method_hook_name']))[:18]
                elif f_type == 2:
                    func_info['func_offset'= None
                    if '_' == func_name[0]:
                        func_name = func_name[1:]
                     
                func_info['method_name'] = func_name
                     
                func_info['ret_type'] = func_ret_type_name
                func_info['args_count'] = num_args
                # print(func_info)
                return func_info
        return None
     
    @classmethod
    def generate_printArgs(self,argNum, isObjc = False):
        if argNum == 0:
            return "// no args"
        else:
            temp = None
            logText = ""
            if isObjc:
                temp = Template(self.objc_logTemplate)
                for i in range(2, argNum):
                    logText += temp.substitute({"index": i})
                    logText += "            "
                 
            else:
                temp = Template(self.logTemplate)
                for i in range(argNum):
                    logText += temp.substitute({"index": i})
                    logText += "            "
            return logText
 
    @classmethod
    def generate_get_hook_adrr(self, modName, offset,fun_name):
        if offset:
            return  f"Module.findBaseAddress('{modName}').add({offset})"
        else:
           return f"Module.findExportByName(null,'{fun_name}')"
 
 
    @classmethod
    def generate_c_func_script(self,funcInfo):
         
        hookAddr  =  self.generate_get_hook_adrr( funcInfo['module_name'],  funcInfo['func_offset'],  funcInfo['method_name'])
   
        argsPrint = self.generate_printArgs(funcInfo['args_count'])
 
        retPrint = "// no return"
        if funcInfo['ret_type'] != 'void':
            retPrint = f"send('{funcInfo['method_name']} ret:' + retval);"
 
        temp = Template(self.hook_c_fun_template)
        result = temp.substitute(
            
                "hookAddr":hookAddr,
                "functionName": funcInfo['method_name'],
                "args": argsPrint,
                "result": retPrint,
            }
        )
        return(result)
 
    @classmethod
    def generate_objc_func_script(self,funcInfo):
         
        argsPrint = self.generate_printArgs(funcInfo['args_count'], True)
 
        retPrint = "// no return"
        if funcInfo['ret_type'] != 'void':
            ret_temp = '''var ret = retval
                if (targetMethod.returnType == "pointer"){
                    ret = ObjC.Object(retval)
                }
                send(`$className:$functionName ret:` + ret)'''
            temp = Template(ret_temp)
            retPrint = temp.substitute(
                
                    "className": funcInfo['cls_name'],
                    "functionName": funcInfo['method_name'],
                }
            )
         
 
        temp = Template(self.hook_objc_fun_template)
        result = temp.substitute(
            
                "className": funcInfo['cls_name'],
                "methodHookName": funcInfo['method_hook_name'],
                "functionName": funcInfo['method_name'],
                "args": argsPrint,
                "result": retPrint,
            }
        )
        return (result)
 
    @classmethod
    def nop(self,*args):
        print('功能未实现')
        pass
 
    @classmethod
    def gen_frida_script(self):
        gen_fun_list = [self.generate_objc_func_script, self.generate_c_func_script, self.generate_c_func_script]
        funcInfo = self.get_fun_hook_info(idc.here())
        script = None
        if funcInfo:
            script = gen_fun_list[funcInfo['func_type']](funcInfo)
        else:
            ida_kernwin.warning('无法获取函数信息')
        return script
 
class IMenuAction(ida_kernwin.action_handler_t):
    TopDescription = 'IdaFridaIos'
    @classmethod
    def name(self):
        return  str(self.__name__)
 
    @classmethod
    def register(self):
        return idaapi.register_action(idaapi.action_desc_t(
                self.name(),
                self.description,
                self()
            ))
 
    @classmethod
    def unregister(self):
        idaapi.unregister_action(self.name())
 
    def update(self, ctx):
        if (
                ctx.widget_type == idaapi.BWN_FUNCS
                or ctx.widget_type == idaapi.BWN_PSEUDOCODE
                or ctx.widget_type == idaapi.BWN_DISASM
        ):
            idaapi.attach_action_to_popup(
                ctx.widget, None, self.name(), self.TopDescription
            )
            return idaapi.AST_ENABLE_FOR_WIDGET
        return idaapi.AST_DISABLE_FOR_WIDGET
 
    @classmethod
    def set_clipboard(self, txt):
        cb = QApplication.clipboard()
        cb.setText(txt, mode=cb.Clipboard)
        print("脚本已复制")
     
    @classmethod
    def show_script(self,script_txt):
        self.set_clipboard(script_txt)
        # 调用 AskText 函数创建文本编辑弹出窗口
        idaapi.ask_text(0, script_txt, '脚本已经生成并复制到剪切板')
 
class GenfridaHook(IMenuAction):
    description = 'IosIdaFrida--生成frida hook 脚本'
    def activate(self, ctx):
        sc = SG.gen_frida_script()
        if sc:
            self.show_script(sc)
 
class IdaFridaIos(idaapi.plugin_t):
    flags = idaapi.PLUGIN_KEEP
    wanted_name = "IosIdaFrida"
    comment = "A plug-in for automatic generate frida script for march-o file"
    wanted_hotkey = "Alt+F8"
 
    def init(self):
        GenfridaHook.register()
        return idaapi.PLUGIN_KEEP
 
    def deinit(self):
        GenfridaHook.unregister()
 
    def run(self, arg):
        print(self.comment)
       
    def term(self):
        self.deinit()
        return idaapi.PLUGIN_OK
 
def PLUGIN_ENTRY():
    return IdaFridaIos()

Github地址

IosIdaFrida


[注意]传递专业知识、拓宽行业人脉——看雪讲师团队等你加入!

最后于 2023-9-26 18:17 被xxjj678编辑 ,原因:
收藏
免费 3
支持
分享
最新回复 (6)
雪    币: 6209
活跃值: (5645)
能力值: ( LV5,RANK:65 )
在线值:
发帖
回帖
粉丝
2
感谢分享
2023-9-26 18:24
0
雪    币: 9034
活跃值: (5281)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
jgs
3
收藏学习,谢谢楼主分享。
2023-9-26 19:18
0
雪    币: 3535
活跃值: (31016)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
4
感谢分享
2023-9-27 09:49
1
雪    币: 2428
活跃值: (10698)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
5
感谢大佬分享
2023-10-6 10:49
0
雪    币: 1229
活跃值: (1765)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
6

大兄弟 有个 建议, 如果是OC 函数完全没必要,通过ida 获取函数参数的类型信息的, 因为参数都按指针算就行了,根据需要 自行 new ObjC.Object() 类型转换,并且已知函数名称  用正则匹配就能 获取出 函数的参数数量         

最后于 2023-11-16 17:29 被mb_fssslkzs编辑 ,原因:
2023-11-16 17:26
0
雪    币: 4
能力值: ( LV1,RANK:0 )
在线值:
发帖
回帖
粉丝
7
mb_fssslkzs 大兄弟&nbsp;有个&nbsp;建议,&nbsp;如果是OC&nbsp;函数完全没必要,通过ida&nbsp;获取函数参数的类型信息的,&nbsp;因 ...
这么写的原因是当时测试如果参数是基本数据类型,转object 对象frida会挂
2023-11-21 22:03
0
游客
登录 | 注册 方可回帖
返回
//