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,162 @@
1
+ import json
2
+ import time
3
+ from pathlib import Path
4
+ from typing import Any, Dict, List, Optional, Set, Tuple
5
+
6
+ from ..core.context import PipelineContext, WorkspaceState
7
+ from ..storage.findings_db import FindingsDB
8
+ from ..reporting.diff_report import generate_diff_html
9
+ from .base import BaseAnalysisPlugin
10
+
11
+
12
+ DIFF_GROUPS: List[Tuple[str, str, List[str]]] = [
13
+ ("metadata", "Identity & Signing", ["APP-001", "APP-003", "APP-004", "APP-005", "APP-006", "APP-013", "APP-014", "APP-017", "SIG-002", "SIG-004", "SIG-007"]),
14
+ ("permissions", "Permissions", ["PER-001", "PER-003", "PER-006"]),
15
+ ("components", "Components & Exposure", ["ACT-001", "ACT-004", "ACT-005", "SRV-001", "SRV-002", "REC-001", "REC-002", "PRO-001", "PRO-003"]),
16
+ ("intents", "Intents & Deep Links", ["INT-002", "INT-003", "INT-004"]),
17
+ ("network", "Domains & URLs", ["NET-001", "NET-002", "URL-001", "URL-002", "URL-004"]),
18
+ ("native", "Native Libs & JNI", ["NAT-001", "NAT-005"]),
19
+ ("security", "Security & Config Candidates", ["CFG-001", "CFG-004", "CFG-005", "SEC-002", "SEC-003", "SEC-004", "SEC-006"]),
20
+ ]
21
+
22
+
23
+ def _load_group_set(db: FindingsDB, catalog_ids: List[str], scope_filter: Optional[List[str]] = None) -> Dict[Tuple[str, str], Dict[str, Any]]:
24
+ rows = db.query_findings(catalog_ids=catalog_ids, scopes=scope_filter)
25
+ out: Dict[Tuple[str, str], Dict[str, Any]] = {}
26
+ for r in rows:
27
+ key = (r["catalog_id"], r["value"])
28
+ if key not in out:
29
+ out[key] = {
30
+ "catalog_id": r["catalog_id"],
31
+ "title": r.get("title") or "",
32
+ "value": r["value"],
33
+ "layer": r.get("layer") or "",
34
+ "scope": r.get("scope") or "app",
35
+ "file_path": r.get("file_path") or "",
36
+ "line_no": r.get("line_no") or 0,
37
+ }
38
+ return out
39
+
40
+
41
+ class DiffPlugin(BaseAnalysisPlugin):
42
+ name = "diff"
43
+ description = "Compare two DexSect workspaces across metadata, permissions, components, URLs, native & security"
44
+
45
+ def compare(
46
+ self,
47
+ ws1_root: Path,
48
+ ws2_root: Path,
49
+ scope_filter: Optional[List[str]] = None,
50
+ ) -> Dict[str, Any]:
51
+ t0 = time.time()
52
+ db1_path = ws1_root / "10_Analysis" / "findings.db"
53
+ db2_path = ws2_root / "10_Analysis" / "findings.db"
54
+ if not db1_path.is_file():
55
+ raise FileNotFoundError(f"findings.db missing in baseline workspace: {ws1_root}")
56
+ if not db2_path.is_file():
57
+ raise FileNotFoundError(f"findings.db missing in target workspace: {ws2_root}")
58
+
59
+ db1 = FindingsDB(db1_path)
60
+ db2 = FindingsDB(db2_path)
61
+ try:
62
+ sections: Dict[str, Any] = {}
63
+ tot_added = 0
64
+ tot_removed = 0
65
+
66
+ for gkey, gtitle, cids in DIFF_GROUPS:
67
+ s1 = _load_group_set(db1, cids, scope_filter)
68
+ s2 = _load_group_set(db2, cids, scope_filter)
69
+
70
+ added_keys = sorted(set(s2.keys()) - set(s1.keys()))
71
+ removed_keys = sorted(set(s1.keys()) - set(s2.keys()))
72
+
73
+ added = [s2[k] for k in added_keys]
74
+ removed = [s1[k] for k in removed_keys]
75
+ tot_added += len(added)
76
+ tot_removed += len(removed)
77
+
78
+ sections[gkey] = {
79
+ "title": gtitle,
80
+ "baseline_count": len(s1),
81
+ "target_count": len(s2),
82
+ "added_count": len(added),
83
+ "removed_count": len(removed),
84
+ "added": added,
85
+ "removed": removed,
86
+ }
87
+
88
+ return {
89
+ "generated_at": time.strftime("%Y-%m-%d %H:%M:%S"),
90
+ "duration_sec": round(time.time() - t0, 3),
91
+ "baseline": str(ws1_root),
92
+ "target": str(ws2_root),
93
+ "scope_filter": scope_filter or ["all"],
94
+ "summary": {"total_added": tot_added, "total_removed": tot_removed},
95
+ "sections": sections,
96
+ }
97
+ finally:
98
+ db1.close()
99
+ db2.close()
100
+
101
+ def execute(self, ctx: PipelineContext, **kwargs: Any) -> Dict[str, Any]:
102
+ other_ws = Path(kwargs["target_ws"])
103
+ return self.compare(ctx.state.root, other_ws, scope_filter=kwargs.get("scope_filter"))
104
+
105
+
106
+ def format_diff_output(diff_data: Dict[str, Any], fmt: str = "table") -> str:
107
+ fmt = fmt.lower()
108
+ if fmt == "html":
109
+ return generate_diff_html(diff_data)
110
+ if fmt == "json":
111
+ return json.dumps(diff_data, indent=2, ensure_ascii=False)
112
+
113
+ if fmt == "md":
114
+ lines = [
115
+ "# DexSect Workspace Diff Report",
116
+ "",
117
+ f"- **Baseline (`-`):** `{diff_data['baseline']}`",
118
+ f"- **Target (`+`):** `{diff_data['target']}`",
119
+ f"- **Added:** `{diff_data['summary']['total_added']}` | **Removed:** `{diff_data['summary']['total_removed']}`",
120
+ "",
121
+ ]
122
+ for sec in diff_data["sections"].values():
123
+ lines.append(f"## {sec['title']} (+{sec['added_count']} / -{sec['removed_count']})")
124
+ lines.append("")
125
+ if not sec["added"] and not sec["removed"]:
126
+ lines.append("_No changes._\n")
127
+ continue
128
+ lines.append("| Change | Catalog ID | Title | Value | Layer |")
129
+ lines.append("| :---: | :--- | :--- | :--- | :--- |")
130
+ for it in sec["added"][:200]:
131
+ val = str(it["value"]).replace("|", "\\|")[:120]
132
+ lines.append(f"| `+` | `{it['catalog_id']}` | {it['title']} | `{val}` | `{it['layer']}` |")
133
+ for it in sec["removed"][:200]:
134
+ val = str(it["value"]).replace("|", "\\|")[:120]
135
+ lines.append(f"| `-` | `{it['catalog_id']}` | {it['title']} | `{val}` | `{it['layer']}` |")
136
+ lines.append("")
137
+ return "\n".join(lines)
138
+
139
+ lines = [
140
+ "=" * 78,
141
+ "DEXSECT :: WORKSPACE DIFFERENTIAL ANALYSIS",
142
+ "=" * 78,
143
+ f"Baseline (-) : {diff_data['baseline']}",
144
+ f"Target (+) : {diff_data['target']}",
145
+ f"Changes : +{diff_data['summary']['total_added']} added | -{diff_data['summary']['total_removed']} removed",
146
+ "-" * 78,
147
+ ]
148
+ for sec in diff_data["sections"].values():
149
+ if not sec["added"] and not sec["removed"]:
150
+ lines.append(f"[{sec['title']}] No changes (count={sec['target_count']})")
151
+ continue
152
+ lines.append(f"\n[{sec['title']}] (+{sec['added_count']} / -{sec['removed_count']})")
153
+ for it in sec["added"][:60]:
154
+ lines.append(f" + [{it['catalog_id']}] {it['title']}: {str(it['value'])[:100]}")
155
+ if len(sec["added"]) > 60:
156
+ lines.append(f" ... (+{len(sec['added']) - 60} more added)")
157
+ for it in sec["removed"][:60]:
158
+ lines.append(f" - [{it['catalog_id']}] {it['title']}: {str(it['value'])[:100]}")
159
+ if len(sec["removed"]) > 60:
160
+ lines.append(f" ... (-{len(sec['removed']) - 60} more removed)")
161
+ lines.append("=" * 78)
162
+ return "\n".join(lines)
@@ -0,0 +1,172 @@
1
+ import hashlib
2
+ import json
3
+ import time
4
+ from pathlib import Path
5
+ from typing import Any, Dict, List, Optional, Set
6
+
7
+ from ..core.context import PipelineContext
8
+ from ..inspectors.assets_db_inspector import AssetsDbInspector
9
+ from ..inspectors.base import BaseInspector
10
+ from ..inspectors.bundle_inspector import BundleInspector
11
+ from ..inspectors.code_inspector import CodeInspector
12
+ from ..inspectors.custom_rules_inspector import CustomRulesInspector, load_rule_packs
13
+ from ..inspectors.dex_inspector import DexInspector
14
+ from ..inspectors.manifest_inspector import ManifestInspector
15
+ from ..inspectors.native_fw_inspector import NativeFwInspector
16
+ from ..inspectors.resources_inspector import ResourcesInspector
17
+ from ..inspectors.scanner_inspector import ScannerInspector
18
+ from ..inspectors.signing_inspector import SigningInspector
19
+ from ..storage.findings_db import FindingsDB
20
+ from .base import BaseAnalysisPlugin
21
+
22
+
23
+ def get_registered_inspectors(rule_paths: Optional[List[Path]] = None) -> List[BaseInspector]:
24
+ return [
25
+ BundleInspector(),
26
+ SigningInspector(),
27
+ ManifestInspector(),
28
+ ResourcesInspector(),
29
+ DexInspector(),
30
+ AssetsDbInspector(),
31
+ CodeInspector(),
32
+ NativeFwInspector(),
33
+ ScannerInspector(),
34
+ CustomRulesInspector(rule_paths=rule_paths),
35
+ ]
36
+
37
+
38
+ class InspectPlugin(BaseAnalysisPlugin):
39
+ name = "inspect"
40
+ description = "Run catalog-driven static inspectors with live progress and store provenance-backed findings in findings.db"
41
+
42
+ def execute(
43
+ self,
44
+ ctx: PipelineContext,
45
+ profile: str = "standard",
46
+ only_filters: Optional[Set[str]] = None,
47
+ skip_filters: Optional[Set[str]] = None,
48
+ unit_filter: Optional[str] = None,
49
+ rule_paths: Optional[List[Path]] = None,
50
+ deterministic: bool = False,
51
+ ) -> Dict[str, Any]:
52
+ t0 = time.time()
53
+ analysis_dir = ctx.state.root / "10_Analysis"
54
+ analysis_dir.mkdir(parents=True, exist_ok=True)
55
+ db_path = analysis_dir / "findings.db"
56
+ summary_path = analysis_dir / "inspection_summary.json"
57
+
58
+ only_set = {x.lower() for x in (only_filters or set())}
59
+ skip_set = {x.lower() for x in (skip_filters or set())}
60
+
61
+ units = ctx.state.get_units()
62
+ if unit_filter:
63
+ units = [u for u in units if u.unit_id == unit_filter]
64
+
65
+ has_custom = bool(load_rule_packs(rule_paths or []))
66
+ inspectors = [
67
+ ins for ins in get_registered_inspectors(rule_paths=rule_paths)
68
+ if ins.is_selected(only_set, skip_set) and (ins.name != 'custom_rules' or has_custom)
69
+ ]
70
+
71
+ ui = ctx.ui
72
+ owns_ui = not ui.started
73
+ if owns_ui:
74
+ ui.start()
75
+
76
+ ui.begin_phase("INSPECT", f"INSPECT ({profile.upper()})", "Catalog-Engine", metric_label="Findings", stage_key="inspect")
77
+ ui.set_meta(
78
+ input=ctx.cfg.target_path.name,
79
+ type=ctx.state.data.get("input_kind") or "WORKSPACE",
80
+ output=str(ctx.state.root),
81
+ jobs=str(len(inspectors)),
82
+ )
83
+ ui.update_stats(total=len(inspectors))
84
+ ui.push_event("INFO", f"Starting {len(inspectors)} inspector(s) across {len(units)} unit(s)")
85
+ ui.render()
86
+
87
+ db = FindingsDB(db_path)
88
+ if not only_set and not unit_filter:
89
+ db.clear_all()
90
+
91
+ ins_names = {ins.name for ins in inspectors}
92
+ ctx.runtime_cache["run_scanner_with_code"] = ("code" in ins_names and "scanner" in ins_names)
93
+ results_meta: Dict[str, Any] = {}
94
+ try:
95
+ for idx, ins in enumerate(inspectors, start=1):
96
+ ui.reset_task_timer()
97
+ ui.set_active(
98
+ id=f"I{idx:02d}",
99
+ name=ins.name,
100
+ role="INSPECTOR",
101
+ depth=str(len(units)),
102
+ hash=profile,
103
+ step=ins.description[:44],
104
+ )
105
+ ui.push_stream(f"Running {ins.name}: {ins.description}")
106
+ ui.render()
107
+
108
+ if only_set or unit_filter:
109
+ db.clear_inspectors_catalog_ids(ins.catalog_ids)
110
+
111
+ res = ins.run(ctx, db, units, profile)
112
+ results_meta[ins.name] = {
113
+ "status": res.status,
114
+ "duration_sec": res.duration_sec,
115
+ "findings_count": res.findings_count,
116
+ "summary": res.summary,
117
+ }
118
+
119
+ ui.inc_stat("success")
120
+ ui.inc_stat("done")
121
+ ui.inc_stat("files_indexed", res.findings_count)
122
+ db_sz = sum(p.stat().st_size for p in (db_path, db_path.with_name(db_path.name + "-wal")) if p.is_file())
123
+ ui.update_stats(bytes_indexed=db_sz)
124
+ ui.push_event("OK", f"{ins.name}: {res.findings_count} items ({res.duration_sec}s)")
125
+ ui.render()
126
+
127
+ ui.set_active(id="FTS", name="Search Index", role="SQLITE", depth="-", hash="FTS5", step="REBUILD_INDEX")
128
+ ui.push_stream("Rebuilding SQLite FTS5 full-text search index...")
129
+ ui.render()
130
+ db.rebuild_fts()
131
+
132
+ hash_obj = hashlib.sha256()
133
+ hash_basis = {
134
+ "dexsect_version": ctx.state.data.get("dexsect_version", ""),
135
+ "profile": profile,
136
+ "only": sorted(only_set),
137
+ "skip": sorted(skip_set),
138
+ "unit_hashes": sorted(u.sha256 for u in units),
139
+ "rules_count": len(load_rule_packs(rule_paths or [])),
140
+ }
141
+ hash_obj.update(json.dumps(hash_basis, sort_keys=True).encode("utf-8"))
142
+ analysis_hash = hash_obj.hexdigest()
143
+
144
+ payload = {
145
+ "profile": profile,
146
+ "deterministic": deterministic,
147
+ "analysis_hash": analysis_hash,
148
+ "generated_at": time.strftime("%Y-%m-%d %H:%M:%S"),
149
+ "duration_sec": round(time.time() - t0, 3),
150
+ "workspace_root": str(ctx.state.root),
151
+ "db_path": str(db_path),
152
+ "counts_by_domain": db.counts_by_domain(),
153
+ "counts_by_catalog": db.counts_by_catalog(),
154
+ "inspectors": results_meta,
155
+ }
156
+ summary_path.write_text(json.dumps(payload, indent=2, ensure_ascii=False), encoding="utf-8")
157
+ ctx.state.data["extensions"]["inspect"] = {
158
+ "summary_file": str(summary_path),
159
+ "db_file": str(db_path),
160
+ "profile": profile,
161
+ "analysis_hash": analysis_hash,
162
+ "updated_at": payload["generated_at"],
163
+ }
164
+ ctx.state.save()
165
+ ui.finish_stage("inspect", "COMPLETED", payload["duration_sec"])
166
+ ui.push_event("OK", f"Inspection completed in {payload['duration_sec']}s")
167
+ ui.render()
168
+ return payload
169
+ finally:
170
+ db.close()
171
+ if owns_ui:
172
+ ui.stop()
@@ -0,0 +1,80 @@
1
+ import json
2
+ import time
3
+ from pathlib import Path
4
+ from typing import Any, Dict, List, Optional
5
+
6
+ from ..core.context import PipelineContext
7
+ from ..reporting.analysis_report import generate_analysis_reports
8
+ from ..reporting.sarif_report import generate_sarif_report
9
+ from ..storage.findings_db import FindingsDB
10
+ from .base import BaseAnalysisPlugin
11
+
12
+
13
+ class ReportPlugin(BaseAnalysisPlugin):
14
+ name = "report"
15
+ description = "Generate mobile-first interactive HTML (i18n), Markdown, and JSON reports"
16
+
17
+ def execute(
18
+ self,
19
+ ctx: PipelineContext,
20
+ formats: Optional[List[str]] = None,
21
+ out_dir: Optional[Path] = None,
22
+ lang: str = "en",
23
+ include_noise: bool = False,
24
+ full_json: bool = False,
25
+ ) -> Dict[str, Any]:
26
+ t0 = time.time()
27
+ analysis_dir = ctx.state.root / "10_Analysis"
28
+ db_path = analysis_dir / "findings.db"
29
+ summary_path = analysis_dir / "inspection_summary.json"
30
+ target_out = out_dir or ctx.state.report_dir
31
+
32
+ if not db_path.is_file():
33
+ raise FileNotFoundError(
34
+ f"findings.db not found at {db_path}. Run 'dexsect inspect <workspace>' first."
35
+ )
36
+
37
+ summary_data: Dict[str, Any] = {}
38
+ if summary_path.is_file():
39
+ try:
40
+ summary_data = json.loads(summary_path.read_text(encoding="utf-8", errors="replace"))
41
+ except Exception:
42
+ summary_data = {}
43
+
44
+ ui = ctx.ui
45
+ owns_ui = not ui.started
46
+ if owns_ui:
47
+ ui.start()
48
+
49
+ fmts = formats or ["all"]
50
+ ui.begin_phase("REPORT", f"REPORT ({lang.upper()})", "HTML / MD / JSON", metric_label="Reports", stage_key="report")
51
+ ui.set_meta(input=ctx.cfg.target_path.name, type="REPORT", output=str(target_out))
52
+ ui.update_stats(total=1)
53
+ ui.set_active(id="RPT", name="Analysis Reports", role=lang.upper(), depth="0", hash=",".join(fmts), step="BUILD_REPORTS")
54
+ ui.push_stream(f"Generating reports ({', '.join(fmts)} | lang={lang})...")
55
+ ui.render()
56
+
57
+ db = FindingsDB(db_path)
58
+ try:
59
+ files = generate_analysis_reports(ctx.state, db, summary_data, target_out, fmts, lang=lang, include_noise=include_noise, full_json=full_json)
60
+ if 'sarif' in fmts or 'all' in fmts:
61
+ files['sarif'] = generate_sarif_report(ctx.state, db, target_out / 'ANALYSIS_REPORT.sarif', include_noise=include_noise)
62
+ dur = round(time.time() - t0, 3)
63
+ ui.inc_stat("success")
64
+ ui.inc_stat("done")
65
+ ui.inc_stat("files_indexed", len(files))
66
+ ui.finish_stage("report", "COMPLETED", dur)
67
+ ui.push_event("OK", f"Generated {len(files)} report file(s) ({lang}) in {dur}s")
68
+ ui.render()
69
+
70
+ ctx.state.data["extensions"]["report"] = {
71
+ "files": {k: str(v) for k, v in files.items()},
72
+ "lang": lang,
73
+ "generated_at": time.strftime("%Y-%m-%d %H:%M:%S"),
74
+ }
75
+ ctx.state.save()
76
+ return {"duration_sec": dur, "lang": lang, "files": {k: str(v) for k, v in files.items()}}
77
+ finally:
78
+ db.close()
79
+ if owns_ui:
80
+ ui.stop()
@@ -0,0 +1,141 @@
1
+ import json
2
+ import time
3
+ from pathlib import Path
4
+ from typing import Any, Dict, List, Set
5
+
6
+ from ..core.context import PipelineContext
7
+ from ..storage.findings_db import FindingsDB
8
+ from .base import BaseAnalysisPlugin
9
+
10
+
11
+ class TracePlugin(BaseAnalysisPlugin):
12
+ name = "trace"
13
+ description = "Correlate an artifact, class, URL, permission, or JNI symbol across Manifest, Java, Smali, and Native layers"
14
+
15
+ def trace_target(self, ws_root: Path, query: str, limit: int = 150) -> Dict[str, Any]:
16
+ t0 = time.time()
17
+ db_path = ws_root / "10_Analysis" / "findings.db"
18
+ if not db_path.is_file():
19
+ raise FileNotFoundError(f"findings.db missing in workspace: {ws_root}")
20
+
21
+ db = FindingsDB(db_path)
22
+ try:
23
+ direct = db.query_findings(text_query=query, limit=limit)
24
+ related_classes: Set[str] = set()
25
+ related_libs: Set[str] = set()
26
+ related_units: Set[str] = set()
27
+
28
+ for r in direct:
29
+ related_units.add(r["unit_id"])
30
+ if r.get("class_name"):
31
+ related_classes.add(r["class_name"])
32
+ val = str(r.get("value", ""))
33
+ cid = r["catalog_id"]
34
+ if cid in ("ACT-001", "ACT-004", "ACT-005", "SRV-001", "REC-001", "PRO-001") and "." in val:
35
+ related_classes.add(val.split(" ", 1)[0])
36
+ elif cid == "NAT-005":
37
+ # Extract Java class from demangled Java_com_pkg_Cls_method()
38
+ sig = val.split("(", 1)[0].strip()
39
+ if "." in sig:
40
+ related_classes.add(sig.rsplit(".", 1)[0])
41
+ elif cid == "REF-002":
42
+ lib_tok = val.split("|", 1)[0].strip().strip("\"'")
43
+ if lib_tok:
44
+ related_libs.add(f"lib{lib_tok}.so" if not lib_tok.endswith(".so") else lib_tok)
45
+ elif cid in ("NAT-001", "NAT-002") and r.get("title"):
46
+ related_libs.add(Path(r.get("file_path") or val).name)
47
+
48
+ # 2nd-hop cross-layer expansion
49
+ manifest_links: List[Dict[str, Any]] = []
50
+ intent_links: List[Dict[str, Any]] = []
51
+ java_links: List[Dict[str, Any]] = []
52
+ native_links: List[Dict[str, Any]] = []
53
+ network_links: List[Dict[str, Any]] = []
54
+
55
+ seen_ids: Set[int] = {r["id"] for r in direct}
56
+
57
+ def _route(row: Dict[str, Any]) -> None:
58
+ cid = row["catalog_id"]
59
+ if cid.startswith(("ACT-", "SRV-", "REC-", "PRO-", "PER-", "SIG-")):
60
+ manifest_links.append(row)
61
+ elif cid.startswith("INT-"):
62
+ intent_links.append(row)
63
+ elif cid.startswith(("NAT-",)):
64
+ native_links.append(row)
65
+ elif cid.startswith(("URL-", "NET-", "NAPI-", "CFG-")):
66
+ network_links.append(row)
67
+ else:
68
+ java_links.append(row)
69
+
70
+ for r in direct:
71
+ _route(r)
72
+
73
+ for cls in sorted(related_classes)[:25]:
74
+ for r in db.query_findings(text_query=cls, limit=80):
75
+ if r["id"] not in seen_ids:
76
+ seen_ids.add(r["id"])
77
+ _route(r)
78
+
79
+ for lib in sorted(related_libs)[:15]:
80
+ for r in db.query_findings(catalog_ids=["NAT-*", "REF-002"], text_query=lib.replace("lib", "").replace(".so", ""), limit=80):
81
+ if r["id"] not in seen_ids:
82
+ seen_ids.add(r["id"])
83
+ _route(r)
84
+
85
+ return {
86
+ "query": query,
87
+ "workspace": str(ws_root),
88
+ "duration_sec": round(time.time() - t0, 3),
89
+ "direct_hits": len(direct),
90
+ "correlated_classes": sorted(related_classes)[:30],
91
+ "correlated_libs": sorted(related_libs)[:20],
92
+ "layers": {
93
+ "manifest_and_permissions": manifest_links[:limit],
94
+ "intents_and_deeplinks": intent_links[:limit],
95
+ "java_smali_and_security": java_links[:limit],
96
+ "native_and_jni": native_links[:limit],
97
+ "network_and_configs": network_links[:limit],
98
+ },
99
+ }
100
+ finally:
101
+ db.close()
102
+
103
+ def execute(self, ctx: PipelineContext, **kwargs: Any) -> Dict[str, Any]:
104
+ return self.trace_target(ctx.state.root, kwargs["query"], limit=kwargs.get("limit", 150))
105
+
106
+
107
+ def format_trace_output(trace_data: Dict[str, Any], fmt: str = "tree") -> str:
108
+ if fmt.lower() == "json":
109
+ return json.dumps(trace_data, indent=2, ensure_ascii=False)
110
+
111
+ lines = [
112
+ "=" * 78,
113
+ f"DEXSECT :: CROSS-LAYER TRACE ('{trace_data['query']}')",
114
+ "=" * 78,
115
+ f"Workspace : {trace_data['workspace']}",
116
+ f"Direct Hits : {trace_data['direct_hits']} (in {trace_data['duration_sec']}s)",
117
+ f"Related Classes : {', '.join(trace_data['correlated_classes'][:8]) or '(none)'}",
118
+ f"Related Libraries : {', '.join(trace_data['correlated_libs'][:8]) or '(none)'}",
119
+ "-" * 78,
120
+ ]
121
+
122
+ labels = [
123
+ ("manifest_and_permissions", "[1] MANIFEST, COMPONENTS & PERMISSIONS"),
124
+ ("intents_and_deeplinks", "[2] INTENTS & DEEP LINKS"),
125
+ ("java_smali_and_security", "[3] JAVA / KOTLIN / SMALI & INDICATORS"),
126
+ ("native_and_jni", "[4] NATIVE ELF (.so) & JNI BRIDGES"),
127
+ ("network_and_configs", "[5] NETWORK, URLS & CONFIGURATIONS"),
128
+ ]
129
+ for key, title in labels:
130
+ items = trace_data["layers"].get(key, [])
131
+ lines.append(f"\n{title} ({len(items)})")
132
+ if not items:
133
+ lines.append(" (none)")
134
+ continue
135
+ for r in items[:25]:
136
+ loc = f"{Path(r['file_path']).name}:{r['line_no']}" if r.get("file_path") else "-"
137
+ lines.append(f" ├─ [{r['catalog_id']} | u:{r['unit_id']} | {r.get('scope', 'app')}] {r.get('title')}: {str(r['value'])[:100]} ({loc})")
138
+ if len(items) > 25:
139
+ lines.append(f" └─ ... ({len(items) - 25} more items)")
140
+ lines.append("=" * 78)
141
+ return "\n".join(lines)
File without changes