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 json
2
+ import os
3
+ import re
4
+ import time
5
+ from pathlib import Path
6
+ from typing import Any, Dict, List, Set, Tuple
7
+
8
+ from ..core.context import ArtifactUnit, PipelineContext
9
+ from ..storage.findings_db import FindingItem, FindingsDB
10
+ from .base import BaseInspector, InspectorResult
11
+ from .text_scanner import classify_code_scope, scan_text_lines
12
+
13
+
14
+ PKG_RE = re.compile(r"^\s*package\s+([a-zA-Z0-9_.]+)\s*;")
15
+ TYPE_DECL_RE = re.compile(r"\b(?:public|private|protected|abstract|final|static|\s)*(class|interface|enum|@interface)\s+([A-Za-z0-9_$]+)")
16
+ NATIVE_METHOD_RE = re.compile(r"\bnative\s+[\w.<>\[\],\s]+\s+([A-Za-z0-9_$]+)\s*\([^)]*\)")
17
+ PERM_STR_RE = re.compile(r'"((?:android\.permission|[a-z0-9_]+\.permission)\.[A-Z0-9_]+)"')
18
+ JADX_INLINE_WARN_RE = re.compile(r"/\*\s*JADX\s+(?:WARN|ERROR):\s*(.+?)\*/")
19
+ SMALI_API_FALLBACK_RE = re.compile(
20
+ r"(Ldalvik/system/(?:DexClassLoader|PathClassLoader|InMemoryDexClassLoader)|"
21
+ r"Ljava/lang/Runtime;->exec|"
22
+ r"Ljavax/crypto/Cipher;->getInstance|"
23
+ r"Ljava/security/MessageDigest;->getInstance|"
24
+ r"Ljavax/net/ssl/(?:X509TrustManager|HostnameVerifier)|"
25
+ r"Ljava/lang/System;->load(?:Library)?)"
26
+ )
27
+
28
+ CODE_PREFILTER_RE = re.compile(
29
+ r"(?:Intent|Extra|PendingIntent|OkHttpClient|Retrofit|HttpURLConnection|HttpsURLConnection|"
30
+ r"Volley|RequestQueue|HttpClient|CronetEngine|Socket|WebSocketListener|Proxy|InetAddress|"
31
+ r"Class\.forName|ClassLoader|System\.load|addJavascriptInterface|evaluateJavascript|loadUrl|"
32
+ r"SharedPreferences|Database|ContentResolver|LocationManager|CameraManager|AudioRecord|"
33
+ r"BluetoothAdapter|ClipboardManager|AccessibilityService|getInstalled|queryIntentActivities|"
34
+ r"X509TrustManager|HostnameVerifier|checkServerTrusted|SSLContext|setJavaScriptEnabled|"
35
+ r"setAllowFileAccess|setAllowUniversalAccessFromFileURLs|setWebContentsDebuggingEnabled|"
36
+ r"Cipher\.getInstance|MessageDigest\.getInstance|SecretKeySpec|IvParameterSpec|KeyStore\.getInstance|"
37
+ r"/su|noshufou|xposed|frida-server|isDebuggerConnected|RootBeer|ro\.kernel\.qemu|ObjectInputStream)"
38
+ )
39
+
40
+ CODE_RULES: List[Tuple[str, str, str, str, re.Pattern, str]] = [
41
+ ("INT-005", "Intents & Deep Links", "Code", "Intent Call", re.compile(r"\bnew\s+Intent\s*\(|\.\s*(?:setAction|setComponent|setClassName)\s*\("), "standard"),
42
+ ("INT-006", "Intents & Deep Links", "Code", "Intent Extra", re.compile(r'\.\s*(?:putExtra|getStringExtra|getIntExtra|getBooleanExtra)\s*\(\s*"([^"]+)"'), "deep"),
43
+ ("INT-007", "Intents & Deep Links", "Code", "PendingIntent", re.compile(r"\bPendingIntent\.(?:getActivity|getService|getBroadcast|getForegroundService|getActivities)\s*\("), "standard"),
44
+ ("NAPI-001", "Network & URLs", "Network APIs", "HTTP Client", re.compile(r"\b(?:OkHttpClient|Retrofit|HttpURLConnection|HttpsURLConnection|Volley|RequestQueue|HttpClient|CronetEngine)\b"), "standard"),
45
+ ("NAPI-002", "Network & URLs", "Network APIs", "Socket/WebSocket", re.compile(r"\b(?:ServerSocket|DatagramSocket|WebSocketListener|new\s+Socket\s*\()\b"), "standard"),
46
+ ("NAPI-003", "Network & URLs", "Network APIs", "Proxy/DNS", re.compile(r"\b(?:ProxySelector|InetAddress\.getByName|java\.net\.Proxy)\b"), "deep"),
47
+ ("REF-001", "Code Intelligence", "Sensitive APIs", "Reflection/DynLoad", re.compile(r"\b(?:Class\.forName|DexClassLoader|PathClassLoader|InMemoryDexClassLoader|BaseDexClassLoader)\b"), "standard"),
48
+ ("REF-002", "Code Intelligence", "Sensitive APIs", "Native Load", re.compile(r"\bSystem\.(?:loadLibrary|load)\s*\(([^)]+)\)"), "standard"),
49
+ ("REF-003", "Code Intelligence", "Sensitive APIs", "WebView/JSBridge", re.compile(r"\b(?:addJavascriptInterface|evaluateJavascript|loadUrl)\s*\("), "standard"),
50
+ ("REF-004", "Code Intelligence", "Sensitive APIs", "Storage/DB API", re.compile(r"\b(?:getSharedPreferences|openOrCreateDatabase|SQLiteDatabase|ContentResolver)\b"), "deep"),
51
+ ("REF-005", "Code Intelligence", "Sensitive APIs", "Hardware/Sensor", re.compile(r"\b(?:LocationManager|CameraManager|AudioRecord|BluetoothAdapter|ClipboardManager|AccessibilityService)\b"), "standard"),
52
+ ("REF-006", "Code Intelligence", "Sensitive APIs", "PkgMgr/IPC", re.compile(r"\b(?:getInstalledPackages|getInstalledApplications|queryIntentActivities)\b"), "deep"),
53
+ ("SEC-003", "Security Indicators", "TLS", "TrustManager/Verifier", re.compile(r'(?:implements\s+[^{]*\b(?:X509TrustManager|HostnameVerifier)\b|new\s+(?:X509TrustManager|HostnameVerifier)\s*\(|\.(?:setHostnameVerifier|setDefaultHostnameVerifier|setSSLSocketFactory)\s*\(|public\s+(?:boolean\s+verify|void\s+checkServerTrusted)\s*\(|ALLOW_ALL_HOSTNAME_VERIFIER|SSLContext\.getInstance\s*\(\s*"(?:SSL|SSLv3|TLSv1|TLSv1\.1)")'), "standard"),
54
+ ("SEC-004", "Security Indicators", "WebView", "WebView Security", re.compile(r"\b(?:setJavaScriptEnabled|setAllowFileAccess|setAllowUniversalAccessFromFileURLs|setWebContentsDebuggingEnabled)\s*\([^)]*\)"), "standard"),
55
+ ("SEC-005", "Security Indicators", "Crypto", "Crypto API", re.compile(r"\b(?:Cipher\.getInstance|MessageDigest\.getInstance|SecretKeySpec|IvParameterSpec|KeyStore\.getInstance)\s*\(([^)]*)\)"), "standard"),
56
+ ("SEC-006", "Security Indicators", "Hardening", "Anti-Analysis/Root", re.compile(r"(?:/system/bin/su|/system/xbin/su|com\.noshufou\.android\.su|de\.robv\.android\.xposed|frida-server|isDebuggerConnected|RootBeer|ro\.kernel\.qemu)"), "standard"),
57
+ ("SEC-007", "Security Indicators", "IPC/Storage", "Serialization", re.compile(r"\bObjectInputStream\b"), "standard"),
58
+ ]
59
+
60
+
61
+ class CodeInspector(BaseInspector):
62
+ name = "code"
63
+ description = "Analyze decompiled Java/Kotlin, JADX recovery gap, Smali fallback, scope & shared line scan"
64
+ domains = ["Code Intelligence", "Permissions", "Intents & Deep Links", "Network & URLs", "Security Indicators"]
65
+ catalog_ids = [
66
+ "COD-001", "COD-002", "COD-003", "COD-GAP-001", "COD-GAP-002", "KOT-001",
67
+ "PER-010", "PER-011", "INT-005", "INT-006", "INT-007",
68
+ "NAPI-001", "NAPI-002", "NAPI-003",
69
+ "REF-001", "REF-002", "REF-003", "REF-004", "REF-005", "REF-006",
70
+ "SEC-003", "SEC-004", "SEC-005", "SEC-006", "SEC-007",
71
+ ]
72
+
73
+ def run(
74
+ self,
75
+ ctx: PipelineContext,
76
+ db: FindingsDB,
77
+ units: List[ArtifactUnit],
78
+ profile: str,
79
+ ) -> InspectorResult:
80
+ t0 = time.time()
81
+ findings: List[FindingItem] = []
82
+ summary: Dict[str, Any] = {}
83
+
84
+ app_pkgs: Dict[str, str] = {
85
+ r["unit_id"]: r["value"] for r in db.query_findings(catalog_ids=["APP-001"])
86
+ }
87
+ manifest_perms: Dict[str, Set[str]] = {}
88
+ for r in db.query_findings(catalog_ids=["PER-001", "PER-006"]):
89
+ manifest_perms.setdefault(r["unit_id"], set()).add(r["value"])
90
+
91
+ also_scan_text = ctx.runtime_cache.get("run_scanner_with_code", True)
92
+ text_strings_rows: List[tuple] = []
93
+ seen_domains: Dict[str, Dict[str, str]] = {}
94
+ seen_text_vals: Set[Tuple[str, str, str, str]] = set()
95
+ java_scanned_units: Set[str] = set()
96
+
97
+ for unit in units:
98
+ java_root = Path(unit.java_dir) if unit.java_dir else None
99
+ dec = Path(unit.decode_dir) if unit.decode_dir else None
100
+ src_scan_root = (java_root / "sources") if (java_root and (java_root / "sources").is_dir()) else java_root
101
+ app_pkg = app_pkgs.get(unit.unit_id, "")
102
+
103
+ packages: Set[str] = set()
104
+ type_counts = {"class": 0, "interface": 0, "enum": 0, "@interface": 0}
105
+ java_rel_classes: Set[str] = set()
106
+ kotlin_meta_hits = 0
107
+ kotlin_modules: List[str] = []
108
+ code_perms_found: Set[str] = set()
109
+ total_lines = 0
110
+ scanned_src_cnt = 0
111
+ last_tick = time.time()
112
+ third_party_caps: Dict[str, int] = {}
113
+
114
+ if dec and (dec / "kotlin").is_dir():
115
+ for km in (dec / "kotlin").rglob("*.kotlin_module"):
116
+ kotlin_modules.append(km.relative_to(dec).as_posix())
117
+ if kotlin_modules:
118
+ findings.append(FindingItem(
119
+ catalog_id="KOT-001", domain="Code Intelligence", subdomain="Kotlin",
120
+ unit_id=unit.unit_id, layer="kotlin", title="Kotlin Modules",
121
+ value=f"{len(kotlin_modules)} modules: {', '.join(kotlin_modules[:10])}",
122
+ ))
123
+
124
+ if src_scan_root and src_scan_root.is_dir():
125
+ for root, _dirs, files in os.walk(src_scan_root):
126
+ for fn in files:
127
+ if not fn.endswith((".java", ".kt")):
128
+ continue
129
+ fp = Path(root) / fn
130
+ scanned_src_cnt += 1
131
+ if time.time() - last_tick >= 0.3:
132
+ last_tick = time.time()
133
+ ctx.ui.push_stream(f"Scanning [{scanned_src_cnt}]: {fn}")
134
+ ctx.ui.render()
135
+
136
+ rel_cls = fp.relative_to(src_scan_root).with_suffix("").as_posix()
137
+ java_rel_classes.add(rel_cls)
138
+ primary_cls = rel_cls.replace("/", ".")
139
+ scope = classify_code_scope(primary_cls, app_pkg)
140
+
141
+ try:
142
+ text = fp.read_text(encoding="utf-8", errors="ignore")
143
+ except OSError:
144
+ continue
145
+
146
+ lines = text.splitlines()
147
+ total_lines += len(lines)
148
+ pkg_name = ""
149
+
150
+ if also_scan_text:
151
+ scan_text_lines(
152
+ unit.unit_id, "java", str(fp), lines, profile, scope,
153
+ findings, text_strings_rows, seen_domains, seen_text_vals,
154
+ class_name=primary_cls,
155
+ )
156
+
157
+ num_lines = len(lines)
158
+ for idx_l, line in enumerate(lines):
159
+ ln_no = idx_l + 1
160
+ if not pkg_name:
161
+ pm = PKG_RE.match(line)
162
+ if pm:
163
+ pkg_name = pm.group(1)
164
+ packages.add(pkg_name)
165
+
166
+ if ln_no <= 80:
167
+ tm = TYPE_DECL_RE.search(line)
168
+ if tm:
169
+ tkind, tname = tm.group(1), tm.group(2)
170
+ type_counts[tkind] = type_counts.get(tkind, 0) + 1
171
+ if profile == "deep" or scope == "app":
172
+ findings.append(FindingItem(
173
+ catalog_id="COD-001", domain="Code Intelligence", subdomain="Java/Kotlin",
174
+ unit_id=unit.unit_id, layer="java", title=tkind,
175
+ value=f"{pkg_name}.{tname}" if pkg_name else tname,
176
+ file_path=str(fp), line_no=ln_no, class_name=primary_cls, scope=scope,
177
+ ))
178
+ if "@Metadata(" in line:
179
+ kotlin_meta_hits += 1
180
+
181
+ if "JADX " in line:
182
+ jwm = JADX_INLINE_WARN_RE.search(line)
183
+ if jwm:
184
+ findings.append(FindingItem(
185
+ catalog_id="COD-GAP-002", domain="Code Intelligence", subdomain="Recovery",
186
+ unit_id=unit.unit_id, layer="java", title="JADX Method Warning/Error",
187
+ value=jwm.group(1).strip()[:240], file_path=str(fp), line_no=ln_no,
188
+ class_name=primary_cls, scope=scope,
189
+ ))
190
+
191
+ if "native " in line:
192
+ nm = NATIVE_METHOD_RE.search(line)
193
+ if nm:
194
+ findings.append(FindingItem(
195
+ catalog_id="COD-003", domain="Code Intelligence", subdomain="JNI",
196
+ unit_id=unit.unit_id, layer="java", title=f"native {nm.group(1)}",
197
+ value=line.strip()[:240], file_path=str(fp), line_no=ln_no,
198
+ class_name=primary_cls, method_name=nm.group(1), scope=scope,
199
+ ))
200
+
201
+ if ".permission." in line:
202
+ for pm in PERM_STR_RE.finditer(line):
203
+ p_str = pm.group(1)
204
+ code_perms_found.add(p_str)
205
+ findings.append(FindingItem(
206
+ catalog_id="PER-010", domain="Permissions", subdomain="Code",
207
+ unit_id=unit.unit_id, layer="java", title="Code Permission Ref",
208
+ value=p_str, file_path=str(fp), line_no=ln_no, class_name=primary_cls, scope=scope,
209
+ ))
210
+
211
+ if not line.lstrip().startswith(("import ", "package ")) and CODE_PREFILTER_RE.search(line):
212
+ target_expr = line
213
+ if line.count("(") > line.count(")") and idx_l + 1 < num_lines:
214
+ target_expr = " ".join(x.strip() for x in lines[idx_l : min(num_lines, idx_l + 4)])
215
+ for cid, dom, sub, title, rx, min_prof in CODE_RULES:
216
+ if min_prof == "deep" and profile != "deep":
217
+ continue
218
+ if profile == "fast" and min_prof != "fast":
219
+ continue
220
+ if scope == "third_party" and profile == "standard":
221
+ if third_party_caps.get(cid, 0) >= 350:
222
+ continue
223
+ m = rx.search(target_expr)
224
+ if m:
225
+ if scope == "third_party":
226
+ third_party_caps[cid] = third_party_caps.get(cid, 0) + 1
227
+ val = m.group(1) if (m.lastindex and m.group(1)) else m.group(0)
228
+ findings.append(FindingItem(
229
+ catalog_id=cid, domain=dom, subdomain=sub,
230
+ unit_id=unit.unit_id, layer="java", title=title,
231
+ value=f"{val.strip()} | {target_expr.strip()[:160]}",
232
+ file_path=str(fp), line_no=ln_no, class_name=primary_cls, scope=scope,
233
+ ))
234
+
235
+ if also_scan_text and scanned_src_cnt > 0:
236
+ java_scanned_units.add(unit.unit_id)
237
+
238
+ findings.append(FindingItem(
239
+ catalog_id="COD-002", domain="Code Intelligence", subdomain="Java/Kotlin",
240
+ unit_id=unit.unit_id, layer="java", title="Code Scale Stats",
241
+ value=f"packages={len(packages)}, files={len(java_rel_classes)}, lines={total_lines}, types={type_counts}",
242
+ extra={"packages": len(packages), "files": len(java_rel_classes), "lines": total_lines, "types": type_counts},
243
+ ))
244
+ if kotlin_meta_hits > 0:
245
+ findings.append(FindingItem(
246
+ catalog_id="KOT-001", domain="Code Intelligence", subdomain="Kotlin",
247
+ unit_id=unit.unit_id, layer="java", title="Kotlin @Metadata Classes",
248
+ value=str(kotlin_meta_hits),
249
+ ))
250
+
251
+ declared = manifest_perms.get(unit.unit_id, set())
252
+ for cp in sorted(code_perms_found - declared):
253
+ findings.append(FindingItem(
254
+ catalog_id="PER-011", domain="Permissions", subdomain="Code",
255
+ unit_id=unit.unit_id, layer="java", title="Undeclared Code Permission",
256
+ value=cp,
257
+ ))
258
+
259
+ jf_file = java_root / "jadx_failed_items.json" if java_root else None
260
+ if jf_file and jf_file.is_file():
261
+ try:
262
+ for item_err in json.loads(jf_file.read_text(encoding="utf-8", errors="ignore"))[:200]:
263
+ findings.append(FindingItem(
264
+ catalog_id="COD-GAP-002", domain="Code Intelligence", subdomain="Recovery",
265
+ unit_id=unit.unit_id, layer="java", title="JADX Log Failure",
266
+ value=str(item_err)[:240], file_path=str(jf_file),
267
+ ))
268
+ except Exception:
269
+ pass
270
+
271
+ missing_from_jadx: List[str] = []
272
+ if dec and dec.is_dir() and java_rel_classes:
273
+ for sdir in dec.iterdir():
274
+ if not (sdir.is_dir() and sdir.name.startswith("smali")):
275
+ continue
276
+ for root, _dirs, files in os.walk(sdir):
277
+ for fn in files:
278
+ if not fn.endswith(".smali") or "$" in fn:
279
+ continue
280
+ rel_s = (Path(root) / fn).relative_to(sdir).with_suffix("").as_posix()
281
+ if rel_s not in java_rel_classes:
282
+ missing_from_jadx.append(rel_s.replace("/", "."))
283
+
284
+ if missing_from_jadx:
285
+ missing_set = set(missing_from_jadx)
286
+ for cls in sorted(missing_from_jadx)[:200]:
287
+ findings.append(FindingItem(
288
+ catalog_id="COD-GAP-001", domain="Code Intelligence", subdomain="Recovery",
289
+ unit_id=unit.unit_id, layer="smali", title="Missing from JADX",
290
+ value=cls, class_name=cls, scope=classify_code_scope(cls, app_pkg),
291
+ ))
292
+ for sdir in dec.iterdir():
293
+ if not (sdir.is_dir() and sdir.name.startswith("smali")):
294
+ continue
295
+ for cls in sorted(missing_set)[:400]:
296
+ sm_p = sdir / (cls.replace(".", "/") + ".smali")
297
+ if not sm_p.is_file():
298
+ continue
299
+ try:
300
+ sm_lines = sm_p.read_text(encoding="utf-8", errors="ignore").splitlines()
301
+ except OSError:
302
+ continue
303
+ c_scope = classify_code_scope(cls, app_pkg)
304
+ if also_scan_text:
305
+ scan_text_lines(
306
+ unit.unit_id, "smali", str(sm_p), sm_lines, profile, c_scope,
307
+ findings, text_strings_rows, seen_domains, seen_text_vals, class_name=cls,
308
+ )
309
+ for sln, sline in enumerate(sm_lines, start=1):
310
+ if "invoke-" in sline:
311
+ sm_m = SMALI_API_FALLBACK_RE.search(sline)
312
+ if sm_m:
313
+ findings.append(FindingItem(
314
+ catalog_id="COD-GAP-002", domain="Code Intelligence", subdomain="Recovery",
315
+ unit_id=unit.unit_id, layer="smali", title="Smali Fallback API",
316
+ value=f"{sm_m.group(1)} | {sline.strip()[:140]}",
317
+ file_path=str(sm_p), line_no=sln, class_name=cls, scope=c_scope,
318
+ ))
319
+
320
+ summary[unit.unit_id] = {
321
+ "packages": len(packages),
322
+ "source_files": len(java_rel_classes),
323
+ "total_lines": total_lines,
324
+ "jadx_missing_classes": len(missing_from_jadx),
325
+ "kotlin_metadata_classes": kotlin_meta_hits,
326
+ }
327
+
328
+ if also_scan_text:
329
+ ctx.runtime_cache["java_scanned_units"] = java_scanned_units
330
+ ctx.runtime_cache["java_seen_domains"] = seen_domains
331
+ if text_strings_rows:
332
+ db.insert_strings(text_strings_rows)
333
+
334
+ inserted = db.insert_findings(findings)
335
+ return InspectorResult(
336
+ name=self.name,
337
+ status="COMPLETED",
338
+ duration_sec=round(time.time() - t0, 3),
339
+ findings_count=inserted,
340
+ summary=summary,
341
+ )
@@ -0,0 +1,178 @@
1
+ import json
2
+ import os
3
+ import re
4
+ import time
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.platform_utils import get_config_dir
10
+ from ..storage.findings_db import FindingItem, FindingsDB
11
+ from .base import BaseInspector, InspectorResult
12
+ from .text_scanner import classify_code_scope
13
+
14
+
15
+ TEXT_EXTS = {".java", ".kt", ".smali", ".xml", ".json", ".js", ".mjs", ".html", ".htm", ".properties", ".yml", ".yaml", ".txt", ".env"}
16
+ MAX_RULE_FILE_BYTES = 15 * 1024 * 1024
17
+
18
+
19
+ def resolve_rule_tokens(raw_tokens: List[str]) -> List[Path]:
20
+ builtin_dir = Path(__file__).resolve().parent.parent / "rules"
21
+ resolved: List[Path] = []
22
+ for tok in raw_tokens:
23
+ t = tok.strip()
24
+ if not t:
25
+ continue
26
+ if t.lower() == "builtin":
27
+ if builtin_dir.is_dir():
28
+ resolved.extend(sorted(builtin_dir.glob("*.json")))
29
+ elif t.lower().startswith("builtin:"):
30
+ name = t.split(":", 1)[1].strip()
31
+ if not name.endswith(".json"):
32
+ name += ".json"
33
+ cand = builtin_dir / name
34
+ if cand.is_file():
35
+ resolved.append(cand)
36
+ else:
37
+ resolved.append(Path(t).expanduser().resolve())
38
+ return resolved
39
+
40
+
41
+ def load_rule_packs(extra_paths: List[Path]) -> List[Dict[str, Any]]:
42
+ rule_files: List[Path] = []
43
+ user_rules_dir = get_config_dir() / "rules"
44
+ if user_rules_dir.is_dir():
45
+ rule_files.extend(sorted(user_rules_dir.glob("*.json")))
46
+ for ep in extra_paths:
47
+ if ep.is_file():
48
+ rule_files.append(ep)
49
+ elif ep.is_dir():
50
+ rule_files.extend(sorted(ep.glob("*.json")))
51
+
52
+ compiled_rules: List[Dict[str, Any]] = []
53
+ seen_files: Set[Path] = set()
54
+ for rf in rule_files:
55
+ rf_res = rf.resolve()
56
+ if rf_res in seen_files:
57
+ continue
58
+ seen_files.add(rf_res)
59
+ try:
60
+ data = json.loads(rf.read_text(encoding="utf-8", errors="replace"))
61
+ pack_name = data.get("pack_name", rf.stem)
62
+ for raw_r in data.get("rules", []):
63
+ pat_str = raw_r.get("regex", "")
64
+ if not pat_str:
65
+ continue
66
+ flags = re.IGNORECASE if raw_r.get("case_insensitive") else 0
67
+ compiled_rules.append({
68
+ "id": str(raw_r.get("id", "CUSTOM-001")),
69
+ "title": str(raw_r.get("title", "Custom Match")),
70
+ "domain": str(raw_r.get("domain", "Custom Rules")),
71
+ "subdomain": str(raw_r.get("subdomain", pack_name)),
72
+ "layers": {str(x).lower() for x in raw_r.get("layers", ["all"])},
73
+ "regex": re.compile(pat_str, flags),
74
+ })
75
+ except Exception:
76
+ continue
77
+ return compiled_rules
78
+
79
+
80
+ class CustomRulesInspector(BaseInspector):
81
+ name = "custom_rules"
82
+ description = "Execute user-defined JSON regex rule packs across workspace layers"
83
+ domains = ["Custom Rules"]
84
+ catalog_ids = ["CUSTOM-*"]
85
+
86
+ def __init__(self, rule_paths: Optional[List[Path]] = None) -> None:
87
+ self.rule_paths = rule_paths or []
88
+
89
+ def run(
90
+ self,
91
+ ctx: PipelineContext,
92
+ db: FindingsDB,
93
+ units: List[ArtifactUnit],
94
+ profile: str,
95
+ ) -> InspectorResult:
96
+ t0 = time.time()
97
+ rules = load_rule_packs(self.rule_paths)
98
+ if not rules:
99
+ return InspectorResult(name=self.name, status="SKIPPED", duration_sec=0.0, findings_count=0)
100
+
101
+ app_pkgs: Dict[str, str] = {
102
+ r["unit_id"]: r["value"] for r in db.query_findings(catalog_ids=["APP-001"])
103
+ }
104
+ findings: List[FindingItem] = []
105
+
106
+ for unit in units:
107
+ dec = Path(unit.decode_dir) if unit.decode_dir else None
108
+ java_dir = Path(unit.java_dir) if unit.java_dir else None
109
+ fw_dir = Path(unit.frameworks_dir) if unit.frameworks_dir else None
110
+ nat_dir = Path(unit.native_dir) if unit.native_dir else None
111
+ app_pkg = app_pkgs.get(unit.unit_id, "")
112
+
113
+ roots = []
114
+ if java_dir and java_dir.is_dir():
115
+ src_sub = java_dir / "sources"
116
+ roots.append(("java", src_sub if src_sub.is_dir() else java_dir))
117
+ if dec and dec.is_dir():
118
+ for sub, lyr in (("res", "resources"), ("assets", "assets"), ("unknown", "assets")):
119
+ if (dec / sub).is_dir():
120
+ roots.append((lyr, dec / sub))
121
+ if fw_dir and fw_dir.is_dir():
122
+ roots.append(("framework", fw_dir))
123
+ if nat_dir and nat_dir.is_dir():
124
+ roots.append(("native", nat_dir))
125
+
126
+ for layer, root_p in roots:
127
+ active_for_layer = [r for r in rules if "all" in r["layers"] or layer in r["layers"]]
128
+ if not active_for_layer:
129
+ continue
130
+ for root, _dirs, files in os.walk(root_p):
131
+ for fn in files:
132
+ fp = Path(root) / fn
133
+ if fp.suffix.lower() not in TEXT_EXTS:
134
+ continue
135
+ try:
136
+ if fp.stat().st_size > MAX_RULE_FILE_BYTES:
137
+ continue
138
+ lines = fp.read_text(encoding="utf-8", errors="ignore").splitlines()
139
+ except OSError:
140
+ continue
141
+
142
+ cls_name = ""
143
+ scope = "app"
144
+ if layer == "java" and java_dir:
145
+ base_j = (java_dir / "sources") if (java_dir / "sources").is_dir() else java_dir
146
+ try:
147
+ cls_name = fp.relative_to(base_j).with_suffix("").as_posix().replace("/", ".")
148
+ scope = classify_code_scope(cls_name, app_pkg)
149
+ except ValueError:
150
+ pass
151
+
152
+ for ln_no, line in enumerate(lines, start=1):
153
+ for rule in active_for_layer:
154
+ m = rule["regex"].search(line)
155
+ if m:
156
+ val = m.group(1) if (m.lastindex and m.group(1)) else m.group(0)
157
+ findings.append(FindingItem(
158
+ catalog_id=rule["id"],
159
+ domain=rule["domain"],
160
+ subdomain=rule["subdomain"],
161
+ unit_id=unit.unit_id,
162
+ layer=layer,
163
+ title=rule["title"],
164
+ value=val[:300],
165
+ file_path=str(fp),
166
+ line_no=ln_no,
167
+ class_name=cls_name,
168
+ scope=scope,
169
+ ))
170
+
171
+ inserted = db.insert_findings(findings)
172
+ return InspectorResult(
173
+ name=self.name,
174
+ status="COMPLETED",
175
+ duration_sec=round(time.time() - t0, 3),
176
+ findings_count=inserted,
177
+ summary={"rules_loaded": len(rules)},
178
+ )
@@ -0,0 +1,144 @@
1
+ import os
2
+ import re
3
+ import struct
4
+ import time
5
+ import zipfile
6
+ from pathlib import Path
7
+ from typing import Any, Dict, List
8
+
9
+ from ..core.context import ArtifactUnit, PipelineContext
10
+ from ..storage.findings_db import FindingItem, FindingsDB
11
+ from .base import BaseInspector, InspectorResult
12
+
13
+
14
+ SMALI_SENSITIVE_RE = re.compile(
15
+ r"(Ldalvik/system/(?:DexClassLoader|PathClassLoader|InMemoryDexClassLoader)|"
16
+ r"Ljava/lang/Runtime;->exec|"
17
+ r"Ljavax/crypto/Cipher;->getInstance|"
18
+ r"Ljava/security/MessageDigest;->getInstance|"
19
+ r"Ljava/lang/System;->load(?:Library)?)"
20
+ )
21
+
22
+
23
+ class DexInspector(BaseInspector):
24
+ name = "dex"
25
+ description = "Extract DEX binary header metadata and Smali structure/invocation stats"
26
+ domains = ["DEX & Smali"]
27
+ catalog_ids = ["DEX-001", "DEX-002", "DEX-003", "DEX-004"]
28
+
29
+ def run(
30
+ self,
31
+ ctx: PipelineContext,
32
+ db: FindingsDB,
33
+ units: List[ArtifactUnit],
34
+ profile: str,
35
+ ) -> InspectorResult:
36
+ t0 = time.time()
37
+ findings: List[FindingItem] = []
38
+ summary: Dict[str, Any] = {}
39
+
40
+ for unit in units:
41
+ src = Path(unit.source_path) if unit.source_path else None
42
+ dec = Path(unit.decode_dir) if unit.decode_dir else None
43
+ dex_info_list = []
44
+
45
+ if src and src.is_file() and zipfile.is_zipfile(src):
46
+ with zipfile.ZipFile(src, "r") as zf:
47
+ for zi in sorted(zf.infolist(), key=lambda z: z.filename):
48
+ if zi.filename == "META-INF/com/android/build/gradle/app-metadata.properties" or (zi.filename.startswith("META-INF/") and zi.filename.endswith(".version")) or zi.filename == "kotlin-tooling-metadata.json":
49
+ raw_meta = zf.read(zi).decode("utf-8", errors="ignore").strip()
50
+ if raw_meta:
51
+ findings.append(FindingItem(
52
+ catalog_id="APP-020", domain="Application Identity", subdomain="Build Tooling",
53
+ unit_id=unit.unit_id, layer="apk_zip", title=f"BuildMeta: {Path(zi.filename).name}",
54
+ value=raw_meta[:400].replace("\n", " | "), file_path=zi.filename,
55
+ ))
56
+ if not zi.filename.lower().endswith(".dex") or "/" in zi.filename:
57
+ continue
58
+ with zf.open(zi) as f:
59
+ hdr = f.read(112)
60
+ ver = ""
61
+ counts = {}
62
+ if len(hdr) >= 104 and hdr[:4] == b"dex\n":
63
+ ver = hdr[4:7].decode("ascii", errors="ignore")
64
+ str_sz, typ_sz, _prt_sz, fld_sz, mth_sz, cls_sz = (
65
+ struct.unpack_from("<I", hdr, 56)[0],
66
+ struct.unpack_from("<I", hdr, 64)[0],
67
+ struct.unpack_from("<I", hdr, 72)[0],
68
+ struct.unpack_from("<I", hdr, 80)[0],
69
+ struct.unpack_from("<I", hdr, 88)[0],
70
+ struct.unpack_from("<I", hdr, 96)[0],
71
+ )
72
+ counts = {
73
+ "strings": str_sz,
74
+ "types": typ_sz,
75
+ "fields": fld_sz,
76
+ "methods": mth_sz,
77
+ "classes": cls_sz,
78
+ }
79
+ findings.append(FindingItem(
80
+ catalog_id="DEX-002", domain="DEX & Smali", subdomain="DEX Header",
81
+ unit_id=unit.unit_id, layer="dex", title=f"Header Counts ({zi.filename})",
82
+ value=f"classes={cls_sz}, methods={mth_sz}, fields={fld_sz}, strings={str_sz}",
83
+ file_path=zi.filename, extra=counts,
84
+ ))
85
+ dex_info_list.append({"name": zi.filename, "size": zi.file_size, "version": ver, **counts})
86
+ findings.append(FindingItem(
87
+ catalog_id="DEX-001", domain="DEX & Smali", subdomain="DEX Header",
88
+ unit_id=unit.unit_id, layer="dex", title=zi.filename,
89
+ value=f"version={ver or 'unknown'}, size={zi.file_size}",
90
+ file_path=zi.filename, extra={"size": zi.file_size, "version": ver},
91
+ ))
92
+
93
+ smali_roots: List[str] = []
94
+ smali_files = 0
95
+ java_missing = (unit.metrics.get('java_files', 0) == 0)
96
+ smali_hit_cap = 0
97
+ if dec and dec.is_dir():
98
+ for d in sorted(dec.iterdir()):
99
+ if d.is_dir() and d.name.startswith("smali"):
100
+ smali_roots.append(d.name)
101
+ for root, _dirs, files in os.walk(d):
102
+ for fn in files:
103
+ if not fn.endswith(".smali"):
104
+ continue
105
+ smali_files += 1
106
+ if (profile == "deep" or java_missing) and smali_hit_cap < 500:
107
+ fp = Path(root) / fn
108
+ try:
109
+ txt = fp.read_text(encoding="utf-8", errors="ignore")
110
+ for ln, line in enumerate(txt.splitlines(), start=1):
111
+ if "invoke-" in line:
112
+ m = SMALI_SENSITIVE_RE.search(line)
113
+ if m:
114
+ smali_hit_cap += 1
115
+ findings.append(FindingItem(
116
+ catalog_id="DEX-004", domain="DEX & Smali", subdomain="Smali",
117
+ unit_id=unit.unit_id, layer="smali", title="Sensitive Smali Invoke",
118
+ value=m.group(1), file_path=str(fp), line_no=ln,
119
+ ))
120
+ except OSError:
121
+ continue
122
+
123
+ if smali_roots:
124
+ findings.append(FindingItem(
125
+ catalog_id="DEX-003", domain="DEX & Smali", subdomain="Smali",
126
+ unit_id=unit.unit_id, layer="smali", title="Smali Structure",
127
+ value=f"roots={len(smali_roots)} ({', '.join(smali_roots)}), smali_files={smali_files}",
128
+ extra={"roots": smali_roots, "smali_files": smali_files},
129
+ ))
130
+
131
+ summary[unit.unit_id] = {
132
+ "dex_files": dex_info_list,
133
+ "smali_roots": smali_roots,
134
+ "smali_files": smali_files,
135
+ }
136
+
137
+ inserted = db.insert_findings(findings)
138
+ return InspectorResult(
139
+ name=self.name,
140
+ status="COMPLETED",
141
+ duration_sec=round(time.time() - t0, 3),
142
+ findings_count=inserted,
143
+ summary=summary,
144
+ )