dexsect 4.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dexsect/__init__.py +4 -0
- dexsect/__main__.py +5 -0
- dexsect/catalog/EXTRACTION_CATALOG.json +4057 -0
- dexsect/catalog/__init__.py +0 -0
- dexsect/cli.py +1272 -0
- dexsect/core/__init__.py +0 -0
- dexsect/core/config.py +177 -0
- dexsect/core/context.py +181 -0
- dexsect/core/i18n.py +40 -0
- dexsect/core/pipeline.py +153 -0
- dexsect/core/platform_utils.py +164 -0
- dexsect/core/runner.py +124 -0
- dexsect/core/theme.py +64 -0
- dexsect/core/ui.py +405 -0
- dexsect/core/utils.py +150 -0
- dexsect/inspectors/__init__.py +0 -0
- dexsect/inspectors/assets_db_inspector.py +235 -0
- dexsect/inspectors/base.py +46 -0
- dexsect/inspectors/bundle_inspector.py +55 -0
- dexsect/inspectors/code_inspector.py +341 -0
- dexsect/inspectors/custom_rules_inspector.py +178 -0
- dexsect/inspectors/dex_inspector.py +144 -0
- dexsect/inspectors/manifest_inspector.py +503 -0
- dexsect/inspectors/native_fw_inspector.py +167 -0
- dexsect/inspectors/resources_inspector.py +195 -0
- dexsect/inspectors/scanner_inspector.py +153 -0
- dexsect/inspectors/signing_inspector.py +423 -0
- dexsect/inspectors/text_scanner.py +336 -0
- dexsect/locales/__init__.py +0 -0
- dexsect/locales/ar.json +130 -0
- dexsect/locales/de.json +51 -0
- dexsect/locales/en.json +110 -0
- dexsect/locales/es.json +51 -0
- dexsect/locales/fr.json +51 -0
- dexsect/locales/ja.json +51 -0
- dexsect/locales/pt.json +51 -0
- dexsect/locales/ru.json +51 -0
- dexsect/locales/tr.json +51 -0
- dexsect/locales/zh.json +51 -0
- dexsect/parsers/__init__.py +0 -0
- dexsect/parsers/axml.py +264 -0
- dexsect/parsers/bundle.py +214 -0
- dexsect/parsers/elf.py +396 -0
- dexsect/phases/__init__.py +0 -0
- dexsect/phases/base.py +102 -0
- dexsect/phases/decode.py +507 -0
- dexsect/phases/decompile.py +408 -0
- dexsect/phases/fingerprint.py +341 -0
- dexsect/phases/frameworks.py +377 -0
- dexsect/phases/mapper.py +41 -0
- dexsect/phases/native.py +188 -0
- dexsect/plugins/__init__.py +0 -0
- dexsect/plugins/base.py +20 -0
- dexsect/plugins/diff.py +162 -0
- dexsect/plugins/inspect.py +172 -0
- dexsect/plugins/report.py +80 -0
- dexsect/plugins/trace.py +141 -0
- dexsect/reporting/__init__.py +0 -0
- dexsect/reporting/analysis_report.py +1190 -0
- dexsect/reporting/diff_report.py +144 -0
- dexsect/reporting/sarif_report.py +109 -0
- dexsect/reporting/unpack_map.py +149 -0
- dexsect/rules/__init__.py +0 -0
- dexsect/rules/anti_analysis.json +45 -0
- dexsect/rules/crypto_audit.json +41 -0
- dexsect/rules/secrets_extended.json +46 -0
- dexsect/storage/__init__.py +0 -0
- dexsect/storage/findings_db.py +460 -0
- dexsect-4.1.0.dist-info/METADATA +532 -0
- dexsect-4.1.0.dist-info/RECORD +74 -0
- dexsect-4.1.0.dist-info/WHEEL +5 -0
- dexsect-4.1.0.dist-info/entry_points.txt +2 -0
- dexsect-4.1.0.dist-info/licenses/LICENSE +21 -0
- dexsect-4.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,460 @@
|
|
|
1
|
+
import csv
|
|
2
|
+
import io
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
import sqlite3
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any, Dict, Iterable, List, Optional, Sequence
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
CTRL_BYTES_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\ufffd]")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _clean_db_text(val: Any) -> str:
|
|
15
|
+
if val is None:
|
|
16
|
+
return ""
|
|
17
|
+
return CTRL_BYTES_RE.sub("", str(val))
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
_CATALOG_REL_CACHE: Optional[Dict[str, str]] = None
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _get_catalog_reliability(cid: str) -> str:
|
|
25
|
+
global _CATALOG_REL_CACHE
|
|
26
|
+
if _CATALOG_REL_CACHE is None:
|
|
27
|
+
_CATALOG_REL_CACHE = {}
|
|
28
|
+
cat_p = Path(__file__).resolve().parent.parent / "catalog" / "EXTRACTION_CATALOG.json"
|
|
29
|
+
if cat_p.is_file():
|
|
30
|
+
try:
|
|
31
|
+
data = json.loads(cat_p.read_text(encoding="utf-8"))
|
|
32
|
+
_CATALOG_REL_CACHE = {
|
|
33
|
+
it["id"]: it.get("reliability", "high")
|
|
34
|
+
for it in data.get("items", [])
|
|
35
|
+
}
|
|
36
|
+
except Exception:
|
|
37
|
+
_CATALOG_REL_CACHE = {}
|
|
38
|
+
if cid.startswith("CUSTOM-"):
|
|
39
|
+
return "medium"
|
|
40
|
+
return _CATALOG_REL_CACHE.get(cid, "high")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass
|
|
44
|
+
class FindingItem:
|
|
45
|
+
catalog_id: str
|
|
46
|
+
domain: str
|
|
47
|
+
subdomain: str
|
|
48
|
+
unit_id: str
|
|
49
|
+
layer: str
|
|
50
|
+
title: str
|
|
51
|
+
value: str
|
|
52
|
+
file_path: str = ""
|
|
53
|
+
line_no: int = 0
|
|
54
|
+
class_name: str = ""
|
|
55
|
+
method_name: str = ""
|
|
56
|
+
scope: str = "app"
|
|
57
|
+
confidence: str = ""
|
|
58
|
+
extra: Dict[str, Any] = field(default_factory=dict)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class FindingsDB:
|
|
62
|
+
def __init__(self, db_path: Path) -> None:
|
|
63
|
+
self.db_path = db_path
|
|
64
|
+
self.db_path.parent.mkdir(parents=True, exist_ok=True)
|
|
65
|
+
self.conn = sqlite3.connect(str(self.db_path))
|
|
66
|
+
self.conn.row_factory = sqlite3.Row
|
|
67
|
+
self.has_fts5 = False
|
|
68
|
+
self._init_schema()
|
|
69
|
+
|
|
70
|
+
def _init_schema(self) -> None:
|
|
71
|
+
cur = self.conn.cursor()
|
|
72
|
+
cur.execute("PRAGMA journal_mode=WAL;")
|
|
73
|
+
cur.execute("PRAGMA synchronous=NORMAL;")
|
|
74
|
+
cur.execute(
|
|
75
|
+
"""
|
|
76
|
+
CREATE TABLE IF NOT EXISTS findings (
|
|
77
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
78
|
+
catalog_id TEXT NOT NULL,
|
|
79
|
+
domain TEXT NOT NULL,
|
|
80
|
+
subdomain TEXT,
|
|
81
|
+
unit_id TEXT NOT NULL,
|
|
82
|
+
layer TEXT,
|
|
83
|
+
title TEXT,
|
|
84
|
+
value TEXT NOT NULL,
|
|
85
|
+
file_path TEXT,
|
|
86
|
+
line_no INTEGER DEFAULT 0,
|
|
87
|
+
class_name TEXT,
|
|
88
|
+
method_name TEXT,
|
|
89
|
+
scope TEXT DEFAULT 'app',
|
|
90
|
+
confidence TEXT DEFAULT 'high',
|
|
91
|
+
extra_json TEXT DEFAULT '{}'
|
|
92
|
+
);
|
|
93
|
+
"""
|
|
94
|
+
)
|
|
95
|
+
cur.execute("CREATE INDEX IF NOT EXISTS idx_findings_cid ON findings(catalog_id);")
|
|
96
|
+
cur.execute("CREATE INDEX IF NOT EXISTS idx_findings_dom ON findings(domain);")
|
|
97
|
+
cur.execute("CREATE INDEX IF NOT EXISTS idx_findings_unit ON findings(unit_id);")
|
|
98
|
+
cur.execute("CREATE INDEX IF NOT EXISTS idx_findings_layer ON findings(layer);")
|
|
99
|
+
|
|
100
|
+
cols_info = {r[1] for r in cur.execute("PRAGMA table_info(findings);").fetchall()}
|
|
101
|
+
if "scope" not in cols_info:
|
|
102
|
+
cur.execute("ALTER TABLE findings ADD COLUMN scope TEXT DEFAULT 'app';")
|
|
103
|
+
if "confidence" not in cols_info:
|
|
104
|
+
cur.execute("ALTER TABLE findings ADD COLUMN confidence TEXT DEFAULT 'high';")
|
|
105
|
+
cur.execute("CREATE INDEX IF NOT EXISTS idx_findings_scope ON findings(scope);")
|
|
106
|
+
cur.execute("CREATE INDEX IF NOT EXISTS idx_findings_conf ON findings(confidence);")
|
|
107
|
+
|
|
108
|
+
cur.execute(
|
|
109
|
+
"""
|
|
110
|
+
CREATE TABLE IF NOT EXISTS strings_index (
|
|
111
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
112
|
+
unit_id TEXT NOT NULL,
|
|
113
|
+
layer TEXT NOT NULL,
|
|
114
|
+
file_path TEXT NOT NULL,
|
|
115
|
+
line_no INTEGER DEFAULT 0,
|
|
116
|
+
value TEXT NOT NULL
|
|
117
|
+
);
|
|
118
|
+
"""
|
|
119
|
+
)
|
|
120
|
+
cur.execute("CREATE INDEX IF NOT EXISTS idx_strings_unit ON strings_index(unit_id);")
|
|
121
|
+
|
|
122
|
+
try:
|
|
123
|
+
cur.execute(
|
|
124
|
+
"""
|
|
125
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS findings_fts USING fts5(
|
|
126
|
+
catalog_id, domain, title, value, file_path, class_name, method_name, extra_json,
|
|
127
|
+
content='findings', content_rowid='id'
|
|
128
|
+
);
|
|
129
|
+
"""
|
|
130
|
+
)
|
|
131
|
+
cur.execute(
|
|
132
|
+
"""
|
|
133
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS strings_fts USING fts5(
|
|
134
|
+
unit_id, layer, file_path, value,
|
|
135
|
+
content='strings_index', content_rowid='id'
|
|
136
|
+
);
|
|
137
|
+
"""
|
|
138
|
+
)
|
|
139
|
+
self.has_fts5 = True
|
|
140
|
+
except sqlite3.OperationalError:
|
|
141
|
+
self.has_fts5 = False
|
|
142
|
+
self.conn.commit()
|
|
143
|
+
|
|
144
|
+
def rebuild_fts(self) -> None:
|
|
145
|
+
if self.has_fts5:
|
|
146
|
+
cur = self.conn.cursor()
|
|
147
|
+
cur.execute("INSERT INTO findings_fts(findings_fts) VALUES('rebuild');")
|
|
148
|
+
cur.execute("INSERT INTO strings_fts(strings_fts) VALUES('rebuild');")
|
|
149
|
+
self.conn.commit()
|
|
150
|
+
|
|
151
|
+
def clear_all(self) -> None:
|
|
152
|
+
cur = self.conn.cursor()
|
|
153
|
+
cur.execute("DELETE FROM findings;")
|
|
154
|
+
cur.execute("DELETE FROM strings_index;")
|
|
155
|
+
self.conn.commit()
|
|
156
|
+
|
|
157
|
+
def clear_inspectors_catalog_ids(self, catalog_ids: Sequence[str]) -> None:
|
|
158
|
+
if not catalog_ids:
|
|
159
|
+
return
|
|
160
|
+
clauses = []
|
|
161
|
+
params: List[str] = []
|
|
162
|
+
for cid in catalog_ids:
|
|
163
|
+
if cid.endswith("*"):
|
|
164
|
+
clauses.append("catalog_id LIKE ?")
|
|
165
|
+
params.append(cid[:-1] + "%")
|
|
166
|
+
else:
|
|
167
|
+
clauses.append("catalog_id = ?")
|
|
168
|
+
params.append(cid)
|
|
169
|
+
cur = self.conn.cursor()
|
|
170
|
+
cur.execute(f"DELETE FROM findings WHERE {' OR '.join(clauses)};", params)
|
|
171
|
+
self.conn.commit()
|
|
172
|
+
|
|
173
|
+
def insert_findings(self, items: Iterable[FindingItem], rebuild_fts: bool = False) -> int:
|
|
174
|
+
rows = [
|
|
175
|
+
(
|
|
176
|
+
it.catalog_id,
|
|
177
|
+
it.domain,
|
|
178
|
+
it.subdomain,
|
|
179
|
+
it.unit_id,
|
|
180
|
+
it.layer,
|
|
181
|
+
_clean_db_text(it.title),
|
|
182
|
+
_clean_db_text(it.value),
|
|
183
|
+
it.file_path,
|
|
184
|
+
it.line_no,
|
|
185
|
+
it.class_name,
|
|
186
|
+
it.method_name,
|
|
187
|
+
it.scope or "app",
|
|
188
|
+
(it.confidence or ("low" if it.scope == "boilerplate" else _get_catalog_reliability(it.catalog_id))),
|
|
189
|
+
json.dumps(it.extra, ensure_ascii=False) if it.extra else "{}",
|
|
190
|
+
)
|
|
191
|
+
for it in items
|
|
192
|
+
]
|
|
193
|
+
if not rows:
|
|
194
|
+
return 0
|
|
195
|
+
cur = self.conn.cursor()
|
|
196
|
+
cur.executemany(
|
|
197
|
+
"""
|
|
198
|
+
INSERT INTO findings (
|
|
199
|
+
catalog_id, domain, subdomain, unit_id, layer, title, value,
|
|
200
|
+
file_path, line_no, class_name, method_name, scope, confidence, extra_json
|
|
201
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
|
|
202
|
+
""",
|
|
203
|
+
rows,
|
|
204
|
+
)
|
|
205
|
+
self.conn.commit()
|
|
206
|
+
if rebuild_fts:
|
|
207
|
+
self.rebuild_fts()
|
|
208
|
+
return len(rows)
|
|
209
|
+
|
|
210
|
+
def insert_strings(self, rows: Iterable[tuple]) -> int:
|
|
211
|
+
batch = [(u, ly, fp, ln, _clean_db_text(v)) for (u, ly, fp, ln, v) in rows]
|
|
212
|
+
if not batch:
|
|
213
|
+
return 0
|
|
214
|
+
cur = self.conn.cursor()
|
|
215
|
+
cur.executemany(
|
|
216
|
+
"INSERT INTO strings_index (unit_id, layer, file_path, line_no, value) VALUES (?, ?, ?, ?, ?);",
|
|
217
|
+
batch,
|
|
218
|
+
)
|
|
219
|
+
self.conn.commit()
|
|
220
|
+
return len(batch)
|
|
221
|
+
|
|
222
|
+
def query_findings(
|
|
223
|
+
self,
|
|
224
|
+
catalog_ids: Optional[Sequence[str]] = None,
|
|
225
|
+
domains: Optional[Sequence[str]] = None,
|
|
226
|
+
unit_ids: Optional[Sequence[str]] = None,
|
|
227
|
+
layers: Optional[Sequence[str]] = None,
|
|
228
|
+
scopes: Optional[Sequence[str]] = None,
|
|
229
|
+
confidences: Optional[Sequence[str]] = None,
|
|
230
|
+
text_query: Optional[str] = None,
|
|
231
|
+
regex_pattern: Optional[str] = None,
|
|
232
|
+
limit: Optional[int] = None,
|
|
233
|
+
unique_only: bool = False,
|
|
234
|
+
) -> List[Dict[str, Any]]:
|
|
235
|
+
clauses: List[str] = []
|
|
236
|
+
params: List[Any] = []
|
|
237
|
+
|
|
238
|
+
if catalog_ids:
|
|
239
|
+
exact = [c for c in catalog_ids if not c.endswith("*")]
|
|
240
|
+
prefixes = [c[:-1] for c in catalog_ids if c.endswith("*")]
|
|
241
|
+
sub_clauses = []
|
|
242
|
+
if exact:
|
|
243
|
+
ph = ",".join("?" for _ in exact)
|
|
244
|
+
sub_clauses.append(f"f.catalog_id IN ({ph})")
|
|
245
|
+
params.extend(exact)
|
|
246
|
+
for pref in prefixes:
|
|
247
|
+
sub_clauses.append("f.catalog_id LIKE ?")
|
|
248
|
+
params.append(f"{pref}%")
|
|
249
|
+
if sub_clauses:
|
|
250
|
+
clauses.append("(" + " OR ".join(sub_clauses) + ")")
|
|
251
|
+
|
|
252
|
+
if domains:
|
|
253
|
+
clauses.append("(" + " OR ".join("LOWER(f.domain) LIKE ?" for _ in domains) + ")")
|
|
254
|
+
params.extend(f"%{d.lower()}%" for d in domains)
|
|
255
|
+
|
|
256
|
+
if unit_ids:
|
|
257
|
+
ph = ",".join("?" for _ in unit_ids)
|
|
258
|
+
clauses.append(f"f.unit_id IN ({ph})")
|
|
259
|
+
params.extend(unit_ids)
|
|
260
|
+
|
|
261
|
+
if layers:
|
|
262
|
+
ph = ",".join("?" for _ in layers)
|
|
263
|
+
clauses.append(f"LOWER(f.layer) IN ({ph})")
|
|
264
|
+
params.extend([ly.lower() for ly in layers])
|
|
265
|
+
|
|
266
|
+
if scopes:
|
|
267
|
+
ph = ",".join("?" for _ in scopes)
|
|
268
|
+
clauses.append(f"LOWER(COALESCE(f.scope, 'app')) IN ({ph})")
|
|
269
|
+
params.extend([sc.lower() for sc in scopes])
|
|
270
|
+
|
|
271
|
+
if confidences:
|
|
272
|
+
ph = ",".join("?" for _ in confidences)
|
|
273
|
+
clauses.append(f"LOWER(COALESCE(f.confidence, 'high')) IN ({ph})")
|
|
274
|
+
params.extend([cf.lower() for cf in confidences])
|
|
275
|
+
|
|
276
|
+
if text_query:
|
|
277
|
+
if self.has_fts5 and not any(ch in text_query for ch in ('"', "*", ":", "-", ".", "/", "@")):
|
|
278
|
+
clauses.append("f.id IN (SELECT rowid FROM findings_fts WHERE findings_fts MATCH ?)")
|
|
279
|
+
params.append(f'"{text_query}"')
|
|
280
|
+
else:
|
|
281
|
+
like_q = f"%{text_query}%"
|
|
282
|
+
clauses.append(
|
|
283
|
+
"(f.value LIKE ? OR f.title LIKE ? OR f.file_path LIKE ? OR f.class_name LIKE ? OR f.extra_json LIKE ?)"
|
|
284
|
+
)
|
|
285
|
+
params.extend([like_q, like_q, like_q, like_q, like_q])
|
|
286
|
+
|
|
287
|
+
where_sql = ("WHERE " + " AND ".join(clauses)) if clauses else ""
|
|
288
|
+
sql = f"""
|
|
289
|
+
SELECT f.id, f.catalog_id, f.domain, f.subdomain, f.unit_id, f.layer,
|
|
290
|
+
f.title, f.value, f.file_path, f.line_no, f.class_name, f.method_name,
|
|
291
|
+
COALESCE(f.scope, 'app') AS scope, COALESCE(f.confidence, 'high') AS confidence, f.extra_json
|
|
292
|
+
FROM findings f
|
|
293
|
+
{where_sql}
|
|
294
|
+
ORDER BY f.catalog_id, f.unit_id, f.id
|
|
295
|
+
"""
|
|
296
|
+
if limit and not regex_pattern and not unique_only:
|
|
297
|
+
sql += f" LIMIT {int(limit)}"
|
|
298
|
+
|
|
299
|
+
rows = [dict(r) for r in self.conn.execute(sql, params).fetchall()]
|
|
300
|
+
for r in rows:
|
|
301
|
+
try:
|
|
302
|
+
r["extra"] = json.loads(r.pop("extra_json") or "{}")
|
|
303
|
+
except Exception:
|
|
304
|
+
r["extra"] = {}
|
|
305
|
+
|
|
306
|
+
if regex_pattern:
|
|
307
|
+
rx = re.compile(regex_pattern, re.IGNORECASE)
|
|
308
|
+
rows = [
|
|
309
|
+
r for r in rows
|
|
310
|
+
if rx.search(r["value"]) or rx.search(r["title"] or "") or rx.search(r["file_path"] or "")
|
|
311
|
+
]
|
|
312
|
+
if unique_only:
|
|
313
|
+
seen_u = set()
|
|
314
|
+
deduped = []
|
|
315
|
+
for r in rows:
|
|
316
|
+
k = (r["catalog_id"], r["value"])
|
|
317
|
+
if k not in seen_u:
|
|
318
|
+
seen_u.add(k)
|
|
319
|
+
deduped.append(r)
|
|
320
|
+
rows = deduped
|
|
321
|
+
if limit:
|
|
322
|
+
rows = rows[:limit]
|
|
323
|
+
return rows
|
|
324
|
+
|
|
325
|
+
def search_strings(
|
|
326
|
+
self,
|
|
327
|
+
text_query: Optional[str] = None,
|
|
328
|
+
regex_pattern: Optional[str] = None,
|
|
329
|
+
unit_ids: Optional[Sequence[str]] = None,
|
|
330
|
+
layers: Optional[Sequence[str]] = None,
|
|
331
|
+
limit: Optional[int] = 200,
|
|
332
|
+
unique_only: bool = False,
|
|
333
|
+
) -> List[Dict[str, Any]]:
|
|
334
|
+
clauses: List[str] = []
|
|
335
|
+
params: List[Any] = []
|
|
336
|
+
if text_query:
|
|
337
|
+
if self.has_fts5 and not any(ch in text_query for ch in ('"', "*", ":", "-", ".", "/", "@")):
|
|
338
|
+
clauses.append("id IN (SELECT rowid FROM strings_fts WHERE strings_fts MATCH ?)")
|
|
339
|
+
params.append(f'"{text_query}"')
|
|
340
|
+
else:
|
|
341
|
+
clauses.append("value LIKE ?")
|
|
342
|
+
params.append(f"%{text_query}%")
|
|
343
|
+
if unit_ids:
|
|
344
|
+
clauses.append(f"unit_id IN ({','.join('?' for _ in unit_ids)})")
|
|
345
|
+
params.extend(unit_ids)
|
|
346
|
+
if layers:
|
|
347
|
+
clauses.append(f"LOWER(layer) IN ({','.join('?' for _ in layers)})")
|
|
348
|
+
params.extend([x.lower() for x in layers])
|
|
349
|
+
|
|
350
|
+
where_sql = ("WHERE " + " AND ".join(clauses)) if clauses else ""
|
|
351
|
+
sql = f"SELECT unit_id, layer, file_path, line_no, value FROM strings_index {where_sql}"
|
|
352
|
+
if limit and not regex_pattern and not unique_only:
|
|
353
|
+
sql += f" LIMIT {int(limit)}"
|
|
354
|
+
rows = [dict(r) for r in self.conn.execute(sql, params).fetchall()]
|
|
355
|
+
if regex_pattern:
|
|
356
|
+
rx = re.compile(regex_pattern, re.IGNORECASE)
|
|
357
|
+
rows = [r for r in rows if rx.search(r["value"])]
|
|
358
|
+
if unique_only:
|
|
359
|
+
seen_s = set()
|
|
360
|
+
dedup_s = []
|
|
361
|
+
for r in rows:
|
|
362
|
+
if r["value"] not in seen_s:
|
|
363
|
+
seen_s.add(r["value"])
|
|
364
|
+
dedup_s.append(r)
|
|
365
|
+
rows = dedup_s
|
|
366
|
+
if limit:
|
|
367
|
+
rows = rows[:limit]
|
|
368
|
+
return rows
|
|
369
|
+
|
|
370
|
+
def _strings_count(self) -> int:
|
|
371
|
+
row = self.conn.execute("SELECT COUNT(*) AS cnt FROM strings_index").fetchone()
|
|
372
|
+
return int(row["cnt"]) if row else 0
|
|
373
|
+
|
|
374
|
+
def summary_by_catalog(self) -> List[Dict[str, Any]]:
|
|
375
|
+
rows = [
|
|
376
|
+
dict(r) for r in self.conn.execute(
|
|
377
|
+
"SELECT catalog_id, domain, COUNT(*) AS cnt FROM findings GROUP BY catalog_id, domain ORDER BY catalog_id"
|
|
378
|
+
).fetchall()
|
|
379
|
+
]
|
|
380
|
+
scnt = self._strings_count()
|
|
381
|
+
if scnt > 0 and not any(r["catalog_id"] == "STR-001" for r in rows):
|
|
382
|
+
rows.append({"catalog_id": "STR-001", "domain": "Strings & Constants", "cnt": scnt})
|
|
383
|
+
rows.sort(key=lambda x: x["catalog_id"])
|
|
384
|
+
return rows
|
|
385
|
+
|
|
386
|
+
def counts_by_catalog(self) -> Dict[str, int]:
|
|
387
|
+
rows = self.conn.execute(
|
|
388
|
+
"SELECT catalog_id, COUNT(*) AS cnt FROM findings GROUP BY catalog_id ORDER BY catalog_id"
|
|
389
|
+
).fetchall()
|
|
390
|
+
res = {r["catalog_id"]: r["cnt"] for r in rows}
|
|
391
|
+
scnt = self._strings_count()
|
|
392
|
+
if scnt > 0:
|
|
393
|
+
res.setdefault("STR-001", scnt)
|
|
394
|
+
return res
|
|
395
|
+
|
|
396
|
+
def counts_by_domain(self) -> Dict[str, int]:
|
|
397
|
+
rows = self.conn.execute(
|
|
398
|
+
"SELECT domain, COUNT(*) AS cnt FROM findings GROUP BY domain ORDER BY domain"
|
|
399
|
+
).fetchall()
|
|
400
|
+
res = {r["domain"]: r["cnt"] for r in rows}
|
|
401
|
+
scnt = self._strings_count()
|
|
402
|
+
if scnt > 0:
|
|
403
|
+
res["Strings & Constants"] = res.get("Strings & Constants", 0) + scnt
|
|
404
|
+
return res
|
|
405
|
+
|
|
406
|
+
def close(self) -> None:
|
|
407
|
+
self.conn.close()
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def format_findings_output(rows: List[Dict[str, Any]], fmt: str) -> str:
|
|
411
|
+
fmt = fmt.lower()
|
|
412
|
+
if fmt == "json":
|
|
413
|
+
return json.dumps(rows, indent=2, ensure_ascii=False)
|
|
414
|
+
if fmt == "jsonl":
|
|
415
|
+
return "\n".join(json.dumps(r, ensure_ascii=False) for r in rows)
|
|
416
|
+
if fmt == "values":
|
|
417
|
+
seen = []
|
|
418
|
+
seen_set = set()
|
|
419
|
+
for r in rows:
|
|
420
|
+
v = r["value"]
|
|
421
|
+
if v not in seen_set:
|
|
422
|
+
seen_set.add(v)
|
|
423
|
+
seen.append(v)
|
|
424
|
+
return "\n".join(seen)
|
|
425
|
+
if fmt in ("csv", "tsv"):
|
|
426
|
+
delim = "\t" if fmt == "tsv" else ","
|
|
427
|
+
buf = io.StringIO()
|
|
428
|
+
cols = ["catalog_id", "domain", "unit_id", "layer", "scope", "confidence", "title", "value", "file_path", "line_no", "class_name", "method_name"]
|
|
429
|
+
writer = csv.DictWriter(buf, fieldnames=cols, delimiter=delim, extrasaction="ignore")
|
|
430
|
+
writer.writeheader()
|
|
431
|
+
writer.writerows(rows)
|
|
432
|
+
return buf.getvalue().rstrip("\r\n")
|
|
433
|
+
if fmt == "md":
|
|
434
|
+
lines = [
|
|
435
|
+
"| ID | Unit | Layer | Title | Value | File | Line |",
|
|
436
|
+
"| :--- | :---: | :--- | :--- | :--- | :--- | :---: |",
|
|
437
|
+
]
|
|
438
|
+
for r in rows:
|
|
439
|
+
val = str(r["value"]).replace("|", "\\|").replace("\n", " ")[:120]
|
|
440
|
+
fp = str(r.get("file_path") or "").replace("|", "\\|")
|
|
441
|
+
lines.append(
|
|
442
|
+
f"| `{r['catalog_id']}` | `{r['unit_id']}` | `{r.get('layer') or '-'}` | "
|
|
443
|
+
f"{r.get('title') or '-'} | `{val}` | `{fp}` | {r.get('line_no') or 0} |"
|
|
444
|
+
)
|
|
445
|
+
return "\n".join(lines)
|
|
446
|
+
|
|
447
|
+
if not rows:
|
|
448
|
+
return "No matching findings."
|
|
449
|
+
lines = [
|
|
450
|
+
f"{'ID':<10} {'Unit':<6} {'Layer':<10} {'Title':<24} {'Value':<42} {'Location'}",
|
|
451
|
+
"-" * 112,
|
|
452
|
+
]
|
|
453
|
+
for r in rows:
|
|
454
|
+
tid = (r.get("title") or "-")[:23]
|
|
455
|
+
val = str(r["value"]).replace("\n", " ")[:41]
|
|
456
|
+
loc = f"{Path(r['file_path']).name}:{r['line_no']}" if r.get("file_path") else "-"
|
|
457
|
+
lines.append(
|
|
458
|
+
f"{r['catalog_id']:<10} {r['unit_id']:<6} {(r.get('layer') or '-'):<10} {tid:<24} {val:<42} {loc}"
|
|
459
|
+
)
|
|
460
|
+
return "\n".join(lines)
|