-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDroidHawk.py
More file actions
2973 lines (2701 loc) · 125 KB
/
Copy pathDroidHawk.py
File metadata and controls
2973 lines (2701 loc) · 125 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
"""
🦅 DroidHawk - Android Bug Bounty Automation Tool (v4.1)
Made by Jojin John
For authorized penetration testing only.
CHANGELOG (v4.1):
- BUG 1: Moved argparse import to top-level to prevent NameError.
- BUG 2: Wrapped Androguard xref_to calls with safety exception handlers for androguard 4.x compatibility.
- BUG 3: Rewrote deep link extractor aapt2 fallback conditional logic for clarity.
- BUG 4: Added screenrecord process polling to automatically detect completion.
- BUG 5: Added polling logic to MobSF scanner to wait for completion before pulling JSON reports.
- BUG 6: Relaxed package name validation in the bug bounty report generator to support custom/blank inputs.
CHANGELOG (v4.0):
- Added persistent configuration via config.json and settings menu.
- Added JADX decompiler integration with auto-grep (Feature 2).
- Added Androguard static analysis module (Feature 3).
- Added Deep Link Extractor & Intent Fuzzer (Feature 4).
- Added Screenshot & Screen Record evidence utilities (Feature 5).
- Added persistent background logcat capture (Feature 6).
- Added MobSF REST API dynamic scanning integration (Feature 7).
- Added TXT, Markdown, and HTML report formatting (Feature 8).
- Added SHA256 integrity checksum verification for downloads (Feature 10).
- Added Bug Bounty report template generator (Feature 11).
- Fixed Bug 1: Correct subprocess argument splitting for Frida server shell launch.
- Fixed Bug 2: Added connection validation and version mismatch warnings for Frida server.
- Fixed Bug 3: Corrected dynamic parameter ordering for aapt/aapt2 component extraction.
- Fixed Bug 4: Implemented Androguard fallback for manifest analysis if aapt is missing.
- Fixed Bug 5: Resolved empty dirname bug in strings grep for single-file targets.
- Fixed Bug 6: Avoided temp file collision in SQLite extraction via unique filenames.
- Fixed Bug 7: Reimplemented cleartext traffic monitor with non-blocking thread queue.
- Fixed Bug 8: Added recursive build-tools search for apksigner on host.
- Fixed Bug 9: Reloaded custom Frida scripts on top of the menu loop.
- Fixed Bug 10: Added timeout parameters to ADB shell command executions.
- Fixed Bug 11: Sanitized and validated all package name inputs to block shell injection.
- Production Hardening: Context managers everywhere, generic try-except wrappers, clean up on exit.
"""
import os
import sys
import time
import zipfile
import shutil
import json
import re
import datetime
import subprocess
import platform
import hashlib
import atexit
import threading
import queue
import argparse
# ── Optional deps (graceful fallback) ────────────────────────────────────────
try:
import requests as _rq
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
try:
from OpenSSL import crypto as _ssl_crypto
HAS_OPENSSL = True
except ImportError:
HAS_OPENSSL = False
try:
from termcolor import force_color as _fc
_fc()
_FORCE_COLOR = True
except Exception:
_FORCE_COLOR = False
# ── Platform ──────────────────────────────────────────────────────────────────
IS_WINDOWS = platform.system() == "Windows"
IS_LINUX = platform.system() == "Linux"
IS_MAC = platform.system() == "Darwin"
# ── Global configuration defaults ────────────────────────────────────────────
CONFIG_FILE = "config.json"
CONFIG = {
"proxy_host": "127.0.0.1",
"proxy_port": "8080",
"reports_dir": "DroidHawk_Reports",
"preferred_serial": "",
"mobsf_api_key": "",
"mobsf_url": "http://localhost:8000",
"default_report_format": "txt",
"last_record_path": "",
"last_record_ts": ""
}
REPORTS_DIR = CONFIG["reports_dir"]
SESSION_LOG = []
custom_scripts = []
# Background process tracking
LOGCAT_PROC = None
LOGCAT_FILE = None
RECORD_PROC = None
ARGS = None
# ── ANSI colours ──────────────────────────────────────────────────────────────
R = "\033[1;31m" # red
G = "\033[1;32m" # green
Y = "\033[1;33m" # yellow
C = "\033[1;36m" # cyan
M = "\033[1;35m" # magenta
B = "\033[1;34m" # blue
W = "\033[0m" # reset
TOOL_NAME = "DroidHawk"
TOOL_VERSION = "v4.0"
TOOL_AUTHOR = "Jojin John"
def ok(msg): print("{}[✓] {}{}".format(G, msg, W))
def err(msg): print("{}[✗] {}{}".format(R, msg, W))
def info(msg): print("{}[*] {}{}".format(C, msg, W))
def warn(msg): print("{}[!] {}{}".format(Y, msg, W))
def log_session(msg):
ts = datetime.datetime.now().strftime("%H:%M:%S")
SESSION_LOG.append("[{}] {}".format(ts, msg))
# ── Config Loader & Saver ─────────────────────────────────────────────────────
def load_config():
global CONFIG, REPORTS_DIR
if os.path.exists(CONFIG_FILE):
try:
with open(CONFIG_FILE, "r", encoding="utf-8") as f:
loaded = json.load(f)
CONFIG.update(loaded)
except Exception:
pass
REPORTS_DIR = CONFIG["reports_dir"]
def save_config():
try:
with open(CONFIG_FILE, "w", encoding="utf-8") as f:
json.dump(CONFIG, f, indent=4)
except Exception as e:
err(f"Failed to save config: {e}")
# ── Exit Cleanup ──────────────────────────────────────────────────────────────
def cleanup():
global LOGCAT_PROC, LOGCAT_FILE, RECORD_PROC
if LOGCAT_PROC:
try:
LOGCAT_PROC.terminate()
except Exception:
pass
if LOGCAT_FILE:
try:
LOGCAT_FILE.close()
except Exception:
pass
if RECORD_PROC:
try:
RECORD_PROC.terminate()
except Exception:
pass
atexit.register(cleanup)
# ── Multi-Format Report Saver ─────────────────────────────────────────────────
def save_report(name, content, fmt=None):
os.makedirs(REPORTS_DIR, exist_ok=True)
ts = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
if not fmt:
fmt = CONFIG.get("default_report_format", "txt")
if fmt == "json":
path = os.path.join(REPORTS_DIR, f"{name}_{ts}.json")
with open(path, "w", encoding="utf-8") as fh:
fh.write(content)
return path
path = os.path.join(REPORTS_DIR, f"{name}_{ts}.{fmt}")
if fmt == "txt":
with open(path, "w", encoding="utf-8") as fh:
fh.write("=" * 60 + "\n")
fh.write(f"{TOOL_NAME} Report — {datetime.datetime.now()}\n")
fh.write(f"Made by {TOOL_AUTHOR}\n")
fh.write("=" * 60 + "\n\n")
fh.write(content)
elif fmt == "md":
with open(path, "w", encoding="utf-8") as fh:
fh.write(f"# {TOOL_NAME} Security Report\n\n")
fh.write(f"**Date:** {datetime.datetime.now()} \n")
fh.write(f"**Author:** {TOOL_AUTHOR} \n\n")
fh.write("---\n\n")
fh.write(content)
elif fmt == "html":
html_template = """<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>DroidHawk Security Report</title>
<style>
body {{
background-color: #121212;
color: #e0e0e0;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
margin: 0;
padding: 40px;
}}
h1 {{
color: #ff3366;
border-bottom: 2px solid #2d2d2d;
padding-bottom: 15px;
}}
.meta {{
color: #888;
margin-bottom: 30px;
}}
.content {{
background-color: #1e1e1e;
border-radius: 8px;
padding: 25px;
box-shadow: 0 4px 6px rgba(0,0,0,0.3);
white-space: pre-wrap;
font-family: monospace;
line-height: 1.5;
font-size: 14px;
}}
footer {{
margin-top: 50px;
color: #555;
font-size: 12px;
text-align: center;
}}
</style>
</head>
<body>
<h1>🦅 DroidHawk Security Report</h1>
<div class="meta">
<strong>Generated on:</strong> {date}<br>
<strong>Author:</strong> {author}
</div>
<div class="content">{content}</div>
<footer>Made with 🦅 DroidHawk — Android Bug Bounty Automation Tool</footer>
</body>
</html>
"""
with open(path, "w", encoding="utf-8") as fh:
fh.write(html_template.format(
date=datetime.datetime.now(),
author=TOOL_AUTHOR,
content=content.replace("<", "<").replace(">", ">")
))
ok(f"Report saved → {path}")
return path
def ask_save_report(name, content):
ch = input(f"\n{C}→ Save report? (y/n): {W}").strip().lower()
if ch != "y":
return
print(f"\n{C}Choose format:{W}")
print(" 1. TXT (Plain Text)")
print(" 2. Markdown")
print(" 3. HTML (Dark Theme)")
fmt_ch = input("→ Choose format [1]: ").strip()
fmt = "txt"
if fmt_ch == "2":
fmt = "md"
elif fmt_ch == "3":
fmt = "html"
save_report(name, content, fmt)
# ── Requests Loader ───────────────────────────────────────────────────────────
def _get_rq():
if not HAS_REQUESTS:
err("requests not installed. Run: pip install requests")
return None
import requests as rq
return rq
# ── Integrity Check ───────────────────────────────────────────────────────────
def verify_sha256(filepath, expected_hash):
if not expected_hash:
return True
sha256 = hashlib.sha256()
try:
with open(filepath, "rb") as f:
while chunk := f.read(8192):
sha256.update(chunk)
calc_hash = sha256.hexdigest()
if calc_hash.lower() == expected_hash.lower():
ok("SHA256 verified ✓")
return True
else:
if os.path.exists(filepath):
os.remove(filepath)
err("Checksum mismatch — download may be corrupted or tampered")
return False
except Exception as e:
err(f"Integrity check failed: {e}")
return False
# ── Input Sanitization & Validation ──────────────────────────────────────────
def validate_package(name):
return bool(re.match(r'^[a-zA-Z][a-zA-Z0-9_]*(\.[a-zA-Z][a-zA-Z0-9_]*)+$', name))
def ask_package():
while True:
name = input(f"{C}→ Package name (e.g. com.example.app): {W}").strip()
if not name:
return ""
if validate_package(name):
return name
err("Invalid package format. Must follow standard Java package naming (e.g. com.company.app).")
# ── ASCII banner & animations ─────────────────────────────────────────────────
LOGO = r"""
____ _ _ _ _ _
| _ \ _ __ ___ (_) __| | | | |__ __ ___ _| | __
| | | | '__/ _ \| |/ _` | |_| '_ \ \ \ /\ / / | |/ /
| |_| | | | (_) | | (_| | _| | | |\ V V /| | <
|____/|_| \___/|_|\__,_|_| |_| |_| \_/\_/ |_|_|\_\
"""
def startup_animation():
if ARGS and ARGS.no_banner:
return
os.system("cls" if IS_WINDOWS else "clear")
colours = [R, C, G]
msgs = ["", " Initializing ...", " Systems Online ✓"]
for col, msg in zip(colours, msgs):
os.system("cls" if IS_WINDOWS else "clear")
print(col + LOGO + W)
print("{}{}{}".format(Y, msg, W))
time.sleep(0.7)
time.sleep(0.3)
def display_banner():
dev_count = len(get_connected_devices())
dev_str = "{}{}{}".format(
G if dev_count else R,
f"{dev_count} device(s) connected" if dev_count else "No device connected",
W)
logcat_status = f"{G}LOGCAT: ON{W}" if LOGCAT_PROC else f"{R}LOGCAT: OFF{W}"
os.system("cls" if IS_WINDOWS else "clear")
print(R + LOGO + W)
print(" {}{} {} | Made by {}{}".format(M, TOOL_NAME, TOOL_VERSION, TOOL_AUTHOR, W))
print(" {}Android Bug Bounty Automation — Authorized Testing Only{}".format(Y, W))
print(" {}Platform: {} {} | {} | {}{}".format(B, platform.system(), platform.release(), dev_str, logcat_status, W))
print()
# ── Environment checks ────────────────────────────────────────────────────────
def initial_environment_check():
if ARGS and ARGS.skip_checks:
return
os.system("cls" if IS_WINDOWS else "clear")
print(R + LOGO + W)
print("{}→ Verifying {} Environment ...{}\n".format(C, TOOL_NAME, W))
checks = [
("Python 3.9+", _chk_python),
("Python PATH", _chk_python_path),
("ADB", _chk_adb),
("frida-tools", _chk_frida),
("curl", _chk_curl),
("requests", _chk_requests),
("objection", _chk_objection),
("apkleaks", _chk_apkleaks),
("jadx", _chk_jadx),
]
results = []
for name, fn in checks:
print("{}[*] Checking {:<20}{}".format(C, name + "...", W), end="", flush=True)
time.sleep(0.15)
ok_flag, detail = fn()
results.append((name, ok_flag, detail))
sym = "{}[✓]{}".format(G, W) if ok_flag else "{}[!]{}".format(Y, W)
print("\r{} {:<22} {}".format(sym, name, detail))
passed = sum(1 for _, s, _ in results if s)
print("\n{}→ {}/{} checks passed.{}".format(C, passed, len(results), W))
if passed < len(results):
warn("Some optional tools missing — affected features will warn you.")
try:
if input("{}→ Continue anyway? (y/n): {}".format(C, W)).strip().lower() != "y":
sys.exit(1)
except KeyboardInterrupt:
sys.exit(1)
else:
ok("Environment ready!")
time.sleep(0.4)
def _chk_python():
if IS_WINDOWS and "Microsoft\\WindowsApps" in sys.executable:
return False, "Use python.org build, not Microsoft Store"
if sys.version_info < (3, 9):
return False, "Need 3.9+ (found {}.{})".format(*sys.version_info[:2])
return True, "Python {}.{}".format(*sys.version_info[:2])
def _chk_python_path():
for cmd in ("python3", "python"):
if shutil.which(cmd):
return True, "found as '{}'".format(cmd)
return False, "not in PATH"
def _chk_adb():
if not shutil.which("adb"):
return False, "not in PATH — install Android SDK Platform-Tools"
try:
ver = subprocess.check_output(["adb","version"], text=True,
stderr=subprocess.DEVNULL, timeout=10).splitlines()[0]
return True, ver
except Exception:
return True, "found"
def _chk_frida():
if not shutil.which("frida"):
return False, "pip install frida-tools"
try:
ver = subprocess.check_output(["frida","--version"], text=True,
stderr=subprocess.DEVNULL, timeout=10).strip()
return True, "frida {}".format(ver)
except Exception:
return True, "found"
def _chk_curl():
return (True, "available") if shutil.which("curl") else (False, "not found")
def _chk_requests():
try:
import requests as _r
return True, "v{}".format(_r.__version__)
except ImportError:
return False, "pip install requests"
def _chk_objection():
return (True, "found") if shutil.which("objection") else (False, "pip install objection (optional)")
def _chk_apkleaks():
return (True, "found") if shutil.which("apkleaks") else (False, "pip install apkleaks (optional)")
def _chk_jadx():
return (True, "found") if (shutil.which("jadx") or shutil.which("jadx.bat")) else (False, "jadx decompiler missing (optional)")
# ── ADB helpers ───────────────────────────────────────────────────────────────
ADB = "adb"
def get_connected_devices():
try:
out = subprocess.check_output([ADB,"devices"], text=True, stderr=subprocess.DEVNULL, timeout=10)
devs = []
for line in out.splitlines()[1:]:
line = line.strip()
if line and "\tdevice" in line:
devs.append(line.split("\t")[0])
return devs
except Exception:
return []
def is_device_connected():
return bool(get_connected_devices())
def select_device():
if ARGS and ARGS.serial:
return ARGS.serial
if CONFIG.get("preferred_serial"):
return CONFIG["preferred_serial"]
devs = get_connected_devices()
if not devs:
return None
if len(devs) == 1:
return devs[0]
print("{}Multiple devices:{}".format(C, W))
for i, d in enumerate(devs, 1):
print(" {}. {}".format(i, d))
try:
ch = input("{}→ Select device #: {}".format(C, W)).strip()
selected = devs[int(ch) - 1]
if input("Save this device serial as preferred? (y/n): ").strip().lower() == 'y':
CONFIG["preferred_serial"] = selected
save_config()
return selected
except (ValueError, IndexError):
return devs[0]
def adb_cmd(args, serial=None, **kwargs):
base = [ADB] + (["-s", serial] if serial else [])
try:
return subprocess.run(base + args, **kwargs)
except subprocess.TimeoutExpired as te:
err(f"ADB execution timed out: {te}")
return subprocess.CompletedProcess(args=base+args, returncode=-1, stdout="", stderr="TimeoutExpired")
except Exception as e:
err(f"ADB command failed: {e}")
return subprocess.CompletedProcess(args=base+args, returncode=-1, stdout="", stderr=str(e))
def adb_shell(cmd_list, serial=None, timeout=15):
try:
r = adb_cmd(["shell"] + cmd_list, serial=serial, capture_output=True, text=True, timeout=timeout)
return r.stdout.strip()
except Exception:
return ""
# ── Tool installer helpers ────────────────────────────────────────────────────
def is_tool_installed(tool):
if tool == "frida-tools":
return bool(shutil.which("frida"))
try:
return subprocess.run([sys.executable, "-m", "pip", "show", tool],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=15).returncode == 0
except Exception:
return False
def pip_install(tool):
try:
subprocess.run([sys.executable, "-m", "pip", "install", "--upgrade", tool], timeout=300)
except Exception as e:
err(f"Pip installation failed for {tool}: {e}")
def load_custom_scripts():
global custom_scripts
custom_scripts = []
default_set = {"SSL-BYE.js", "ROOTER.js", "PintooR.js"}
if os.path.exists("./Fripts"):
try:
for fname in sorted(os.listdir("./Fripts")):
if fname.endswith(".js") and fname not in default_set:
name = os.path.splitext(fname)[0]
custom_scripts.append((name, os.path.join("./Fripts", fname)))
except Exception:
pass
def _press_enter():
try:
input("\n{}→ Press Enter to continue ...{}".format(C, W))
except KeyboardInterrupt:
pass
def _require_device():
"""Print error and return False if no device connected."""
if not is_device_connected():
err("No emulator/device connected. Start one first.")
_press_enter()
return False
return True
# ════════════════════════════════════════════════════════════════
# MENU 1 — Create Virtual Device
# ════════════════════════════════════════════════════════════════
def menu_create_avd():
display_banner()
warn("THIS IS A MANUAL TASK — DroidHawk guides you step-by-step.\n")
steps = [
("Open Android Studio", "Launch → Device Manager → Virtual tab."),
("Create New Device", "Click 'Create Virtual Device', choose Pixel model, click Next."),
("Select System Image", "API 33 (Android 13) x86_64 or arm64 — download if missing."),
("Finish & Launch", "Click Finish, then press the green Play button in AVD Manager."),
]
for i, (title, body) in enumerate(steps, 1):
print(" {}{}.{} {}{}".format(C, i, W, title, W))
print(" {}\n".format(body))
print("{}Tips:{}".format(Y, W))
print(" • API missing? SDK Manager → Android 13 (API 33)")
print(" • Emulator won't start? Enable VT-x / AMD-V in BIOS")
print(" • Docs: https://developer.android.com/studio/run/managing-avds\n")
_press_enter()
# ════════════════════════════════════════════════════════════════
# MENU 2 — Root Emulator
# ════════════════════════════════════════════════════════════════
def menu_root_emulator():
display_banner()
print("{}[ Root Emulator — Magisk + rootAVD ]{}\n".format(C, W))
if not IS_WINDOWS:
warn("Automated rootAVD patching uses Windows .bat files.\n"
" On Linux/macOS run rootAVD.sh manually after download.\n")
if not _require_device():
return
serial = select_device()
ok("Using device: {}".format(serial))
rq = _get_rq()
if not rq:
return
try:
# --- Download Magisk ---
info("Fetching latest Magisk release ...")
magisk_ver = "v30.0"
magisk_file = "Magisk-v30.0.apk"
magisk_url = "https://github.com/topjohnwu/Magisk/releases/download/v30.0/Magisk-v30.0.apk"
expected_magisk_sha = None
try:
resp = rq.get("https://api.github.com/repos/topjohnwu/Magisk/releases/latest", timeout=10)
resp.raise_for_status()
release_json = resp.json()
magisk_ver = release_json["tag_name"]
magisk_file = "Magisk-{}.apk".format(magisk_ver)
# Find matching binary asset
for asset in release_json.get("assets", []):
if asset["name"].endswith(".apk"):
magisk_file = asset["name"]
magisk_url = asset["browser_download_url"]
break
# Try to fetch sha256 checksum asset
for asset in release_json.get("assets", []):
if asset["name"].endswith(".sha256") or (magisk_file + ".sha256" in asset["name"]):
sha_resp = rq.get(asset["browser_download_url"], timeout=10)
if sha_resp.status_code == 200:
expected_magisk_sha = sha_resp.text.strip().split()[0]
break
except Exception as e:
warn(f"GitHub Magisk lookup failed ({e}), using defaults")
if not os.path.exists(magisk_file):
info("Downloading {} ...".format(magisk_file))
data = rq.get(magisk_url, timeout=180)
data.raise_for_status()
with open(magisk_file, "wb") as f:
f.write(data.content)
# Verify Magisk SHA256 integrity
if expected_magisk_sha:
if not verify_sha256(magisk_file, expected_magisk_sha):
_press_enter()
return
else:
ok(f"Magisk {magisk_ver} download complete")
# --- Install Magisk APK ---
info("Installing Magisk APK ...")
r = adb_cmd(["install", "-r", magisk_file], serial=serial,
capture_output=True, text=True)
if r.returncode != 0:
err("APK install failed: {}".format(r.stderr.strip()))
_press_enter()
return
ok("Magisk installed on emulator")
# --- Download rootAVD ---
info("Downloading rootAVD ...")
rAVD_zip = "rootAVD.zip"
rAVD_dir = "rootAVD"
if not os.path.exists(rAVD_zip):
data = rq.get("https://gitlab.com/newbit/rootAVD/-/archive/master/rootAVD-master.zip",
timeout=180)
data.raise_for_status()
with open(rAVD_zip, "wb") as f:
f.write(data.content)
if not os.path.isdir(rAVD_dir):
with zipfile.ZipFile(rAVD_zip) as z:
z.extractall(rAVD_dir)
ok("rootAVD ready")
bat_dir = os.path.join(rAVD_dir, "rootAVD-master")
if IS_WINDOWS:
# List images
info("Listing available system images ...")
cwd = os.getcwd()
os.chdir(bat_dir)
try:
res = subprocess.run('cmd /c "rootAVD.bat ListAllAVDs"',
shell=True, capture_output=True, text=True, timeout=60)
finally:
os.chdir(cwd)
imgs = sorted({l.split()[1] for l in res.stdout.splitlines()
if l.startswith("rootAVD.bat system-images") and "ramdisk.img" in l})
if imgs:
ok("Found images:")
for p in imgs:
print(" {}{}{}".format(C, p, W))
else:
warn("No images auto-detected.")
android_home = os.environ.get(
"ANDROID_HOME",
os.path.join(os.environ.get("LOCALAPPDATA",""), "Android","Sdk"))
img_path = input("{}→ System image path (e.g. system-images\\android-33\\google_apis\\x86_64\\ramdisk.img): {}".format(C, W)).strip()
full_path = os.path.normpath(os.path.join(android_home, img_path))
if not os.path.exists(full_path):
err("Path not found: {}".format(full_path))
_press_enter(); return
info("Patching system image ...")
cwd = os.getcwd()
os.chdir(bat_dir)
try:
res = subprocess.run('cmd /c ".\\rootAVD.bat {}"'.format(img_path),
shell=True, capture_output=True, text=True, timeout=120)
finally:
os.chdir(cwd)
if res.returncode != 0:
err("Patching failed:\n{}".format(res.stderr))
_press_enter(); return
ok("System image patched!")
else:
sh = os.path.join(bat_dir, "rootAVD.sh")
os.chmod(sh, 0o755)
warn("Linux/macOS — run these commands manually:")
print(" cd {}".format(os.path.abspath(bat_dir)))
print(" ./rootAVD.sh ListAllAVDs")
print(" ./rootAVD.sh <path/to/ramdisk.img>")
input("{}→ Press Enter once done ...{}".format(C, W))
warn("COLD BOOT required → Device Manager → your AVD → ⋮ → Cold Boot Now")
print("{}Waiting 90 seconds for boot ...{}".format(Y, W))
for i in range(90, 0, -1):
print("\r{} {}s remaining ...{}".format(C, i, W), end="", flush=True)
time.sleep(1)
print()
# --- Verify root ---
info("Verifying root ...")
r = adb_cmd(["shell", "su", "-c", "echo ROOT_OK"],
serial=serial, capture_output=True, text=True, timeout=15)
if "ROOT_OK" in r.stdout:
ok("Root CONFIRMED! ✓")
log_session("Rooted device: {}".format(serial))
else:
err("Root not confirmed — open Magisk app, tap OK and allow reboot.")
except Exception as exc:
err("Rooting failed: {}".format(exc))
print("\n{}Tip: adb kill-server && adb start-server — resets ADB if stuck{}".format(M, W))
_press_enter()
# ════════════════════════════════════════════════════════════════
# MENU 3 — Install Tools
# ════════════════════════════════════════════════════════════════
def menu_install_tools():
TOOLS = [
("frida", "Core Frida dynamic instrumentation library"),
("frida-tools", "CLI tools: frida-ps, frida-trace, frida-ls-devices"),
("objection", "Runtime mobile exploration & bypass toolkit"),
("reflutter", "Flutter app reverse-engineering"),
("apkleaks", "APK secrets scanner — API keys, tokens, URLs"),
("androguard", "Android static analysis framework"),
("apkid", "APK packer / protector identifier"),
("mobsf", "Mobile Security Framework (pip install mobsf)"),
]
while True:
try:
display_banner()
print("{}[ Install Tools ]{}\n".format(C, W))
for i, (tool, desc) in enumerate(TOOLS, 1):
st = "{}[Installed] {}".format(G, W) if is_tool_installed(tool) \
else "{}[Missing] {}".format(R, W)
print(" {}. {:<20} {}".format(i, tool, st))
print(" {}{}{}\n".format(M, desc, W))
print(" {}. Install ALL missing".format(len(TOOLS)+1))
print(" {}. Back\n".format(len(TOOLS)+2))
ch = input("{}→ Choose: {}".format(C, W)).strip()
if not ch.isdigit():
continue
c = int(ch)
if 1 <= c <= len(TOOLS):
t = TOOLS[c-1][0]
info("Installing {} ...".format(t))
try:
pip_install(t)
ok("{} installed.".format(t))
except Exception as e:
err("Failed: {}".format(e))
_press_enter()
elif c == len(TOOLS)+1:
missing = [t for t,_ in TOOLS if not is_tool_installed(t)]
if not missing:
ok("All tools already installed!")
else:
for t in missing:
info("Installing {} ...".format(t))
try:
pip_install(t)
ok(t)
except Exception as e:
err("{}: {}".format(t, e))
_press_enter()
elif c == len(TOOLS)+2:
break
except KeyboardInterrupt:
print("\n Returning to Main Menu...")
time.sleep(0.5)
break
# ════════════════════════════════════════════════════════════════
# MENU 4 — Configure Emulator
# ════════════════════════════════════════════════════════════════
def _install_frida_server():
display_banner()
print("{}[ Install Frida Server ]{}\n".format(C, W))
if not _require_device(): return
serial = select_device()
rq = _get_rq()
if not rq: return
try:
abi = adb_shell(["getprop", "ro.product.cpu.abi"], serial)
ok("Device ABI: {}".format(abi))
frida_ver = subprocess.check_output(
["frida","--version"], text=True, stderr=subprocess.DEVNULL, timeout=10).strip()
ok("Host frida-tools: {}".format(frida_ver))
# Pull expected SHA256 checksums first
expected_sha = None
sha_url = f"https://github.com/frida/frida/releases/download/{frida_ver}/SHA256SUMS"
try:
sha_resp = rq.get(sha_url, timeout=15)
if sha_resp.status_code == 200:
filename = f"frida-server-{frida_ver}-android-{abi}.xz"
for line in sha_resp.text.splitlines():
if filename in line:
expected_sha = line.split()[0]
break
except Exception as e:
warn(f"Unable to load Frida integrity hashes: {e}")
url = ("https://github.com/frida/frida/releases/download/{v}/"
"frida-server-{v}-android-{a}.xz").format(v=frida_ver, a=abi)
info("Downloading frida-server ...")
r = rq.get(url, timeout=300, stream=True)
r.raise_for_status()
xz = "frida-server-{}-android-{}.xz".format(frida_ver, abi)
out = xz[:-3]
total = int(r.headers.get("content-length", 0))
done = 0
with open(xz, "wb") as f:
for chunk in r.iter_content(8192):
f.write(chunk)
done += len(chunk)
if total:
print("\r {}Progress: {}%{}".format(
C, done*100//total, W), end="", flush=True)
print()
# Verify SHA256 of the archive
if expected_sha:
if not verify_sha256(xz, expected_sha):
_press_enter()
return
import lzma
info("Extracting ...")
with lzma.open(xz) as fin, open(out, "wb") as fout:
fout.write(fin.read())
ok("Extracted: {}".format(out))
info("Pushing to /data/local/tmp/frida-server ...")
adb_cmd(["push", out, "/data/local/tmp/frida-server"], serial=serial, check=True, timeout=30)
adb_cmd(["shell", "chmod", "+x", "/data/local/tmp/frida-server"], serial=serial, check=True, timeout=15)
ok("Frida server installed! ✓")
# Start server in background to test
info("Testing frida-server launch...")
base = [ADB] + (["-s", serial] if serial else [])
subprocess.Popen(base + ["shell", "su", "-c", "nohup /data/local/tmp/frida-server > /dev/null 2>&1 &"])
time.sleep(2)
# Connection check
r_ver = subprocess.run(["frida-ps"] + (["-D", serial] if serial else ["-U"]), capture_output=True, text=True, timeout=10)
if r_ver.returncode != 0:
warn("Unable to connect to frida-server. There might be a version mismatch between host frida-tools and device frida-server, or permission issues.")
else:
ok("Frida server verified and responding! ✓")
# Stop test server
adb_cmd(["shell", "su", "-c", "pkill -f frida-server"], serial=serial, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=15)
log_session("frida-server {} installed on {}".format(frida_ver, serial))
except Exception as e:
err("Failed: {}".format(e))
_press_enter()
def _install_burp_cert():
display_banner()
print("{}[ Install Burp Suite Certificate ]{}\n".format(C, W))
print("{}Prerequisites:{}".format(Y, W))
print(" 1. Burp Suite running on 127.0.0.1:8080")
print(" 2. Emulator proxy set to 127.0.0.1:8080")
print(" 3. Rooted emulator (Magisk)\n")
if not _require_device(): return
serial = select_device()
rq = _get_rq()
if not rq: return
try:
info("Downloading Burp CA certificate ...")
cert_bytes = None
for url in ["http://127.0.0.1:8080/cert", "http://burp/cert"]:
try:
resp = rq.get(url, timeout=10)
resp.raise_for_status()
cert_bytes = resp.content
break
except Exception:
pass
if not cert_bytes:
raise RuntimeError("Cannot reach Burp on 127.0.0.1:8080 — is it running?")
with open("cacert.der", "wb") as f:
f.write(cert_bytes)
if HAS_OPENSSL:
from OpenSSL import crypto as ssl_c
cert = ssl_c.load_certificate(ssl_c.FILETYPE_ASN1, cert_bytes)
pem = ssl_c.dump_certificate(ssl_c.FILETYPE_PEM, cert)
with open("portswigger.crt", "wb") as f:
f.write(pem)
else:
shutil.copy("cacert.der", "portswigger.crt")
ok("Certificate downloaded & converted")
adb_cmd(["push", "portswigger.crt", "/sdcard/portswigger.crt"],
serial=serial, check=True, timeout=30)
ok("Pushed to /sdcard/portswigger.crt")
# AlwaysTrustUserCerts Magisk module
info("Fetching AlwaysTrustUserCerts module ...")
try:
resp = rq.get("https://api.github.com/repos/NVISOsecurity/"
"AlwaysTrustUserCerts/releases/latest", timeout=10)
resp.raise_for_status()
mod_ver = resp.json()["tag_name"]
except Exception:
mod_ver = "v1.3"
mod_file = "AlwaysTrustUserCerts_{}.zip".format(mod_ver)
mod_url = ("https://github.com/NVISOsecurity/AlwaysTrustUserCerts"
"/releases/download/{}/{}".format(mod_ver, mod_file))
if not os.path.exists(mod_file):
data = rq.get(mod_url, timeout=120)
data.raise_for_status()
with open(mod_file, "wb") as f:
f.write(data.content)
ok("Module {} ready".format(mod_ver))
adb_cmd(["push", mod_file, "/data/local/tmp/"+mod_file], serial=serial, check=True, timeout=30)
adb_cmd(["shell","su","-c",
"magisk --install-module /data/local/tmp/{}".format(mod_file)],
serial=serial, check=True, timeout=30)
ok("Magisk module installed")
warn("Now: Settings → Security → Install cert → CA → /sdcard/portswigger.crt")
warn("Waiting 60 s for manual install ...")
for i in range(60, 0, -1):
print("\r{} {}s ...{}".format(C, i, W), end="", flush=True)
time.sleep(1)
print()
adb_cmd(["reboot"], serial=serial, timeout=15)
ok("Emulator rebooting — setup complete! ✓")
log_session("Burp cert installed on {}".format(serial))
except Exception as e:
err("Failed: {}".format(e))
_press_enter()
def _one_click_proxy(port="8080"):
display_banner()
if not _require_device(): return
serial = select_device()
port = input("{}→ Proxy port [8080]: {}".format(C, W)).strip() or "8080"
adb_cmd(["shell","settings","put","global","http_proxy","127.0.0.1:{}".format(port)],
serial=serial, timeout=15)
adb_cmd(["reverse","tcp:{}".format(port),"tcp:{}".format(port)], serial=serial, timeout=15)
ok("Proxy → 127.0.0.1:{} | adb reverse configured".format(port))
_press_enter()
def menu_configure_emulator():
while True:
try:
display_banner()
print("{}[ Configure Emulator ]{}\n".format(C, W))
print(" 1. Install Frida Server")
print(" 2. Install Burp Suite Certificate (Magisk)")
print(" 3. One-Click Burp Proxy Setup")
print(" 4. Back\n")
ch = input("{}→ Choose: {}".format(C, W)).strip()
if ch == "1": _install_frida_server()
elif ch == "2": _install_burp_cert()
elif ch == "3": _one_click_proxy()
elif ch == "4": break
except KeyboardInterrupt:
print("\n Returning to Main Menu...")
time.sleep(0.5)
break
# ════════════════════════════════════════════════════════════════
# MENU 5 — Run Frida Server
# ════════════════════════════════════════════════════════════════
def menu_run_frida_server():
display_banner()
if not _require_device(): return
serial = select_device()
info("Killing any old frida-server instance ...")
adb_cmd(["shell","su","-c","pkill -f frida-server"], serial=serial,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=15)
time.sleep(1)