dexsect 4.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. dexsect/__init__.py +4 -0
  2. dexsect/__main__.py +5 -0
  3. dexsect/catalog/EXTRACTION_CATALOG.json +4057 -0
  4. dexsect/catalog/__init__.py +0 -0
  5. dexsect/cli.py +1272 -0
  6. dexsect/core/__init__.py +0 -0
  7. dexsect/core/config.py +177 -0
  8. dexsect/core/context.py +181 -0
  9. dexsect/core/i18n.py +40 -0
  10. dexsect/core/pipeline.py +153 -0
  11. dexsect/core/platform_utils.py +164 -0
  12. dexsect/core/runner.py +124 -0
  13. dexsect/core/theme.py +64 -0
  14. dexsect/core/ui.py +405 -0
  15. dexsect/core/utils.py +150 -0
  16. dexsect/inspectors/__init__.py +0 -0
  17. dexsect/inspectors/assets_db_inspector.py +235 -0
  18. dexsect/inspectors/base.py +46 -0
  19. dexsect/inspectors/bundle_inspector.py +55 -0
  20. dexsect/inspectors/code_inspector.py +341 -0
  21. dexsect/inspectors/custom_rules_inspector.py +178 -0
  22. dexsect/inspectors/dex_inspector.py +144 -0
  23. dexsect/inspectors/manifest_inspector.py +503 -0
  24. dexsect/inspectors/native_fw_inspector.py +167 -0
  25. dexsect/inspectors/resources_inspector.py +195 -0
  26. dexsect/inspectors/scanner_inspector.py +153 -0
  27. dexsect/inspectors/signing_inspector.py +423 -0
  28. dexsect/inspectors/text_scanner.py +336 -0
  29. dexsect/locales/__init__.py +0 -0
  30. dexsect/locales/ar.json +130 -0
  31. dexsect/locales/de.json +51 -0
  32. dexsect/locales/en.json +110 -0
  33. dexsect/locales/es.json +51 -0
  34. dexsect/locales/fr.json +51 -0
  35. dexsect/locales/ja.json +51 -0
  36. dexsect/locales/pt.json +51 -0
  37. dexsect/locales/ru.json +51 -0
  38. dexsect/locales/tr.json +51 -0
  39. dexsect/locales/zh.json +51 -0
  40. dexsect/parsers/__init__.py +0 -0
  41. dexsect/parsers/axml.py +264 -0
  42. dexsect/parsers/bundle.py +214 -0
  43. dexsect/parsers/elf.py +396 -0
  44. dexsect/phases/__init__.py +0 -0
  45. dexsect/phases/base.py +102 -0
  46. dexsect/phases/decode.py +507 -0
  47. dexsect/phases/decompile.py +408 -0
  48. dexsect/phases/fingerprint.py +341 -0
  49. dexsect/phases/frameworks.py +377 -0
  50. dexsect/phases/mapper.py +41 -0
  51. dexsect/phases/native.py +188 -0
  52. dexsect/plugins/__init__.py +0 -0
  53. dexsect/plugins/base.py +20 -0
  54. dexsect/plugins/diff.py +162 -0
  55. dexsect/plugins/inspect.py +172 -0
  56. dexsect/plugins/report.py +80 -0
  57. dexsect/plugins/trace.py +141 -0
  58. dexsect/reporting/__init__.py +0 -0
  59. dexsect/reporting/analysis_report.py +1190 -0
  60. dexsect/reporting/diff_report.py +144 -0
  61. dexsect/reporting/sarif_report.py +109 -0
  62. dexsect/reporting/unpack_map.py +149 -0
  63. dexsect/rules/__init__.py +0 -0
  64. dexsect/rules/anti_analysis.json +45 -0
  65. dexsect/rules/crypto_audit.json +41 -0
  66. dexsect/rules/secrets_extended.json +46 -0
  67. dexsect/storage/__init__.py +0 -0
  68. dexsect/storage/findings_db.py +460 -0
  69. dexsect-4.1.0.dist-info/METADATA +532 -0
  70. dexsect-4.1.0.dist-info/RECORD +74 -0
  71. dexsect-4.1.0.dist-info/WHEEL +5 -0
  72. dexsect-4.1.0.dist-info/entry_points.txt +2 -0
  73. dexsect-4.1.0.dist-info/licenses/LICENSE +21 -0
  74. dexsect-4.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,341 @@
1
+ import os
2
+ import struct
3
+ import time
4
+ import zipfile
5
+ from pathlib import Path
6
+ from typing import Any, Dict, List, Optional, Set
7
+
8
+ from ..core.context import ArtifactUnit, PipelineContext
9
+ from ..core.runner import CommandRunner
10
+ from .base import BasePhase, PhaseResult
11
+
12
+
13
+ HERMES_MAGIC = b"\xc6\x1f\xbc\x03\xc1\x03\x19\x1f"
14
+ UNITY_METADATA_MAGIC = b"\xaf\x1b\xb1\xfa"
15
+
16
+ FRAMEWORK_SO_PREFIXES = (
17
+ "libflutter.so", "libapp.so",
18
+ "libreactnative", "libhermes", "libjsc.so", "libfbjni.so",
19
+ "libfolly_", "libglog", "libjsi.so", "libturbomodulejsijni.so", "libfabricjni.so",
20
+ "libunity.so", "libil2cpp.so", "libmain.so",
21
+ "libmonodroid.so", "libmonosgen", "libxamarin",
22
+ "libgodot_android.so", "libue4.so", "libunreal.so", "libnativescript.so",
23
+ )
24
+
25
+ PACKER_SO_SIGS = {
26
+ "libjiagu": "Qihoo 360 Jiagu",
27
+ "libprotectclass": "Qihoo 360",
28
+ "libsecexe": "Bangcle / SecNeo",
29
+ "libsecmain": "Bangcle / SecNeo",
30
+ "libdexhelper": "Bangcle DexHelper",
31
+ "libshella": "Tencent Legu",
32
+ "libshellx": "Tencent Legu",
33
+ "libtup": "Tencent Packer",
34
+ "libbaiduprotect": "Baidu Packer",
35
+ "libnesec": "NetEase Packer",
36
+ "libmobisec": "Alibaba MobiSec",
37
+ "libsgmain": "Alibaba Security Guard",
38
+ "libpairipcore": "Google Play Pairip",
39
+ "libijiami": "Ijiami",
40
+ "libexec": "Ijiami",
41
+ "libapkprotect": "APKProtect",
42
+ "libkwscmm": "KiwiSec",
43
+ }
44
+
45
+
46
+ def inspect_hermes_bytes(hdr: bytes) -> Dict[str, Any]:
47
+ if len(hdr) >= 12 and hdr[:8] == HERMES_MAGIC:
48
+ return {"format": "HERMES_BYTECODE", "hermes_version": struct.unpack("<I", hdr[8:12])[0]}
49
+ sample = hdr.decode("utf-8", errors="ignore")
50
+ if sample and all(ch.isprintable() or ch in "\r\n\t" for ch in sample):
51
+ return {"format": "PLAIN_JS_BUNDLE", "hermes_version": None}
52
+ return {"format": "UNKNOWN_BINARY_BUNDLE", "hermes_version": None}
53
+
54
+
55
+ def inspect_unity_meta_bytes(hdr: bytes) -> Dict[str, Any]:
56
+ if len(hdr) >= 8 and hdr[:4] == UNITY_METADATA_MAGIC:
57
+ return {"encrypted": False, "metadata_version": struct.unpack("<i", hdr[4:8])[0]}
58
+ return {"encrypted": True, "metadata_version": None}
59
+
60
+
61
+
62
+ def _is_elf_file(path: Path) -> bool:
63
+ try:
64
+ with path.open("rb") as f:
65
+ return f.read(4) == b"\x7fELF"
66
+ except OSError:
67
+ return False
68
+
69
+ def fingerprint_unit(unit: ArtifactUnit) -> None:
70
+ dec = Path(unit.decode_dir) if unit.decode_dir else None
71
+ src = Path(unit.source_path) if unit.source_path else None
72
+
73
+ abis: Set[str] = set()
74
+ frameworks: Set[str] = set()
75
+ packers: Set[str] = set()
76
+ custom_so: List[str] = []
77
+ fw_so: List[str] = []
78
+ fw_plan: List[Dict[str, Any]] = []
79
+
80
+ flutter_libs: List[str] = []
81
+ flutter_assets_dir: Optional[str] = None
82
+ rn_bundles: List[Dict[str, Any]] = []
83
+ il2cpp_libs: List[str] = []
84
+ unity_meta_path: Optional[str] = None
85
+ unity_meta_info: Dict[str, Any] = {}
86
+ unity_dlls: List[str] = []
87
+ xamarin_dlls: List[str] = []
88
+ xamarin_blobs: List[str] = []
89
+ web_dirs: List[str] = []
90
+ has_kotlin = False
91
+
92
+ if dec and dec.is_dir():
93
+ has_kotlin = (dec / "kotlin").is_dir() or (dec / "smali" / "kotlin").is_dir()
94
+
95
+ lib_dir = dec / "lib"
96
+ if lib_dir.is_dir():
97
+ for abi_ent in sorted(os.scandir(lib_dir), key=lambda e: e.name):
98
+ if not abi_ent.is_dir(follow_symlinks=False):
99
+ continue
100
+ abis.add(abi_ent.name)
101
+ for so_ent in sorted(os.scandir(abi_ent.path), key=lambda e: e.name):
102
+ if not so_ent.is_file(follow_symlinks=False) or not so_ent.name.lower().endswith(".so"):
103
+ continue
104
+ rel_so = f"lib/{abi_ent.name}/{so_ent.name}"
105
+ low = so_ent.name.lower()
106
+ for psig, plabel in PACKER_SO_SIGS.items():
107
+ if psig in low:
108
+ packers.add(f"{plabel} ({rel_so})")
109
+ if low in ("libflutter.so", "libapp.so"):
110
+ frameworks.add("Flutter")
111
+ if low == "libapp.so":
112
+ flutter_libs.append(so_ent.path)
113
+ elif any(k in low for k in ("libreactnative", "libhermes", "libjsc.so")):
114
+ frameworks.add("ReactNative")
115
+ elif low in ("libunity.so", "libil2cpp.so"):
116
+ frameworks.add("Unity")
117
+ if low == "libil2cpp.so":
118
+ il2cpp_libs.append(so_ent.path)
119
+ elif any(k in low for k in ("libmonodroid.so", "libmonosgen", "libxamarin")):
120
+ frameworks.add("Xamarin/.NET")
121
+ elif low in ("libue4.so", "libunreal.so"):
122
+ frameworks.add("UnrealEngine")
123
+ elif low == "libgodot_android.so":
124
+ frameworks.add("Godot")
125
+ elif low == "libnativescript.so":
126
+ frameworks.add("NativeScript")
127
+ elif low.startswith("libpython3"):
128
+ frameworks.add("Python(Chaquopy/Kivy)")
129
+
130
+ if any(low.startswith(pref) for pref in FRAMEWORK_SO_PREFIXES):
131
+ fw_so.append(rel_so)
132
+ else:
133
+ custom_so.append(so_ent.path)
134
+
135
+ for root, _dirs, files in os.walk(dec):
136
+ rel_root = Path(root).relative_to(dec).as_posix()
137
+ if rel_root.startswith(("smali", "res", "META-INF", "lib")):
138
+ continue
139
+ for fn in files:
140
+ fpath = Path(root) / fn
141
+ if fn.lower().endswith(".so") or (fpath.suffix == "" and fpath.stat().st_size >= 64 and _is_elf_file(fpath)):
142
+ so_low = fn.lower()
143
+ rel_so = fpath.relative_to(dec).as_posix()
144
+ for psig, plabel in PACKER_SO_SIGS.items():
145
+ if psig in so_low:
146
+ packers.add(f"{plabel} ({rel_so})")
147
+ if any(so_low.startswith(pref) for pref in FRAMEWORK_SO_PREFIXES):
148
+ fw_so.append(rel_so)
149
+ else:
150
+ custom_so.append(str(fpath))
151
+
152
+ assets_dir = dec / "assets"
153
+ if assets_dir.is_dir():
154
+ if (assets_dir / "flutter_assets").is_dir():
155
+ frameworks.add("Flutter")
156
+ flutter_assets_dir = str(assets_dir / "flutter_assets")
157
+ if (assets_dir / "www").is_dir():
158
+ frameworks.add("Cordova/Ionic")
159
+ web_dirs.append(str(assets_dir / "www"))
160
+ if (assets_dir / "public").is_dir() and (
161
+ (assets_dir / "capacitor.config.json").is_file()
162
+ or (dec / "res" / "xml" / "config.xml").is_file()
163
+ ):
164
+ frameworks.add("Capacitor")
165
+ web_dirs.append(str(assets_dir / "public"))
166
+ if (assets_dir / "bin" / "Data").is_dir():
167
+ frameworks.add("Unity")
168
+
169
+ for root, _dirs, files in os.walk(assets_dir):
170
+ for fn in files:
171
+ fpath = Path(root) / fn
172
+ low = fn.lower()
173
+ rel = fpath.relative_to(dec).as_posix()
174
+ if low == "index.android.bundle" or fpath.suffix.lower() in (".bundle", ".hbc"):
175
+ frameworks.add("ReactNative")
176
+ try:
177
+ with fpath.open("rb") as f:
178
+ b_info = inspect_hermes_bytes(f.read(16))
179
+ except OSError:
180
+ b_info = {"format": "UNREADABLE", "hermes_version": None}
181
+ b_info.update({"path": str(fpath), "rel_path": rel})
182
+ rn_bundles.append(b_info)
183
+ elif low == "global-metadata.dat":
184
+ frameworks.add("Unity")
185
+ unity_meta_path = str(fpath)
186
+ try:
187
+ with fpath.open("rb") as f:
188
+ unity_meta_info = inspect_unity_meta_bytes(f.read(8))
189
+ except OSError:
190
+ unity_meta_info = {}
191
+ elif fpath.suffix.lower() == ".dll" and "bin/data/managed" in rel.lower():
192
+ frameworks.add("Unity")
193
+ unity_dlls.append(str(fpath))
194
+
195
+ for asm_root in (dec / "assemblies", dec / "unknown" / "assemblies"):
196
+ if asm_root.is_dir():
197
+ frameworks.add("Xamarin/.NET")
198
+ for fn in asm_root.iterdir():
199
+ if fn.is_file():
200
+ if fn.suffix.lower() == ".dll":
201
+ xamarin_dlls.append(str(fn))
202
+ elif fn.name.lower() in ("assemblies.blob", "assemblies.manifest"):
203
+ xamarin_blobs.append(str(fn))
204
+
205
+ elif src and src.is_file() and zipfile.is_zipfile(src):
206
+ # Fast direct-ZIP fingerprinting without prior decode!
207
+ with zipfile.ZipFile(src, "r") as zf:
208
+ for zi in zf.infolist():
209
+ nm = zi.filename
210
+ low = nm.lower()
211
+ if nm.startswith("kotlin/"):
212
+ has_kotlin = True
213
+ elif nm.startswith("lib/") and low.endswith(".so"):
214
+ parts = nm.split("/")
215
+ if len(parts) >= 3:
216
+ abi, so_name = parts[1], parts[-1]
217
+ abis.add(abi)
218
+ so_low = so_name.lower()
219
+ for psig, plabel in PACKER_SO_SIGS.items():
220
+ if psig in so_low:
221
+ packers.add(f"{plabel} ({nm})")
222
+ if so_low in ("libflutter.so", "libapp.so"):
223
+ frameworks.add("Flutter")
224
+ elif any(k in so_low for k in ("libreactnative", "libhermes", "libjsc.so")):
225
+ frameworks.add("ReactNative")
226
+ elif so_low in ("libunity.so", "libil2cpp.so"):
227
+ frameworks.add("Unity")
228
+ elif any(k in so_low for k in ("libmonodroid.so", "libmonosgen")):
229
+ frameworks.add("Xamarin/.NET")
230
+ if any(so_low.startswith(pref) for pref in FRAMEWORK_SO_PREFIXES):
231
+ fw_so.append(nm)
232
+ else:
233
+ custom_so.append(nm)
234
+ elif low.startswith("assets/flutter_assets/"):
235
+ frameworks.add("Flutter")
236
+ elif low.startswith("assets/www/"):
237
+ frameworks.add("Cordova/Ionic")
238
+ elif low == "assets/index.android.bundle" or low.endswith((".bundle", ".hbc")):
239
+ frameworks.add("ReactNative")
240
+ with zf.open(zi) as zf_f:
241
+ b_info = inspect_hermes_bytes(zf_f.read(16))
242
+ b_info.update({"path": f"zip://{nm}", "rel_path": nm})
243
+ rn_bundles.append(b_info)
244
+ elif low.endswith("global-metadata.dat"):
245
+ frameworks.add("Unity")
246
+ with zf.open(zi) as zf_f:
247
+ unity_meta_info = inspect_unity_meta_bytes(zf_f.read(8))
248
+
249
+ if "Flutter" in frameworks:
250
+ fw_plan.append({
251
+ "framework": "Flutter",
252
+ "mode": "AOT_RELEASE" if flutter_libs else "DEBUG_JIT",
253
+ "libapp_paths": flutter_libs,
254
+ "flutter_assets": flutter_assets_dir,
255
+ })
256
+ if "ReactNative" in frameworks:
257
+ fw_plan.append({"framework": "ReactNative", "bundles": rn_bundles})
258
+ if "Unity" in frameworks:
259
+ if il2cpp_libs or unity_meta_path or unity_meta_info:
260
+ fw_plan.append({
261
+ "framework": "Unity_IL2CPP",
262
+ "libil2cpp_paths": il2cpp_libs,
263
+ "global_metadata": unity_meta_path,
264
+ "metadata_info": unity_meta_info,
265
+ })
266
+ if unity_dlls:
267
+ fw_plan.append({"framework": "Unity_Mono", "dll_paths": unity_dlls})
268
+ if "Cordova/Ionic" in frameworks or "Capacitor" in frameworks:
269
+ fw_plan.append({"framework": "WebHybrid", "web_dirs": web_dirs})
270
+ if "Xamarin/.NET" in frameworks:
271
+ fw_plan.append({"framework": "Xamarin", "dll_paths": xamarin_dlls, "blobs": xamarin_blobs})
272
+
273
+ if not frameworks:
274
+ stack = "Native Android (Kotlin/Java)" if has_kotlin else "Native Android (Java)"
275
+ else:
276
+ stack = " + ".join(sorted(frameworks)) + (" + Kotlin" if has_kotlin else "")
277
+
278
+ unit.abis = sorted(abis)
279
+ unit.frameworks = sorted(frameworks)
280
+ unit.primary_stack = stack
281
+ unit.packer_hints = sorted(packers)
282
+ unit.custom_so_paths = sorted(custom_so)
283
+ unit.framework_so_paths = sorted(fw_so)
284
+ unit.framework_plan = fw_plan
285
+ unit.phase_status["fingerprint"] = "SUCCESS"
286
+
287
+
288
+ class FingerprintPhase(BasePhase):
289
+ name = "fingerprint"
290
+ description = "Detect runtime stack, hybrid frameworks, packers, and classify native libraries"
291
+ metric_label = "Libs"
292
+
293
+ def run(self, ctx: PipelineContext, runner: CommandRunner, phase_idx: str) -> PhaseResult:
294
+ t0 = time.time()
295
+ state = ctx.state
296
+ ui = ctx.ui
297
+ units = state.get_units()
298
+
299
+ ui.begin_phase(phase_idx, "FINGERPRINT", "Python-Static-Detector", metric_label="Libs")
300
+ ui.update_stats(total=len(units))
301
+ ui.push_event("INFO", f"Fingerprinting {len(units)} unit(s)")
302
+ ui.render()
303
+
304
+ succeeded = 0
305
+ for unit in units:
306
+ if runner.interrupted:
307
+ break
308
+ ui.reset_task_timer()
309
+ ui.set_active(
310
+ id=unit.unit_id, name=unit.name, role=unit.role,
311
+ depth=str(unit.depth), hash=unit.sha256, step="SCAN_SIGNATURES"
312
+ )
313
+ ui.render()
314
+
315
+ fingerprint_unit(unit)
316
+ state.upsert_unit(unit)
317
+ succeeded += 1
318
+ total_so = len(unit.custom_so_paths) + len(unit.framework_so_paths)
319
+ ui.inc_stat("success")
320
+ ui.inc_stat("done")
321
+ ui.inc_stat("files_indexed", total_so)
322
+ ui.push_stream(f"[{unit.unit_id}] Stack: {unit.primary_stack}")
323
+ ui.push_event("OK", f"[{unit.unit_id}] {unit.primary_stack}")
324
+ if unit.packer_hints:
325
+ ui.push_event("WARN", f"Packer indicator in {unit.name}")
326
+ ui.render()
327
+
328
+ state.save()
329
+ status = "INTERRUPTED" if runner.interrupted else "COMPLETED"
330
+ dur = time.time() - t0
331
+ summary = {
332
+ "status": status,
333
+ "duration_sec": round(dur, 2),
334
+ "processed": succeeded,
335
+ "succeeded": succeeded,
336
+ "failed": 0,
337
+ "skipped": 0,
338
+ }
339
+ state.set_phase_summary(self.name, summary)
340
+ state.log(self.name, f"Finished fingerprint phase: {status}")
341
+ return PhaseResult(name=self.name, status=status, duration_sec=dur, processed=succeeded, succeeded=succeeded, details=summary)