-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathIDAFrida.py
613 lines (507 loc) · 20.2 KB
/
IDAFrida.py
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
import ida_kernwin
import ida_name
import idaapi
###################
# from: https://github.com/igogo-x86/HexRaysPyTools
class ActionManager(object):
def __init__(self):
self.__actions = []
def register(self, action):
self.__actions.append(action)
idaapi.register_action(
idaapi.action_desc_t(action.name, action.description, action, action.hotkey)
)
def initialize(self):
pass
def finalize(self):
for action in self.__actions:
idaapi.unregister_action(action.name)
action_manager = ActionManager()
class Action(idaapi.action_handler_t):
"""
Convenience wrapper with name property allowing to be registered in IDA using ActionManager
"""
description = None
hotkey = None
def __init__(self):
super(Action, self).__init__()
@property
def name(self):
return "FridaIDA:" + type(self).__name__
def activate(self, ctx):
# type: (idaapi.action_activation_ctx_t) -> None
raise NotImplementedError
def update(self, ctx):
# type: (idaapi.action_activation_ctx_t) -> None
raise NotImplementedError
############################################################################
import ida_funcs
import idc
import json
import os
from PyQt5 import QtCore
from PyQt5.Qt import QApplication
from PyQt5.QtWidgets import QDialog, QHBoxLayout, QVBoxLayout, QTextEdit, QLineEdit, QDialogButtonBox, QPushButton
# [offset] => offset of target function in hex value format.
# [funcname] => function name
# [filename] => input file name of IDA. e.g. xxx.so / xxx.exe
default_func_hook_template = """
//[filename]->[funcname]
(function () {
// @ts-ignore
function waitForLoadLibraryNative(libName,callback){
// @ts-ignore
Interceptor.attach(Module.findExportByName(null, "dlopen"), {
onEnter: function(args) {
var pathptr = args[0];
if (pathptr !== undefined && pathptr != null) {
// @ts-ignore
var path = ptr(pathptr).readCString();
// @ts-ignore
if (path.indexOf(libName) >= 0) {
this.findedLib = true;
}
}
},
onLeave: function(retval) {
if (this.findedLib) {
if(callback){
callback();
callback=null;
}
}
}
})
// @ts-ignore
Interceptor.attach(Module.findExportByName(null, "android_dlopen_ext"), {
onEnter: function(args) {
var pathptr = args[0];
if (pathptr !== undefined && pathptr != null) {
// @ts-ignore
var path = ptr(pathptr).readCString();
// @ts-ignore
if (path.indexOf(libName) >= 0) {
this.findedLib = true;
}
}
},
onLeave: function(retval) {
if (this.findedLib) {
if(callback){
callback();
callback=null;
}
}
}
});
}
// @ts-ignore
function print_arg(addr) {
try {
return ""+addr+"(pointer) memory dump:\\n"+hexdump(addr) + "\\n";
} catch (e) {
return addr + "\\n";
}
}
// @ts-ignore
function hook_native_addr(funcPtr, paramsNum) {
var module = Process.findModuleByAddress(funcPtr);
if(module==null){
module=Process.findModuleByName("[filename]")
}
try {
Interceptor.attach(funcPtr, {
onEnter: function (args) {
this.logs = "";
this.params = [];
// @ts-ignore
this.logs=this.logs.concat("So: " + module.name +"["+module.base+"]" + " Method: [funcname] offset: " + ptr(funcPtr).sub(module.base) + "\\n");
for (let i = 0; i < paramsNum; i++) {
this.params.push(args[i]);
this.logs=this.logs.concat("this.args" + i + " onEnter: " + print_arg(args[i]));
}
}, onLeave: function (retval) {
for (let i = 0; i < paramsNum; i++) {
this.logs=this.logs.concat("this.args" + i + " onLeave: " + print_arg(this.params[i]));
}
this.logs=this.logs.concat("retval onLeave: " + print_arg(retval) + "\\n");
console.log(this.logs);
}
});
} catch (e) {
console.log(e);
}
}
let module=Module.findBaseAddress("[filename]");
if(module==null){
waitForLoadLibraryNative("[filename]",function(){
// @ts-ignore
hook_native_addr(Module.findBaseAddress("[filename]").add([offset]), [nargs]);
});
}else{
// @ts-ignore
hook_native_addr(Module.findBaseAddress("[filename]").add([offset]), [nargs]);
}
})();
"""
default_address_hook_template = """
//[filename]->[address]: [registers]
(function () {
// @ts-ignore
function waitForLoadLibraryNative(libName,callback){
// @ts-ignore
Interceptor.attach(Module.findExportByName(null, "dlopen"), {
onEnter: function(args) {
var pathptr = args[0];
if (pathptr !== undefined && pathptr != null) {
// @ts-ignore
var path = ptr(pathptr).readCString();
// @ts-ignore
if (path.indexOf(libName) >= 0) {
this.findedLib = true;
}
}
},
onLeave: function(retval) {
if (this.findedLib) {
if(callback){
callback();
callback=null;
}
}
}
})
// @ts-ignore
Interceptor.attach(Module.findExportByName(null, "android_dlopen_ext"), {
onEnter: function(args) {
var pathptr = args[0];
if (pathptr !== undefined && pathptr != null) {
// @ts-ignore
var path = ptr(pathptr).readCString();
// @ts-ignore
if (path.indexOf(libName) >= 0) {
this.findedLib = true;
}
}
},
onLeave: function(retval) {
if (this.findedLib) {
if(callback){
callback();
callback=null;
}
}
}
});
}
// @ts-ignore
function print_arg(addr) {
try {
var module = Process.findRangeByAddress(addr);
if (module != null) return ""+addr+"(pointer) memory dump:\\n"+hexdump(addr) + "\\n";
return ptr(addr) + "\\n";
} catch (e) {
return addr + "\\n";
}
}
// @ts-ignore
function hook_native_addr(address, registers) {
var module = Process.findModuleByAddress(address);
try {
Interceptor.attach(address, {
onEnter: function (args) {
this.logs = "";
// @ts-ignore
this.logs=this.logs.concat("So: " + module.name +"["+module.base+"]" + " Address: " + ptr(address).sub(module.base) + " [registers] " + "\\n");
if(registers!=null&®isters.trim()!==""){
for (let register of registers.trim().split(" ")) {
if(register==null||register.trim()=="")continue;
// @ts-ignore
this.logs=this.logs.concat("this.context." + register + " onEnter: " + print_arg(this.context[register.trim()]));
}
}
console.log(this.logs);
}
});
} catch (e) {
console.log(e);
}
}
let module=Module.findBaseAddress("[filename]");
if(module==null){
waitForLoadLibraryNative("[filename]",function(){
// @ts-ignore
hook_native_addr(Module.findBaseAddress("[filename]").add([address]), "[registers]");
});
}else{
// @ts-ignore
hook_native_addr(Module.findBaseAddress("[filename]").add([address]), "[registers]");
}
})();
"""
class Configuration:
def __init__(self) -> None:
self.frida_cmd = """frida -U --attach-name="com.example.app" -l gen.js --no-pause"""
self.template_func = default_func_hook_template
self.template_address = default_address_hook_template
if os.path.exists("IDAFrida.json"):
self.load()
def set_frida_cmd(self, s):
self.frida_cmd = s
self.store()
def set_template_func(self, s):
self.template_func = s
self.store()
def set_template_address(self, s):
self.template_address = s
self.store()
def reset(self):
self.__init__()
def store(self):
try:
data = {"frida_cmd": self.frida_cmd, "template_func": self.template_func,
"template_address": self.template_address}
open("IDAFrida.json", "w").write(json.dumps(data))
except Exception as e:
print(e)
def load(self):
try:
data = json.loads(open("IDAFrida.json", "r").read())
self.frida_cmd = data["frida_cmd"]
self.template_func = data["template_func"]
self.template_address = data["template_address"]
except Exception as e:
print(e)
global_config = Configuration()
class FuncConfigurationUI(QDialog):
def __init__(self, conf: Configuration) -> None:
super(FuncConfigurationUI, self).__init__()
self.conf = conf
self.setFixedWidth(700)
self.setFixedHeight(700)
self.edit_template = QTextEdit()
self.edit_template.setPlainText(self.conf.template_func)
layout = QVBoxLayout()
layout.addWidget(self.edit_template)
btn_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
btn_box.setCenterButtons(True)
btn_box.accepted.connect(self.accepted)
btn_box.rejected.connect(self.rejected)
layout.addWidget(btn_box)
self.setLayout(layout)
def rejected(self):
self.close()
def accepted(self):
self.conf.set_template_address(self.edit_template.toPlainText())
self.conf.store()
self.close()
class AddressConfigurationUI(QDialog):
def __init__(self, conf: Configuration) -> None:
super(AddressConfigurationUI, self).__init__()
self.setFixedWidth(700)
self.setFixedHeight(700)
self.conf = conf
self.edit_template = QTextEdit()
self.edit_template.setPlainText(self.conf.template_address)
layout = QVBoxLayout()
layout.addWidget(self.edit_template)
btn_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
btn_box.setCenterButtons(True)
btn_box.accepted.connect(self.accepted)
btn_box.rejected.connect(self.rejected)
layout.addWidget(btn_box)
self.setLayout(layout)
def rejected(self):
self.close()
def accepted(self):
self.conf.set_template_address(self.edit_template.toPlainText())
self.conf.store()
self.close()
class ScriptGenerator:
def __init__(self, configuration: Configuration) -> None:
self.conf = configuration
self.imagebase = idaapi.get_imagebase()
@staticmethod
def get_idb_filename():
return os.path.basename(idaapi.get_input_file_path())
@staticmethod
def get_idb_path():
return os.path.dirname(idaapi.get_input_file_path())
def get_function_name(self,
ea): # https://hex-rays.com/products/ida/support/ida74_idapython_no_bc695_porting_guide.shtml
"""
Get the real function name
"""
# Try to demangle
function_name = idc.demangle_name(idc.get_func_name(ea), idc.get_inf_attr(idc.INF_SHORT_DN))
# if function_name:
# function_name = function_name.split("(")[0]
# Function name is not mangled
if not function_name:
function_name = idc.get_func_name(ea)
if not function_name:
function_name = idc.get_name(ea, ida_name.GN_VISIBLE)
# If we still have no function name, make one up. Format is - 'UNKN_FNC_4120000'
if not function_name:
function_name = "UNKN_FNC_%s" % hex(ea)
return function_name
def generate_func_stub(self, repdata: dict):
s = self.conf.template_func
for key, v in repdata.items():
s = s.replace("[%s]" % key, v)
return s
def generate_address_stub(self, repdata: dict):
s = self.conf.template_address
for key, v in repdata.items():
s = s.replace("[%s]" % key, v)
return s
def generate_for_funcs(self, func_addr_list) -> str:
stubs = []
for func_addr in func_addr_list:
dec_func = idaapi.decompile(func_addr)
repdata = {
"filename": self.get_idb_filename(),
"funcname": self.get_function_name(func_addr),
"offset": hex(func_addr - self.imagebase),
"nargs": hex(dec_func.type.get_nargs())
}
stubs.append(self.generate_func_stub(repdata))
return "\n".join(stubs)
def generate_for_address(self, address, registers) -> str:
repdata = {
"filename": self.get_idb_filename(),
"address": hex(address - self.imagebase),
"registers": registers
}
return self.generate_address_stub(repdata)
def generate_for_funcs_to_file(self, func_addr_list, filename) -> bool:
data = self.generate_for_funcs(func_addr_list)
try:
open(filename, "w").write(data)
print("The generated Frida script has been exported to the file: ", filename)
except Exception as e:
print(e)
return False
try:
QApplication.clipboard().setText(data)
print("The generated Frida script has been copied to the clipboard!")
except Exception as e:
print(e)
return False
return True
def generate_for_address_to_file(self, address, registers, filename) -> bool:
data = self.generate_for_address(address, registers)
try:
open(filename, "w").write(data)
print("The generated Frida script has been exported to the file: ", filename)
except Exception as e:
print(e)
return False
try:
QApplication.clipboard().setText(data)
print("The generated Frida script has been copied to the clipboard!")
except Exception as e:
print(e)
return False
return True
class Frida:
def __init__(self, conf: Configuration) -> None:
self.conf = conf
class IDAFridaMenuAction(Action):
TopDescription = "IDAFrida"
def __init__(self):
super(IDAFridaMenuAction, self).__init__()
def activate(self, ctx) -> None:
raise NotImplemented
def update(self, ctx) -> None:
if ctx.form_type == idaapi.BWN_FUNCS or ctx.form_type == idaapi.BWN_PSEUDOCODE or ctx.form_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
class InputRegistersUI(QDialog):
def __init__(self) -> None:
super(InputRegistersUI, self).__init__()
self.setWindowTitle("Please enter the registers separated by spaces")
self.setFixedWidth(600)
self.edit_template = QLineEdit()
self.edit_template.setClearButtonEnabled(True)
self.edit_template.setPlaceholderText("eg: x0 x1 x2 x3....")
layout = QVBoxLayout()
btn_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
btn_box.setCenterButtons(True)
btn_box.accepted.connect(self.accepted)
btn_box.rejected.connect(self.rejected)
layout.addWidget(self.edit_template)
layout.addWidget(btn_box)
self.setLayout(layout)
def rejected(self):
self.close()
def accepted(self):
gen = ScriptGenerator(global_config)
idb_path = os.path.dirname(idaapi.get_input_file_path())
out_file = os.path.join(idb_path, "IDAhook.js")
text=self.edit_template.text()
text=text.strip()
gen.generate_for_address_to_file(idaapi.get_screen_ea(),text, out_file)
self.close()
class GenerateFridaHookScript(IDAFridaMenuAction):
description = "Generate Frida Script on current func"
def __init__(self):
super(GenerateFridaHookScript, self).__init__()
def activate(self, ctx):
gen = ScriptGenerator(global_config)
idb_path = os.path.dirname(idaapi.get_input_file_path())
out_file = os.path.join(idb_path, "IDAhook.js")
if ctx.form_type == idaapi.BWN_FUNCS:
selected = [idaapi.getn_func(idx).start_ea for idx in
ctx.chooser_selection] # from "idaapi.getn_func(idx - 1)" to "idaapi.getn_func(idx)"
else:
selected = [idaapi.get_func(idaapi.get_screen_ea()).start_ea]
gen.generate_for_funcs_to_file(selected, out_file)
class GenerateFridaHookScriptOnCurrentAddress(IDAFridaMenuAction):
description = "Generate Frida Script on current address"
def __init__(self):
super(GenerateFridaHookScriptOnCurrentAddress, self).__init__()
def activate(self, ctx):
ui = InputRegistersUI()
ui.show()
ui.exec_()
def update(self, ctx) -> None:
if ctx.form_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
class RunGeneratedScript(IDAFridaMenuAction):
description = "Run Generated Script"
def __init__(self):
super(RunGeneratedScript, self).__init__()
def activate(self, ctx):
print("template")
class ViewFridaTemplateFunc(IDAFridaMenuAction):
description = "View Frida func hook Template"
def __init__(self):
super(ViewFridaTemplateFunc, self).__init__()
def activate(self, ctx):
ui = FuncConfigurationUI(global_config)
ui.show()
ui.exec_()
class ViewFridaTemplateAddress(IDAFridaMenuAction):
description = "View Frida address hook Template"
def __init__(self):
super(ViewFridaTemplateAddress, self).__init__()
def activate(self, ctx):
ui = AddressConfigurationUI(global_config)
ui.show()
ui.exec_()
class SetFridaRunCommand(IDAFridaMenuAction):
description = "Set Frida Command"
def __init__(self):
super(SetFridaRunCommand, self).__init__()
def activate(self, ctx):
print("template")
action_manager.register(GenerateFridaHookScript())
action_manager.register(GenerateFridaHookScriptOnCurrentAddress())
# action_manager.register(RunGeneratedScript())
action_manager.register(ViewFridaTemplateFunc())
action_manager.register(ViewFridaTemplateAddress())
# action_manager.register(SetFridaRunCommand())