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.
- dexsect/__init__.py +4 -0
- dexsect/__main__.py +5 -0
- dexsect/catalog/EXTRACTION_CATALOG.json +4057 -0
- dexsect/catalog/__init__.py +0 -0
- dexsect/cli.py +1272 -0
- dexsect/core/__init__.py +0 -0
- dexsect/core/config.py +177 -0
- dexsect/core/context.py +181 -0
- dexsect/core/i18n.py +40 -0
- dexsect/core/pipeline.py +153 -0
- dexsect/core/platform_utils.py +164 -0
- dexsect/core/runner.py +124 -0
- dexsect/core/theme.py +64 -0
- dexsect/core/ui.py +405 -0
- dexsect/core/utils.py +150 -0
- dexsect/inspectors/__init__.py +0 -0
- dexsect/inspectors/assets_db_inspector.py +235 -0
- dexsect/inspectors/base.py +46 -0
- dexsect/inspectors/bundle_inspector.py +55 -0
- dexsect/inspectors/code_inspector.py +341 -0
- dexsect/inspectors/custom_rules_inspector.py +178 -0
- dexsect/inspectors/dex_inspector.py +144 -0
- dexsect/inspectors/manifest_inspector.py +503 -0
- dexsect/inspectors/native_fw_inspector.py +167 -0
- dexsect/inspectors/resources_inspector.py +195 -0
- dexsect/inspectors/scanner_inspector.py +153 -0
- dexsect/inspectors/signing_inspector.py +423 -0
- dexsect/inspectors/text_scanner.py +336 -0
- dexsect/locales/__init__.py +0 -0
- dexsect/locales/ar.json +130 -0
- dexsect/locales/de.json +51 -0
- dexsect/locales/en.json +110 -0
- dexsect/locales/es.json +51 -0
- dexsect/locales/fr.json +51 -0
- dexsect/locales/ja.json +51 -0
- dexsect/locales/pt.json +51 -0
- dexsect/locales/ru.json +51 -0
- dexsect/locales/tr.json +51 -0
- dexsect/locales/zh.json +51 -0
- dexsect/parsers/__init__.py +0 -0
- dexsect/parsers/axml.py +264 -0
- dexsect/parsers/bundle.py +214 -0
- dexsect/parsers/elf.py +396 -0
- dexsect/phases/__init__.py +0 -0
- dexsect/phases/base.py +102 -0
- dexsect/phases/decode.py +507 -0
- dexsect/phases/decompile.py +408 -0
- dexsect/phases/fingerprint.py +341 -0
- dexsect/phases/frameworks.py +377 -0
- dexsect/phases/mapper.py +41 -0
- dexsect/phases/native.py +188 -0
- dexsect/plugins/__init__.py +0 -0
- dexsect/plugins/base.py +20 -0
- dexsect/plugins/diff.py +162 -0
- dexsect/plugins/inspect.py +172 -0
- dexsect/plugins/report.py +80 -0
- dexsect/plugins/trace.py +141 -0
- dexsect/reporting/__init__.py +0 -0
- dexsect/reporting/analysis_report.py +1190 -0
- dexsect/reporting/diff_report.py +144 -0
- dexsect/reporting/sarif_report.py +109 -0
- dexsect/reporting/unpack_map.py +149 -0
- dexsect/rules/__init__.py +0 -0
- dexsect/rules/anti_analysis.json +45 -0
- dexsect/rules/crypto_audit.json +41 -0
- dexsect/rules/secrets_extended.json +46 -0
- dexsect/storage/__init__.py +0 -0
- dexsect/storage/findings_db.py +460 -0
- dexsect-4.1.0.dist-info/METADATA +532 -0
- dexsect-4.1.0.dist-info/RECORD +74 -0
- dexsect-4.1.0.dist-info/WHEEL +5 -0
- dexsect-4.1.0.dist-info/entry_points.txt +2 -0
- dexsect-4.1.0.dist-info/licenses/LICENSE +21 -0
- dexsect-4.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,377 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import re
|
|
3
|
+
import time
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any, Dict, List
|
|
6
|
+
|
|
7
|
+
from ..core.context import ArtifactUnit, PipelineContext
|
|
8
|
+
from ..core.runner import CommandRunner
|
|
9
|
+
from ..core.utils import extract_strings_chunked, pure_js_beautify, safe_slug
|
|
10
|
+
from .base import BasePhase, PhaseResult
|
|
11
|
+
from .fingerprint import fingerprint_unit, inspect_hermes_bytes, inspect_unity_meta_bytes
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
DART_PKG_RE = re.compile(r"package:[a-zA-Z0-9_./\-]+\.dart")
|
|
15
|
+
UNITY_NS_RE = re.compile(r"^[A-Z][a-zA-Z0-9_]*(?:\.[A-Z][a-zA-Z0-9_]*){1,5}$")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
DART_SDK_VER_RE = re.compile(r"(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?\s+\((?:stable|beta|dev)\))")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _extract_sourcemaps(search_dirs: List[Path], out_dir: Path) -> int:
|
|
23
|
+
recovered = 0
|
|
24
|
+
sm_root = out_dir / "sourcemaps_src"
|
|
25
|
+
for sdir in search_dirs:
|
|
26
|
+
if not sdir.is_dir():
|
|
27
|
+
continue
|
|
28
|
+
for map_file in sorted(sdir.rglob("*.map")):
|
|
29
|
+
if not map_file.is_file():
|
|
30
|
+
continue
|
|
31
|
+
try:
|
|
32
|
+
data = json.loads(map_file.read_text(encoding="utf-8", errors="replace"))
|
|
33
|
+
except Exception:
|
|
34
|
+
continue
|
|
35
|
+
sources = data.get("sources")
|
|
36
|
+
contents = data.get("sourcesContent")
|
|
37
|
+
if not isinstance(sources, list) or not isinstance(contents, list):
|
|
38
|
+
continue
|
|
39
|
+
for idx, src_name in enumerate(sources):
|
|
40
|
+
if idx >= len(contents) or not isinstance(contents[idx], str):
|
|
41
|
+
continue
|
|
42
|
+
clean = str(src_name).replace("webpack:///", "").replace("file:///", "").lstrip("/\\")
|
|
43
|
+
parts = [pt for pt in Path(clean).parts if pt not in ("..", ".", "")]
|
|
44
|
+
if not parts:
|
|
45
|
+
parts = [f"source_{idx}.js"]
|
|
46
|
+
dest = sm_root.joinpath(*parts)
|
|
47
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
48
|
+
dest.write_text(contents[idx], encoding="utf-8")
|
|
49
|
+
recovered += 1
|
|
50
|
+
return recovered
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class FrameworksPhase(BasePhase):
|
|
54
|
+
name = "frameworks"
|
|
55
|
+
description = "Unpack and format Flutter, React Native (JS/Hermes), Unity, WebHybrid, and Xamarin artifacts"
|
|
56
|
+
metric_label = "Artifacts"
|
|
57
|
+
|
|
58
|
+
def _unpack_flutter(
|
|
59
|
+
self, ctx: PipelineContext, runner: CommandRunner, uid: str, fw: Dict[str, Any], out_dir: Path
|
|
60
|
+
) -> Dict[str, Any]:
|
|
61
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
62
|
+
outputs: List[str] = []
|
|
63
|
+
tool_used = "built-in"
|
|
64
|
+
|
|
65
|
+
libapps = [Path(p) for p in fw.get("libapp_paths", []) if Path(p).is_file()]
|
|
66
|
+
if libapps:
|
|
67
|
+
target = next((p for p in libapps if "arm64-v8a" in str(p)), libapps[0])
|
|
68
|
+
ctx.ui.push_stream(f"Extracting Dart package index from {target.name}...")
|
|
69
|
+
strings = extract_strings_chunked(target, max_strings=60000)
|
|
70
|
+
dart_pkgs = sorted({m.group(0) for s in strings for m in DART_PKG_RE.finditer(s)})
|
|
71
|
+
pkg_file = out_dir / "dart_packages.txt"
|
|
72
|
+
str_file = out_dir / "libapp_strings.txt"
|
|
73
|
+
pkg_file.write_text("\n".join(dart_pkgs) + "\n", encoding="utf-8")
|
|
74
|
+
str_file.write_text("\n".join(strings) + "\n", encoding="utf-8")
|
|
75
|
+
outputs.extend([str(pkg_file), str(str_file)])
|
|
76
|
+
dart_vers = sorted({m.group(1) for s in strings for m in DART_SDK_VER_RE.finditer(s)})
|
|
77
|
+
meta_f = out_dir / "flutter_metadata.json"
|
|
78
|
+
meta_f.write_text(json.dumps({"dart_sdk_versions": dart_vers, "dart_packages_count": len(dart_pkgs)}, indent=2), encoding="utf-8")
|
|
79
|
+
outputs.append(str(meta_f))
|
|
80
|
+
|
|
81
|
+
blutter = ctx.cfg.tools.get("blutter")
|
|
82
|
+
arm64_dir = next((p.parent for p in libapps if p.parent.name == "arm64-v8a"), None)
|
|
83
|
+
if blutter and blutter.found and arm64_dir:
|
|
84
|
+
blutter_out = out_dir / "blutter_out"
|
|
85
|
+
cmd = (["python3", blutter.path] if blutter.path.endswith(".py") else [blutter.path]) + [
|
|
86
|
+
str(arm64_dir), str(blutter_out)
|
|
87
|
+
]
|
|
88
|
+
tlog = ctx.state.task_log_dir / f"fw_{uid}_blutter.log"
|
|
89
|
+
rc = runner.run_streamed(cmd, tlog, on_line=ctx.ui.push_stream, on_tick=ctx.ui.render)
|
|
90
|
+
tool_used = f"blutter (rc={rc})"
|
|
91
|
+
if rc == 0 and blutter_out.is_dir():
|
|
92
|
+
outputs.append(str(blutter_out))
|
|
93
|
+
|
|
94
|
+
assets_dir = fw.get("flutter_assets")
|
|
95
|
+
if assets_dir and Path(assets_dir).is_dir():
|
|
96
|
+
idx_file = out_dir / "flutter_assets_index.txt"
|
|
97
|
+
idx_list = sorted(p.relative_to(assets_dir).as_posix() for p in Path(assets_dir).rglob("*") if p.is_file())
|
|
98
|
+
idx_file.write_text("\n".join(idx_list) + "\n", encoding="utf-8")
|
|
99
|
+
outputs.append(str(idx_file))
|
|
100
|
+
|
|
101
|
+
return {"framework": "Flutter", "tool": tool_used, "outputs": outputs}
|
|
102
|
+
|
|
103
|
+
def _unpack_react_native(
|
|
104
|
+
self, ctx: PipelineContext, runner: CommandRunner, uid: str, fw: Dict[str, Any], out_dir: Path
|
|
105
|
+
) -> Dict[str, Any]:
|
|
106
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
107
|
+
outputs: List[str] = []
|
|
108
|
+
tools_used: List[str] = []
|
|
109
|
+
|
|
110
|
+
jsb = ctx.cfg.tools.get("js-beautify")
|
|
111
|
+
hbc_dec = ctx.cfg.tools.get("hbc-decompiler")
|
|
112
|
+
hbc_dis = ctx.cfg.tools.get("hbc-disassembler")
|
|
113
|
+
hbctool = ctx.cfg.tools.get("hbctool")
|
|
114
|
+
skip_disasm = ctx.cfg.is_skipped("disasm")
|
|
115
|
+
|
|
116
|
+
for idx, b in enumerate(fw.get("bundles", []), start=1):
|
|
117
|
+
b_path = Path(b.get("path", ""))
|
|
118
|
+
if not b_path.is_file():
|
|
119
|
+
continue
|
|
120
|
+
fmt = b.get("format", "UNKNOWN")
|
|
121
|
+
slug = safe_slug(b_path.name)
|
|
122
|
+
|
|
123
|
+
if fmt == "PLAIN_JS_BUNDLE":
|
|
124
|
+
pretty = out_dir / f"{idx:02d}_{slug}.pretty.js"
|
|
125
|
+
if jsb and jsb.found:
|
|
126
|
+
tlog = ctx.state.task_log_dir / f"fw_{uid}_{slug}_jsb.log"
|
|
127
|
+
rc = runner.run_streamed([jsb.path, "-o", str(pretty), str(b_path)], tlog, on_tick=ctx.ui.render)
|
|
128
|
+
tools_used.append(f"js-beautify(rc={rc})")
|
|
129
|
+
if not pretty.is_file():
|
|
130
|
+
raw = b_path.read_text(encoding="utf-8", errors="replace")
|
|
131
|
+
pretty.write_text(pure_js_beautify(raw), encoding="utf-8")
|
|
132
|
+
tools_used.append("built-in-js-formatter")
|
|
133
|
+
outputs.append(str(pretty))
|
|
134
|
+
|
|
135
|
+
elif fmt == "HERMES_BYTECODE":
|
|
136
|
+
hver = b.get("hermes_version")
|
|
137
|
+
ctx.ui.push_stream(f"Unpacking Hermes v{hver}: {b_path.name}")
|
|
138
|
+
strings = extract_strings_chunked(b_path, max_strings=60000)
|
|
139
|
+
s_file = out_dir / f"{idx:02d}_{slug}_strings.txt"
|
|
140
|
+
s_file.write_text("\n".join(strings) + "\n", encoding="utf-8")
|
|
141
|
+
outputs.append(str(s_file))
|
|
142
|
+
|
|
143
|
+
if hbc_dec and hbc_dec.found:
|
|
144
|
+
dec_js = out_dir / f"{idx:02d}_{slug}_decompiled.js"
|
|
145
|
+
tlog = ctx.state.task_log_dir / f"fw_{uid}_{slug}_hbcdec.log"
|
|
146
|
+
rc = runner.run_streamed([hbc_dec.path, str(b_path), str(dec_js)], tlog, on_line=ctx.ui.push_stream, on_tick=ctx.ui.render)
|
|
147
|
+
tools_used.append(f"hbc-decompiler(rc={rc})")
|
|
148
|
+
if dec_js.is_file():
|
|
149
|
+
outputs.append(str(dec_js))
|
|
150
|
+
elif hbctool and hbctool.found:
|
|
151
|
+
dis_dir = out_dir / f"{idx:02d}_{slug}_hbctool"
|
|
152
|
+
tlog = ctx.state.task_log_dir / f"fw_{uid}_{slug}_hbctool.log"
|
|
153
|
+
rc = runner.run_streamed([hbctool.path, "disasm", str(b_path), str(dis_dir)], tlog, on_line=ctx.ui.push_stream, on_tick=ctx.ui.render)
|
|
154
|
+
tools_used.append(f"hbctool(rc={rc})")
|
|
155
|
+
if dis_dir.is_dir():
|
|
156
|
+
outputs.append(str(dis_dir))
|
|
157
|
+
|
|
158
|
+
if not skip_disasm and hbc_dis and hbc_dis.found and not runner.interrupted:
|
|
159
|
+
hasm = out_dir / f"{idx:02d}_{slug}.hasm"
|
|
160
|
+
tlog = ctx.state.task_log_dir / f"fw_{uid}_{slug}_hbcdis.log"
|
|
161
|
+
rc = runner.run_streamed([hbc_dis.path, str(b_path), str(hasm)], tlog, on_line=ctx.ui.push_stream, on_tick=ctx.ui.render)
|
|
162
|
+
tools_used.append(f"hbc-disassembler(rc={rc})")
|
|
163
|
+
if hasm.is_file():
|
|
164
|
+
outputs.append(str(hasm))
|
|
165
|
+
|
|
166
|
+
bundle_dirs = list({Path(b["path"]).parent for b in fw.get("bundles", []) if b.get("path") and Path(b["path"]).is_file()})
|
|
167
|
+
sm_cnt = _extract_sourcemaps(bundle_dirs, out_dir)
|
|
168
|
+
if sm_cnt > 0:
|
|
169
|
+
outputs.append(str(out_dir / "sourcemaps_src"))
|
|
170
|
+
return {"framework": "ReactNative", "tool": ", ".join(tools_used) or "built-in", "outputs": outputs, "sourcemaps_recovered": sm_cnt}
|
|
171
|
+
|
|
172
|
+
def _unpack_unity_il2cpp(
|
|
173
|
+
self, ctx: PipelineContext, runner: CommandRunner, uid: str, fw: Dict[str, Any], out_dir: Path
|
|
174
|
+
) -> Dict[str, Any]:
|
|
175
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
176
|
+
outputs: List[str] = []
|
|
177
|
+
tool_used = "built-in"
|
|
178
|
+
|
|
179
|
+
meta_str = fw.get("global_metadata")
|
|
180
|
+
meta_info = fw.get("metadata_info", {})
|
|
181
|
+
libs = [Path(p) for p in fw.get("libil2cpp_paths", []) if Path(p).is_file()]
|
|
182
|
+
|
|
183
|
+
if meta_str and Path(meta_str).is_file() and not meta_info.get("encrypted"):
|
|
184
|
+
meta_file = Path(meta_str)
|
|
185
|
+
strings = extract_strings_chunked(meta_file, max_strings=80000)
|
|
186
|
+
namespaces = sorted({s for s in strings if UNITY_NS_RE.match(s)})
|
|
187
|
+
ns_file = out_dir / "il2cpp_namespaces.txt"
|
|
188
|
+
st_file = out_dir / "il2cpp_strings.txt"
|
|
189
|
+
ns_file.write_text("\n".join(namespaces) + "\n", encoding="utf-8")
|
|
190
|
+
st_file.write_text("\n".join(strings) + "\n", encoding="utf-8")
|
|
191
|
+
outputs.extend([str(ns_file), str(st_file)])
|
|
192
|
+
|
|
193
|
+
dumper = ctx.cfg.tools.get("Il2CppDumper")
|
|
194
|
+
if dumper and dumper.found and libs:
|
|
195
|
+
target_so = next((p for p in libs if "arm64-v8a" in str(p)), libs[0])
|
|
196
|
+
dump_dir = out_dir / "il2cpp_dump"
|
|
197
|
+
dump_dir.mkdir(parents=True, exist_ok=True)
|
|
198
|
+
tlog = ctx.state.task_log_dir / f"fw_{uid}_il2cpp.log"
|
|
199
|
+
rc = runner.run_streamed([dumper.path, str(target_so), str(meta_file), str(dump_dir)], tlog, on_line=ctx.ui.push_stream, on_tick=ctx.ui.render)
|
|
200
|
+
tool_used = f"Il2CppDumper(rc={rc})"
|
|
201
|
+
if dump_dir.is_dir():
|
|
202
|
+
outputs.append(str(dump_dir))
|
|
203
|
+
|
|
204
|
+
return {"framework": "Unity_IL2CPP", "tool": tool_used, "outputs": outputs}
|
|
205
|
+
|
|
206
|
+
def _unpack_dotnet(
|
|
207
|
+
self, ctx: PipelineContext, runner: CommandRunner, uid: str, label: str, fw: Dict[str, Any], out_dir: Path
|
|
208
|
+
) -> Dict[str, Any]:
|
|
209
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
210
|
+
outputs: List[str] = []
|
|
211
|
+
tool_used = "built-in"
|
|
212
|
+
|
|
213
|
+
dll_paths = [Path(p) for p in fw.get("dll_paths", []) if Path(p).is_file()]
|
|
214
|
+
inv = out_dir / "dll_inventory.txt"
|
|
215
|
+
inv.write_text("\n".join(sorted(p.name for p in dll_paths)) + "\n", encoding="utf-8")
|
|
216
|
+
outputs.append(str(inv))
|
|
217
|
+
|
|
218
|
+
sys_pref = ("System.", "Mono.", "mscorlib", "netstandard", "Microsoft.", "UnityEngine.", "Unity.")
|
|
219
|
+
custom_dlls = [p for p in dll_paths if not p.name.startswith(sys_pref)]
|
|
220
|
+
ilspy = ctx.cfg.tools.get("ilspycmd")
|
|
221
|
+
|
|
222
|
+
for dll in custom_dlls[:15]:
|
|
223
|
+
if ilspy and ilspy.found and not runner.interrupted:
|
|
224
|
+
cs_out = out_dir / "decompiled_cs" / dll.stem
|
|
225
|
+
cs_out.mkdir(parents=True, exist_ok=True)
|
|
226
|
+
tlog = ctx.state.task_log_dir / f"fw_{uid}_{safe_slug(dll.stem)}_ilspy.log"
|
|
227
|
+
rc = runner.run_streamed([ilspy.path, "-p", "-o", str(cs_out), str(dll)], tlog, on_tick=ctx.ui.render)
|
|
228
|
+
tool_used = f"ilspycmd(rc={rc})"
|
|
229
|
+
outputs.append(str(cs_out))
|
|
230
|
+
|
|
231
|
+
return {"framework": label, "tool": tool_used, "outputs": outputs}
|
|
232
|
+
|
|
233
|
+
def _unpack_web(self, ctx: PipelineContext, runner: CommandRunner, uid: str, fw: Dict[str, Any], out_dir: Path) -> Dict[str, Any]:
|
|
234
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
235
|
+
fmt_dir = out_dir / "formatted_js"
|
|
236
|
+
fmt_dir.mkdir(parents=True, exist_ok=True)
|
|
237
|
+
jsb = ctx.cfg.tools.get("js-beautify")
|
|
238
|
+
formatted_cnt = 0
|
|
239
|
+
|
|
240
|
+
for wd_str in fw.get("web_dirs", []):
|
|
241
|
+
wd = Path(wd_str)
|
|
242
|
+
if not wd.is_dir():
|
|
243
|
+
continue
|
|
244
|
+
for fpath in sorted(wd.rglob("*")):
|
|
245
|
+
if fpath.is_file() and fpath.suffix.lower() in (".js", ".mjs"):
|
|
246
|
+
dest = fmt_dir / fpath.relative_to(wd)
|
|
247
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
248
|
+
if jsb and jsb.found:
|
|
249
|
+
tlog = ctx.state.task_log_dir / f"fw_{uid}_webjsb.log"
|
|
250
|
+
runner.run_streamed([jsb.path, "-o", str(dest), str(fpath)], tlog, on_tick=ctx.ui.render)
|
|
251
|
+
if not dest.is_file():
|
|
252
|
+
dest.write_text(pure_js_beautify(fpath.read_text(encoding="utf-8", errors="replace")), encoding="utf-8")
|
|
253
|
+
formatted_cnt += 1
|
|
254
|
+
|
|
255
|
+
sm_cnt = _extract_sourcemaps([Path(w) for w in fw.get("web_dirs", [])], out_dir)
|
|
256
|
+
outs = [str(fmt_dir)]
|
|
257
|
+
if sm_cnt > 0:
|
|
258
|
+
outs.append(str(out_dir / "sourcemaps_src"))
|
|
259
|
+
return {"framework": "WebHybrid", "tool": "js-beautify/built-in", "outputs": outs, "js_formatted": formatted_cnt, "sourcemaps_recovered": sm_cnt}
|
|
260
|
+
|
|
261
|
+
def _build_standalone_plan(self, unit: ArtifactUnit) -> None:
|
|
262
|
+
src = Path(unit.source_path)
|
|
263
|
+
if not src.exists():
|
|
264
|
+
return
|
|
265
|
+
if src.is_dir():
|
|
266
|
+
if (src / "flutter_assets").is_dir() or any(src.glob("**/libapp.so")):
|
|
267
|
+
unit.framework_plan = [{"framework": "Flutter", "libapp_paths": [str(p) for p in src.rglob("libapp.so")], "flutter_assets": str(src / "flutter_assets")}]
|
|
268
|
+
elif any(src.glob("**/*.js")) or any(src.glob("**/*.html")):
|
|
269
|
+
unit.framework_plan = [{"framework": "WebHybrid", "web_dirs": [str(src)]}]
|
|
270
|
+
return
|
|
271
|
+
|
|
272
|
+
low = src.name.lower()
|
|
273
|
+
if low == "index.android.bundle" or src.suffix.lower() in (".bundle", ".hbc"):
|
|
274
|
+
with src.open("rb") as f:
|
|
275
|
+
b_info = inspect_hermes_bytes(f.read(16))
|
|
276
|
+
b_info.update({"path": str(src), "rel_path": src.name})
|
|
277
|
+
unit.framework_plan = [{"framework": "ReactNative", "bundles": [b_info]}]
|
|
278
|
+
elif low == "libapp.so":
|
|
279
|
+
unit.framework_plan = [{"framework": "Flutter", "mode": "AOT_RELEASE", "libapp_paths": [str(src)], "flutter_assets": None}]
|
|
280
|
+
elif low == "global-metadata.dat":
|
|
281
|
+
with src.open("rb") as f:
|
|
282
|
+
m_info = inspect_unity_meta_bytes(f.read(8))
|
|
283
|
+
unit.framework_plan = [{"framework": "Unity_IL2CPP", "libil2cpp_paths": [], "global_metadata": str(src), "metadata_info": m_info}]
|
|
284
|
+
elif src.suffix.lower() == ".dll":
|
|
285
|
+
unit.framework_plan = [{"framework": "Xamarin", "dll_paths": [str(src)], "blobs": []}]
|
|
286
|
+
|
|
287
|
+
def run(self, ctx: PipelineContext, runner: CommandRunner, phase_idx: str) -> PhaseResult:
|
|
288
|
+
t0 = time.time()
|
|
289
|
+
state = ctx.state
|
|
290
|
+
ui = ctx.ui
|
|
291
|
+
fw_root = state.root / "05_Frameworks"
|
|
292
|
+
fw_root.mkdir(parents=True, exist_ok=True)
|
|
293
|
+
units = state.get_units()
|
|
294
|
+
|
|
295
|
+
ui.begin_phase(phase_idx, "FRAMEWORKS UNPACK", "Hybrid-Unpackers", metric_label="Outputs")
|
|
296
|
+
ui.update_stats(total=len(units))
|
|
297
|
+
ui.render()
|
|
298
|
+
|
|
299
|
+
processed = succeeded = skipped = 0
|
|
300
|
+
for unit in units:
|
|
301
|
+
if runner.interrupted:
|
|
302
|
+
break
|
|
303
|
+
|
|
304
|
+
if not unit.framework_plan and not unit.phase_status.get("fingerprint"):
|
|
305
|
+
if unit.role == "STANDALONE" or Path(unit.source_path).is_dir():
|
|
306
|
+
self._build_standalone_plan(unit)
|
|
307
|
+
if not unit.framework_plan:
|
|
308
|
+
fingerprint_unit(unit)
|
|
309
|
+
|
|
310
|
+
ui.reset_task_timer()
|
|
311
|
+
ui.set_active(
|
|
312
|
+
id=unit.unit_id, name=unit.name, role=unit.role,
|
|
313
|
+
depth=str(unit.depth), hash=unit.sha256, step="CHECK_PLAN"
|
|
314
|
+
)
|
|
315
|
+
ui.render()
|
|
316
|
+
|
|
317
|
+
if not unit.framework_plan:
|
|
318
|
+
skipped += 1
|
|
319
|
+
processed += 1
|
|
320
|
+
ui.inc_stat("skipped")
|
|
321
|
+
ui.inc_stat("done")
|
|
322
|
+
unit.phase_status["frameworks"] = "SKIPPED_NATIVE"
|
|
323
|
+
state.upsert_unit(unit)
|
|
324
|
+
ui.push_event("INFO", f"Skipped (Native): {unit.name}")
|
|
325
|
+
continue
|
|
326
|
+
|
|
327
|
+
out_root = fw_root / f"{unit.unit_id}_{safe_slug(unit.name)}"
|
|
328
|
+
fw_results: List[Dict[str, Any]] = []
|
|
329
|
+
|
|
330
|
+
for fw in unit.framework_plan:
|
|
331
|
+
if runner.interrupted:
|
|
332
|
+
break
|
|
333
|
+
ftype = fw.get("framework")
|
|
334
|
+
ui.set_active(step=f"UNPACK_{ftype}")
|
|
335
|
+
ui.render()
|
|
336
|
+
|
|
337
|
+
if ftype == "Flutter":
|
|
338
|
+
res = self._unpack_flutter(ctx, runner, unit.unit_id, fw, out_root / "flutter")
|
|
339
|
+
elif ftype == "ReactNative":
|
|
340
|
+
res = self._unpack_react_native(ctx, runner, unit.unit_id, fw, out_root / "react_native")
|
|
341
|
+
elif ftype == "Unity_IL2CPP":
|
|
342
|
+
res = self._unpack_unity_il2cpp(ctx, runner, unit.unit_id, fw, out_root / "unity_il2cpp")
|
|
343
|
+
elif ftype in ("Unity_Mono", "Xamarin"):
|
|
344
|
+
res = self._unpack_dotnet(ctx, runner, unit.unit_id, ftype, fw, out_root / ftype.lower())
|
|
345
|
+
elif ftype == "WebHybrid":
|
|
346
|
+
res = self._unpack_web(ctx, runner, unit.unit_id, fw, out_root / "web_hybrid")
|
|
347
|
+
else:
|
|
348
|
+
res = {"framework": ftype, "tool": "none", "outputs": []}
|
|
349
|
+
|
|
350
|
+
fw_results.append(res)
|
|
351
|
+
ui.inc_stat("files_indexed", len(res.get("outputs", [])))
|
|
352
|
+
ui.push_event("OK", f"[{unit.unit_id}] {ftype} ({res.get('tool')})")
|
|
353
|
+
|
|
354
|
+
unit.frameworks_dir = str(out_root)
|
|
355
|
+
unit.metrics["framework_outputs"] = fw_results
|
|
356
|
+
unit.phase_status["frameworks"] = "SUCCESS"
|
|
357
|
+
state.upsert_unit(unit)
|
|
358
|
+
state.save()
|
|
359
|
+
succeeded += 1
|
|
360
|
+
processed += 1
|
|
361
|
+
ui.inc_stat("success")
|
|
362
|
+
ui.inc_stat("done")
|
|
363
|
+
ui.render()
|
|
364
|
+
|
|
365
|
+
status = "INTERRUPTED" if runner.interrupted else "COMPLETED"
|
|
366
|
+
dur = time.time() - t0
|
|
367
|
+
summary = {
|
|
368
|
+
"status": status,
|
|
369
|
+
"duration_sec": round(dur, 2),
|
|
370
|
+
"processed": processed,
|
|
371
|
+
"succeeded": succeeded,
|
|
372
|
+
"failed": 0,
|
|
373
|
+
"skipped": skipped,
|
|
374
|
+
}
|
|
375
|
+
state.set_phase_summary(self.name, summary)
|
|
376
|
+
state.log(self.name, f"Finished frameworks phase: {status}")
|
|
377
|
+
return PhaseResult(name=self.name, status=status, duration_sec=dur, processed=processed, succeeded=succeeded, skipped=skipped, details=summary)
|
dexsect/phases/mapper.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import time
|
|
2
|
+
|
|
3
|
+
from ..core.context import PipelineContext
|
|
4
|
+
from ..core.runner import CommandRunner
|
|
5
|
+
from ..reporting.unpack_map import generate_unpack_maps
|
|
6
|
+
from .base import BasePhase, PhaseResult
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class MapPhase(BasePhase):
|
|
10
|
+
name = "map"
|
|
11
|
+
description = "Generate workspace.json index and UNPACK_MAP.txt / UNPACK_MAP.md"
|
|
12
|
+
metric_label = "Maps"
|
|
13
|
+
|
|
14
|
+
def run(self, ctx: PipelineContext, runner: CommandRunner, phase_idx: str) -> PhaseResult:
|
|
15
|
+
t0 = time.time()
|
|
16
|
+
ui = ctx.ui
|
|
17
|
+
state = ctx.state
|
|
18
|
+
|
|
19
|
+
ui.begin_phase(phase_idx, "UNPACK MAP", "Workspace-Mapper", metric_label="Maps")
|
|
20
|
+
ui.update_stats(total=1)
|
|
21
|
+
ui.set_active(id="MAP", name="UNPACK_MAP", role="INDEX", depth="0", hash=state.data.get("input_kind", "-"), step="WRITE_MAPS")
|
|
22
|
+
ui.render()
|
|
23
|
+
|
|
24
|
+
state.save()
|
|
25
|
+
maps = generate_unpack_maps(state)
|
|
26
|
+
|
|
27
|
+
dur = time.time() - t0
|
|
28
|
+
ui.inc_stat("success")
|
|
29
|
+
ui.inc_stat("done")
|
|
30
|
+
ui.inc_stat("files_indexed", len(maps))
|
|
31
|
+
ui.push_event("OK", f"Generated {maps['txt'].name} & {maps['md'].name}")
|
|
32
|
+
ui.render()
|
|
33
|
+
|
|
34
|
+
summary = {
|
|
35
|
+
"status": "COMPLETED",
|
|
36
|
+
"duration_sec": round(dur, 2),
|
|
37
|
+
"txt_map": str(maps["txt"]),
|
|
38
|
+
"md_map": str(maps["md"]),
|
|
39
|
+
}
|
|
40
|
+
state.set_phase_summary(self.name, summary)
|
|
41
|
+
return PhaseResult(name=self.name, status="COMPLETED", duration_sec=dur, processed=1, succeeded=1, details=summary)
|
dexsect/phases/native.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
import time
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any, Dict, List
|
|
6
|
+
|
|
7
|
+
from ..core.context import ArtifactUnit, PipelineContext
|
|
8
|
+
from ..core.runner import CommandRunner
|
|
9
|
+
from ..core.utils import extract_strings_chunked, safe_slug
|
|
10
|
+
from ..parsers.elf import ELF_MAGIC, parse_elf
|
|
11
|
+
from .base import BasePhase, PhaseResult
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
KNOWN_ABIS = {"arm64-v8a", "armeabi-v7a", "armeabi", "x86", "x86_64", "riscv64"}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _is_elf(path: Path) -> bool:
|
|
18
|
+
try:
|
|
19
|
+
with path.open("rb") as f:
|
|
20
|
+
return f.read(4) == ELF_MAGIC
|
|
21
|
+
except OSError:
|
|
22
|
+
return False
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _location_bucket(so_path: Path, decode_dir: Path) -> str:
|
|
26
|
+
try:
|
|
27
|
+
rel_parts = so_path.relative_to(decode_dir).parts
|
|
28
|
+
if len(rel_parts) >= 3 and rel_parts[0] == "lib" and rel_parts[1] in KNOWN_ABIS:
|
|
29
|
+
return rel_parts[1]
|
|
30
|
+
if len(rel_parts) >= 2:
|
|
31
|
+
return safe_slug("_".join(rel_parts[:-1]), max_len=40)
|
|
32
|
+
except ValueError:
|
|
33
|
+
pass
|
|
34
|
+
return so_path.parent.name or "native"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class NativePhase(BasePhase):
|
|
38
|
+
name = "native"
|
|
39
|
+
description = "Unpack ELF32/64 metadata, DT_NEEDED, symbols, demangled JNI exports, and raw strings"
|
|
40
|
+
metric_label = "Libs"
|
|
41
|
+
|
|
42
|
+
def _gather_so_files(self, unit: ArtifactUnit, include_all_so: bool) -> List[Path]:
|
|
43
|
+
src = Path(unit.source_path) if unit.source_path else None
|
|
44
|
+
if src and src.is_file() and (src.suffix.lower() == ".so" or _is_elf(src)):
|
|
45
|
+
return [src]
|
|
46
|
+
|
|
47
|
+
if not include_all_so and unit.custom_so_paths:
|
|
48
|
+
existing = [Path(p) for p in unit.custom_so_paths if Path(p).is_file()]
|
|
49
|
+
if existing:
|
|
50
|
+
return existing
|
|
51
|
+
|
|
52
|
+
dec = Path(unit.decode_dir) if unit.decode_dir else None
|
|
53
|
+
found: List[Path] = []
|
|
54
|
+
scan_root = dec if (dec and dec.is_dir()) else (src if (src and src.is_dir()) else None)
|
|
55
|
+
if scan_root:
|
|
56
|
+
for root, _dirs, files in os.walk(scan_root):
|
|
57
|
+
rel_root = Path(root).relative_to(scan_root).as_posix()
|
|
58
|
+
if rel_root.startswith(("smali", "res", "META-INF")):
|
|
59
|
+
continue
|
|
60
|
+
for fn in sorted(files):
|
|
61
|
+
p = Path(root) / fn
|
|
62
|
+
if fn.lower().endswith(".so") or (p.suffix == "" and p.stat().st_size >= 64 and _is_elf(p)):
|
|
63
|
+
found.append(p)
|
|
64
|
+
return sorted(set(found))
|
|
65
|
+
|
|
66
|
+
def run(self, ctx: PipelineContext, runner: CommandRunner, phase_idx: str) -> PhaseResult:
|
|
67
|
+
t0 = time.time()
|
|
68
|
+
cfg = ctx.cfg
|
|
69
|
+
state = ctx.state
|
|
70
|
+
ui = ctx.ui
|
|
71
|
+
native_root = state.root / "06_Native_Libs"
|
|
72
|
+
native_root.mkdir(parents=True, exist_ok=True)
|
|
73
|
+
skip_strings = cfg.is_skipped("so-strings")
|
|
74
|
+
|
|
75
|
+
units = state.get_units()
|
|
76
|
+
work_items = []
|
|
77
|
+
for unit in units:
|
|
78
|
+
so_list = self._gather_so_files(unit, cfg.all_so)
|
|
79
|
+
if so_list:
|
|
80
|
+
work_items.append((unit, so_list))
|
|
81
|
+
|
|
82
|
+
total_libs = sum(len(lst) for _, lst in work_items)
|
|
83
|
+
ui.begin_phase(phase_idx, "NATIVE ELF UNPACK", "Python-ELF32/64", metric_label="Libs")
|
|
84
|
+
ui.update_stats(total=total_libs)
|
|
85
|
+
ui.push_event("INFO", f"Queued {total_libs} native ELF/.so library(s)")
|
|
86
|
+
ui.render()
|
|
87
|
+
|
|
88
|
+
if total_libs == 0:
|
|
89
|
+
state.log(self.name, "No .so/ELF libraries found in lib/, assets/, jniLibs/, or unknown/.")
|
|
90
|
+
|
|
91
|
+
processed = succeeded = total_jni = 0
|
|
92
|
+
for unit, so_list in work_items:
|
|
93
|
+
if runner.interrupted:
|
|
94
|
+
break
|
|
95
|
+
|
|
96
|
+
dec = Path(unit.decode_dir) if unit.decode_dir else Path(unit.source_path).parent
|
|
97
|
+
unit_out = native_root / f"{unit.unit_id}_{safe_slug(unit.name)}"
|
|
98
|
+
lib_summaries: List[Dict[str, Any]] = []
|
|
99
|
+
|
|
100
|
+
for so_path in so_list:
|
|
101
|
+
if runner.interrupted:
|
|
102
|
+
break
|
|
103
|
+
bucket = _location_bucket(so_path, dec)
|
|
104
|
+
lib_out = unit_out / bucket / safe_slug(so_path.name)
|
|
105
|
+
lib_out.mkdir(parents=True, exist_ok=True)
|
|
106
|
+
|
|
107
|
+
ui.reset_task_timer()
|
|
108
|
+
ui.set_active(
|
|
109
|
+
id=unit.unit_id, name=so_path.name, role=bucket,
|
|
110
|
+
depth=str(unit.depth), hash=unit.sha256, step="ELF_SYMBOLS",
|
|
111
|
+
)
|
|
112
|
+
ui.push_stream(f"Unpacking ELF: {so_path.name} ({bucket})")
|
|
113
|
+
ui.render()
|
|
114
|
+
|
|
115
|
+
elf = parse_elf(so_path)
|
|
116
|
+
(lib_out / "elf_info.json").write_text(json.dumps(elf, indent=2), encoding="utf-8")
|
|
117
|
+
|
|
118
|
+
jni_lines = [f"{j['symbol']} -> {j['demangled']}" for j in elf["jni_exports"]]
|
|
119
|
+
(lib_out / "jni_exports.txt").write_text(
|
|
120
|
+
"\n".join(jni_lines) + ("\n" if jni_lines else ""), encoding="utf-8"
|
|
121
|
+
)
|
|
122
|
+
(lib_out / "exports.txt").write_text("\n".join(elf["exported_functions"]) + "\n", encoding="utf-8")
|
|
123
|
+
(lib_out / "imports.txt").write_text("\n".join(elf["imported_functions"]) + "\n", encoding="utf-8")
|
|
124
|
+
|
|
125
|
+
str_cnt = 0
|
|
126
|
+
if not skip_strings:
|
|
127
|
+
ui.set_active(step="ELF_STRINGS")
|
|
128
|
+
ui.render()
|
|
129
|
+
strings = extract_strings_chunked(so_path, max_strings=40000)
|
|
130
|
+
str_cnt = len(strings)
|
|
131
|
+
(lib_out / "strings.txt").write_text("\n".join(strings) + "\n", encoding="utf-8")
|
|
132
|
+
|
|
133
|
+
lib_summaries.append({
|
|
134
|
+
"name": so_path.name,
|
|
135
|
+
"location": bucket,
|
|
136
|
+
"source_path": str(so_path),
|
|
137
|
+
"size_bytes": elf["size_bytes"],
|
|
138
|
+
"valid_elf": elf["valid_elf"],
|
|
139
|
+
"machine": elf["machine"],
|
|
140
|
+
"build_id": elf["build_id"],
|
|
141
|
+
"stripped": elf["stripped"],
|
|
142
|
+
"needed_libs": elf["needed_libs"],
|
|
143
|
+
"jni_count": len(elf["jni_exports"]),
|
|
144
|
+
"exported_count": len(elf["exported_functions"]),
|
|
145
|
+
"imported_count": len(elf["imported_functions"]),
|
|
146
|
+
"strings_count": str_cnt,
|
|
147
|
+
"output_dir": str(lib_out),
|
|
148
|
+
})
|
|
149
|
+
|
|
150
|
+
processed += 1
|
|
151
|
+
succeeded += 1
|
|
152
|
+
total_jni += len(elf["jni_exports"])
|
|
153
|
+
ui.inc_stat("success")
|
|
154
|
+
ui.inc_stat("done")
|
|
155
|
+
ui.inc_stat("files_indexed", 1)
|
|
156
|
+
ui.inc_stat("bytes_indexed", elf["size_bytes"])
|
|
157
|
+
if elf["jni_exports"]:
|
|
158
|
+
ui.push_event("FOUND", f"{so_path.name}: {len(elf['jni_exports'])} JNI symbols")
|
|
159
|
+
else:
|
|
160
|
+
ui.push_event("OK", f"{so_path.name} ({elf['machine']})")
|
|
161
|
+
ui.render()
|
|
162
|
+
|
|
163
|
+
unit.native_dir = str(unit_out)
|
|
164
|
+
unit.metrics["native_libs_unpacked"] = lib_summaries
|
|
165
|
+
unit.phase_status["native"] = "SUCCESS"
|
|
166
|
+
state.upsert_unit(unit)
|
|
167
|
+
state.save()
|
|
168
|
+
|
|
169
|
+
processed_ids = {u.unit_id for u, _ in work_items}
|
|
170
|
+
for unit in units:
|
|
171
|
+
if unit.unit_id not in processed_ids:
|
|
172
|
+
unit.phase_status["native"] = "SKIPPED_NO_SO"
|
|
173
|
+
state.upsert_unit(unit)
|
|
174
|
+
state.save()
|
|
175
|
+
|
|
176
|
+
status = "INTERRUPTED" if runner.interrupted else "COMPLETED"
|
|
177
|
+
dur = time.time() - t0
|
|
178
|
+
summary = {
|
|
179
|
+
"status": status,
|
|
180
|
+
"duration_sec": round(dur, 2),
|
|
181
|
+
"libs_processed": processed,
|
|
182
|
+
"succeeded": succeeded,
|
|
183
|
+
"total_jni_symbols": total_jni,
|
|
184
|
+
"all_so_mode": cfg.all_so,
|
|
185
|
+
}
|
|
186
|
+
state.set_phase_summary(self.name, summary)
|
|
187
|
+
state.log(self.name, f"Finished native phase: {status} ({processed} libs)")
|
|
188
|
+
return PhaseResult(name=self.name, status=status, duration_sec=dur, processed=processed, succeeded=succeeded, details=summary)
|
|
File without changes
|
dexsect/plugins/base.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
from typing import Any, Dict
|
|
3
|
+
|
|
4
|
+
from ..core.context import PipelineContext
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class BaseAnalysisPlugin(ABC):
|
|
8
|
+
"""
|
|
9
|
+
Extension hook reserved for future Deep Inspection & Reporting engines.
|
|
10
|
+
Future plugins (e.g., Manifest Auditor, Secret/URL Scanner, HTML Reporter)
|
|
11
|
+
subclass this interface and read directly from ctx.state (workspace.json).
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
name: str = "base_plugin"
|
|
15
|
+
description: str = ""
|
|
16
|
+
|
|
17
|
+
@abstractmethod
|
|
18
|
+
def execute(self, ctx: PipelineContext) -> Dict[str, Any]:
|
|
19
|
+
"""Run analysis/reporting over the unpacked WorkspaceState."""
|
|
20
|
+
raise NotImplementedError
|