-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1961 lines (1734 loc) · 78.4 KB
/
main.py
File metadata and controls
1961 lines (1734 loc) · 78.4 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
"""
GAMA — Greyware Analysis and Mitigation Approach
CenturiaLabs / ClickSafe UAE — v1.0
Interactive orchestrator. Every step is an analyst choice.
Technology collects. The analyst interprets.
"""
import os
import sys
import json
import shutil
import subprocess
from datetime import datetime
from pathlib import Path
# ─── ANSI colours ───────────────────────────────────────────────
class C:
RESET = "\033[0m"
BOLD = "\033[1m"
DIM = "\033[2m"
RED = "\033[91m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
BLUE = "\033[94m"
PURPLE = "\033[95m"
CYAN = "\033[96m"
WHITE = "\033[97m"
GRAY = "\033[90m"
def clr(text, color): return f"{color}{text}{C.RESET}"
def bold(text): return f"{C.BOLD}{text}{C.RESET}"
def ok(text): print(f" {clr('✓', C.GREEN)} {text}")
def warn(text): print(f" {clr('!', C.YELLOW)} {text}")
def err(text): print(f" {clr('✗', C.RED)} {text}")
def info(text): print(f" {clr('·', C.CYAN)} {text}")
def sep(): print(f" {clr('─' * 58, C.GRAY)}")
WORKSPACE_ROOT = Path(__file__).parent / "workspace"
MODULES_DIR = Path(__file__).parent / "modules"
RULES_DIR = Path(__file__).parent / "rules"
FRIDA_DIR = Path(__file__).parent / "frida_scripts"
# ─── session state ─────────────────────────────────────────────
session = {
"workspace": None,
"apk_path": None,
"apk_name": None,
"hypothesis": None,
"phase": 0,
"findings": [],
}
# ─── workspace utilities ──────────────────────────────────────────
def load_workspace(ws_path: Path):
meta = ws_path / "meta.json"
if meta.exists():
with open(meta) as f:
data = json.load(f)
session.update(data)
session["workspace"] = ws_path
ok(f"Workspace loaded: {bold(ws_path.name)}")
if session.get("hypothesis"):
info(f"Active hypothesis: {session['hypothesis'][:80]}...")
else:
warn("meta.json not found in the selected workspace.")
def save_session():
if not session["workspace"]:
return
meta = session["workspace"] / "meta.json"
data = {k: str(v) if isinstance(v, Path) else v
for k, v in session.items() if k != "workspace"}
with open(meta, "w") as f:
json.dump(data, f, indent=2, default=str)
def findings_path():
if not session["workspace"]:
return None
return session["workspace"] / "findings.jsonl"
def add_finding(phase, technique, description, evidence, classification="hypothesis"):
"""Append a finding to the workspace JSONL log. Append-only."""
finding = {
"timestamp": datetime.now().isoformat(),
"phase": phase,
"gama_technique": technique,
"description": description,
"evidence": evidence,
"classification": classification,
"analyst_note": ""
}
fp = findings_path()
if fp:
with open(fp, "a") as f:
f.write(json.dumps(finding) + "\n")
session["findings"].append(finding)
return finding
def load_findings():
fp = findings_path()
if not fp or not fp.exists():
return []
findings = []
with open(fp) as f:
for line in f:
line = line.strip()
if line:
try:
findings.append(json.loads(line))
except json.JSONDecodeError:
pass
return findings
# ─── banner ─────────────────────────────────────────────────────
def print_banner():
os.system("clear")
print(f"""
{clr(' ██████╗ █████╗ ███╗ ███╗ █████╗', C.BLUE)}
{clr(' ██╔════╝ ██╔══██╗████╗ ████║██╔══██╗', C.BLUE)}
{clr(' ██║ ███╗███████║██╔████╔██║███████║', C.BLUE)}
{clr(' ██║ ██║██╔══██║██║╚██╔╝██║██╔══██║', C.BLUE)}
{clr(' ╚██████╔╝██║ ██║██║ ╚═╝ ██║██║ ██║', C.BLUE)}
{clr(' ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝', C.BLUE)}
{bold('Greyware Analysis and Mitigation Approach')} {clr('v1.0', C.GRAY)}
{clr('CenturiaLabs · ClickSafe UAE', C.GRAY)}
{clr('Technology collects. The analyst interprets.', C.DIM)}
""")
def print_status_bar():
ws = session["workspace"].name if session["workspace"] else clr("none", C.RED)
apk = session["apk_name"] or clr("none", C.RED)
ph = f"Phase {session['phase']}"
nf = len(load_findings())
hyp = "✓" if session.get("hypothesis") else clr("✗", C.RED)
print(f" {clr('workspace', C.GRAY)} {bold(ws)} "
f"{clr('APK', C.GRAY)} {bold(apk)} "
f"{clr('phase', C.GRAY)} {bold(ph)} "
f"{clr('findings', C.GRAY)} {bold(nf)} "
f"{clr('hypothesis', C.GRAY)} {hyp}")
sep()
# ─── main menu ────────────────────────────────────────────
def main_menu():
print_banner()
print_status_bar()
print(f"""
{bold('WORKSPACE')}
{clr('1', C.CYAN)} New workspace (new analysis)
{clr('2', C.CYAN)} Open existing workspace
{clr('3', C.CYAN)} List workspaces
{bold('ANALYSIS — GAMA PHASES')}
{clr('4', C.PURPLE)} Phase 0 — Intake and threat hypothesis
{clr('5', C.PURPLE)} Phase 1 — Static analysis (APK, manifest, smali)
{clr('6', C.PURPLE)} Phase 2 — URI schemes and IPC channels
{clr('7', C.PURPLE)} Phase 3 — Dynamic setup (checklist + Frida)
{clr('8', C.CYAN)} Phase 4 — Network analysis (Zeek / pcap)
{clr('9', C.YELLOW)} Phase 5 — Correlation and finding classification
{clr('10', C.YELLOW)} Phase 6 — Enforcement rule generation
{clr('11', C.YELLOW)} Phase 7 — Report and disclosure
{bold('FINDINGS')}
{clr('12', C.GREEN)} View current findings
{clr('13', C.GREEN)} Add manual finding
{clr('14', C.GREEN)} Modify finding classification
{clr('0', C.GRAY)} Exit
""")
return input(f" {clr('▶', C.BLUE)} ").strip()
# ─── Tab completion for file paths ───────────────────────────────
def _enable_tab_completion():
try:
import readline
import glob
def completer(text, state):
matches = glob.glob(text + '*')
return matches[state] if state < len(matches) else None
readline.set_completer(completer)
readline.parse_and_bind("tab: complete")
except Exception:
pass # readline not available on all platforms (e.g. Windows)
_enable_tab_completion()
# ─── XAPK / APKS handler ─────────────────────────────────────────
def resolve_apk(input_path: str) -> tuple:
"""
Accepts .apk, .xapk, or .apks input.
XAPK and APKS are ZIP archives — extracts the base APK automatically.
Returns (apk_path, apk_name, notes) or (None, None, error_msg).
"""
ap = Path(input_path.strip("'\"").rstrip("/"))
# ── If user passed a directory: look for APK files inside ────
if ap.is_dir():
candidates = (
list(ap.glob("*.apk")) +
list(ap.glob("*.xapk")) +
list(ap.glob("*.apks"))
)
if not candidates:
return None, None, f"Directory contains no APK/XAPK/APKS files: {ap}"
if len(candidates) == 1:
info(f"Found: {candidates[0].name}")
ap = candidates[0]
else:
print(f"\n {bold('Multiple APK files found — choose one:')}")
for i, c in enumerate(candidates, 1):
size = round(c.stat().st_size / 1024 / 1024, 1)
print(f" {clr(str(i), C.CYAN)} {c.name} {clr(f'({size} MB)', C.GRAY)}")
choice = input(f" {clr('▶', C.BLUE)} ").strip()
try:
ap = candidates[int(choice) - 1]
except (ValueError, IndexError):
return None, None, "Invalid selection."
if not ap.exists():
return None, None, f"File not found: {ap}"
suffix = ap.suffix.lower()
# Standard APK — pass through
if suffix == ".apk":
return str(ap.resolve()), ap.name, None
# XAPK or APKS — both are ZIP archives
if suffix in (".xapk", ".apks"):
import zipfile
if not zipfile.is_zipfile(ap):
return None, None, f"{suffix.upper()} file is not a valid ZIP archive"
extract_dir = ap.parent / f"{ap.stem}_extracted"
extract_dir.mkdir(exist_ok=True)
with zipfile.ZipFile(ap) as z:
members = z.namelist()
info(f"Archive contents: {members}")
apk_members = [m for m in members if m.endswith('.apk')]
if not apk_members:
return None, None, f"No .apk found inside {suffix.upper()} archive"
# Prefer base.apk, otherwise pick the largest
base = next((m for m in apk_members if 'base' in m.lower()), None)
if not base:
sizes = {m: z.getinfo(m).file_size for m in apk_members}
base = max(sizes, key=sizes.get)
out_path = extract_dir / Path(base).name
with z.open(base) as src, open(out_path, 'wb') as dst:
dst.write(src.read())
ok(f"Extracted base APK: {out_path.name}")
splits = [m for m in apk_members if m != base]
if splits:
info(f"Split APKs (for reference): {splits}")
return str(out_path.resolve()), out_path.name, f"Extracted from {ap.name}"
return None, None, (
f"Unsupported format: '{ap.suffix}' (supported: .apk, .xapk, .apks)\n"
f" Did you mean to pass a directory? Try: {ap.parent}/"
)
# ─── 1. New workspace ─────────────────────────────────────────
def new_workspace():
print_banner()
print(f" {bold('NEW WORKSPACE')}\n")
name = input(f" Analysis name {clr('(e.g. graveyard-empire-v2.1)', C.GRAY)}: ").strip()
if not name:
err("Invalid name.")
input(" Press enter to continue...")
return
# filesystem-safe slug
slug = name.lower().replace(" ", "-").replace("/", "-")
slug = "".join(c if c.isalnum() or c == "-" else "-" for c in slug)
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
ws = WORKSPACE_ROOT / f"{ts}_{slug}"
# Guard against collision (should not happen with seconds, but be safe)
suffix = 0
while ws.exists():
suffix += 1
ws = WORKSPACE_ROOT / f"{ts}_{slug}_{suffix}"
# Create workspace directories
ws.mkdir(parents=True, exist_ok=True)
for subdir in ("static", "dynamic", "network", "rules", "report"):
(ws / subdir).mkdir(exist_ok=True)
# apk / xapk / apks
apk_input = input(f" APK path {clr('(.apk / .xapk / .apks — press enter to skip)', C.GRAY)}: ").strip()
apk_path = None
apk_name = None
if apk_input:
apk_path, apk_name, note = resolve_apk(apk_input)
if apk_path:
if note:
info(note)
else:
warn(f"Could not resolve APK: {note} — you can set it later.")
session["workspace"] = ws
session["apk_path"] = apk_path
session["apk_name"] = apk_name
session["hypothesis"] = None
session["phase"] = 0
session["findings"] = []
save_session()
ok(f"Workspace created: {ws}")
info("Structure: static/ dynamic/ network/ rules/ report/")
input(" Press enter to continue...")
# ─── 2. Open workspace ──────────────────────────────────────────
def open_workspace():
print_banner()
print(f" {bold('OPEN WORKSPACE')}\n")
workspaces = sorted(WORKSPACE_ROOT.glob("*"), key=lambda p: p.stat().st_mtime, reverse=True)
if not workspaces:
warn("No workspaces found.")
input(" Press enter to continue...")
return
for i, ws in enumerate(workspaces[:15], 1):
meta = ws / "meta.json"
apk = ""
phase = "0"
if meta.exists():
try:
d = json.loads(meta.read_text())
apk = d.get("apk_name", "")
phase = str(d.get("phase", 0))
except Exception:
pass
nf = len(list(ws.glob("findings.jsonl")))
print(f" {clr(str(i), C.CYAN)} {bold(ws.name)}"
f" {clr(apk, C.GRAY)} phase {phase}")
choice = input(f"\n {clr('▶', C.BLUE)} Number: ").strip()
try:
ws = workspaces[int(choice) - 1]
load_workspace(ws)
except (ValueError, IndexError):
err("Invalid choice.")
input(" Press enter to continue...")
# ─── 3. List workspaces ─────────────────────────────────────────
def list_workspaces():
print_banner()
print(f" {bold('EXISTING WORKSPACES')}\n")
workspaces = sorted(WORKSPACE_ROOT.glob("*"), key=lambda p: p.stat().st_mtime, reverse=True)
if not workspaces:
warn("No workspaces found.")
for ws in workspaces:
findings_count = 0
fp = ws / "findings.jsonl"
if fp.exists():
findings_count = sum(1 for _ in fp.open())
meta = ws / "meta.json"
apk = ""
if meta.exists():
try:
apk = json.loads(meta.read_text()).get("apk_name", "")
except Exception:
pass
mtime = datetime.fromtimestamp(ws.stat().st_mtime).strftime("%d/%m %H:%M")
print(f" {clr(mtime, C.GRAY)} {bold(ws.name)}"
f" {clr(apk or '—', C.GRAY)}"
f" {clr(str(findings_count) + ' findings', C.GREEN if findings_count else C.GRAY)}")
input("\n Press enter to continue...")
# ─── helper: requires active workspace ──────────────────────────
def require_workspace():
if not session["workspace"]:
warn("No active workspace. Create or open a workspace first.")
input(" Press enter to continue...")
return False
return True
# ─── PHASE 0: Intake and Threat Hypothesis ─────────────────────────
def phase0_intake():
if not require_workspace(): return
print_banner()
print(f" {bold('PHASE 0 — INTAKE AND THREAT HYPOTHESIS')}\n")
print(f" {clr('Before touching the code. Formulate the hypothesis.', C.DIM)}\n")
# APK se non impostato
if not session["apk_path"]:
apk_input = input(f" APK path: ").strip()
if apk_input:
ap = Path(apk_input.strip("'\""))
if ap.exists():
session["apk_path"] = str(ap.resolve())
session["apk_name"] = ap.name
save_session()
sep()
print(f" {bold('APPLICATION METADATA')}")
fields = {
"app_name": "Application name",
"developer": "Developer / Entity",
"category": "Play Store category",
"version": "Version analysed",
"apk_sha256": "APK SHA-256",
"declared_size": "Declared size (MB)",
"actual_size": "Actual APK size (MB)",
"permissions": "Anomalous permissions detected",
"sdks": "SDK dependencies identified",
}
meta_out = {}
for key, label in fields.items():
val = input(f" {clr(label, C.CYAN)}: ").strip()
if val:
meta_out[key] = val
# auto-calculate size delta if APK present
if session.get("apk_path"):
ap = Path(session["apk_path"])
if ap.exists():
actual_mb = round(ap.stat().st_size / 1024 / 1024, 2)
info(f"APK size detected automatically: {bold(str(actual_mb))} MB")
meta_out["actual_size_auto"] = actual_mb
sep()
print(f"\n {bold('THREAT HYPOTHESIS')}")
print(f" {clr('Describe in natural language what you suspect.', C.DIM)}")
print(f" {clr('Example: \"I suspect this app collects device data', C.DIM)}")
print(f" {clr(' via SDK-level bypass invisible to the network layer.\"', C.DIM)}\n")
hypothesis = input(f" {clr('Primary hypothesis', C.YELLOW)}: ").strip()
sep()
print(f"\n {bold('FALSIFICATION CRITERIA')}")
print(f" {clr('When can you say the hypothesis is WRONG?', C.DIM)}\n")
null_hypothesis = input(f" {clr('Null hypothesis', C.GRAY)}: ").strip()
sep()
print(f"\n {bold('SUSPICION TRIGGERS')}")
print(f" {clr('What triggered this analysis?', C.DIM)}\n")
triggers = []
print(f" {clr('Enter triggers (empty enter to finish):', C.GRAY)}")
while True:
t = input(f" {clr('+', C.GREEN)} ").strip()
if not t: break
triggers.append(t)
# save all
session["hypothesis"] = hypothesis
session["phase"] = max(session["phase"], 1)
out = {
"phase": 0,
"timestamp": datetime.now().isoformat(),
"metadata": meta_out,
"hypothesis": hypothesis,
"null_hypothesis": null_hypothesis,
"triggers": triggers,
}
out_path = session["workspace"] / "static" / "phase0_intake.json"
with open(out_path, "w") as f:
json.dump(out, f, indent=2)
save_session()
ok(f"Intake saved: {out_path.name}")
info("Recommended next step: Phase 1 — Static analysis")
input(" Press enter to continue...")
# ─── PHASE 1: Static Analysis ─────────────────────────────────────
def phase1_static():
if not require_workspace(): return
print_banner()
print(f" {bold('PHASE 1 — STATIC ANALYSIS')}\n")
if not session.get("apk_path"):
warn("APK not set in workspace.")
apk_input = input(f" APK path {clr('(.apk / .xapk / .apks)', C.GRAY)}: ").strip()
if not apk_input: return
apk_path, apk_name, note = resolve_apk(apk_input)
if not apk_path:
err(f"Could not resolve APK: {note}")
input(" Press enter to continue...")
return
if note:
info(note)
session["apk_path"] = apk_path
session["apk_name"] = apk_name
save_session()
apk = Path(session["apk_path"])
static_dir = session["workspace"] / "static"
sep()
print(f" {bold('APK')}")
info(f"File: {apk}")
info(f"Size: {round(apk.stat().st_size / 1024 / 1024, 2)} MB")
info(f"Suffix: {apk.suffix.lower()}")
sep()
print(f" {bold('TOOLS DETECTED')}")
tools = {
"apktool": shutil.which("apktool"),
"jadx": shutil.which("jadx"),
"aapt2": shutil.which("aapt2"),
"strings": shutil.which("strings"),
"readelf": shutil.which("readelf"),
}
critical_missing = []
for tool, path in tools.items():
if path:
ok(f"{tool}: {clr(path, C.GRAY)}")
else:
warn(f"{tool}: {clr('not found', C.RED)}")
if tool in ("apktool", "jadx"):
critical_missing.append(tool)
if critical_missing:
sep()
err(f"Critical tools missing: {', '.join(critical_missing)}")
info("Operations 1-4 and 'Run all' will not produce results without apktool.")
info("Install apktool: sudo apt install apktool OR https://apktool.org")
sep()
print(f"\n {bold('AVAILABLE OPERATIONS')}\n")
print(f" {clr('1', C.CYAN)} Decompile APK with apktool")
print(f" {clr('2', C.CYAN)} Decompile APK with jadx (Java source)")
print(f" {clr('3', C.PURPLE)} Extract and analyse AndroidManifest.xml")
print(f" {clr('4', C.PURPLE)} URI scheme scanner (manifest + smali)")
print(f" {clr('5', C.PURPLE)} SDK fingerprint (smali class names)")
print(f" {clr('6', C.PURPLE)} Size delta (declared vs actual)")
print(f" {clr('7', C.PURPLE)} List native .so files")
print(f" {clr('8', C.YELLOW)} Run all operations")
print(f" {clr('0', C.GRAY)} Back to main menu\n")
choice = input(f" {clr('▶', C.BLUE)} ").strip()
if choice == "1":
_run_apktool(apk, static_dir)
elif choice == "2":
_run_jadx(apk, static_dir)
elif choice == "3":
_analyze_manifest(static_dir)
elif choice == "4":
_scan_uri_schemes(static_dir)
elif choice == "5":
_sdk_fingerprint(static_dir)
elif choice == "6":
_size_delta(apk)
elif choice == "7":
_list_native_libs(static_dir)
elif choice == "8":
_run_apktool(apk, static_dir)
_analyze_manifest(static_dir)
_scan_uri_schemes(static_dir)
_sdk_fingerprint(static_dir)
_size_delta(apk)
_list_native_libs(static_dir)
elif choice == "0":
return
session["phase"] = max(session["phase"], 2)
save_session()
input("\n Press enter to continue...")
def _run_apktool(apk, static_dir):
sep()
print(f"\n {bold('APKTOOL — DECOMPILATION')}")
# Check apktool is available before attempting anything
apktool_bin = shutil.which("apktool")
if not apktool_bin:
err("apktool not found in PATH.")
info("Install: https://apktool.org | apt install apktool | brew install apktool")
info(f"Current PATH: {__import__('os').environ.get('PATH','(empty)')}")
return
info(f"apktool: {apktool_bin}")
info(f"APK: {apk} ({round(apk.stat().st_size/1024/1024,1)} MB)")
out_dir = static_dir / "apktool_out"
if out_dir.exists():
overwrite = input(f" Output already exists. Overwrite? {clr('[y/N]', C.GRAY)}: ").strip().lower()
if overwrite not in ('y', 'Y'):
info("Operation skipped.")
return
shutil.rmtree(out_dir)
info("Decompiling — this may take 30-120 seconds for large APKs...")
try:
result = subprocess.run(
[apktool_bin, "d", str(apk), "-o", str(out_dir), "-f", "--no-debug-info"],
capture_output=True, text=True, timeout=300
)
except FileNotFoundError:
err(f"apktool binary not executable: {apktool_bin}")
return
except subprocess.TimeoutExpired:
err("apktool timed out after 5 minutes.")
return
if result.returncode == 0:
ok(f"Output: {out_dir}")
smali_count = len(list(out_dir.rglob("*.smali")))
ok(f"Smali files extracted: {bold(str(smali_count))}")
if smali_count == 0:
warn("0 smali files — APK may be corrupt or heavily obfuscated.")
warn(f"Try: apktool d \"{apk}\" -o {out_dir} -f")
else:
err("apktool failed:")
print(f" {clr(result.stderr[:600], C.RED)}")
if result.stdout:
print(f" stdout: {result.stdout[:200]}")
def _run_jadx(apk, static_dir):
sep()
print(f"\n {bold('JADX — JAVA SOURCE')}")
jadx_bin = shutil.which("jadx")
if not jadx_bin:
err("jadx not found in PATH.")
info("Install: https://github.com/skylot/jadx/releases | brew install jadx")
return
info(f"jadx: {jadx_bin}")
out_dir = static_dir / "jadx_out"
if out_dir.exists():
overwrite = input(f" Output already exists. Overwrite? {clr('[y/N]', C.GRAY)}: ").strip().lower()
if overwrite not in ('y', 'Y'):
info("Operation skipped.")
return
shutil.rmtree(out_dir)
info("Recovering Java source — this may take 60-180 seconds...")
try:
result = subprocess.run(
[jadx_bin, "-d", str(out_dir), "--no-res", "--show-bad-code", str(apk)],
capture_output=True, text=True, timeout=600
)
except FileNotFoundError:
err(f"jadx binary not executable: {jadx_bin}")
return
except subprocess.TimeoutExpired:
err("jadx timed out after 10 minutes.")
return
java_count = len(list(out_dir.rglob("*.java"))) if out_dir.exists() else 0
if java_count > 0:
ok(f"Java files recovered: {bold(str(java_count))}")
ok(f"Output: {out_dir}")
else:
warn("jadx completed with 0 Java files.")
if result.stderr:
print(f" stderr: {clr(result.stderr[:400], C.YELLOW)}")
def _analyze_manifest(static_dir):
sep()
print(f"\n {bold('ANDROIDMANIFEST.XML — ANALYSIS')}")
manifest = static_dir / "apktool_out" / "AndroidManifest.xml"
if not manifest.exists():
warn("Manifest not found. Run apktool first (option 1).")
return
import xml.etree.ElementTree as ET
try:
tree = ET.parse(manifest)
root = tree.getroot()
ns = {"android": "http://schemas.android.com/apk/res/android"}
findings = {
"permissions": [],
"exported_components": [],
"intent_filters": [],
"custom_schemes": [],
"meta_data": [],
"services": [],
"receivers": [],
"providers": [],
}
# permissions
for perm in root.findall(".//uses-permission"):
name = perm.get("{http://schemas.android.com/apk/res/android}name", "")
findings["permissions"].append(name)
# componenti esportati
for tag in ["activity", "service", "receiver", "provider"]:
for el in root.findall(f".//{tag}"):
exported = el.get("{http://schemas.android.com/apk/res/android}exported", "")
name = el.get("{http://schemas.android.com/apk/res/android}name", "")
if tag == "service": findings["services"].append(name)
if tag == "receiver": findings["receivers"].append(name)
if tag == "provider": findings["providers"].append(name)
if exported == "true":
findings["exported_components"].append({"tag": tag, "name": name})
# intent filters con scheme custom
for intent_filter in el.findall(".//intent-filter"):
for data in intent_filter.findall(".//data"):
scheme = data.get("{http://schemas.android.com/apk/res/android}scheme", "")
if scheme and scheme not in ["http", "https", "ftp", "content", "file", "android"]:
findings["custom_schemes"].append({
"scheme": scheme,
"component": name,
"component_type": tag
})
# meta-data
for meta in root.findall(".//meta-data"):
mname = meta.get("{http://schemas.android.com/apk/res/android}name", "")
mvalue = meta.get("{http://schemas.android.com/apk/res/android}value", "")
if mname:
findings["meta_data"].append({"name": mname, "value": mvalue})
# output
print(f"\n {clr('DECLARED PERMISSIONS', C.BOLD)} ({len(findings['permissions'])})")
dangerous = ["READ_CONTACTS","READ_PHONE_STATE","ACCESS_FINE_LOCATION",
"RECORD_AUDIO","READ_CALL_LOG","GET_ACCOUNTS","CAMERA",
"READ_SMS","QUERY_ALL_PACKAGES","PACKAGE_USAGE_STATS"]
for p in findings["permissions"]:
short = p.replace("android.permission.", "")
if any(d in p for d in dangerous):
print(f" {clr('!', C.YELLOW)} {bold(short)}")
else:
print(f" {clr('·', C.GRAY)} {short}")
print(f"\n {clr('EXPORTED COMPONENTS', C.BOLD)} ({len(findings['exported_components'])})")
for c in findings["exported_components"]:
print(f" {clr('!', C.YELLOW)} [{c['tag']}] {c['name']}")
print(f"\n {clr('CUSTOM URI SCHEMES', C.BOLD)} ({len(findings['custom_schemes'])})")
for s in findings["custom_schemes"]:
print(f" {clr('!!!', C.RED)} {bold(s['scheme'] + '://')} [{s['component_type']}] {s['component']}")
# auto-finding
add_finding(
phase=1,
technique="GAMA-T001",
description=f"URI scheme custom registrato: {s['scheme']}://",
evidence=f"AndroidManifest.xml — {s['component_type']}: {s['component']}",
classification="hypothesis"
)
print(f"\n {clr('META-DATA', C.BOLD)} ({len(findings['meta_data'])})")
for m in findings["meta_data"][:20]:
val_display = m['value'][:60] if m['value'] else clr("(no value)", C.GRAY)
print(f" {clr('·', C.GRAY)} {m['name'][:50]} = {val_display}")
# save output
out_path = static_dir / "manifest_analysis.json"
with open(out_path, "w") as f:
json.dump(findings, f, indent=2)
ok(f"\n Analysis saved: {out_path.name}")
except ET.ParseError as e:
err(f"XML parse error: {e}")
def _scan_uri_schemes(static_dir):
"""
Universal URI scheme scanner.
Cerca QUALSIASI pattern :// — non firme note.
La logica classifica per contesto, non per nome.
Questo trova le mutazioni sconosciute, non solo i casi documentati.
"""
sep()
print(f"\n {bold('URI SCHEME SCANNER — LOGIC, NOT SIGNATURES')}")
print(f" {clr('Scans every :// in code. Classification by context, not by name.', C.DIM)}\n")
smali_dir = static_dir / "apktool_out"
if not smali_dir.exists():
warn("Directory apktool_out non trovata. Run apktool first.")
return
import re
# ── cosa consideriamo "noto e benigno" ───────────────────────
# These are not removed — kept separate to avoid pollutirati to avoid
# polluting l'output. L'analyst can still view them.
SYSTEM_SCHEMES = {
"http", "https", "ftp", "ftps", "content", "file",
"android", "intent", "market", "mailto", "tel", "sms",
"geo", "mms", "voicemail", "xmpp", "rtsp", "blob",
"data", "javascript", "about", "ws", "wss",
}
# ── pattern: cattura scheme://qualcosa ───────────────────────
# Searches strings, smali annotations, constant values.
# Not limited to quoted strings — also checks .field, const-string etc.
SCHEME_RE = re.compile(
r'(?:const-string[^"]*"|["\']|[=\(,\s])'
r'([a-zA-Z][a-zA-Z0-9+\-._]{1,30})' # underscore added: wv_hybrid, fb_sdk etc.
r'://'
r'([^\s"\'\\<>]{0,120})',
re.MULTILINE
)
# ── pattern: metodi che gestiscono URL/scheme ────────────────
HANDLER_RE = re.compile(
r'(shouldOverrideUrlLoading|shouldInterceptRequest'
r'|loadUrl|evaluateJavascript|addJavascriptInterface'
r'|handleIntent|parseUri|Uri\.parse|Uri\.fromString'
r'|Intent\.parseUri|startActivity|getScheme\(\))',
re.IGNORECASE
)
# ── counters and collectors ─────────────────────────────────
all_schemes = {} # scheme -> [{file, line, context, full_match}]
handler_hits = [] # file con metodi di gestione URL
base64_schemes = [] # scheme trovati dopo decode base64 (se presenti)
smali_files = list(smali_dir.rglob("*.smali"))
info(f"Universal scan of {bold(str(len(smali_files)))} smali files...")
for sf in smali_files:
try:
text = sf.read_text(errors="ignore")
lines = text.splitlines()
rel = str(sf.relative_to(static_dir))
# ── cerca :// ───────────────────────────────────────
for match in SCHEME_RE.finditer(text):
scheme = match.group(1).lower()
path_ctx = match.group(2)[:60] if match.group(2) else ""
full = match.group(0)[:80]
# trova numero di riga approssimativo
pos = match.start()
line_no = text[:pos].count("\n") + 1
entry = {
"file": rel,
"line": line_no,
"context": path_ctx,
"snippet": full.strip(),
}
if scheme not in all_schemes:
all_schemes[scheme] = []
all_schemes[scheme].append(entry)
# ── cerca handler methods ────────────────────────────
for match in HANDLER_RE.finditer(text):
line_no = text[:match.start()].count("\n") + 1
handler_hits.append({
"method": match.group(1),
"file": rel,
"line": line_no,
})
# ── cerca stringhe Base64 che contengono :// ─────────
import base64 as b64mod
b64_re = re.compile(r'[A-Za-z0-9+/]{16,}={0,3}') # fixed: 16 min, include ==
for b64match in b64_re.finditer(text):
raw = b64match.group(0)
decoded = None
for attempt in [raw, raw + "=", raw + "=="]:
try:
decoded = b64mod.b64decode(attempt).decode("utf-8", errors="ignore")
break
except Exception:
continue
if decoded and "://" in decoded:
line_no = text[:b64match.start()].count("\n") + 1
base64_schemes.append({
"file": rel,
"line": line_no,
"decoded": decoded[:120],
"raw": raw[:40] + "...",
})
except Exception:
pass
# ── logic-based classification ───────────────────────────────
# Non "is mv://" — ma "these properties make it suspicious"
def suspicion_score(scheme, occurrences):
score = 0
notes = []
# 1. Non è un sistema noto → sospetto base
if scheme not in SYSTEM_SCHEMES:
score += 3
notes.append("schema non-standard")
# 2. Molto corto (2-4 char) → probabilmente custom SDK
if len(scheme) <= 4 and scheme not in SYSTEM_SCHEMES:
score += 2
notes.append(f"short name ({len(scheme)} chars) — typical custom SDK")
# 3. Appare in file sotto percorsi di SDK noti
sdk_paths = ["mbridge","mintegral","unity","adjust","appsflyer",
"firebase","moloco","bytedance","pangle","ironsource",
"applovin","vungle","inmobi","tapjoy","chartboost"]
sdk_files = [o["file"] for o in occurrences
if any(s in o["file"].lower() for s in sdk_paths)]
if sdk_files:
score += 3
notes.append(f"found in SDK path ({sdk_files[0].split('/')[1] if '/' in sdk_files[0] else sdk_files[0]})")
# 4. Alta frequenza in distinct files → usato come canale
n_files = len(set(o["file"] for o in occurrences))
if n_files >= 5:
score += 2
notes.append(f"found in {n_files} distinct files")
elif n_files >= 2:
score += 1
# 5. Il contesto contiene termini di tracking/ad
tracking_terms = ["uid","did","device","track","click","install",
"event","session","user","ad","impression","bid"]
ctx_blob = " ".join(o.get("context","") for o in occurrences).lower()
matched_terms = [t for t in tracking_terms if t in ctx_blob]
if matched_terms:
score += len(matched_terms)
notes.append(f"tracking context: {', '.join(matched_terms[:3])}")
# 6. Appare vicino a handler methods (WebView ecc.)
scheme_files = set(o["file"] for o in occurrences)
handler_files = set(h["file"] for h in handler_hits)
overlap = scheme_files & handler_files
if overlap:
score += 3
notes.append("co-located with WebView/Intent handler")
return score, notes
# ── separation: system / unknown / suspicious ───────────────
system_found = {}
unknown_found = {}
suspicious = {}
for scheme, occs in all_schemes.items():
score, notes = suspicion_score(scheme, occs)
entry = {"occurrences": occs, "score": score, "notes": notes}
if scheme in SYSTEM_SCHEMES:
system_found[scheme] = entry
elif score >= 5:
suspicious[scheme] = entry
else:
unknown_found[scheme] = entry
# ── output ───────────────────────────────────────────────────
print(f" {clr('SUSPICIOUS SCHEMES (score ≥ 5)', C.RED)} "
f"{clr('— GAMA-T001 candidates', C.DIM)}\n")
if not suspicious:
ok("No high-score schemes. Check the 'unknown' section.")
else:
for scheme, data in sorted(suspicious.items(),
key=lambda x: x[1]["score"], reverse=True):
score = data["score"]
notes = data["notes"]
occs = data["occurrences"]
n_files = len(set(o["file"] for o in occs))
print(f" {clr('!!!', C.RED)} {bold(scheme + '://')} "
f"{clr(f'score={score}', C.RED)} "
f"{clr(f'{len(occs)} occurrences in {n_files} file', C.GRAY)}")
for note in notes:
print(f" {clr('→', C.YELLOW)} {note}")
# mostra prime more occurrences con snippet
for occ in occs[:2]:
print(f" {clr(occ['file'][:65], C.GRAY)}:{occ['line']}")
if occ.get("snippet"):
print(f" {clr(occ['snippet'], C.DIM)}")
if len(occs) > 2:
print(f" {clr(f'... and {len(occs)-2} more occurrences', C.GRAY)}")
print()
# auto-finding for very high score
if score >= 7:
add_finding(
phase=1,
technique="GAMA-T001",
description=f"High-suspicion URI scheme: {scheme}:// (score={score})",
evidence=f"{len(occs)} occurrences in {n_files} file — signals: {'; '.join(notes)}",
classification="hypothesis"
)
print(f" {clr('UNCLASSIFIED SCHEMES (score < 5)', C.YELLOW)} "
f"{clr('— review manually', C.DIM)}\n")
for scheme, data in sorted(unknown_found.items(),
key=lambda x: x[1]["score"], reverse=True):
occs = data["occurrences"]
score = data["score"]
n_files = len(set(o["file"] for o in occs))
print(f" {clr('?', C.YELLOW)} {scheme + '://':<25} "
f"score={score} "
f"{clr(f'{len(occs)}x / {n_files} file', C.GRAY)}")
print(f"\n {clr('SYSTEM SCHEMES FOUND', C.GRAY)} "
f"{clr('(count only)', C.DIM)}")
for scheme in sorted(system_found.keys()):
n = len(system_found[scheme]["occurrences"])
print(f" {clr('·', C.GRAY)} {scheme + '://':<20} {n}x")
# ── Base64 encoded schemes ───────────────────────────────────