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,503 @@
1
+ import re
2
+ import time
3
+ import xml.etree.ElementTree as ET
4
+ import zipfile
5
+ from collections import defaultdict, deque
6
+ from pathlib import Path
7
+ from typing import Any, Dict, List, Optional, Tuple
8
+
9
+ from ..core.context import ArtifactUnit, PipelineContext
10
+ from ..parsers.axml import decode_axml_bytes
11
+ from ..storage.findings_db import FindingItem, FindingsDB
12
+ from .base import BaseInspector, InspectorResult
13
+ from .text_scanner import classify_code_scope
14
+
15
+
16
+ ANDROID_NS = "{http://schemas.android.com/apk/res/android}"
17
+
18
+
19
+ def _attr(elem: ET.Element, name: str, default: Optional[str] = None) -> Optional[str]:
20
+ return elem.attrib.get(f"{ANDROID_NS}{name}", elem.attrib.get(name, default))
21
+
22
+
23
+ def _parse_apktool_yml(yml_path: Optional[Path]) -> Dict[str, str]:
24
+ info: Dict[str, str] = {}
25
+ if not yml_path or not yml_path.is_file():
26
+ return info
27
+ try:
28
+ text = yml_path.read_text(encoding="utf-8", errors="replace")
29
+ for key in ("minSdkVersion", "targetSdkVersion", "versionCode", "versionName"):
30
+ m = re.search(rf"^\s*{key}:\s*['\"]?([^'\"\r\n]+)['\"]?", text, re.MULTILINE)
31
+ if m:
32
+ info[key] = m.group(1).strip()
33
+ except OSError:
34
+ pass
35
+ return info
36
+
37
+
38
+ def _build_line_index(xml_text: str) -> Dict[str, deque]:
39
+ idx: Dict[str, deque] = defaultdict(deque)
40
+ for ln_no, line in enumerate(xml_text.splitlines(), start=1):
41
+ for m in re.finditer(r'(?:android:name|package)="([^"]+)"', line):
42
+ idx[m.group(1)].append(ln_no)
43
+ return idx
44
+
45
+
46
+ def _resolve_string_ref(val: Optional[str], decode_dir: Optional[Path]) -> Optional[str]:
47
+ if not val or not decode_dir:
48
+ return val
49
+ if val.startswith("@string/"):
50
+ key = val.split("/", 1)[1]
51
+ sxml = decode_dir / "res" / "values" / "strings.xml"
52
+ if sxml.is_file():
53
+ try:
54
+ root = ET.parse(sxml).getroot()
55
+ for el in root.findall("string"):
56
+ if el.attrib.get("name") == key and el.text:
57
+ return f"{el.text} ({val})"
58
+ except Exception:
59
+ pass
60
+ return val
61
+
62
+
63
+ def _parse_intent_filters(comp: ET.Element) -> List[Dict[str, Any]]:
64
+ filters = []
65
+ for if_el in comp.findall("intent-filter"):
66
+ actions = [_attr(a, "name", "") for a in if_el.findall("action")]
67
+ cats = [_attr(c, "name", "") for c in if_el.findall("category")]
68
+ data_list = []
69
+ for d in if_el.findall("data"):
70
+ dd = {}
71
+ for k in ("scheme", "host", "port", "path", "pathPrefix", "pathPattern", "mimeType"):
72
+ v = _attr(d, k)
73
+ if v:
74
+ dd[k] = v
75
+ if dd:
76
+ data_list.append(dd)
77
+ filters.append({
78
+ "autoVerify": _attr(if_el, "autoVerify", "false"),
79
+ "actions": [a for a in actions if a],
80
+ "categories": [c for c in cats if c],
81
+ "data": data_list,
82
+ })
83
+ return filters
84
+
85
+
86
+ def _parse_metadata(parent: ET.Element) -> List[Dict[str, Optional[str]]]:
87
+ out = []
88
+ for md in parent.findall("meta-data"):
89
+ out.append({
90
+ "name": _attr(md, "name"),
91
+ "value": _attr(md, "value"),
92
+ "resource": _attr(md, "resource"),
93
+ })
94
+ return out
95
+
96
+
97
+ class ManifestInspector(BaseInspector):
98
+ name = "manifest"
99
+ description = "Extract APP, PER, ACT, SRV, REC, PRO, INT, and manifest SEC items"
100
+ domains = ["Application Identity", "Permissions", "Components", "Intents & Deep Links", "Security Indicators"]
101
+ catalog_ids = [
102
+ "APP-*", "PER-001", "PER-002", "PER-003", "PER-004", "PER-005", "PER-006", "PER-007", "PER-008", "PER-009",
103
+ "ACT-*", "SRV-*", "REC-*", "PRO-*", "INT-001", "INT-002", "INT-003", "INT-004", "SEC-001", "SEC-002", "SEC-008",
104
+ ]
105
+
106
+ def _load_manifest_xml(self, unit: ArtifactUnit) -> Tuple[Optional[str], str]:
107
+ if unit.manifest_xml and Path(unit.manifest_xml).is_file():
108
+ p = Path(unit.manifest_xml)
109
+ raw = p.read_bytes()
110
+ return decode_axml_bytes(raw), str(p)
111
+ src = Path(unit.source_path) if unit.source_path else None
112
+ if src and src.is_file():
113
+ if src.suffix.lower() == ".xml":
114
+ return decode_axml_bytes(src.read_bytes()), str(src)
115
+ if zipfile.is_zipfile(src):
116
+ with zipfile.ZipFile(src, "r") as zf:
117
+ if "AndroidManifest.xml" in zf.namelist():
118
+ return decode_axml_bytes(zf.read("AndroidManifest.xml")), f"{src}!AndroidManifest.xml"
119
+ return None, ""
120
+
121
+ def run(
122
+ self,
123
+ ctx: PipelineContext,
124
+ db: FindingsDB,
125
+ units: List[ArtifactUnit],
126
+ profile: str,
127
+ ) -> InspectorResult:
128
+ t0 = time.time()
129
+ findings: List[FindingItem] = []
130
+ summary: Dict[str, Any] = {"units": {}}
131
+ perm_across_units: Dict[str, List[str]] = defaultdict(list)
132
+
133
+ for unit in units:
134
+ xml_text, m_path = self._load_manifest_xml(unit)
135
+ if not xml_text:
136
+ continue
137
+ try:
138
+ root = ET.fromstring(xml_text)
139
+ except ET.ParseError:
140
+ continue
141
+
142
+ dec_dir = Path(unit.decode_dir) if unit.decode_dir else None
143
+ yml_info = _parse_apktool_yml(Path(unit.apktool_yml) if unit.apktool_yml else None)
144
+ ln_idx = _build_line_index(xml_text)
145
+
146
+ def add(
147
+ cid: str,
148
+ dom: str,
149
+ sub: str,
150
+ title: str,
151
+ val: Optional[str],
152
+ extra: Optional[Dict] = None,
153
+ scope: str = "app",
154
+ ) -> None:
155
+ if val is None or val == "":
156
+ return
157
+ findings.append(FindingItem(
158
+ catalog_id=cid,
159
+ domain=dom,
160
+ subdomain=sub,
161
+ unit_id=unit.unit_id,
162
+ layer="manifest",
163
+ title=title,
164
+ value=str(val),
165
+ file_path=m_path,
166
+ line_no=(ln_idx[str(val)][0] if ln_idx.get(str(val)) else 0),
167
+ scope=scope,
168
+ extra=extra or {},
169
+ ))
170
+
171
+ # 01. APP-*
172
+ pkg = root.attrib.get("package", "")
173
+ vname = _attr(root, "versionName") or yml_info.get("versionName", "")
174
+ vcode = _attr(root, "versionCode") or yml_info.get("versionCode", "")
175
+ csdk = _attr(root, "compileSdkVersion") or root.attrib.get("platformBuildVersionCode", "")
176
+ uses_sdk = root.find("uses-sdk")
177
+ min_sdk = (_attr(uses_sdk, "minSdkVersion") if uses_sdk is not None else None) or yml_info.get("minSdkVersion", "")
178
+ tgt_sdk = (_attr(uses_sdk, "targetSdkVersion") if uses_sdk is not None else None) or yml_info.get("targetSdkVersion", "")
179
+
180
+ add("APP-001", "Application Identity", "Core", "Package Name", pkg)
181
+ add("APP-003", "Application Identity", "Core", "Version Name", vname)
182
+ add("APP-004", "Application Identity", "Core", "Version Code", vcode)
183
+ add("APP-005", "Application Identity", "SDK", "Min SDK", min_sdk)
184
+ add("APP-006", "Application Identity", "SDK", "Target SDK", tgt_sdk)
185
+ add("APP-007", "Application Identity", "SDK", "Compile SDK", csdk)
186
+ add("APP-010", "Application Identity", "Application", "Shared User ID", _attr(root, "sharedUserId"))
187
+ add("APP-011", "Application Identity", "Application", "Shared User Label", _attr(root, "sharedUserLabel"))
188
+ add("APP-012", "Application Identity", "Manifest", "Install Location", _attr(root, "installLocation"))
189
+
190
+ dex_names: List[str] = []
191
+ src_p = Path(unit.source_path) if unit.source_path else None
192
+ if src_p and src_p.is_file() and zipfile.is_zipfile(src_p):
193
+ with zipfile.ZipFile(src_p, "r") as zf:
194
+ dex_names = [n for n in zf.namelist() if n.lower().endswith(".dex") and "/" not in n]
195
+ if len(dex_names) > 1:
196
+ add("APP-019", "Application Identity", "Runtime", "MultiDex", f"{len(dex_names)} DEX files: {', '.join(sorted(dex_names))}")
197
+
198
+ app_el = root.find("application")
199
+ app_flags: Dict[str, Any] = {}
200
+ if app_el is not None:
201
+ lbl = _resolve_string_ref(_attr(app_el, "label"), dec_dir)
202
+ app_cls = _attr(app_el, "name")
203
+ dbg = _attr(app_el, "debuggable", "false")
204
+ bkp = _attr(app_el, "allowBackup", "true")
205
+ clr = _attr(app_el, "usesCleartextTraffic")
206
+ nsc = _attr(app_el, "networkSecurityConfig")
207
+ app_flags = {"debuggable": dbg, "allowBackup": bkp, "cleartext": clr, "networkSecurityConfig": nsc}
208
+
209
+ add("APP-002", "Application Identity", "Core", "App Label", lbl)
210
+ add("APP-008", "Application Identity", "Application", "Application Class", app_cls)
211
+ add("APP-009", "Application Identity", "Application", "Process Name", _attr(app_el, "process"))
212
+ add("APP-013", "Application Identity", "Flags", "Debuggable", dbg)
213
+ add("APP-014", "Application Identity", "Flags", "Allow Backup", bkp)
214
+ add("APP-015", "Application Identity", "Flags", "Full Backup Content", _attr(app_el, "fullBackupContent"))
215
+ add("APP-016", "Application Identity", "Flags", "Data Extraction Rules", _attr(app_el, "dataExtractionRules"))
216
+ add("APP-017", "Application Identity", "Flags", "Cleartext Traffic", clr)
217
+ add("APP-018", "Application Identity", "Flags", "RTL & LargeHeap", f"supportsRtl={_attr(app_el, 'supportsRtl')}, largeHeap={_attr(app_el, 'largeHeap')}")
218
+ add("APP-021", "Application Identity", "UI", "Theme & Icon", f"theme={_attr(app_el, 'theme')}, icon={_attr(app_el, 'icon')}")
219
+ add("APP-022", "Application Identity", "Flags", "Network Security Config", nsc)
220
+
221
+ for md in _parse_metadata(app_el):
222
+ if md["name"]:
223
+ md_scope = "third_party" if md["name"].startswith(("com.google.", "com.facebook.", "com.applovin.", "com.bytedance.")) else "app"
224
+ add("APP-020", "Application Identity", "Application", f"MetaData: {md['name']}", md["value"] or md["resource"] or "", md, scope=md_scope)
225
+
226
+ add("SEC-001", "Security Indicators", "Manifest", "Manifest Security Flags",
227
+ f"debuggable={dbg}, allowBackup={bkp}, cleartext={clr}, testOnly={_attr(app_el, 'testOnly', 'false')}", app_flags)
228
+
229
+ if nsc and nsc.startswith("@xml/") and dec_dir:
230
+ nsc_file = dec_dir / "res" / "xml" / f"{nsc.split('/', 1)[1]}.xml"
231
+ if nsc_file.is_file():
232
+ try:
233
+ nroot = ET.parse(nsc_file).getroot()
234
+ for tag_name in ("base-config", "domain-config", "debug-overrides"):
235
+ for cfg_el in nroot.findall(tag_name):
236
+ domains_txt = [d.text.strip() for d in cfg_el.findall("domain") if d.text]
237
+ pins = [p.text.strip() for p in cfg_el.findall(".//pin") if p.text]
238
+ certs = [_attr(c, "src") for c in cfg_el.findall(".//certificates")]
239
+ val_str = (
240
+ f"{tag_name} cleartext={cfg_el.attrib.get('cleartextTrafficPermitted')} "
241
+ f"domains={domains_txt} certs={certs} pins={len(pins)}"
242
+ )
243
+ findings.append(FindingItem(
244
+ catalog_id="SEC-002", domain="Security Indicators", subdomain="Network",
245
+ unit_id=unit.unit_id, layer="resources", title=f"NSC {tag_name}",
246
+ value=val_str, file_path=str(nsc_file),
247
+ extra={"domains": domains_txt, "certs": certs, "pins": pins},
248
+ ))
249
+ except Exception:
250
+ pass
251
+
252
+ # 03. PER-*
253
+ seen_unit_perms: Dict[str, int] = defaultdict(int)
254
+ for p_tag, cid in (("uses-permission", "PER-001"), ("uses-permission-sdk-23", "PER-006")):
255
+ for pel in root.findall(p_tag):
256
+ pname = _attr(pel, "name")
257
+ if not pname:
258
+ continue
259
+ seen_unit_perms[pname] += 1
260
+ perm_across_units[pname].append(unit.unit_id)
261
+ pflags = _attr(pel, "usesPermissionFlags")
262
+ max_sdk = _attr(pel, "maxSdkVersion")
263
+ add(cid, "Permissions", "Manifest", "Requested Permission", pname, {"flags": pflags, "maxSdk": max_sdk})
264
+ if pflags or max_sdk:
265
+ add("PER-007", "Permissions", "Manifest", f"Permission Flags ({pname})", f"flags={pflags}, maxSdk={max_sdk}")
266
+
267
+ for p_el in root.findall("permission"):
268
+ cname = _attr(p_el, "name")
269
+ plvl = _attr(p_el, "protectionLevel", "normal")
270
+ if cname:
271
+ add("PER-003", "Permissions", "Manifest", "Custom Permission", cname, {"protectionLevel": plvl})
272
+ add("PER-004", "Permissions", "Manifest", f"Protection Level ({cname})", plvl)
273
+
274
+ for pg in root.findall("permission-group") + root.findall("permission-tree"):
275
+ gname = _attr(pg, "name")
276
+ if gname:
277
+ add("PER-005", "Permissions", "Manifest", pg.tag, gname)
278
+
279
+ for q_el in root.findall("queries"):
280
+ for q_pkg in q_el.findall("package"):
281
+ qn = _attr(q_pkg, "name")
282
+ if qn:
283
+ add("APP-020", "Application Identity", "Queries", "Manifest Query Package", qn)
284
+ for q_int in q_el.findall("intent"):
285
+ qacts = [_attr(a, "name", "") for a in q_int.findall("action")]
286
+ if qacts:
287
+ add("INT-001", "Intents & Deep Links", "Manifest", "Queries Intent", ", ".join(qacts))
288
+
289
+ for uf in root.findall("uses-feature"):
290
+ ufn = _attr(uf, "name") or _attr(uf, "glEsVersion")
291
+ if ufn:
292
+ add("APP-020", "Application Identity", "Features", "Uses-Feature", f"{ufn} (req={_attr(uf, 'required', 'true')})")
293
+
294
+ # 04. Components (ACT, SRV, REC, PRO) + INT-*
295
+ comp_counts = {"activities": 0, "services": 0, "receivers": 0, "providers": 0, "unprotected_exported": 0}
296
+ if app_el is not None:
297
+ for act_tag in ("activity", "activity-alias"):
298
+ for el in app_el.findall(act_tag):
299
+ comp_counts["activities"] += 1
300
+ name = _attr(el, "name", "") or ""
301
+ c_scope = classify_code_scope(name, pkg)
302
+ filters = _parse_intent_filters(el)
303
+ exp_raw = _attr(el, "exported")
304
+ is_exp = (exp_raw.lower() == "true") if exp_raw is not None else bool(filters)
305
+ enabled = _attr(el, "enabled", "true")
306
+ perm = _attr(el, "permission")
307
+ add("ACT-001", "Components", "Activities", "Activity", name, {"tag": act_tag, "exported": is_exp, "enabled": enabled}, scope=c_scope)
308
+ if act_tag == "activity-alias":
309
+ add("ACT-002", "Components", "Activities", "Activity Alias Target", f"{name} -> {_attr(el, 'targetActivity')}", scope=c_scope)
310
+ if is_exp:
311
+ add("ACT-004", "Components", "Activities", "Exported Activity", name, {"permission": perm, "explicit": exp_raw is not None}, scope=c_scope)
312
+ if not perm:
313
+ comp_counts["unprotected_exported"] += 1
314
+ add("ACT-005", "Components", "Activities", "Unprotected Exported Activity", name, scope=c_scope)
315
+ add("SEC-008", "Security Indicators", "Components", "Unprotected Exported", f"Activity: {name}", scope=c_scope)
316
+ add("ACT-006", "Components", "Activities", f"Enabled={enabled}", name, scope=c_scope)
317
+ if perm:
318
+ add("ACT-010", "Components", "Activities", f"Permission on {name}", perm, scope=c_scope)
319
+ add("PER-008", "Permissions", "Manifest", f"Activity Guard ({name})", perm, scope=c_scope)
320
+ lm = _attr(el, "launchMode")
321
+ ta = _attr(el, "taskAffinity")
322
+ if lm or ta:
323
+ add("ACT-008", "Components", "Activities", f"Launch/Task ({name})", f"launchMode={lm}, taskAffinity={ta}", scope=c_scope)
324
+ if profile in ("standard", "deep"):
325
+ add("ACT-009", "Components", "Activities", f"UI Attrs ({name})", f"theme={_attr(el, 'theme')}, orientation={_attr(el, 'screenOrientation')}, configChanges={_attr(el, 'configChanges')}", scope=c_scope)
326
+
327
+ for flt in filters:
328
+ add("ACT-007", "Components", "Activities", f"IntentFilter ({name})", f"actions={flt['actions']}, cats={flt['categories']}", flt, scope=c_scope)
329
+ if "android.intent.action.MAIN" in flt["actions"] and "android.intent.category.LAUNCHER" in flt["categories"]:
330
+ add("ACT-003", "Components", "Activities", "Launcher Activity", name, scope=c_scope)
331
+ self._emit_intent_findings(
332
+ unit.unit_id, name, flt, m_path,
333
+ (ln_idx[name][0] if ln_idx.get(name) else 0), findings, c_scope,
334
+ )
335
+
336
+ for el in app_el.findall("service"):
337
+ comp_counts["services"] += 1
338
+ name = _attr(el, "name", "") or ""
339
+ c_scope = classify_code_scope(name, pkg)
340
+ filters = _parse_intent_filters(el)
341
+ exp_raw = _attr(el, "exported")
342
+ is_exp = (exp_raw.lower() == "true") if exp_raw is not None else bool(filters)
343
+ enabled = _attr(el, "enabled", "true")
344
+ perm = _attr(el, "permission")
345
+ add("SRV-001", "Components", "Services", "Service", name, {"exported": is_exp, "enabled": enabled}, scope=c_scope)
346
+ if is_exp:
347
+ add("SRV-002", "Components", "Services", "Exported Service", f"{name} (perm={perm})", scope=c_scope)
348
+ if not perm:
349
+ comp_counts["unprotected_exported"] += 1
350
+ add("SEC-008", "Security Indicators", "Components", "Unprotected Exported", f"Service: {name}", scope=c_scope)
351
+ add("SRV-003", "Components", "Services", f"Enabled={enabled}", name, scope=c_scope)
352
+ if perm:
353
+ add("SRV-005", "Components", "Services", f"Service Permission ({name})", perm, scope=c_scope)
354
+ add("PER-008", "Permissions", "Manifest", f"Service Guard ({name})", perm, scope=c_scope)
355
+ fst = _attr(el, "foregroundServiceType")
356
+ if fst:
357
+ add("SRV-006", "Components", "Services", f"ForegroundType ({name})", fst, scope=c_scope)
358
+ iso = _attr(el, "isolatedProcess")
359
+ proc = _attr(el, "process")
360
+ if iso or proc:
361
+ add("SRV-007", "Components", "Services", f"Process/Isolated ({name})", f"isolated={iso}, process={proc}", scope=c_scope)
362
+ for flt in filters:
363
+ add("SRV-004", "Components", "Services", f"IntentFilter ({name})", f"actions={flt['actions']}", flt, scope=c_scope)
364
+ self._emit_intent_findings(
365
+ unit.unit_id, name, flt, m_path,
366
+ (ln_idx[name][0] if ln_idx.get(name) else 0), findings, c_scope,
367
+ )
368
+ for md in _parse_metadata(el):
369
+ if md["name"]:
370
+ add("SRV-008", "Components", "Services", f"Service MetaData ({name})", f"{md['name']}={md['value'] or md['resource']}", scope=c_scope)
371
+
372
+ for el in app_el.findall("receiver"):
373
+ comp_counts["receivers"] += 1
374
+ name = _attr(el, "name", "") or ""
375
+ c_scope = classify_code_scope(name, pkg)
376
+ filters = _parse_intent_filters(el)
377
+ exp_raw = _attr(el, "exported")
378
+ is_exp = (exp_raw.lower() == "true") if exp_raw is not None else bool(filters)
379
+ enabled = _attr(el, "enabled", "true")
380
+ perm = _attr(el, "permission")
381
+ add("REC-001", "Components", "Receivers", "Receiver", name, {"exported": is_exp, "enabled": enabled}, scope=c_scope)
382
+ if is_exp:
383
+ add("REC-002", "Components", "Receivers", "Exported Receiver", f"{name} (perm={perm})", scope=c_scope)
384
+ if not perm:
385
+ comp_counts["unprotected_exported"] += 1
386
+ add("SEC-008", "Security Indicators", "Components", "Unprotected Exported", f"Receiver: {name}", scope=c_scope)
387
+ add("REC-003", "Components", "Receivers", f"Enabled={enabled}", name, scope=c_scope)
388
+ if perm:
389
+ add("PER-008", "Permissions", "Manifest", f"Receiver Guard ({name})", perm, scope=c_scope)
390
+ for flt in filters:
391
+ add("REC-004", "Components", "Receivers", f"IntentFilter ({name})", f"actions={flt['actions']}", flt, scope=c_scope)
392
+ self._emit_intent_findings(
393
+ unit.unit_id, name, flt, m_path,
394
+ (ln_idx[name][0] if ln_idx.get(name) else 0), findings, c_scope,
395
+ )
396
+ for md in _parse_metadata(el):
397
+ if md["name"]:
398
+ add("REC-005", "Components", "Receivers", f"Receiver MetaData ({name})", f"{md['name']}={md['value'] or md['resource']}", scope=c_scope)
399
+
400
+ for el in app_el.findall("provider"):
401
+ comp_counts["providers"] += 1
402
+ name = _attr(el, "name", "") or ""
403
+ c_scope = classify_code_scope(name, pkg)
404
+ auth = _attr(el, "authorities", "")
405
+ exp_raw = _attr(el, "exported")
406
+ is_exp = (exp_raw.lower() == "true") if exp_raw is not None else False
407
+ enabled = _attr(el, "enabled", "true")
408
+ perm = _attr(el, "permission")
409
+ rperm = _attr(el, "readPermission")
410
+ wperm = _attr(el, "writePermission")
411
+ grant = _attr(el, "grantUriPermissions")
412
+
413
+ add("PRO-001", "Components", "Providers", "Provider", name, scope=c_scope)
414
+ add("PRO-002", "Components", "Providers", f"Authorities ({name})", auth, scope=c_scope)
415
+ if is_exp:
416
+ add("PRO-003", "Components", "Providers", "Exported Provider", f"{name} | authorities={auth} | perm={perm or rperm or wperm}", scope=c_scope)
417
+ if not (perm or rperm or wperm):
418
+ comp_counts["unprotected_exported"] += 1
419
+ add("SEC-008", "Security Indicators", "Components", "Unprotected Exported", f"Provider: {name} ({auth})", scope=c_scope)
420
+ add("PRO-004", "Components", "Providers", f"Enabled/Init ({name})", f"enabled={enabled}, initOrder={_attr(el, 'initOrder')}", scope=c_scope)
421
+ if perm or rperm or wperm or grant:
422
+ mat = f"perm={perm}, read={rperm}, write={wperm}, grantUri={grant}"
423
+ add("PRO-005", "Components", "Providers", f"Provider Permissions ({name})", mat, scope=c_scope)
424
+ add("PER-009", "Permissions", "Manifest", f"Provider Perms ({name})", mat, scope=c_scope)
425
+ for pp in el.findall("path-permission") + el.findall("grant-uri-permission"):
426
+ add("PRO-006", "Components", "Providers", f"{pp.tag} ({name})", str(dict(pp.attrib)), scope=c_scope)
427
+
428
+ for md in _parse_metadata(el):
429
+ if not md["name"]:
430
+ continue
431
+ add("PRO-007", "Components", "Providers", f"MetaData ({name})", f"{md['name']}={md['value'] or md['resource']}", scope=c_scope)
432
+ if md["name"] == "android.support.FILE_PROVIDER_PATHS" and md["resource"] and md["resource"].startswith("@xml/") and dec_dir:
433
+ fp_xml = dec_dir / "res" / "xml" / f"{md['resource'].split('/', 1)[1]}.xml"
434
+ if fp_xml.is_file():
435
+ try:
436
+ fproot = ET.parse(fp_xml).getroot()
437
+ for p_el in list(fproot):
438
+ path_desc = f"{p_el.tag} name={p_el.attrib.get('name')} path={p_el.attrib.get('path')}"
439
+ findings.append(FindingItem(
440
+ catalog_id="PRO-007", domain="Components", subdomain="Providers",
441
+ unit_id=unit.unit_id, layer="resources", title=f"FileProvider Path ({name})",
442
+ value=path_desc, file_path=str(fp_xml), scope=c_scope,
443
+ ))
444
+ except Exception:
445
+ pass
446
+
447
+ summary["units"][unit.unit_id] = {
448
+ "package": pkg,
449
+ "version_name": vname,
450
+ "version_code": vcode,
451
+ "min_sdk": min_sdk,
452
+ "target_sdk": tgt_sdk,
453
+ "permissions_count": len(seen_unit_perms),
454
+ "components": comp_counts,
455
+ "flags": app_flags,
456
+ }
457
+
458
+ for pname, uids in sorted(perm_across_units.items()):
459
+ if len(uids) > 1:
460
+ findings.append(FindingItem(
461
+ catalog_id="PER-002", domain="Permissions", subdomain="Manifest",
462
+ unit_id=",".join(sorted(set(uids))), layer="manifest", title="Duplicate Permission",
463
+ value=pname, extra={"units": uids},
464
+ ))
465
+
466
+ inserted = db.insert_findings(findings)
467
+ return InspectorResult(
468
+ name=self.name,
469
+ status="COMPLETED",
470
+ duration_sec=round(time.time() - t0, 3),
471
+ findings_count=inserted,
472
+ summary=summary,
473
+ )
474
+
475
+ def _emit_intent_findings(
476
+ self, uid: str, comp_name: str, flt: Dict[str, Any], m_path: str, line_no: int, out: List[FindingItem], scope: str
477
+ ) -> None:
478
+ for act in flt["actions"]:
479
+ out.append(FindingItem(
480
+ catalog_id="INT-001", domain="Intents & Deep Links", subdomain="Manifest",
481
+ unit_id=uid, layer="manifest", title=f"Action ({comp_name})",
482
+ value=act, file_path=m_path, line_no=line_no, scope=scope,
483
+ ))
484
+ for d in flt["data"]:
485
+ scheme = d.get("scheme", "")
486
+ if scheme and scheme.lower() not in ("http", "https"):
487
+ out.append(FindingItem(
488
+ catalog_id="INT-002", domain="Intents & Deep Links", subdomain="Deep Links",
489
+ unit_id=uid, layer="manifest", title=f"Custom Scheme ({comp_name})",
490
+ value=scheme, file_path=m_path, line_no=line_no, scope=scope, extra=d,
491
+ ))
492
+ out.append(FindingItem(
493
+ catalog_id="INT-003", domain="Intents & Deep Links", subdomain="Deep Links",
494
+ unit_id=uid, layer="manifest", title=f"Deep Link ({comp_name})",
495
+ value=f"{scheme}://{d.get('host', '*')}{d.get('path') or d.get('pathPrefix') or d.get('pathPattern') or ''}",
496
+ file_path=m_path, line_no=line_no, scope=scope, extra=d,
497
+ ))
498
+ if flt.get("autoVerify") == "true" and scheme.lower() in ("http", "https") and d.get("host"):
499
+ out.append(FindingItem(
500
+ catalog_id="INT-004", domain="Intents & Deep Links", subdomain="App Links",
501
+ unit_id=uid, layer="manifest", title=f"App Link ({comp_name})",
502
+ value=d["host"], file_path=m_path, line_no=line_no, scope=scope, extra=d,
503
+ ))