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
dexsect/phases/base.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from abc import ABC, abstractmethod
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any, Dict, List
|
|
6
|
+
|
|
7
|
+
from ..core.context import ArtifactUnit, PipelineContext, WorkspaceState
|
|
8
|
+
from ..core.runner import CommandRunner
|
|
9
|
+
from ..core.utils import compute_sha256, count_tree
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass
|
|
13
|
+
class PhaseResult:
|
|
14
|
+
name: str
|
|
15
|
+
status: str # COMPLETED, PARTIAL, SKIPPED, INTERRUPTED, FAILED
|
|
16
|
+
duration_sec: float = 0.0
|
|
17
|
+
processed: int = 0
|
|
18
|
+
succeeded: int = 0
|
|
19
|
+
failed: int = 0
|
|
20
|
+
skipped: int = 0
|
|
21
|
+
details: Dict[str, Any] = field(default_factory=dict)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class BasePhase(ABC):
|
|
25
|
+
name: str = "base"
|
|
26
|
+
description: str = ""
|
|
27
|
+
metric_label: str = "Files"
|
|
28
|
+
|
|
29
|
+
@abstractmethod
|
|
30
|
+
def run(self, ctx: PipelineContext, runner: CommandRunner, phase_idx: str) -> PhaseResult:
|
|
31
|
+
raise NotImplementedError
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def bootstrap_external_target(state: WorkspaceState, target: Path) -> None:
|
|
35
|
+
"""
|
|
36
|
+
Populate WorkspaceState when the user supplies an externally unpacked directory
|
|
37
|
+
or a standalone file (.dex, .so, .bundle, etc.) without a prior decode run.
|
|
38
|
+
"""
|
|
39
|
+
if state.get_units():
|
|
40
|
+
return
|
|
41
|
+
|
|
42
|
+
if target.is_dir():
|
|
43
|
+
# Check if directory itself is an unpacked APK folder (has AndroidManifest.xml or smali or lib or assets)
|
|
44
|
+
is_apk_root = any(
|
|
45
|
+
(target / marker).exists()
|
|
46
|
+
for marker in ("AndroidManifest.xml", "apktool.yml", "smali", "lib", "assets")
|
|
47
|
+
)
|
|
48
|
+
if is_apk_root:
|
|
49
|
+
f_cnt, b_tot = count_tree(target)
|
|
50
|
+
manifest_p = target / "AndroidManifest.xml"
|
|
51
|
+
yml_p = target / "apktool.yml"
|
|
52
|
+
unit = ArtifactUnit(
|
|
53
|
+
unit_id="0001",
|
|
54
|
+
role="EXTERNAL_DIR",
|
|
55
|
+
name=target.name,
|
|
56
|
+
depth=0,
|
|
57
|
+
sha256="external_dir",
|
|
58
|
+
source_path=str(target),
|
|
59
|
+
decode_dir=str(target),
|
|
60
|
+
manifest_xml=str(manifest_p) if manifest_p.is_file() else "",
|
|
61
|
+
apktool_yml=str(yml_p) if yml_p.is_file() else "",
|
|
62
|
+
phase_status={"decode": "EXTERNAL"},
|
|
63
|
+
metrics={"files_count": f_cnt, "bytes_total": b_tot},
|
|
64
|
+
)
|
|
65
|
+
state.upsert_unit(unit)
|
|
66
|
+
state.data["input_kind"] = "EXTERNAL_DECODED_DIR"
|
|
67
|
+
state.save()
|
|
68
|
+
return
|
|
69
|
+
|
|
70
|
+
# Otherwise scan subdirectories for .apk / .dex / .so files
|
|
71
|
+
discovered: List[Path] = []
|
|
72
|
+
for entry in sorted(target.rglob("*")):
|
|
73
|
+
if entry.is_file() and entry.suffix.lower() in (".apk", ".dex", ".so"):
|
|
74
|
+
discovered.append(entry)
|
|
75
|
+
for p in discovered[:100]:
|
|
76
|
+
uid = state.next_unit_id()
|
|
77
|
+
unit = ArtifactUnit(
|
|
78
|
+
unit_id=uid,
|
|
79
|
+
role="STANDALONE",
|
|
80
|
+
name=p.stem,
|
|
81
|
+
depth=0,
|
|
82
|
+
sha256=compute_sha256(p),
|
|
83
|
+
source_path=str(p),
|
|
84
|
+
)
|
|
85
|
+
state.upsert_unit(unit)
|
|
86
|
+
state.data["input_kind"] = "EXTERNAL_DIR"
|
|
87
|
+
state.save()
|
|
88
|
+
return
|
|
89
|
+
|
|
90
|
+
if target.is_file():
|
|
91
|
+
uid = state.next_unit_id()
|
|
92
|
+
unit = ArtifactUnit(
|
|
93
|
+
unit_id=uid,
|
|
94
|
+
role="STANDALONE",
|
|
95
|
+
name=target.stem,
|
|
96
|
+
depth=0,
|
|
97
|
+
sha256=compute_sha256(target),
|
|
98
|
+
source_path=str(target),
|
|
99
|
+
)
|
|
100
|
+
state.upsert_unit(unit)
|
|
101
|
+
state.data["input_kind"] = f"STANDALONE_{target.suffix.lstrip('.').upper() or 'FILE'}"
|
|
102
|
+
state.save()
|
dexsect/phases/decode.py
ADDED
|
@@ -0,0 +1,507 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
import shutil
|
|
4
|
+
import time
|
|
5
|
+
from collections import Counter, deque
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Deque, Dict, List, Set, Tuple
|
|
9
|
+
|
|
10
|
+
from ..core.context import ArtifactUnit, PipelineContext
|
|
11
|
+
from ..core.runner import CommandRunner
|
|
12
|
+
from ..core.utils import compute_sha256, count_tree, safe_slug
|
|
13
|
+
import zipfile
|
|
14
|
+
from ..parsers.axml import decode_axml_bytes
|
|
15
|
+
from ..parsers.bundle import extract_apk_units
|
|
16
|
+
from .base import BasePhase, PhaseResult
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class _DecodeJob:
|
|
21
|
+
apk_path: Path
|
|
22
|
+
role: str
|
|
23
|
+
depth: int
|
|
24
|
+
task_root: Path
|
|
25
|
+
decode_dir: Path
|
|
26
|
+
rel_label: str
|
|
27
|
+
display_name: str
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class DecodePhase(BasePhase):
|
|
31
|
+
name = "decode"
|
|
32
|
+
description = "Extract bundles (.apk/.xapk/.apks/.apkm) and recursively decode with Apktool"
|
|
33
|
+
metric_label = "Files"
|
|
34
|
+
|
|
35
|
+
def _index_and_discover(
|
|
36
|
+
self,
|
|
37
|
+
unit_id: str,
|
|
38
|
+
decode_dir: Path,
|
|
39
|
+
inv_file: Path,
|
|
40
|
+
out_root: Path,
|
|
41
|
+
ext_counter: Counter,
|
|
42
|
+
parent_depth: int,
|
|
43
|
+
parent_rel: str,
|
|
44
|
+
do_inv: bool,
|
|
45
|
+
do_embedded: bool,
|
|
46
|
+
ui,
|
|
47
|
+
) -> Tuple[int, int, List[_DecodeJob]]:
|
|
48
|
+
count = 0
|
|
49
|
+
total_bytes = 0
|
|
50
|
+
rows: List[str] = []
|
|
51
|
+
found_apks: List[Path] = []
|
|
52
|
+
stack = [decode_dir]
|
|
53
|
+
|
|
54
|
+
while stack:
|
|
55
|
+
cur = stack.pop()
|
|
56
|
+
try:
|
|
57
|
+
with os.scandir(cur) as it:
|
|
58
|
+
for entry in it:
|
|
59
|
+
try:
|
|
60
|
+
if entry.is_dir(follow_symlinks=False):
|
|
61
|
+
stack.append(Path(entry.path))
|
|
62
|
+
elif entry.is_file(follow_symlinks=False):
|
|
63
|
+
p = Path(entry.path)
|
|
64
|
+
if do_embedded and entry.name.lower().endswith(".apk"):
|
|
65
|
+
found_apks.append(p)
|
|
66
|
+
size = entry.stat(follow_symlinks=False).st_size
|
|
67
|
+
count += 1
|
|
68
|
+
total_bytes += size
|
|
69
|
+
if do_inv:
|
|
70
|
+
ext = p.suffix.lower().lstrip(".") or "[none]"
|
|
71
|
+
rel = p.relative_to(out_root).as_posix()
|
|
72
|
+
rows.append(f"{unit_id}\t{rel}\t{size}\t{ext}\n")
|
|
73
|
+
ext_counter[ext] += 1
|
|
74
|
+
if len(rows) >= 2000:
|
|
75
|
+
with inv_file.open("a", encoding="utf-8") as f:
|
|
76
|
+
f.writelines(rows)
|
|
77
|
+
rows.clear()
|
|
78
|
+
ui.set_active(step=f"INVENTORY ({count:,} files)")
|
|
79
|
+
except OSError:
|
|
80
|
+
continue
|
|
81
|
+
except OSError:
|
|
82
|
+
continue
|
|
83
|
+
|
|
84
|
+
if do_inv and rows:
|
|
85
|
+
with inv_file.open("a", encoding="utf-8") as f:
|
|
86
|
+
f.writelines(rows)
|
|
87
|
+
|
|
88
|
+
jobs: List[_DecodeJob] = []
|
|
89
|
+
for apk_f in sorted(found_apks):
|
|
90
|
+
h = compute_sha256(apk_f)
|
|
91
|
+
slug = safe_slug(apk_f.stem)
|
|
92
|
+
rel = f"03_Embedded_APKs/{parent_rel}/{slug}_{h[:8]}"
|
|
93
|
+
t_root = out_root / rel
|
|
94
|
+
jobs.append(
|
|
95
|
+
_DecodeJob(
|
|
96
|
+
apk_path=apk_f,
|
|
97
|
+
role="EMBEDDED",
|
|
98
|
+
depth=parent_depth + 1,
|
|
99
|
+
task_root=t_root,
|
|
100
|
+
decode_dir=t_root / "decoded",
|
|
101
|
+
rel_label=rel,
|
|
102
|
+
display_name=apk_f.stem,
|
|
103
|
+
)
|
|
104
|
+
)
|
|
105
|
+
return count, total_bytes, jobs
|
|
106
|
+
|
|
107
|
+
def _index_files(self, unit_id: str, decode_dir: Path, inv_file: Path, out_root: Path, ext_counter: Counter) -> Tuple[int, int]:
|
|
108
|
+
count = 0
|
|
109
|
+
total_bytes = 0
|
|
110
|
+
rows: List[str] = []
|
|
111
|
+
stack = [decode_dir]
|
|
112
|
+
|
|
113
|
+
while stack:
|
|
114
|
+
cur = stack.pop()
|
|
115
|
+
try:
|
|
116
|
+
with os.scandir(cur) as it:
|
|
117
|
+
for entry in it:
|
|
118
|
+
try:
|
|
119
|
+
if entry.is_dir(follow_symlinks=False):
|
|
120
|
+
stack.append(Path(entry.path))
|
|
121
|
+
elif entry.is_file(follow_symlinks=False):
|
|
122
|
+
size = entry.stat(follow_symlinks=False).st_size
|
|
123
|
+
p = Path(entry.path)
|
|
124
|
+
ext = p.suffix.lower().lstrip(".") or "[none]"
|
|
125
|
+
rel = p.relative_to(out_root).as_posix()
|
|
126
|
+
rows.append(f"{unit_id}\t{rel}\t{size}\t{ext}\n")
|
|
127
|
+
ext_counter[ext] += 1
|
|
128
|
+
count += 1
|
|
129
|
+
total_bytes += size
|
|
130
|
+
except OSError:
|
|
131
|
+
continue
|
|
132
|
+
except OSError:
|
|
133
|
+
continue
|
|
134
|
+
|
|
135
|
+
if rows:
|
|
136
|
+
with inv_file.open("a", encoding="utf-8") as f:
|
|
137
|
+
f.writelines(rows)
|
|
138
|
+
return count, total_bytes
|
|
139
|
+
|
|
140
|
+
def _discover_embedded(self, decode_dir: Path, parent_depth: int, parent_rel: str, out_root: Path) -> List[_DecodeJob]:
|
|
141
|
+
found: List[Path] = []
|
|
142
|
+
stack = [decode_dir]
|
|
143
|
+
while stack:
|
|
144
|
+
cur = stack.pop()
|
|
145
|
+
try:
|
|
146
|
+
with os.scandir(cur) as it:
|
|
147
|
+
for entry in it:
|
|
148
|
+
try:
|
|
149
|
+
if entry.is_dir(follow_symlinks=False):
|
|
150
|
+
stack.append(Path(entry.path))
|
|
151
|
+
elif entry.is_file(follow_symlinks=False) and entry.name.lower().endswith(".apk"):
|
|
152
|
+
found.append(Path(entry.path))
|
|
153
|
+
except OSError:
|
|
154
|
+
continue
|
|
155
|
+
except OSError:
|
|
156
|
+
continue
|
|
157
|
+
|
|
158
|
+
jobs: List[_DecodeJob] = []
|
|
159
|
+
for apk_f in sorted(found):
|
|
160
|
+
h = compute_sha256(apk_f)
|
|
161
|
+
slug = safe_slug(apk_f.stem)
|
|
162
|
+
rel = f"03_Embedded_APKs/{parent_rel}/{slug}_{h[:8]}"
|
|
163
|
+
t_root = out_root / rel
|
|
164
|
+
jobs.append(
|
|
165
|
+
_DecodeJob(
|
|
166
|
+
apk_path=apk_f,
|
|
167
|
+
role="EMBEDDED",
|
|
168
|
+
depth=parent_depth + 1,
|
|
169
|
+
task_root=t_root,
|
|
170
|
+
decode_dir=t_root / "decoded",
|
|
171
|
+
rel_label=rel,
|
|
172
|
+
display_name=apk_f.stem,
|
|
173
|
+
)
|
|
174
|
+
)
|
|
175
|
+
return jobs
|
|
176
|
+
|
|
177
|
+
def run(self, ctx: PipelineContext, runner: CommandRunner, phase_idx: str) -> PhaseResult:
|
|
178
|
+
t0 = time.time()
|
|
179
|
+
cfg = ctx.cfg
|
|
180
|
+
state = ctx.state
|
|
181
|
+
ui = ctx.ui
|
|
182
|
+
|
|
183
|
+
apktool = cfg.tools.get("apktool")
|
|
184
|
+
if not apktool or not apktool.found:
|
|
185
|
+
msg = "apktool is required for decode phase but was not found in PATH."
|
|
186
|
+
state.record_error(self.name, str(cfg.target_path), msg)
|
|
187
|
+
return PhaseResult(name=self.name, status="FAILED", duration_sec=time.time() - t0, failed=1)
|
|
188
|
+
|
|
189
|
+
ui.begin_phase(phase_idx, "DECODE (APKTOOL)", apktool.version or "apktool", metric_label="Files")
|
|
190
|
+
state.log(self.name, f"Started decode phase on {cfg.target_path}")
|
|
191
|
+
|
|
192
|
+
out = state.root
|
|
193
|
+
bundle_dir = out / "00_Bundle_Extracted"
|
|
194
|
+
main_dir = out / "01_Main_APK"
|
|
195
|
+
apk_inv = state.inv_dir / "apks.tsv"
|
|
196
|
+
file_inv = state.inv_dir / "files.tsv"
|
|
197
|
+
|
|
198
|
+
if not apk_inv.exists():
|
|
199
|
+
apk_inv.write_text("ID\tROLE\tNAME\tDEPTH\tSHA256\tSTATUS\tSOURCE\tOUTPUT\n", encoding="utf-8")
|
|
200
|
+
if not file_inv.exists():
|
|
201
|
+
file_inv.write_text("UNIT_ID\tRELATIVE_PATH\tSIZE_BYTES\tEXTENSION\n", encoding="utf-8")
|
|
202
|
+
|
|
203
|
+
skip_lang = cfg.is_skipped("lang-splits")
|
|
204
|
+
skip_smali = cfg.is_skipped("smali")
|
|
205
|
+
skip_res = cfg.is_skipped("res")
|
|
206
|
+
skip_dbg = cfg.is_skipped("debug-info")
|
|
207
|
+
skip_embedded = cfg.is_skipped("embedded")
|
|
208
|
+
skip_inv = cfg.is_skipped("inventory")
|
|
209
|
+
|
|
210
|
+
try:
|
|
211
|
+
kind, bundle_units, bundle_meta = extract_apk_units(
|
|
212
|
+
cfg.target_path, bundle_dir, skip_lang_splits=skip_lang
|
|
213
|
+
)
|
|
214
|
+
except Exception as exc:
|
|
215
|
+
state.record_error(self.name, str(cfg.target_path), str(exc))
|
|
216
|
+
ui.push_event("ERR", f"Bundle extraction failed: {exc}")
|
|
217
|
+
return PhaseResult(name=self.name, status="FAILED", duration_sec=time.time() - t0, failed=1)
|
|
218
|
+
|
|
219
|
+
state.data["input_kind"] = kind
|
|
220
|
+
ui.set_meta(input=cfg.target_path.name, type=kind, output=str(out), jobs=str(cfg.jobs))
|
|
221
|
+
if bundle_meta:
|
|
222
|
+
(state.inv_dir / "bundle_manifest.json").write_text(
|
|
223
|
+
json.dumps(bundle_meta, indent=2, ensure_ascii=False), encoding="utf-8"
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
queue: Deque[_DecodeJob] = deque()
|
|
227
|
+
for bu in bundle_units:
|
|
228
|
+
if bu.role == "MAIN":
|
|
229
|
+
t_root = main_dir
|
|
230
|
+
rel = "01_Main_APK"
|
|
231
|
+
else:
|
|
232
|
+
h_short = compute_sha256(bu.apk_path)[:8]
|
|
233
|
+
rel = f"02_Split_APKs/{safe_slug(bu.display_name)}_{h_short}"
|
|
234
|
+
t_root = out / rel
|
|
235
|
+
queue.append(
|
|
236
|
+
_DecodeJob(
|
|
237
|
+
apk_path=bu.apk_path,
|
|
238
|
+
role=bu.role,
|
|
239
|
+
depth=0,
|
|
240
|
+
task_root=t_root,
|
|
241
|
+
decode_dir=t_root / "decoded",
|
|
242
|
+
rel_label=rel,
|
|
243
|
+
display_name=bu.display_name,
|
|
244
|
+
)
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
ui.update_stats(total=len(queue))
|
|
248
|
+
ui.push_event("INFO", f"Queued {len(queue)} initial unit(s) ({kind})")
|
|
249
|
+
ui.render()
|
|
250
|
+
|
|
251
|
+
seen_in_run: Set[str] = set()
|
|
252
|
+
existing_by_hash: Dict[str, ArtifactUnit] = {
|
|
253
|
+
u.sha256: u for u in state.get_units() if u.sha256
|
|
254
|
+
}
|
|
255
|
+
ext_counter: Counter = Counter()
|
|
256
|
+
ts_tag = time.strftime("%Y%m%d_%H%M%S")
|
|
257
|
+
processed = succeeded = failed = resumed = duplicates = skipped = 0
|
|
258
|
+
|
|
259
|
+
while queue and not runner.interrupted:
|
|
260
|
+
job = queue.popleft()
|
|
261
|
+
ui.reset_task_timer()
|
|
262
|
+
|
|
263
|
+
if job.depth > cfg.max_depth:
|
|
264
|
+
skipped += 1
|
|
265
|
+
processed += 1
|
|
266
|
+
ui.inc_stat("skipped")
|
|
267
|
+
ui.inc_stat("done")
|
|
268
|
+
ui.push_event("WARN", f"Max depth ({cfg.max_depth}) reached: {job.display_name}")
|
|
269
|
+
continue
|
|
270
|
+
|
|
271
|
+
apk_hash = compute_sha256(job.apk_path)
|
|
272
|
+
|
|
273
|
+
if apk_hash in seen_in_run:
|
|
274
|
+
duplicates += 1
|
|
275
|
+
processed += 1
|
|
276
|
+
ui.inc_stat("duplicates")
|
|
277
|
+
ui.inc_stat("done")
|
|
278
|
+
ui.push_event("WARN", f"Duplicate skipped: {job.display_name}")
|
|
279
|
+
continue
|
|
280
|
+
seen_in_run.add(apk_hash)
|
|
281
|
+
|
|
282
|
+
existing_unit = existing_by_hash.get(apk_hash)
|
|
283
|
+
unit_id = existing_unit.unit_id if existing_unit else state.next_unit_id()
|
|
284
|
+
|
|
285
|
+
ui.set_active(
|
|
286
|
+
id=unit_id,
|
|
287
|
+
name=job.display_name,
|
|
288
|
+
role=job.role,
|
|
289
|
+
depth=str(job.depth),
|
|
290
|
+
hash=apk_hash,
|
|
291
|
+
step="CHECK_STATE",
|
|
292
|
+
)
|
|
293
|
+
ui.render()
|
|
294
|
+
|
|
295
|
+
job.task_root.mkdir(parents=True, exist_ok=True)
|
|
296
|
+
complete_marker = job.task_root / ".apktool_complete"
|
|
297
|
+
inv_marker = job.task_root / ".inventory_complete"
|
|
298
|
+
|
|
299
|
+
# Resume already decoded task
|
|
300
|
+
if cfg.resume and complete_marker.exists() and job.decode_dir.is_dir():
|
|
301
|
+
resumed += 1
|
|
302
|
+
processed += 1
|
|
303
|
+
ui.inc_stat("resumed")
|
|
304
|
+
ui.inc_stat("done")
|
|
305
|
+
|
|
306
|
+
f_cnt = existing_unit.metrics.get("files_count", 0) if existing_unit else 0
|
|
307
|
+
b_tot = existing_unit.metrics.get("bytes_total", 0) if existing_unit else 0
|
|
308
|
+
if f_cnt == 0:
|
|
309
|
+
f_cnt, b_tot = count_tree(job.decode_dir)
|
|
310
|
+
ui.inc_stat("files_indexed", f_cnt)
|
|
311
|
+
ui.inc_stat("bytes_indexed", b_tot)
|
|
312
|
+
|
|
313
|
+
manifest_p = job.decode_dir / "AndroidManifest.xml"
|
|
314
|
+
yml_p = job.decode_dir / "apktool.yml"
|
|
315
|
+
unit = existing_unit or ArtifactUnit(
|
|
316
|
+
unit_id=unit_id,
|
|
317
|
+
role=job.role,
|
|
318
|
+
name=job.display_name,
|
|
319
|
+
depth=job.depth,
|
|
320
|
+
sha256=apk_hash,
|
|
321
|
+
source_path=str(job.apk_path),
|
|
322
|
+
)
|
|
323
|
+
unit.decode_dir = str(job.decode_dir)
|
|
324
|
+
unit.manifest_xml = str(manifest_p) if manifest_p.is_file() else ""
|
|
325
|
+
unit.apktool_yml = str(yml_p) if yml_p.is_file() else ""
|
|
326
|
+
unit.phase_status["decode"] = "PARTIAL_NORES" if (existing_unit and existing_unit.phase_status.get("decode") == "PARTIAL_NORES") else "SUCCESS"
|
|
327
|
+
unit.metrics["files_count"] = f_cnt
|
|
328
|
+
unit.metrics["bytes_total"] = b_tot
|
|
329
|
+
state.upsert_unit(unit)
|
|
330
|
+
existing_by_hash[apk_hash] = unit
|
|
331
|
+
state.save()
|
|
332
|
+
|
|
333
|
+
ui.push_event("INFO", f"Resumed: {job.display_name} ({f_cnt} files)")
|
|
334
|
+
if not skip_embedded:
|
|
335
|
+
emb = self._discover_embedded(job.decode_dir, job.depth, job.rel_label, out)
|
|
336
|
+
if emb:
|
|
337
|
+
queue.extend(emb)
|
|
338
|
+
ui.inc_stat("total", len(emb))
|
|
339
|
+
ui.push_event("FOUND", f"Queued {len(emb)} embedded APK(s)")
|
|
340
|
+
ui.render()
|
|
341
|
+
continue
|
|
342
|
+
|
|
343
|
+
if job.decode_dir.exists():
|
|
344
|
+
backup = job.decode_dir.with_name(f"{job.decode_dir.name}.partial_{ts_tag}")
|
|
345
|
+
shutil.move(str(job.decode_dir), str(backup))
|
|
346
|
+
|
|
347
|
+
cmd = [
|
|
348
|
+
apktool.path,
|
|
349
|
+
"d",
|
|
350
|
+
"--keep-broken-res",
|
|
351
|
+
"--match-original",
|
|
352
|
+
"--verbose",
|
|
353
|
+
"--jobs",
|
|
354
|
+
str(cfg.jobs),
|
|
355
|
+
]
|
|
356
|
+
if skip_smali:
|
|
357
|
+
cmd.append("--no-src")
|
|
358
|
+
else:
|
|
359
|
+
cmd.append("--all-src")
|
|
360
|
+
if skip_res:
|
|
361
|
+
cmd.append("--no-res")
|
|
362
|
+
if skip_dbg:
|
|
363
|
+
cmd.append("--no-debug-info")
|
|
364
|
+
cmd.extend(["-o", str(job.decode_dir), str(job.apk_path)])
|
|
365
|
+
|
|
366
|
+
task_log = state.task_log_dir / f"decode_{unit_id}_{safe_slug(job.display_name)}.log"
|
|
367
|
+
ui.set_active(step="APKTOOL_DECODE")
|
|
368
|
+
ui.render()
|
|
369
|
+
state.log(self.name, f"Decoding [{unit_id}] {job.apk_path}")
|
|
370
|
+
|
|
371
|
+
rc = runner.run_streamed(
|
|
372
|
+
cmd,
|
|
373
|
+
task_log,
|
|
374
|
+
on_line=ui.push_stream,
|
|
375
|
+
on_tick=ui.render,
|
|
376
|
+
inject_java_xmx=True,
|
|
377
|
+
)
|
|
378
|
+
|
|
379
|
+
if runner.interrupted:
|
|
380
|
+
break
|
|
381
|
+
|
|
382
|
+
# Automatic --no-res fallback if Apktool failed due to resource obfuscation (e.g., AndResGuard)
|
|
383
|
+
res_fallback_used = False
|
|
384
|
+
if rc != 0 and not skip_res:
|
|
385
|
+
ui.push_event("WARN", f"Apktool res failed (rc={rc}); retrying with --no-res fallback...")
|
|
386
|
+
state.log(self.name, f"Retrying [{unit_id}] with --no-res fallback")
|
|
387
|
+
if job.decode_dir.exists():
|
|
388
|
+
shutil.rmtree(job.decode_dir, ignore_errors=True)
|
|
389
|
+
fb_cmd = [x for x in cmd if x not in ("--keep-broken-res",)]
|
|
390
|
+
fb_cmd.insert(2, "--no-res")
|
|
391
|
+
fb_log = state.task_log_dir / f"decode_{unit_id}_{safe_slug(job.display_name)}_nores.log"
|
|
392
|
+
rc = runner.run_streamed(
|
|
393
|
+
fb_cmd, fb_log, on_line=ui.push_stream, on_tick=ui.render, inject_java_xmx=True
|
|
394
|
+
)
|
|
395
|
+
if runner.interrupted:
|
|
396
|
+
break
|
|
397
|
+
if rc == 0 and job.decode_dir.is_dir():
|
|
398
|
+
res_fallback_used = True
|
|
399
|
+
# Ensure readable AndroidManifest.xml via pure-Python AXML decoder
|
|
400
|
+
m_out = job.decode_dir / "AndroidManifest.xml"
|
|
401
|
+
try:
|
|
402
|
+
if m_out.is_file():
|
|
403
|
+
m_out.write_text(decode_axml_bytes(m_out.read_bytes()), encoding="utf-8")
|
|
404
|
+
elif zipfile.is_zipfile(job.apk_path):
|
|
405
|
+
with zipfile.ZipFile(job.apk_path, "r") as zf:
|
|
406
|
+
if "AndroidManifest.xml" in zf.namelist():
|
|
407
|
+
m_out.write_text(decode_axml_bytes(zf.read("AndroidManifest.xml")), encoding="utf-8")
|
|
408
|
+
except Exception:
|
|
409
|
+
pass
|
|
410
|
+
state.record_error(
|
|
411
|
+
self.name, job.display_name,
|
|
412
|
+
"Apktool resources failed; recovered smali/assets/lib/manifest via --no-res fallback",
|
|
413
|
+
exit_code=0, log_file=str(task_log),
|
|
414
|
+
)
|
|
415
|
+
|
|
416
|
+
processed += 1
|
|
417
|
+
manifest_p = job.decode_dir / "AndroidManifest.xml"
|
|
418
|
+
yml_p = job.decode_dir / "apktool.yml"
|
|
419
|
+
|
|
420
|
+
unit = existing_unit or ArtifactUnit(
|
|
421
|
+
unit_id=unit_id,
|
|
422
|
+
role=job.role,
|
|
423
|
+
name=job.display_name,
|
|
424
|
+
depth=job.depth,
|
|
425
|
+
sha256=apk_hash,
|
|
426
|
+
source_path=str(job.apk_path),
|
|
427
|
+
)
|
|
428
|
+
unit.decode_dir = str(job.decode_dir) if job.decode_dir.is_dir() else ""
|
|
429
|
+
unit.manifest_xml = str(manifest_p) if manifest_p.is_file() else ""
|
|
430
|
+
unit.apktool_yml = str(yml_p) if yml_p.is_file() else ""
|
|
431
|
+
|
|
432
|
+
if rc == 0 and job.decode_dir.is_dir():
|
|
433
|
+
complete_marker.touch()
|
|
434
|
+
succeeded += 1
|
|
435
|
+
ui.inc_stat("success")
|
|
436
|
+
unit.phase_status["decode"] = "PARTIAL_NORES" if res_fallback_used else "SUCCESS"
|
|
437
|
+
ui.push_event("OK", f"Decoded [{unit_id}] {job.display_name}")
|
|
438
|
+
|
|
439
|
+
do_inv = (not skip_inv) and (not inv_marker.exists())
|
|
440
|
+
ui.set_active(step="INVENTORY & SCAN")
|
|
441
|
+
f_cnt, b_tot, emb = self._index_and_discover(
|
|
442
|
+
unit_id, job.decode_dir, file_inv, out, ext_counter,
|
|
443
|
+
job.depth, job.rel_label, do_inv=do_inv, do_embedded=(not skip_embedded), ui=ui,
|
|
444
|
+
)
|
|
445
|
+
if do_inv:
|
|
446
|
+
inv_marker.touch()
|
|
447
|
+
|
|
448
|
+
unit.metrics["files_count"] = f_cnt
|
|
449
|
+
unit.metrics["bytes_total"] = b_tot
|
|
450
|
+
ui.inc_stat("files_indexed", f_cnt)
|
|
451
|
+
ui.inc_stat("bytes_indexed", b_tot)
|
|
452
|
+
|
|
453
|
+
with apk_inv.open("a", encoding="utf-8") as f:
|
|
454
|
+
f.write(
|
|
455
|
+
f"{unit_id}\t{job.role}\t{job.display_name}\t{job.depth}\t"
|
|
456
|
+
f"{apk_hash}\tSUCCESS\t{job.apk_path}\t{job.decode_dir}\n"
|
|
457
|
+
)
|
|
458
|
+
|
|
459
|
+
if emb:
|
|
460
|
+
queue.extend(emb)
|
|
461
|
+
ui.inc_stat("total", len(emb))
|
|
462
|
+
ui.push_event("FOUND", f"Queued {len(emb)} embedded APK(s)")
|
|
463
|
+
else:
|
|
464
|
+
failed += 1
|
|
465
|
+
ui.inc_stat("failed")
|
|
466
|
+
unit.phase_status["decode"] = "FAILED"
|
|
467
|
+
state.record_error(self.name, job.display_name, f"Apktool exited with {rc}", exit_code=rc, log_file=str(task_log))
|
|
468
|
+
ui.push_event("FAIL", f"Apktool exit {rc}: {job.display_name}")
|
|
469
|
+
with apk_inv.open("a", encoding="utf-8") as f:
|
|
470
|
+
f.write(
|
|
471
|
+
f"{unit_id}\t{job.role}\t{job.display_name}\t{job.depth}\t"
|
|
472
|
+
f"{apk_hash}\tFAILED\t{job.apk_path}\t{job.decode_dir}\n"
|
|
473
|
+
)
|
|
474
|
+
|
|
475
|
+
state.upsert_unit(unit)
|
|
476
|
+
existing_by_hash[apk_hash] = unit
|
|
477
|
+
state.save()
|
|
478
|
+
ui.inc_stat("done")
|
|
479
|
+
ui.render()
|
|
480
|
+
|
|
481
|
+
status = "INTERRUPTED" if runner.interrupted else ("FAILED" if failed > 0 and succeeded == 0 and resumed == 0 else "COMPLETED")
|
|
482
|
+
dur = time.time() - t0
|
|
483
|
+
summary = {
|
|
484
|
+
"status": status,
|
|
485
|
+
"duration_sec": round(dur, 2),
|
|
486
|
+
"processed": processed,
|
|
487
|
+
"succeeded": succeeded,
|
|
488
|
+
"resumed": resumed,
|
|
489
|
+
"failed": failed,
|
|
490
|
+
"duplicates": duplicates,
|
|
491
|
+
"skipped": skipped,
|
|
492
|
+
"files_indexed": ui.stats["files_indexed"],
|
|
493
|
+
"bytes_indexed": ui.stats["bytes_indexed"],
|
|
494
|
+
"top_extensions": dict(ext_counter.most_common(20)),
|
|
495
|
+
}
|
|
496
|
+
state.set_phase_summary(self.name, summary)
|
|
497
|
+
state.log(self.name, f"Finished decode phase: {status}")
|
|
498
|
+
return PhaseResult(
|
|
499
|
+
name=self.name,
|
|
500
|
+
status=status,
|
|
501
|
+
duration_sec=dur,
|
|
502
|
+
processed=processed,
|
|
503
|
+
succeeded=succeeded + resumed,
|
|
504
|
+
failed=failed,
|
|
505
|
+
skipped=skipped + duplicates,
|
|
506
|
+
details=summary,
|
|
507
|
+
)
|