-
Notifications
You must be signed in to change notification settings - Fork 20
/
Jeb4frida.py
203 lines (165 loc) · 8.62 KB
/
Jeb4frida.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
# -*- coding: utf-8 -*-
#?description=Helper JEB script to generate Frida hooks
#?shortcut=
from com.pnfsoftware.jeb.client.api import IScript, IGraphicalClientContext
from com.pnfsoftware.jeb.core import Artifact
from com.pnfsoftware.jeb.core.input import FileInput
from com.pnfsoftware.jeb.core.units.code.android import IDexUnit, IApkUnit
from com.pnfsoftware.jeb.core.units.code.android.dex import DexPoolType
from com.pnfsoftware.jeb.core.units.code.java import IJavaSourceUnit, IJavaMethod
from com.pnfsoftware.jeb.core.units import INativeCodeUnit
from com.pnfsoftware.jeb.core.units.code.asm.decompiler import INativeSourceUnit
from com.pnfsoftware.jeb.core.units import UnitUtil
from java.awt.datatransfer import StringSelection
from java.awt.datatransfer import Clipboard
from java.awt import Toolkit
from java.io import File
import re
"""
Helper JEB script to generate Frida hooks
"""
class Jeb4frida(IScript):
def run(self, ctx):
print(u"🔥 Jeb4frida...")
# Require script to be run in JEB GUI
if not isinstance(ctx, IGraphicalClientContext):
print(u"❌ This script must be run within a graphical client.")
return
view = ctx.getFocusedView()
unit = view.getUnit()
if isinstance(unit, IJavaSourceUnit) or isinstance(unit, IDexUnit):
print(u"IJavaSourceUnit / IDexUnit detected")
# Both IJavaSourceUnit and IDexUnit have getDecompiler()
dexdec = unit.getDecompiler()
self.handle_java_dex(ctx, dexdec)
return
if isinstance(unit, INativeSourceUnit) or isinstance(unit, INativeCodeUnit):
print(u"INativeSourceUnit / INativeCodeUnit detected...")
self.handle_native(ctx, unit)
return
return
def handle_java_dex(self, ctx, dexdec):
f = ctx.getFocusedFragment()
assert f, 'Need a focused fragment'
# a DEX-style address: TYPENAME->METHODNAME(PARAMTYPES)RETTYPE+OFFSET
dex_addr = f.getActiveAddress()
# strip the offset if present
dex_addr = dex_addr.split('+')[0]
# we won't be looping through inner classes, for now...
class_dex_addr = dex_addr.split('->')[0]
java_class = dexdec.getClass(class_dex_addr, True) # True to decompile if not done yet
if ";->" in dex_addr: # single method
java_methods = [dexdec.getMethod(dex_addr, True)] # True to decompile if not done yet
else: # all methods
java_methods = java_class.getMethods()
print(u"🔥 Here\'s a fresh Frida hook...")
print('-' * 100)
print(self.gen_how_to(ctx))
print(self.gen_java_hook(java_class, java_methods))
def to_canonical_name(self, dalvik_name):
dalvik_name = dalvik_name.replace('/', '.')
type_name = {
'C': "char",
'I': "int",
'B': "byte",
'Z': "boolean",
'F': "float",
'D': "double",
'S': "short",
'J': "long",
'V': "void",
'L': dalvik_name[1:-1],
'[': dalvik_name
}
return type_name[dalvik_name[0]]
def gen_java_hook(self, java_class, java_methods):
class_name = java_class.getType().toString()
class_name_var = class_name.split('.')[-1]
frida_hook = u" var {} = Java.use('{}');\n".format(class_name_var, class_name)
for idx, java_method in enumerate(java_methods):
method_name = java_method.getName().strip('<>')
method_name_var = u"{}_{}_{:x}".format(class_name_var, method_name, idx)
method_name = '$init' if method_name == "init" else method_name
if method_name == "clinit":
print(u"//❌ Encountered <clinit>, skipping...\n//\tPS: Send PR if you know how to fix this.")
continue
method_parameters = java_method.getParameters()
if len(method_parameters) > 0 and method_parameters[0].getIdentifier().toString() == "this": # pop "this"
method_parameters = method_parameters[1:]
method_arguments = [m.getIdentifier().toString() for m in method_parameters]
method_overload_parameters = []
for p in method_parameters:
method_overload_parameters.append(u'"{}"'.format(self.to_canonical_name(p.getType().getSignature())))
frida_hook += u"""
var {method_name_var} = {class_name_var}.{method_name}.overload({method_overload});
{method_name_var}.implementation = function({method_arguments}) {{
console.log(`[+] Hooked {class_name}.{method_name}({method_arguments})`);
return {method_name_var}.call(this{hack}{method_arguments});
}};""".format(
class_name_var=class_name_var,
class_name=class_name,
method_name_var=method_name_var,
method_name=method_name,
method_overload=', '.join(method_overload_parameters),
method_arguments=', '.join(method_arguments),
hack=', ' if len(method_arguments) > 0 else '')
return u"Java.perform(function() {{\n{}\n}});".format(frida_hook)
def handle_native(self, ctx, unit):
f = ctx.getFocusedFragment()
assert f, 'Need a focused fragment'
active_address = f.getActiveAddress()
assert active_address, 'Put cursor somewhere else...'
active_address = active_address.split('+')[0] # strip offset
decompiler = unit.getDecompiler()
code_unit = decompiler.getCodeUnit() # ICodeUnit
elf = code_unit.getCodeObjectContainer() # ICodeObjectUnit
lib_name = elf.getName()
code_method = code_unit.getMethod(active_address) # ICodeMethod -> INativeMethodItem
method_real_name = code_method.getName(False) # we need the real name instead of renamed one
func_offset = hex(code_method.getMemoryAddress() - code_unit.getVirtualImageBase()).rstrip("L")
func_retval_type = code_method.getReturnType().getName(True) if code_method.getReturnType() is not None else "undefined"
func_parameter_names = code_method.getParameterNames()
func_parameter_types = code_method.getParameterTypes()
func_args = u""
for idx, func_parameter_name in enumerate(func_parameter_names):
func_args += u"this.{} = args[{}]; // {}\n ".format(func_parameter_name, idx, func_parameter_types[idx].getName())
if method_real_name.startswith("Java_"):
print("Java native method detected...")
native_pointer = u"Module.getExportByName('{lib_name}', '{func_name}')".format(lib_name=lib_name, func_name=method_real_name)
elif method_real_name.startswith(u"→"):
print("Trampoline detected...")
native_pointer = u"Module.getExportByName('{lib_name}', '{func_name}')".format(lib_name=lib_name, func_name=method_real_name.lstrip(u"→"))
elif re.match(r'sub_[A-F0-9]+', method_real_name):
print("Need to calculate offset...")
native_pointer = u"Module.findBaseAddress('{lib_name}').add({func_offset})".format(lib_name=lib_name, func_offset=func_offset)
else:
print("Everything else...")
native_pointer = u"Module.getExportByName('{lib_name}', '{func_name}')".format(lib_name=lib_name, func_name=method_real_name)
frida_hook = u"""
var interval = setInterval(function() {{
if (Module.findBaseAddress("{lib_name}")) {{
clearInterval(interval);
Interceptor.attach({native_pointer}, {{ // offset {func_offset}
onEnter(args) {{
{func_args}
}}, onLeave(retval) {{ // return type: {func_retval_type}
console.log(`[+] Hooked {lib_name}[{func_name}]({func_params}) -> ${{retval}}`);
// retval.replace(0x0)
}}
}});
return;
}}
}}, 0);""".format(lib_name=lib_name, func_name=method_real_name, native_pointer=native_pointer,
func_offset=func_offset, func_retval_type=func_retval_type, func_args=func_args,
func_params=', '.join(func_parameter_names))
print(u"🔥 Here\'s a fresh Frida hook...")
print('-' * 100)
print(self.gen_how_to(ctx))
print(frida_hook)
def gen_how_to(self, ctx):
project = ctx.getMainProject()
assert project, "Need a project..."
# Find the first IApkUnit in the project
apk = project.findUnit(IApkUnit)
assert apk, "Need an apk unit"
return u"// Usage: frida -U -f {} -l hook.js --no-pause".format(apk.getPackageName())