forked from CreditTone/hooker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hooker.py
433 lines (398 loc) · 15 KB
/
hooker.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
'''
Created on 2020年3月23日
@author: stephen
'''
import frida, sys
import os
import io
import re
import getopt
import traceback
import run_env
import base64
import time
import colorful
import platform
from run_env import xinitPyScript
warn = colorful.red
info = colorful.yellow
def readRadarDexfile():
f = open("radar.dex","rb")
data = f.read()
f.close()
return data
def checkRadarDex(packageName, online_script):
radarClass = "gz.radar.ClassRadar"
if online_script.exports.containsclass(radarClass):
return
data = readRadarDexfile()
radarDexPath = '/data/user/0/'+packageName+'/radar.dex';
if not online_script.exports.checkfile(radarDexPath, len(data)):
radarDexBase64 = base64.b64encode(data).decode()
#info("update radar.dex......"+str(len(radarDexBase64)))
online_script.exports.write(radarDexPath, radarDexBase64)
time.sleep(1)
online_script.exports.loaddex('gz.radar.ClassRadar', radarDexPath)
if not online_script.exports.containsclass(radarClass):
warn("injecting radar.dex failure.")
def on_message(message, data):
pass
def is_number(s):
try:
int(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
def getPidMap():
pidMap = {}
lines = os.popen("frida-ps -U").readlines();
for line in lines:
result = re.search("(\d+)\s+([a-z\d\.]+)($|:)", line.strip())
if not result:
continue
pidMap[result.group(1)] = result.group(2)
return pidMap
#target可以是pid或者packageName
def attach(target):
packageName = target
if is_number(target):#pid
packageName = getPidMap()[target]
online_session = None
online_script = None
rdev = None
remoteDriver = run_env.getRemoteDriver() #ip:port
try:
if remoteDriver:
rdev = frida.get_device_manager().add_remote_device(remoteDriver)
elif platform.system().find("Windows") != -1:
warn("推荐使用linux或mac操作系统获得更好的兼容性.")
rdev = frida.get_remote_device()
else:
rdev = frida.get_usb_device(1000)
#print(f"attach {target}")
if is_number(target):
pid = int(target)
online_session = frida.core.Session(rdev._impl.attach(pid))
else:
online_session = rdev.attach(target)
if online_session == None:
warn("attaching fail to " + target)
online_script = online_session.create_script(run_env.rpc_jscode)
online_script.on('message', on_message)
online_script.load()
checkRadarDex(packageName, online_script)
createHookingEnverment(packageName, online_script.exports.mainactivity())
except Exception:
warn(traceback.format_exc())
return online_session,online_script,packageName
def detach(online_session):
if online_session != None:
online_session.detach()
def existsClass(target,className):
online_session = None
online_script = None
try:
online_session,online_script,_ = attach(target);
info(online_script.exports.containsclass(className))
except Exception:
warn(traceback.format_exc())
finally:
detach(online_session)
def findclasses(target, classRegex):
online_session = None
online_script = None
try:
online_session,online_script,_ = attach(target);
info(online_script.exports.findclasses(classRegex));
except Exception:
warn(traceback.format_exc())
finally:
detach(online_session)
def findclasses2(target, className):
online_session = None
online_script = None
try:
online_session,online_script,_ = attach(target);
info(online_script.exports.findclasses2(className));
except Exception:
warn(traceback.format_exc())
finally:
detach(online_session)
def createFile(filename, text):
file = None
try:
file = open(filename, mode='w+')
file.write(text)
except Exception:
warn(traceback.format_exc())
finally:
if file != None:
file.close()
def onlyCheckHookingEnverment(target):
online_session = None
try:
online_session,_,_ = attach(target);
except Exception:
print(traceback.format_exc())
finally:
detach(online_session)
def createHookingEnverment(packageName, mainActivity):
if not os.path.exists(packageName):
os.makedirs(packageName)
os.makedirs(packageName+"/xinit")
shellPrefix = "#!/bin/bash\nHOOKER_DRIVER=$(cat ../.hooker_driver)\n"
logHooking = shellPrefix + "echo \"hooking $1\" > log\ndate | tee -ai log\n" + "frida $HOOKER_DRIVER -l $1 " + packageName + " | tee -ai log"
attach_shell = shellPrefix + "frida $HOOKER_DRIVER -l $1 " + packageName
spawn_shell = f"{shellPrefix}\nfrida $HOOKER_DRIVER --no-pause -f {packageName} -l $1"
xinitPyScript = run_env.xinitPyScript + "xinitDeploy('"+packageName+"')"
spiderPyScript = run_env.spiderPyScript.replace("{appPackageName}", packageName).replace("{mainActivity}", mainActivity)
disableSslPinningPyScript = run_env.disableSslPinningPyScript.replace("{appPackageName}", packageName)
createFile(packageName+"/hooking", logHooking)
createFile(packageName+"/attach", attach_shell)
createFile(packageName+"/spawn", spawn_shell)
createFile(packageName+"/xinitdeploy", xinitPyScript)
createFile(packageName+"/disable_sslpinning", disableSslPinningPyScript)
createFile(packageName+"/spider.py", spiderPyScript)
createFile(packageName + "/kill", shellPrefix + "frida-kill $HOOKER_DRIVER "+packageName)
createFile(packageName+"/objection", shellPrefix + "objection -d -g "+packageName+" explore")
os.popen('chmod 777 ' + packageName +'/hooking').readlines()
os.popen('chmod 777 ' + packageName +'/attach').readlines()
os.popen('chmod 777 ' + packageName +'/xinitdeploy').readlines()
os.popen('chmod 777 ' + packageName +'/disable_sslpinning').readlines()
os.popen('chmod 777 ' + packageName +'/kill').readlines()
os.popen('chmod 777 ' + packageName +'/objection').readlines()
os.popen('chmod 777 ' + packageName +'/spawn').readlines()
createFile(packageName + "/ssl_log.js", run_env.ssl_log_jscode)
createFile(packageName + "/url.js", run_env.url_jscode)
createFile(packageName + "/edit_text.js", run_env.edit_text_jscode)
createFile(packageName + "/text_view.js", run_env.text_view_jscode)
createFile(packageName + "/click.js", run_env.click_jscode)
createFile(packageName + "/hook_RN.js", run_env.hook_RN_jscode)
createFile(packageName + "/keystore_dump.js", run_env.keystore_dump_jscode)
createFile(packageName + "/dump_dex.js", run_env.dump_dex_jscode)
createFile(packageName + "/android_ui.js", run_env.android_ui_jscode.replace("com.smile.gifmaker", packageName))
createFile(packageName + "/activity_events.js", run_env.activity_events_jscode.replace("com.smile.gifmaker", packageName))
createFile(packageName + "/object_store.js", run_env.object_store_jscode.replace("com.smile.gifmaker", packageName))
createFile(packageName + "/just_trust_me.js", run_env.just_trust_me_jscode.replace("com.smile.gifmaker", packageName))
createFile(packageName + "/just_trust_me_okhttp_hook_finder.js", run_env.just_trust_me_okhttp_hook_finder_jscode.replace("com.smile.gifmaker", packageName))
def hookJs(target, hookCmdArg, savePath = None):
online_session = None
online_script = None
packageName = None
try:
ganaretoionJscode = ""
online_session,online_script,packageName = attach(target);
appversion = online_script.exports.appversion();
classes = hookCmdArg.split(",")
for classN in classes:
spaceSpatrater = classN.find(":")
className = classN
toSpace = "*"
if spaceSpatrater > 0:
className = classN[:spaceSpatrater]
toSpace = classN[spaceSpatrater+1:]
jscode = online_script.exports.hookjs(className, toSpace);
ganaretoionJscode += ("\n//"+classN+"\n")
ganaretoionJscode += jscode
if savePath == None:
defaultFilename = hookCmdArg.replace(".", "_").replace(":", "_").replace("$", "_").replace("__", "_") + ".js"
savePath = packageName+"/"+defaultFilename;
else:
savePath = packageName+"/"+savePath;
if len(ganaretoionJscode):
ganaretoionJscode = run_env.loadxinit_dexfile_template_jscode.replace("{PACKAGENAME}", packageName) + "\n" + ganaretoionJscode
warpExtraInfo = "//crack by " + packageName + " " + appversion + "\n"
warpExtraInfo += "//"+hookCmdArg + "\n"
warpExtraInfo += run_env.base_jscode
warpExtraInfo += ganaretoionJscode
createFile(savePath, warpExtraInfo)
info("Hooking js code have generated. Path is " + savePath+".")
else:
warn("Not found any classes by pattern "+hookCmdArg+".")
except Exception:
warn(traceback.format_exc())
finally:
detach(online_session)
def hookStr(target, keyword):
online_session = None
packageName = None
try:
online_session,_,packageName = attach(target);
jscode = io.open('./js/string_hooker.js','r',encoding= 'utf8').read()
jscode = jscode.replace("惊雷", keyword)
savePath = packageName+"/str_"+keyword+".js";
createFile(savePath, jscode)
info("Hooking js code have generated. Path is " + savePath+".")
except Exception:
print(traceback.format_exc())
finally:
detach(online_session)
def hookParma(target, keyword):
online_session = None
packageName = None
try:
online_session,_,packageName = attach(target);
jscode = io.open('./js/param_hook.js','r',encoding= 'utf8').read()
jscode = jscode.replace("NStokensig", keyword)
savePath = packageName+"/param_"+keyword+".js";
createFile(savePath, jscode)
info("Hooking js code have generated. Path is " + savePath+".")
except Exception:
print(traceback.format_exc())
finally:
detach(online_session)
def printActivitys(target):
online_session = None
online_script = None
try:
online_session,online_script,_ = attach(target);
info(online_script.exports.activitys())
except Exception:
print(traceback.format_exc())
finally:
detach(online_session)
def printServices(target):
online_session = None
online_script = None
try:
online_session,online_script,_ = attach(target);
info(online_script.exports.services())
except Exception:
print(traceback.format_exc())
finally:
detach(online_session)
def printObject(target, objectId):
online_session = None
online_script = None
try:
online_session,online_script,_ = attach(target);
info(online_script.exports.objectinfo(objectId))
except Exception:
print(traceback.format_exc())
finally:
detach(online_session)
def object2Explain(target, objectId):
online_session = None
online_script = None
try:
online_session,online_script,_ = attach(target);
info(online_script.exports.objecttoexplain(objectId))
except Exception:
print(traceback.format_exc())
finally:
detach(online_session)
def printView(target, viewId):
online_session = None
online_script = None
try:
online_session,online_script,_ = attach(target);
report = online_script.exports.viewinfo(viewId)
info(report);
except Exception:
print(traceback.format_exc())
finally:
detach(online_session)
def printModuleName(target, moduleName):
online_session = None
online_script = None
try:
online_session,online_script,_ = attach(target);
info(online_script.exports.so(moduleName))
except Exception:
print(traceback.format_exc())
finally:
detach(online_session)
if __name__ == '__main__':
try:
opts, args = getopt.getopt(sys.argv[1:], "hp:x:a:b:c:d:v:s:t:l:e:j:k:l:g:o:m:",[])
except getopt.GetoptError:
sys.exit(2);
#这个packageName可以是进程名也可以是进程号
packageName = None
e = None
findclassesClassRegex = None
findclasses2ClassName = None
JhookLine = None
KhookLine = None
LhookLine = None
genarateEnv = False
out = None
activity = False
service = False
objectId = None
object2ExplainObjectId = None
viewId = None
moduleName = False
#print(opts)
for op, value in opts:
if op in ("-p", "--package"):
packageName = value
elif op in ("-s", "--scan"):
findclassesClassRegex = value
elif op in ("-t"):
findclasses2ClassName = value
elif op in ("-e", "--exist"):
e = value
elif op in ("-j", "--hookjs"):
JhookLine = value
elif op in ("-k", "--hookstr"):
KhookLine = value
elif op in ("-l"):
LhookLine = value
elif op in ("-g"):
genarateEnv = True;
elif op in ("-o", "--out"):
out = value;
elif op in ("-a"):
activity = True;
elif op in ("-b"):
service = True;
elif op in ("-c"):
objectId = value;
elif op in ("-d"):
object2ExplainObjectId = value;
elif op in ("-v"):
viewId = value;
elif op in ("-m"):
moduleName = value;
if packageName == None:
warn("packageName is none")
sys.exit(2);
#初始化应用目录
if genarateEnv and packageName:
run_env.init(packageName)
onlyCheckHookingEnverment(packageName)
if e != None:
existsClass(packageName, e)
elif findclassesClassRegex:
findclasses(packageName, findclassesClassRegex)
elif findclasses2ClassName:
findclasses2(packageName, findclasses2ClassName)
elif JhookLine:
hookJs(packageName, JhookLine, out)
elif KhookLine != None:
hookStr(packageName, KhookLine)
elif LhookLine != None:
hookParma(packageName, LhookLine)
elif activity:
printActivitys(packageName)
elif service:
printServices(packageName)
elif objectId:
printObject(packageName, objectId)
elif object2ExplainObjectId:
object2Explain(packageName, object2ExplainObjectId)
elif viewId:
printView(packageName, viewId)
elif moduleName:
printModuleName(packageName, moduleName)
elif not genarateEnv:
warn(opts)
sys.exit(2);