forked from CreditTone/hooker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhooker.py
More file actions
executable file
·1514 lines (1416 loc) · 57.6 KB
/
hooker.py
File metadata and controls
executable file
·1514 lines (1416 loc) · 57.6 KB
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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
'''
Created on 2020年3月23日
@author: stephen
'''
default_frida_server_arm = "frida-server-16.7.19-android-arm"
default_frida_server_arm64 = "frida-server-16.7.19-android-arm64"
import frida, sys
import os
import io
import re
import stat
import pwd
import grp
import time
import json
import getopt
import traceback
import base64
import time
import platform
import threading
import adbutils
import hashlib
import shutil
import textwrap
import zipfile
import queue
import sqlite3
import itertools
import jsbeautifier
import subprocess
import filecmp
from git import Repo
from datetime import datetime
from collections import Counter
from androguard.core.bytecodes import apk
from androguard.core.bytecodes import dvm
from androguard.core.analysis.analysis import MethodAnalysis
from androguard.core import androconf
from prompt_toolkit import PromptSession
from prompt_toolkit.completion import Completer, Completion
from prompt_toolkit.completion import WordCompleter
from prompt_toolkit.completion import NestedCompleter
from prompt_toolkit.patch_stdout import patch_stdout
from wcwidth import wcswidth
def withColor(string, fg, bg=49):
print("\33[0m\33[%d;%dm%s\33[0m" % (fg, bg, string))
#front color
Red = 1
Green = 2
Yellow = 3
Blue = 4
Magenta = 5
Cyan = 6
White = 7
def red(string):
return withColor(string, Red+30) # Red
def green(string):
return withColor(string, Green+30) # Green
def yellow(string):
return withColor(string, Yellow+30) # Yellow
def blue(string):
return withColor(string, Blue+30) # Blue
def magenta(string):
return withColor(string, Magenta+30) # Magenta
def cyan(string):
return withColor(string, Cyan+30) # Cyan
def white(string):
return withColor(string, White+30) # White
def print_js_file(filenames :list):
if not filenames:
return
GREEN = "\033[32m"
RESET = "\033[0m"
columns, _ = shutil.get_terminal_size()
# 计算每个字段宽度
max_len = max(len(name) for name in filenames) + 2
items_per_line = max(1, columns // max_len)
# 输出带颜色的文件名
for i in range(0, len(filenames), items_per_line):
line = "".join(f"{GREEN}{name.ljust(max_len)}{RESET}" for name in filenames[i:i + items_per_line])
print(line)
def read_js_resource(filename):
return io.open('./js/' + filename,'r',encoding= 'utf8').read()
cmd_session = None
warn = red
info = yellow
adb_device = None
def _init_adb_device():
global adb_device
adb_device = adbutils.adb.device()
_init_adb_device()
def run_su_command(cmd, not_read=False):
#print("run_su_command:", cmd)
conn = adb_device.shell(["su", "-c", cmd], stream=True)
try:
if not_read:
time.sleep(1)
return
output = conn.read_until_close()
return output.strip()
finally:
try:
conn.close()
except Exception as e:
pass
#初始化frida运行环境
def is_frida_working_via_attach(target_package="com.android.systemui"):
try:
__device = frida.get_usb_device(timeout=3) # or use add_remote_device(ip)
pid = __device.get_process(target_package).pid # 先确认包是否存在
_session = __device.attach(pid)
_session.detach()
return True
except frida.ServerNotRunningError:
return False
except frida.ProcessNotFoundError:
#info("⚠️ 找不到进程,说明包名可能错误,但 frida 正常")
return True # 仍然说明 frida-server 已连通
except frida.TimedOutError:
#info("❌ 连接超时,frida-server 可能未运行或设备未连接")
return False
except Exception as e:
#print("其他异常:", e)
return False
def check_remote_file_exists(path):
result = adb_device.shell(f"test -f {path} && echo exists || echo missing")
return result.strip() == "exists"
def check_remote_dir_exists(path):
result = adb_device.shell(f"[ -d {path} ] && echo exists || echo not_exists")
return result.strip() == "exists"
def get_cpu_arch():
abi = adb_device.shell("getprop ro.product.cpu.abi").strip()
if "arm64" in abi:
return "arm64"
elif "armeabi" in abi:
return "arm"
elif "x86_64" in abi:
return "x86_64"
elif "x86" in abi:
return "x86"
return "arm64"
def choose_frida_server():
cpu_arch = get_cpu_arch()
if "arm64" == cpu_arch:
return default_frida_server_arm64
elif "arm" == cpu_arch:
return default_frida_server_arm
info("For simulator, please start frida-server manually first. Thank you")
sys.exit(2)
def pull_file_to_local(remote_file, local_path, is_debug=True):
adb_device.sync.pull(remote_file, local_path)
if is_debug:
info(f"pull {remote_file} to {local_path} successful")
def push_file_to_remote(local_path, remote_path, is_debug=True):
# info(f"push {local_path} to {remote_path}")
try:
# 先尝试标准推送
adb_device.sync.push(local_path, remote_path)
except AdbError as e:
#info("检测到API兼容性问题,降级到更基本的adb push命令")
# 降级到更基本的adb push命令
subprocess.run(
["adb", "push", local_path, remote_path],
check=True
)
if is_debug:
info(f"push {local_path} to {remote_path} successful")
def is_root():
return "system" in run_su_command("ls /data/")
def ensure_root():
if is_root():
return True
else:
try:
adb_device.root() # adbutils 内置封装
if is_root():
info("Switched to root successfully ✅")
return True
else:
info("❌ Failed to switch: device does not support root")
return False
except Exception as e:
info(f"❌ Failed to switch to root: {e}")
return False
# 自动化部署frida-server
if not is_frida_working_via_attach():
if not ensure_root():
info("❌ Cannot auto-deploy frida-server. Please start frida-server manually and try again.")
sys.exit(2)
frida_server_file = choose_frida_server()
remote_frida_server_file = f"/data/mobile-deploy/{frida_server_file}"
if not check_remote_dir_exists("/data/mobile-deploy/"):
run_su_command("mkdir /data/mobile-deploy/")
if not check_remote_file_exists(remote_frida_server_file):
push_file_to_remote(f"mobile-deploy/{frida_server_file}", "/sdcard/")
run_su_command(f"mv /sdcard/{frida_server_file} {remote_frida_server_file}")
run_su_command(f"chmod +x {remote_frida_server_file}")
run_su_command(f"cd /data/mobile-deploy/ && ./{choose_frida_server()} > /sdcard/f_server.log 2>&1 &", True)
success = False
for index in range(20):
if is_frida_working_via_attach():
info("frida-server started successfully ✅")
success = True
break
time.sleep(0.5)
if not success:
info("❌ Failed to start frida-server automatically. Please start it manually and try again.")
sys.exit(2)
# 全局变量
current_identifier = None
current_identifier_name = None
current_identifier_version = None
current_identifier_pid = None
current_identifier_install_path = None
current_identifier_uid = None
current_local_apk_path = None
current_identifier_cache_db = None
current_identifier_cache_readonly_db = None
current_identifier_stop_event = None
frida_device = None
resource_rpc_jscode = read_js_resource("rpc.js")
resource_hook_js_prepare_jscode = read_js_resource("_hook_js_prepare.js")
resource_hook_js_enhance_jscode = read_js_resource("_hook_js_enhance.js")
def _init_resource_jscode():
global resource_rpc_jscode
global resource_hook_js_prepare_jscode
global resource_hook_js_enhance_jscode
resource_rpc_jscode = read_js_resource("rpc.js")
resource_hook_js_prepare_jscode = read_js_resource("_hook_js_prepare.js")
resource_hook_js_enhance_jscode = read_js_resource("_hook_js_enhance.js")
_init_resource_jscode()
#print(f"resource_rpc_jscode:{resource_rpc_jscode}")
def _init_frida_device():
global frida_device
def getRemoteDriver():
text = io.open(".hooker_driver",'r',encoding= 'utf8').read()
if not text:
return None
searchResult = re.search('\d+\.\d+\.\d+\.\d+:\d+', text)
if searchResult:
return searchResult.group()
return None
if frida_device:
return
remoteDriver = getRemoteDriver() #ip:port
if remoteDriver:
frida_device = frida.get_device_manager().add_remote_device(remoteDriver)
else:
frida_device = frida.get_usb_device(1000)
_init_frida_device()
def start_app(package_name):
global current_identifier_pid
shell_result = adb_device.shell(f"dumpsys package {package_name} | grep -A 1 MAIN | grep {package_name}").strip()
m = re.search(r"\s+([^\s]+)\s+filter", shell_result)
if m:
main_activity = m.group(1)
#print(f"am start -n {main_activity}")
adb_device.shell(f"am start -n {main_activity}")
else:
adb_device.shell(f"monkey -p {package_name} -c android.intent.category.LAUNCHER 1")
for j in range(100):
time.sleep(0.5)
if package_name in adb_device.shell("dumpsys activity activities | grep mResumedActivity"):
break
apps = frida_device.enumerate_applications()
for app in sorted(apps, key=lambda x: x.pid or 0):
if app.pid != 0 and app.identifier == package_name:
current_identifier_pid = app.pid
return app.pid, app.name
return None, None
def restart_app(package_name):
global current_identifier_pid
info(f"Restarting {current_identifier_name} Please wait for a few seconds")
adb_device.app_stop(package_name)
time.sleep(1)
app_pid, app_name = start_app(package_name)
current_identifier_pid = app_pid
def ensure_app_in_foreground(package_name):
uid = None
shell_result = adb_device.shell(f"dumpsys package {package_name} | grep userId=").strip()
matchx = re.search(r"userId=(\d+)", shell_result)
if matchx:
uid = int(matchx.group(1))
else:
warn("UID not found.")
apk_path = adb_device.shell(f"pm path {package_name}").strip().replace("package:", "")
apk_path = apk_path[:apk_path.index("base.apk")+8]
#print(f"apk_path:{apk_path}")
appinstall_path = apk_path.rsplit("/", 1)[0]
appinfo = None
version_name = None
if 'app_info' in dir(adb_device):
appinfo = adb_device.app_info(package_name)
version_name = appinfo.version_name
else:
appinfo = adb_device.package_info(package_name)
version_name = appinfo["version_name"]
# 获取当前正在运行的所有进程
proc_map = {}
apps = frida_device.enumerate_applications()
for app in sorted(apps, key=lambda x: x.pid or 0):
if app.pid != 0: # 只列出运行中的
proc_map[app.identifier] = (app.pid, app.name)
is_running = package_name in proc_map
# 获取当前前台 activity
foreground_output = adb_device.shell("dumpsys activity activities | grep mResumedActivity")
is_foreground = package_name in foreground_output
if is_running:
if is_foreground:
info(f"✅ App {package_name} is already in the foreground")
else:
info(f"📲 App {package_name} is running in the background, bringing it to the foreground...")
# 通过 am 启动主 Activity,会自动 bring 到前台
adb_device.shell(f"monkey -p {package_name} -c android.intent.category.LAUNCHER 1")
return proc_map[package_name][0], proc_map[package_name][1], version_name, appinstall_path, uid
else:
info(f"🚀 App {package_name} is not running, starting it now...")
#adb_device.shell(f"monkey -p {package_name} -c android.intent.category.LAUNCHER 1")
app_pid, app_name = start_app(package_name)
return app_pid, app_name, version_name, appinstall_path, uid
def get_remote_file_md5(file_path):
# 检查文件是否存在并获取长度
check_cmd = f"md5sum {file_path}"
result = run_su_command(check_cmd).strip()
if "No such file" in result or "Permission denied" in result or not result:
#warn("No such file")
return ""
try:
# 56cf2745f4884b4dfcc1e193d0118c05 radar.dex
m = re.search("[\w]{32}", result)
if m:
return m.group()
else:
return ""
except Exception:
return ""
def get_local_file_md5(filepath, chunk_size=8192):
md5 = hashlib.md5()
try:
with open(filepath, 'rb') as f:
while True:
chunk = f.read(chunk_size)
if not chunk:
break
md5.update(chunk)
return md5.hexdigest()
except FileNotFoundError:
warn(f"File Not Found: {filepath}")
return None
def read_local_file(filename):
return io.open(filename,'r',encoding= 'utf8').read()
def check_dependency_files():
def process_dex_dependency_files():
compara_and_update_file("mobile-deploy/radar.dex", "/data/local/tmp/radar.dex")
compara_and_update_file("mobile-deploy/libext64.so", f"/data/data/{current_identifier}/files/libext64.so")
compara_and_update_file("mobile-deploy/libext.so", f"/data/data/{current_identifier}/files/libext.so")
t = threading.Thread(target=process_dex_dependency_files)
t.daemon = True
t.start()
def compara_and_update_file(local_file, remote_file):
local_md5 = get_local_file_md5(local_file)
filename = remote_file.split("/")[-1]
sdcard_remote_md5 = get_remote_file_md5(f"/sdcard/{filename}")
#先把radar.dex拷贝到sdcard,后期更新radar.dex直接从sdcard拷过去
if local_md5 != sdcard_remote_md5:
push_file_to_remote(local_file, "/sdcard/", False)
remote_md5 = get_remote_file_md5(remote_file)
#print(f"local_md5:{local_md5} remote_md5:{remote_md5}")
if local_md5 != remote_md5:
#info(f"update {filename} into {remote_file}")
run_su_command(f"cp /sdcard/{filename} {remote_file}", True)
run_su_command(f"chmod 777 {remote_file}", True)
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 _get_min_pid_by_name(process_name):
# 获取所有进程
processes = frida_device.enumerate_processes()
# 存储符合条件的进程 ID
matching_pids = []
for process in processes:
# 如果进程名包含目标进程名
if process_name in process.name:
matching_pids.append(process.pid)
# 如果找到符合条件的进程,返回最小的进程 ID
if matching_pids:
return min(matching_pids)
else:
# 如果没有找到匹配的进程,返回 None
return None
def attach_rpc(use_v8=False):
global frida_device
online_session = None
online_script = None
online_session = frida_device.attach(current_identifier_pid)
if online_session == None:
warn("attaching fail to device")
return None, None
if use_v8:
online_script = online_session.create_script(resource_rpc_jscode, runtime="v8")
else:
online_script = online_session.create_script(resource_rpc_jscode)
# print(f"rpc_jscode:{resource_rpc_jscode}")
online_script.on('message', on_message)
online_script.load()
# online_script.exports_sync.loadradardex()
return online_session, online_script
def attach(script_file, use_v8=False):
if not os.path.isfile(script_file):
warn(f"attach {script_file} File Not found")
return None, None
script_jscode = read_local_file(script_file)
script_jscode = script_jscode
global frida_device
online_session = None
online_script = None
online_session = frida_device.attach(current_identifier_pid)
if online_session == None:
warn("attaching fail to device")
return None, None
if use_v8:
#info("use v8 js engine")
online_script = online_session.create_script(script_jscode, runtime="v8")
else:
online_script = online_session.create_script(script_jscode)
#online_script.on('message', on_message)
online_script.load()
#sys.stdin.read()
return online_session, online_script
def spawn(script_file, use_v8=False):
if not os.path.isfile(script_file):
warn(f"{script_file} File Not found")
return None, None
script_jscode = read_local_file(script_file)
global frida_device
current_identifier_pid = frida_device.spawn([current_identifier])
online_script = None
online_session = frida_device.attach(current_identifier_pid)
if online_session == None:
warn("attaching fail to device")
return None, None
if use_v8:
online_script = online_session.create_script(script_jscode, runtime="v8")
else:
online_script = online_session.create_script(script_jscode)
# online_script.on('message', on_message)
online_script.load()
frida_device.resume(current_identifier_pid)
#sys.stdin.read()
return online_session, online_script
def detach(online_session):
if online_session != None:
online_session.detach()
def exists_class(target, className):
online_session = None
online_script = None
try:
online_session, online_script,_ = attach_rpc(target);
info(online_script.exports_sync.containsclass(className))
except Exception:
warn(traceback.format_exc())
finally:
detach(online_session)
def create_workingdir_file(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 create_working_dir_enverment():
global current_identifier
global frida_device
global current_identifier_name
global current_identifier_version
packageName = current_identifier
if not os.path.exists(packageName):
os.makedirs(packageName)
info(f"Creating working directory: {packageName}")
info(f"Generating frida shortcut command...")
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 -N " + packageName + " | tee -ai log"
attach_shell = shellPrefix + "frida $HOOKER_DRIVER -l $1 -N " + packageName
spawn_shell = f"{shellPrefix}\nfrida $HOOKER_DRIVER --runtime=v8 -f {packageName} -l $1"
create_workingdir_file(packageName+"/hooking", logHooking)
create_workingdir_file(packageName+"/attach", attach_shell)
create_workingdir_file(packageName+"/spawn", spawn_shell)
create_workingdir_file(packageName + "/kill", shellPrefix + "frida-kill $HOOKER_DRIVER "+packageName)
create_workingdir_file(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 +'/kill').readlines()
os.popen('chmod 777 ' + packageName +'/objection').readlines()
os.popen('chmod 777 ' + packageName +'/spawn').readlines()
info(f"Generating built-in frida script...")
init_js_files = [
"url.js",
"android_ui.js",
"edit_text.js",
"text_view.js",
"click.js",
"activity_events.js",
"object_store.js",
"keystore_dump.js",
"ssl_log.js",
"just_trust_me.js",
"just_trust_me_for_ios.js",
"hook_register_natives.js",
"dump_dex.js",
"trace_init_proc.js",
"hook_artmethod_register.js",
"find_anit_frida_so.js",
"hook_jni_method_trace.js",
"replace_dlsym_get_pthread_create.js",
"find_boringssl_custom_verify_func.js",
"get_device_info.js",
"apk_shell_scanner.js",
"bypass_frida_svc_detect.js",
"bypass_root_detect.js",
"bypass_vpn_detect.js",
"hook_encryption_algo.js",
"hook_encryption_algo2.js"
]
for js_file in init_js_files:
if not os.path.exists(f"js/{js_file}"):
info(f"File not Found: js/{js_file}")
continue
jscode = read_js_resource(js_file)
create_workingdir_file(f"{packageName}/{js_file}", jscode.replace("com.smile.gifmaker", packageName))
info(f"Copying APK {current_identifier_install_path}/base.apk to working directory please waiting for a few seconds")
global current_local_apk_path
current_local_apk_path = f"{packageName}/{current_identifier_name.replace(' ', '')}_{current_identifier_version}.apk"
pull_file_to_local(f"{current_identifier_install_path}/base.apk", current_local_apk_path)
info(f"Working directory create successful")
def init_working_dir_enverment():
global current_local_apk_path
current_local_apk_path = f"{current_identifier}/{current_identifier_name.replace(' ', '')}_{current_identifier_version}.apk"
if os.path.isfile(current_local_apk_path):
return
if os.path.isdir(current_local_apk_path):
os.popen(f'rm -rf {current_local_apk_path}').readlines()
#print(f"current_identifier_install_path:{current_identifier_install_path}")
pull_file_to_local(f"{current_identifier_install_path}/base.apk", current_local_apk_path)
info(f"Working directory init successful")
def hook_js(hookCmdArg, savePath = None):
online_session = None
online_script = None
packageName = current_identifier
try:
ganaretoionJscode = ""
online_session, online_script = attach_rpc(use_v8=False);
appversion = current_identifier_version
spaceSpatrater = hookCmdArg.find(":")
className = hookCmdArg
toSpace = "*"
file_method_name = "allfunc"
if spaceSpatrater > 0:
className = hookCmdArg[:spaceSpatrater]
toSpace = hookCmdArg[spaceSpatrater+1:]
if "<init>" in toSpace:
toSpace = "_"
file_method_name = "_init"
else:
toSpace = toSpace.split("(")[0]
file_method_name = toSpace
if not online_script.exports_sync.containsclass(className):
warn(f"Class Not Found {className}")
return
jscode = online_script.exports_sync.hookjs(className, toSpace);
ganaretoionJscode += ("\n//"+hookCmdArg+"\n")
ganaretoionJscode += jscode
if savePath == None:
defaultFilename = className.replace(":", ".").replace("$", ".").replace("__", ".")+ "." + file_method_name + ".js"
savePath = packageName+"/"+defaultFilename;
else:
defaultFilename = savePath
savePath = packageName+"/"+savePath;
if len(ganaretoionJscode):
ganaretoionJscode = resource_hook_js_prepare_jscode + "\n" + ganaretoionJscode + "\n\n\n\n\n//---------------------may be you need--------------------\n\n" + resource_hook_js_enhance_jscode
warpExtraInfo = f"//cracked by {current_identifier_name} {appversion}\n"
warpExtraInfo += "//"+hookCmdArg + "\n\n"
warpExtraInfo += ganaretoionJscode
create_workingdir_file(savePath, jsbeautifier.beautify(warpExtraInfo))
info("frida hook script: " + defaultFilename)
else:
warn("Not found any classes by pattern "+hookCmdArg+".")
except Exception:
warn(traceback.format_exc())
finally:
detach(online_session)
def print_activitys():
online_session = None
online_script = None
try:
online_session,online_script = attach_rpc();
info(online_script.exports_sync.activitys())
except Exception:
print(traceback.format_exc())
finally:
detach(online_session)
def print_services():
online_session = None
online_script = None
try:
online_session, online_script = attach_rpc();
info(online_script.exports_sync.services())
except Exception:
print(traceback.format_exc())
finally:
detach(online_session)
def print_object(objectId):
online_session = None
online_script = None
try:
online_session, online_script = attach_rpc();
info(online_script.exports_sync.objectinfo(objectId))
except Exception:
print(traceback.format_exc())
finally:
detach(online_session)
def object_to_explain(objectId):
online_session = None
online_script = None
try:
online_session, online_script = attach_rpc();
info(online_script.exports_sync.objecttoexplain(objectId))
except Exception:
print(traceback.format_exc())
finally:
detach(online_session)
def print_view(viewId):
online_session = None
online_script = None
try:
online_session, online_script = attach_rpc();
report = online_script.exports_sync.viewinfo(viewId)
info(report);
except Exception:
print(traceback.format_exc())
finally:
detach(online_session)
def list_working_dir():
js_files = {
filename: None
for filename in os.listdir(current_identifier)
if filename.endswith(".js")
}
print_js_file(list(js_files.keys()))
def execute_script(script_file, is_spawn=False):
if not os.path.isfile(f"{current_identifier}/{script_file}"):
warn(f"{current_identifier}/{script_file} File Not found")
return
online_session = None
online_script = None
use_v8 = "just_trust_me.js" in script_file
try:
if is_spawn:
online_session, online_script = spawn(f"{current_identifier}/{script_file}", use_v8)
else:
online_session, online_script = attach(f"{current_identifier}/{script_file}", use_v8)
while online_session != None:
try:
with patch_stdout():
text = cmd_session.prompt("CTRL + C to stop > ", handle_sigint=True)
except KeyboardInterrupt:
info(f"Interrupting {script_file}")
break
except EOFError:
warn("Exiting...")
break
except Exception:
print(traceback.format_exc())
finally:
info(f"detach {script_file}")
detach(online_session)
info(f"detach {script_file} success")
info(f"{script_file} exits successful")
if is_spawn:
restart_app(current_identifier)
def just_trust_me():
execute_script("just_trust_me.js", True)
def un_proxy():
run_su_command("for i in $(iptables -t nat -L OUTPUT --line-numbers | grep REDIRECT |grep 12345 | awk \"{print \$1}\" | sort -rn); do iptables -t nat -D OUTPUT $i; done")
run_su_command("iptables -t nat -F REDSOCKS")
run_su_command("iptables -t nat -D OUTPUT -p tcp -j REDSOCKS")
run_su_command("iptables -t nat -X REDSOCKS")
run_su_command("killall redsocks")
run_su_command("pid=$(ps -ef | grep '[r]edsocks' | awk '{print $2}'); [ -n \"$pid\" ] && kill -9 $pid")
def set_proxy(proxy):
pattern = r'(http|socks5)://(\d{2,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d+)$'
m = re.search(pattern, proxy.strip())
if not m:
warn(f"proxy scheme error: {proxy}")
return
proxy_type = m.group(1)
if proxy_type == "http":
proxy_type = "http-relay"
proxy_ip = m.group(2)
proxy_port = m.group(3)
config = (
"base {\n"
" log_debug = on;\n"
" log_info = on;\n"
" daemon = on;\n"
" redirector = iptables;\n"
"}\n\n"
)
if proxy_type == "http-relay":
config += (
"redsocks {\n"
" local_ip = 127.0.0.1;\n"
" local_port = 12345;\n"
f" ip = {proxy_ip};\n"
f" port = {proxy_port};\n"
f" type = http-relay;\n"
"}"
)
else:
config += (
"redsocks {\n"
" local_ip = 127.0.0.1;\n"
" local_port = 12345;\n"
f" ip = {proxy_ip};\n"
f" port = {proxy_port};\n"
f" type = {proxy_type};\n"
"}"
)
if not check_remote_file_exists("/sdcard/redsocks"):
push_file_to_remote(f"mobile-deploy/redsocks", "/sdcard/redsocks", False)
run_su_command(f"cp /sdcard/redsocks /data/local/tmp/redsocks")
run_su_command(f"chmod 700 /data/local/tmp/redsocks")
if not check_remote_file_exists("/sdcard/libevent-2.1.so"):
push_file_to_remote(f"mobile-deploy/libevent-2.1.so", "/sdcard/libevent-2.1.so", False)
run_su_command(f"cp /sdcard/libevent-2.1.so /data/local/tmp/libevent-2.1.so")
if not check_remote_file_exists("/data/local/tmp/redsocks"):
run_su_command(f"cp /sdcard/redsocks /data/local/tmp/redsocks")
run_su_command(f"cp /sdcard/libevent-2.1.so /data/local/tmp/libevent-2.1.so")
run_su_command(f"chmod 700 /data/local/tmp/redsocks")
un_proxy()
adb_device.shell(f"rm -f /data/local/tmp/redsocks.conf")
adb_device.shell(f"echo '{config}' > /data/local/tmp/redsocks.conf")
time.sleep(1)
run_su_command(f"LD_LIBRARY_PATH=/data/local/tmp/ /data/local/tmp/redsocks -c /data/local/tmp/redsocks.conf")
if proxy_type == "http-relay":
run_su_command(f"iptables -t nat -N REDSOCKS")
run_su_command(f"iptables -t nat -A REDSOCKS -d 0.0.0.0/8 -j RETURN")
run_su_command(f"iptables -t nat -A REDSOCKS -d 127.0.0.0/8 -j RETURN")
run_su_command(f"iptables -t nat -A REDSOCKS -d 192.168.1.0/24 -j RETURN")
run_su_command(f"iptables -t nat -A REDSOCKS -p tcp -j REDIRECT --to-ports 12345")
# run_su_command(f"iptables -t nat -L -nv")
# run_su_command(f"iptables -t nat -A OUTPUT -p tcp --dport 80 -j REDIRECT --to 12345")
# run_su_command(f"iptables -t nat -A OUTPUT -p tcp --dport 443 -j REDIRECT --to 12345")
elif proxy_type.startswith("socks"):
run_su_command(f"iptables -t nat -A OUTPUT -p tcp -m owner --uid-owner {current_identifier_uid} -j REDIRECT --to-ports 12345")
info(f"proxy {proxy} OK")
else:
warn(f"Cannot set proxy {proxy}")
return
if not os.path.exists('.cache'):
os.makedirs('.cache')
def open_or_create_db():
global current_identifier_cache_db
if current_identifier_cache_db:
return current_identifier_cache_db
db_path=f'.cache/{current_identifier}_{current_identifier_version}_class_methods.db'
conn = sqlite3.connect(db_path, check_same_thread=False)
current_identifier_cache_db = conn
cursor = conn.cursor()
# 检查是否存在 app_methods 表
cursor.execute('''
SELECT name FROM sqlite_master
WHERE type='table' AND name='app_methods'
''')
table_exists = cursor.fetchone()
if table_exists:
cursor.execute("PRAGMA table_info(app_methods)")
columns = [row[1] for row in cursor.fetchall()]
if 'filename' not in columns:
cursor.execute("DROP TABLE IF EXISTS app_methods")
conn.commit()
table_exists = False
if not table_exists:
# 创建表
cursor.execute('''
CREATE TABLE app_methods (
id INTEGER PRIMARY KEY AUTOINCREMENT,
filename TEXT NOT NULL,
class_package_name TEXT NOT NULL,
class_name TEXT NOT NULL,
method_name TEXT NOT NULL,
readable_proto_list TEXT
)
''')
# 创建索引
cursor.execute('CREATE INDEX idx_class_package_prefix ON app_methods(class_package_name)')
cursor.execute('CREATE INDEX idx_class_name ON app_methods(class_name)')
conn.commit()
return current_identifier_cache_db
def insert_if_not_exists(cursor, filename, class_package_name, class_name,
method_name, readable_proto_list):
# 查询是否存在相同 class_package_name 和 class_name 的记录
cursor.execute('''
SELECT 1 FROM app_methods
WHERE class_package_name = ? AND class_name = ?
LIMIT 1
''', (class_package_name, class_name))
exists = cursor.fetchone()
if not exists:
cursor.execute('''
INSERT INTO app_methods (
filename, class_package_name, class_name,
method_name, readable_proto_list
) VALUES (?, ?, ?, ?, ?)
''', (
filename, class_package_name, class_name,
method_name, readable_proto_list
))
current_identifier_cache_db.commit()
return exists
def ensure_readonly_copy_fresh():
"""
确保只读数据库副本是最新的,如果过旧或主库有更新则拷贝。
设置 current_identifier_cache_readonly_db 为连接对象。
"""
global current_identifier_cache_readonly_db # 注意声明为全局变量
base_path = f'.cache/{current_identifier}_{current_identifier_version}_class_methods.db'
readonly_path = f'.cache/{current_identifier}_{current_identifier_version}_tmp_readonly_class_methods.db'
# 主库不存在直接报错
if not os.path.exists(base_path):
raise FileNotFoundError(f"主数据库不存在: {base_path}")
now = time.time()
# 如果只读文件不存在,则直接拷贝
if not os.path.exists(readonly_path):
shutil.copy2(base_path, readonly_path)
else:
readonly_ctime = os.path.getctime(readonly_path)
# 如果只读副本距现在小于30秒,则不更新
if now - readonly_ctime < 30:
pass # 不拷贝
else:
base_ctime = os.path.getctime(base_path)
if base_ctime > readonly_ctime:
shutil.copy2(base_path, readonly_path)
# 连接(无论是否拷贝,都会使用只读副本连接)
readonly_uri = f'file:{readonly_path}?mode=ro'
current_identifier_cache_readonly_db = sqlite3.connect(readonly_uri, uri=True, check_same_thread=False)
def count_methods_by_app_version():
ensure_readonly_copy_fresh()
cursor = current_identifier_cache_readonly_db.cursor()
cursor.execute('SELECT COUNT(*) FROM app_methods')
count = cursor.fetchone()[0]
return count
def query_class_name_by_prefix(class_name_prefix, class_name, limit=15):
# 拷贝最新主库文件(如果需要)
ensure_readonly_copy_fresh()
cursor = current_identifier_cache_readonly_db.cursor()
if class_name and not "." in class_name:
if class_name_prefix:
cursor.execute('''
SELECT class_package_name, class_name, readable_proto_list FROM app_methods
WHERE class_name = ? AND class_package_name LIKE ?
LIMIT ?
''', (class_name, f'%{class_name_prefix}%', limit))
#print("1")
results = cursor.fetchall()
if results:
return results
cursor.execute('''
SELECT class_package_name, class_name, readable_proto_list FROM app_methods
WHERE class_name LIKE ? AND class_package_name LIKE ?
LIMIT ?
''', (f'{class_name}%', f'%{class_name_prefix}%', limit))
#print("2")
results = cursor.fetchall()
if results:
return results
else:
cursor.execute('''
SELECT class_package_name, class_name, readable_proto_list FROM app_methods
WHERE class_name = ?
LIMIT ?
''', (class_name, limit))
#print("3")
results = cursor.fetchall()
if results:
return results
cursor.execute('''
SELECT class_package_name, class_name, readable_proto_list FROM app_methods
WHERE class_name LIKE ?
LIMIT ?
''', (f'{class_name}%', limit))
#print("4")
results = cursor.fetchall()
if results:
return results
return []
cursor.execute('''
SELECT class_package_name, class_name, readable_proto_list FROM app_methods
WHERE class_package_name LIKE ?
LIMIT ?
''', (f'{class_name_prefix}%', limit))
#print("5")
results = cursor.fetchall()