timecs 2.0.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 (94) hide show
  1. app.py +3014 -0
  2. ast_scanner.py +36187 -0
  3. banner.py +146 -0
  4. ci_reporter.py +570 -0
  5. cli.py +2347 -0
  6. config_loader.py +307 -0
  7. cross_file_engine.py +1781 -0
  8. delivery_models.py +145 -0
  9. delivery_repository.py +78 -0
  10. diff_scan.py +127 -0
  11. durable_delivery_sink.py +103 -0
  12. event_bus.py +155 -0
  13. event_publisher.py +345 -0
  14. event_taxonomy.py +313 -0
  15. function_summarizer.py +354 -0
  16. html_auditor.py +274 -0
  17. iac_auditor.py +400 -0
  18. in_app_adapter.py +115 -0
  19. js_scanner.py +895 -0
  20. manifest_parser.py +960 -0
  21. master_rules_bank.py +389 -0
  22. notification_models.py +346 -0
  23. notification_policy.py +309 -0
  24. notification_repository.py +118 -0
  25. notification_routes.py +394 -0
  26. notification_service.py +199 -0
  27. osv_client.py +437 -0
  28. remediation/__init__.py +39 -0
  29. remediation/base.py +102 -0
  30. remediation/contracts.py +196 -0
  31. remediation/cwe1188_binding.py +78 -0
  32. remediation/cwe1336_jinja.py +91 -0
  33. remediation/cwe22_path_traversal.py +348 -0
  34. remediation/cwe295_ssl.py +87 -0
  35. remediation/cwe327_weak_hash.py +78 -0
  36. remediation/cwe377_tempfile.py +77 -0
  37. remediation/cwe489_debug.py +80 -0
  38. remediation/cwe502_yaml.py +89 -0
  39. remediation/cwe614_cookie.py +91 -0
  40. remediation/cwe78_cmdi.py +415 -0
  41. remediation/cwe798_credentials.py +153 -0
  42. remediation/cwe89_sqli.py +425 -0
  43. remediation/cwe916_password_hash.py +131 -0
  44. remediation/cwe95_eval.py +77 -0
  45. remediation/dispatcher.py +114 -0
  46. remediation/orchestrator.py +541 -0
  47. remediation/patch_engine.py +213 -0
  48. remediation/verification.py +253 -0
  49. rule_engine.py +1535 -0
  50. sarif_adapter.py +719 -0
  51. sarif_exporter.py +88 -0
  52. sca_reachability/__init__.py +28 -0
  53. sca_reachability/ast_analyzer.py +366 -0
  54. sca_reachability/call_graph.py +203 -0
  55. sca_reachability/contracts.py +365 -0
  56. sca_reachability/dist_import_map.py +46 -0
  57. sca_reachability/engine.py +603 -0
  58. sca_reachability/resolver.py +169 -0
  59. scanners/__init__.py +70 -0
  60. scanners/container_scanner.py +323 -0
  61. scanners/cve_index.py +521 -0
  62. scanners/iac_scanner.py +328 -0
  63. scanners/sbom.py +183 -0
  64. scanners/sca_scanner.py +667 -0
  65. scanners/secret_scanner.py +345 -0
  66. scanners/yaml_lite.py +217 -0
  67. secret_filters.py +435 -0
  68. secret_scanner.py +943 -0
  69. sqlite_delivery_repository.py +277 -0
  70. sqlite_notification_repository.py +441 -0
  71. ssrf_guard.py +276 -0
  72. staged_scanner.py +492 -0
  73. suppression_resolver.py +282 -0
  74. symbol_indexer.py +424 -0
  75. tcs/__init__.py +1 -0
  76. tcs/analysis/__init__.py +1 -0
  77. tcs/analysis/def_use.py +408 -0
  78. tcs/analysis/function_contracts.py +290 -0
  79. tcs/parallel_analyzer.py +276 -0
  80. tcs/parallel_scanner.py +630 -0
  81. tcs/treesitter_packer.py +1446 -0
  82. tcs_cli.py +2086 -0
  83. tcs_config.py +218 -0
  84. tcs_gui.py +2123 -0
  85. timecs-2.0.0.dist-info/METADATA +142 -0
  86. timecs-2.0.0.dist-info/RECORD +94 -0
  87. timecs-2.0.0.dist-info/WHEEL +5 -0
  88. timecs-2.0.0.dist-info/entry_points.txt +4 -0
  89. timecs-2.0.0.dist-info/licenses/LICENSE +201 -0
  90. timecs-2.0.0.dist-info/top_level.txt +49 -0
  91. version_matcher.py +934 -0
  92. webhook_adapter.py +495 -0
  93. webhook_client.py +483 -0
  94. webhook_formatters.py +245 -0
rule_engine.py ADDED
@@ -0,0 +1,1535 @@
1
+ """
2
+ TimeCodeSecurity Rule Engine.
3
+ Defines typed SecurityRule representations and provides declarative rule matching,
4
+ safety evaluation, remediation, and severity mappings.
5
+ """
6
+
7
+ from __future__ import annotations
8
+ import ast
9
+ import importlib.util
10
+ import os
11
+ from dataclasses import dataclass, field
12
+ from typing import Callable, Optional, Dict, Any, List, Set
13
+
14
+
15
+ def _load_master_rules_bank():
16
+ """Load master_rules_bank.py from the repository root (pure-data module).
17
+
18
+ Returns None on any failure so production imports never break if the bank
19
+ file is absent; the merge below is then simply a no-op.
20
+ """
21
+ path = os.path.join(
22
+ os.path.dirname(os.path.abspath(__file__)), "master_rules_bank.py"
23
+ )
24
+ try:
25
+ spec = importlib.util.spec_from_file_location("_tcs_master_rules_bank", path)
26
+ if spec is None or spec.loader is None:
27
+ return None
28
+ mod = importlib.util.module_from_spec(spec)
29
+ spec.loader.exec_module(mod)
30
+ return mod
31
+ except Exception:
32
+ return None
33
+
34
+
35
+ _MASTER_RULES_BANK = _load_master_rules_bank()
36
+
37
+ try:
38
+ import yaml
39
+ except ImportError:
40
+ yaml = None
41
+
42
+
43
+ def load_yaml_rules(rules_dir: Optional[str] = None) -> List[Dict[str, Any]]:
44
+ """Safely loads declarative security rules from YAML files (Semgrep-style).
45
+
46
+ FALLBACK INVARIANT:
47
+ If YAML files are missing, unreadable, or yaml module is unavailable,
48
+ falls back cleanly to native internal dictionaries without raising exceptions.
49
+ """
50
+ if yaml is None:
51
+ return []
52
+
53
+ if rules_dir is None:
54
+ rules_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "rules")
55
+
56
+ if not os.path.isdir(rules_dir):
57
+ return []
58
+
59
+ loaded_rules: List[Dict[str, Any]] = []
60
+ try:
61
+ rule_files = sorted(
62
+ f for f in os.listdir(rules_dir)
63
+ if f.endswith(".yaml") or f.endswith(".yml")
64
+ )
65
+ except Exception:
66
+ return []
67
+
68
+ for fname in rule_files:
69
+ fpath = os.path.join(rules_dir, fname)
70
+ try:
71
+ with open(fpath, "r", encoding="utf-8") as rf:
72
+ content = yaml.safe_load(rf)
73
+ if isinstance(content, dict):
74
+ if "id" in content and "cwe" in content and "sinks" in content:
75
+ loaded_rules.append(content)
76
+ elif isinstance(content, list):
77
+ for item in content:
78
+ if isinstance(item, dict) and "id" in item and "cwe" in item and "sinks" in item:
79
+ loaded_rules.append(item)
80
+ except Exception:
81
+ continue
82
+
83
+ return loaded_rules
84
+
85
+
86
+ # Global cached declarative rules
87
+ DECLARATIVE_YAML_RULES: List[Dict[str, Any]] = load_yaml_rules()
88
+ DECLARATIVE_RULES_BY_CWE: Dict[str, Dict[str, Any]] = {
89
+ r["cwe"]: r for r in DECLARATIVE_YAML_RULES if "cwe" in r
90
+ }
91
+ DECLARATIVE_RULES_BY_ID: Dict[str, Dict[str, Any]] = {
92
+ r["id"]: r for r in DECLARATIVE_YAML_RULES if "id" in r
93
+ }
94
+
95
+
96
+ def get_declarative_rule(cwe_or_id: str) -> Optional[Dict[str, Any]]:
97
+ """Retrieve a declarative rule dictionary by CWE ID or Rule ID."""
98
+ return DECLARATIVE_RULES_BY_CWE.get(cwe_or_id) or DECLARATIVE_RULES_BY_ID.get(cwe_or_id)
99
+
100
+
101
+
102
+ @dataclass(frozen=True)
103
+ class SecurityRule:
104
+ cwe_id: str
105
+ name: str
106
+ category: str
107
+ operation: str
108
+ confirmed_severity: str
109
+ potential_severity: str
110
+ remediation: str
111
+ sarif_metadata: Dict[str, Any] = field(default_factory=dict)
112
+ sink_matcher: Optional[Callable[[ast.AST, str, Optional[str]], bool]] = None
113
+ safety_filter: Optional[Callable[[ast.Call, str], bool]] = None
114
+
115
+ def matches_sink(self, node: ast.AST, name: str, canon_name: Optional[str] = None) -> bool:
116
+ if self.sink_matcher:
117
+ return self.sink_matcher(node, name, canon_name)
118
+ return False
119
+
120
+ def is_safe(self, node: ast.Call, sink_name: str) -> bool:
121
+ if self.safety_filter:
122
+ return self.safety_filter(node, sink_name)
123
+ return False
124
+
125
+ def get_severity(self, confidence_label: str) -> str:
126
+ if confidence_label == "CONFIRMED":
127
+ return self.confirmed_severity
128
+ return self.potential_severity
129
+
130
+
131
+ class RuleRegistry:
132
+ def __init__(self):
133
+ self._rules: Dict[str, SecurityRule] = {}
134
+
135
+ def register(self, rule: SecurityRule) -> None:
136
+ self._rules[rule.cwe_id] = rule
137
+
138
+ def get_rule(self, cwe_id: str) -> Optional[SecurityRule]:
139
+ return self._rules.get(cwe_id)
140
+
141
+ def match_sink(self, node: ast.AST, name: str, canon_name: Optional[str] = None) -> Optional[SecurityRule]:
142
+ for rule in self._rules.values():
143
+ if rule.matches_sink(node, name, canon_name):
144
+ return rule
145
+ return None
146
+
147
+ def check_safety(self, node: ast.Call, sink_name: str) -> bool:
148
+ for rule in self._rules.values():
149
+ if rule.is_safe(node, sink_name):
150
+ return True
151
+ return False
152
+
153
+ def all_rules(self) -> List[SecurityRule]:
154
+ return list(self._rules.values())
155
+
156
+
157
+ # ==============================================================================
158
+ # CWE-89 (SQL Injection) Pilot Rule Implementation
159
+ # ==============================================================================
160
+
161
+ # `execute` is also an ordinary method name in first-party code, so matching it by name
162
+ # alone reports any helper that happens to be called `execute`. A call only enters the SQL
163
+ # family when its receiver names a database role/driver, or when an argument literally
164
+ # reads as a statement.
165
+ _EXECUTE_FAMILY = frozenset({
166
+ "execute", "executemany", "executescript", "execute_values", "execute_batch",
167
+ })
168
+
169
+ _DB_RECEIVER_TOKENS = frozenset({
170
+ "cursor", "cursors", "crsr", "cur", "conn", "conns", "con", "cnx", "connection",
171
+ "connections", "connect", "engine", "engines", "session", "sessions", "sess",
172
+ "db", "dbs", "dbh", "dbapi", "database", "sqlite", "sqlite3", "psycopg", "psycopg2",
173
+ "psycopg3", "mysql", "mysqldb", "pymysql", "oracle", "oracledb", "sqlalchemy",
174
+ "asyncpg", "aiosqlite", "pymssql", "pyodbc", "django", "peewee", "tortoise",
175
+ })
176
+
177
+ _SQL_STATEMENT_PREFIXES = (
178
+ "select", "insert", "update", "delete", "with", "replace", "merge",
179
+ "create", "drop", "alter", "truncate", "begin", "commit", "rollback", "set",
180
+ )
181
+
182
+
183
+ def _receiver_tokens(node: ast.AST, candidate: str) -> Set[str]:
184
+ """Identifier tokens naming the receiver of a call, plus the spelling's own lead parts.
185
+
186
+ The dotted parts of the matched name are included because a canonicalised spelling such
187
+ as `sqlite3.Cursor.execute` carries driver evidence the AST receiver alone cannot show.
188
+ Tokens split on `.` and `_`, so `test_conn` yields {test, conn} and matches while
189
+ `local_lib` yields {local, lib} and does not.
190
+ """
191
+ tokens: Set[str] = set()
192
+ for piece in candidate.split(".")[:-1]:
193
+ tokens.update(token for token in piece.lower().split("_") if token)
194
+
195
+ current = node.func.value if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) else None
196
+ for _ in range(12):
197
+ if current is None:
198
+ break
199
+ if isinstance(current, ast.Name):
200
+ spelling, current = current.id, None
201
+ elif isinstance(current, ast.Attribute):
202
+ spelling, current = current.attr, current.value
203
+ elif isinstance(current, ast.Call):
204
+ spelling, current = "", current.func
205
+ elif isinstance(current, ast.Subscript):
206
+ spelling, current = "", current.value
207
+ else:
208
+ break
209
+ tokens.update(token for token in spelling.lower().split("_") if token)
210
+
211
+ return tokens
212
+
213
+
214
+ def _has_sql_shaped_argument(node: ast.AST) -> bool:
215
+ """True when an argument of the call contains literal text that reads as a statement."""
216
+ if not isinstance(node, ast.Call):
217
+ return False
218
+ values = [*node.args, *(keyword.value for keyword in node.keywords)]
219
+ for value in values:
220
+ for part in ast.walk(value):
221
+ if isinstance(part, ast.JoinedStr):
222
+ chunks = [
223
+ chunk.value for chunk in part.values
224
+ if isinstance(chunk, ast.Constant) and isinstance(chunk.value, str)
225
+ ]
226
+ elif isinstance(part, ast.Constant) and isinstance(part.value, str):
227
+ chunks = [part.value]
228
+ else:
229
+ continue
230
+ for chunk in chunks:
231
+ head = chunk.strip().split(" ", 1)[0].lower().rstrip("(")
232
+ if head in _SQL_STATEMENT_PREFIXES:
233
+ return True
234
+ return False
235
+
236
+
237
+ def _is_database_execute_call(node: ast.AST, candidate: str) -> bool:
238
+ """Whether an execute-family match is a database call, not a same-named helper."""
239
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
240
+ method = node.func.attr.lower()
241
+ else:
242
+ method = candidate.rsplit(".", 1)[-1].lower()
243
+ if method not in _EXECUTE_FAMILY:
244
+ return True
245
+ if _receiver_tokens(node, candidate) & _DB_RECEIVER_TOKENS:
246
+ return True
247
+ return _has_sql_shaped_argument(node)
248
+
249
+
250
+ def _cwe89_sink_matcher(node: ast.AST, name: str, canon_name: Optional[str] = None) -> bool:
251
+ """Matches method calls for SQL execution (execute, executemany, raw, extra, RawSQL)."""
252
+ target_names = {"execute", "executemany", "raw", "extra", "RawSQL"}
253
+ if "CWE-89" in DECLARATIVE_RULES_BY_CWE:
254
+ target_names = target_names | {str(s) for s in DECLARATIVE_RULES_BY_CWE["CWE-89"].get("sinks", []) if s}
255
+ for candidate in (name, canon_name):
256
+ if candidate:
257
+ if candidate in target_names or any(candidate.endswith(f".{t}") for t in target_names):
258
+ if _is_database_execute_call(node, candidate):
259
+ return True
260
+ if isinstance(node, ast.Call):
261
+ if isinstance(node.func, ast.Attribute) and node.func.attr in target_names:
262
+ if _is_database_execute_call(node, name or node.func.attr):
263
+ return True
264
+ if isinstance(node.func, ast.Name) and node.func.id in target_names:
265
+ return True
266
+ if isinstance(node.func, ast.Attribute) and node.func.attr == "execute":
267
+ val = node.func.value
268
+ while isinstance(val, ast.Call) and isinstance(val.func, ast.Attribute):
269
+ if val.func.attr == "cursor":
270
+ return True
271
+ val = val.func.value
272
+ return False
273
+
274
+
275
+ def _operation_slot(node: ast.Call) -> Optional[ast.expr]:
276
+ """The statement slot of an execute-family call, positional first or by driver keyword."""
277
+ if node.args:
278
+ return node.args[0]
279
+ for keyword in node.keywords:
280
+ if keyword.arg in ("operation", "sql", "statement", "query"):
281
+ return keyword.value
282
+ return None
283
+
284
+
285
+ def _is_static_statement(expr: Optional[ast.expr]) -> bool:
286
+ """A plain string literal: there is nothing left for an argument to interpolate into."""
287
+ return isinstance(expr, ast.Constant) and isinstance(expr.value, str)
288
+
289
+
290
+ def _cwe89_safety_filter(node: ast.Call, sink_name: str) -> bool:
291
+ """
292
+ Exempts parameterized queries: calls to .execute with > 1 argument or keyword bindings,
293
+ or .raw with params, or RawSQL with params.
294
+ """
295
+ if sink_name:
296
+ if sink_name.endswith(".execute") or sink_name == "execute":
297
+ if len(node.args) > 1 or getattr(node, "keywords", []):
298
+ return True
299
+ # DB-API slot semantics for the bulk family: executemany(operation, seq_of_parameters)
300
+ # binds everything past the operation slot through the driver, so the call is only
301
+ # injectable through slot 0. A static statement there means no argument can contribute
302
+ # SQL text, which is why the plain `.execute` exemption on argument count is not reused.
303
+ if sink_name.rsplit(".", 1)[-1] in (_EXECUTE_FAMILY - {"execute"}):
304
+ if len(node.args) > 1 or getattr(node, "keywords", []):
305
+ if _is_static_statement(_operation_slot(node)):
306
+ return True
307
+ if sink_name.endswith(".raw") or sink_name == "raw":
308
+ if len(node.args) > 1 or any(kw.arg == "params" for kw in getattr(node, "keywords", [])):
309
+ return True
310
+ if sink_name.endswith(".RawSQL") or sink_name == "RawSQL":
311
+ if len(node.args) > 1 or any(kw.arg == "params" for kw in getattr(node, "keywords", [])):
312
+ return True
313
+ if sink_name.endswith(".extra") or sink_name == "extra":
314
+ if any(kw.arg == "params" for kw in getattr(node, "keywords", [])):
315
+ return True
316
+ return False
317
+
318
+
319
+ CWE_89_RULE = SecurityRule(
320
+ cwe_id="CWE-89",
321
+ name="SqlInjection",
322
+ category="SQL_INJECTION",
323
+ operation="SQL_EXECUTION",
324
+ confirmed_severity="CRITICAL",
325
+ potential_severity="MEDIUM",
326
+ remediation="Use parameterized SQL queries with bind variables instead of string concatenation/formatting, e.g., cursor.execute('SELECT * FROM tbl WHERE id = ?', (user_id,)).",
327
+ sarif_metadata={
328
+ "id": "CWE-89",
329
+ "name": "SqlInjection",
330
+ "shortDescription": {
331
+ "text": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"
332
+ },
333
+ "fullDescription": {
334
+ "text": "The software constructs an SQL command using untrusted input from an upstream component without parameterization or proper escaping, allowing arbitrary SQL execution."
335
+ },
336
+ "helpUri": "https://cwe.mitre.org/data/definitions/89.html",
337
+ "defaultConfiguration": {
338
+ "level": "error"
339
+ },
340
+ "properties": {
341
+ "precision": "high",
342
+ "security-severity": "8.5",
343
+ "tags": ["security", "external/cwe/cwe-89"]
344
+ }
345
+ },
346
+ sink_matcher=_cwe89_sink_matcher,
347
+ safety_filter=_cwe89_safety_filter
348
+ )
349
+
350
+ # ==============================================================================
351
+ # CWE-95 (Code Execution / eval & exec) Rule Implementation
352
+ # ==============================================================================
353
+
354
+ def _cwe95_sink_matcher(node: ast.AST, name: str, canon_name: Optional[str] = None) -> bool:
355
+ """Matches direct and qualified calls to eval, exec, and compile."""
356
+ target_sinks = {"eval", "exec", "compile", "builtins.eval", "builtins.exec", "builtins.compile"}
357
+ if "CWE-95" in DECLARATIVE_RULES_BY_CWE:
358
+ target_sinks = target_sinks | {str(s) for s in DECLARATIVE_RULES_BY_CWE["CWE-95"].get("sinks", []) if s}
359
+ candidates = {c for c in (name, canon_name) if c}
360
+ return any(c in target_sinks for c in candidates)
361
+
362
+
363
+ CWE_95_RULE = SecurityRule(
364
+ cwe_id="CWE-95",
365
+ name="CodeExecution",
366
+ category="CODE_EXECUTION",
367
+ operation="ARBITRARY_CODE_EXECUTION",
368
+ confirmed_severity="CRITICAL",
369
+ potential_severity="HIGH",
370
+ remediation="Avoid passing untrusted input to eval(). Use ast.literal_eval() for parsing Python literals, or parse structured data using json.loads().",
371
+ sarif_metadata={
372
+ "id": "CWE-95",
373
+ "name": "CodeExecution",
374
+ "shortDescription": {
375
+ "text": "Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"
376
+ },
377
+ "fullDescription": {
378
+ "text": "The software receives input from an upstream source and executes it via eval() or exec() without proper sanitization, allowing arbitrary code execution."
379
+ },
380
+ "helpUri": "https://cwe.mitre.org/data/definitions/95.html",
381
+ "defaultConfiguration": {
382
+ "level": "error"
383
+ },
384
+ "properties": {
385
+ "precision": "high",
386
+ "security-severity": "9.8",
387
+ "tags": ["security", "external/cwe/cwe-95"]
388
+ }
389
+ },
390
+ sink_matcher=_cwe95_sink_matcher,
391
+ safety_filter=None
392
+ )
393
+
394
+ # ==============================================================================
395
+ # CWE-78 (Command Injection / os.system & subprocess.*) Rule Implementation
396
+ # ==============================================================================
397
+
398
+ CWE78_SINKS = {
399
+ "os.system",
400
+ "subprocess.run",
401
+ "subprocess.call",
402
+ "subprocess.check_call",
403
+ "subprocess.check_output",
404
+ "subprocess.Popen",
405
+ }
406
+ if "CWE-78" in DECLARATIVE_RULES_BY_CWE:
407
+ CWE78_SINKS.update(str(s) for s in DECLARATIVE_RULES_BY_CWE["CWE-78"].get("sinks", []) if s)
408
+
409
+
410
+ def _cwe78_sink_matcher(node: ast.AST, name: str, canon_name: Optional[str] = None) -> bool:
411
+ """Matches direct and qualified calls to os.system and subprocess execution functions."""
412
+ candidates = {c for c in (name, canon_name) if c}
413
+ return bool(candidates & CWE78_SINKS)
414
+
415
+
416
+ def _cwe78_safety_filter(node: ast.Call, sink_name: str) -> bool:
417
+ """
418
+ Exempts subprocess invocations using shell=False or static argument lists without shell=True.
419
+ os.system always executes via shell and is never exempted.
420
+ """
421
+ if sink_name in ("subprocess.run", "subprocess.call", "subprocess.check_call", "subprocess.check_output", "subprocess.Popen"):
422
+ shell_kw = next((kw.value.value for kw in getattr(node, 'keywords', []) if kw.arg == "shell" and isinstance(kw.value, ast.Constant)), None)
423
+ if shell_kw is False:
424
+ return True
425
+ if shell_kw is None and node.args and isinstance(node.args[0], ast.List):
426
+ if all(isinstance(elt, ast.Constant) for elt in node.args[0].elts):
427
+ return True
428
+ return False
429
+
430
+
431
+ CWE_78_RULE = SecurityRule(
432
+ cwe_id="CWE-78",
433
+ name="CommandInjection",
434
+ category="COMMAND_INJECTION",
435
+ operation="OS_COMMAND_EXECUTION",
436
+ confirmed_severity="CRITICAL",
437
+ potential_severity="HIGH",
438
+ remediation="Avoid shell execution with dynamic input. Use subprocess.run() with an argument list and shell=False, e.g., subprocess.run(['cmd', arg], shell=False).",
439
+ sarif_metadata={
440
+ "id": "CWE-78",
441
+ "name": "CommandInjection",
442
+ "shortDescription": {
443
+ "text": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"
444
+ },
445
+ "fullDescription": {
446
+ "text": "The software executes an OS command using untrusted input without proper neutralization, allowing attackers to execute arbitrary system commands."
447
+ },
448
+ "helpUri": "https://cwe.mitre.org/data/definitions/78.html",
449
+ "defaultConfiguration": {
450
+ "level": "error"
451
+ },
452
+ "properties": {
453
+ "precision": "high",
454
+ "security-severity": "9.5",
455
+ "tags": ["security", "external/cwe/cwe-78"]
456
+ }
457
+ },
458
+ sink_matcher=_cwe78_sink_matcher,
459
+ safety_filter=_cwe78_safety_filter
460
+ )
461
+
462
+ # ==============================================================================
463
+ # CWE-22 (Path Traversal / open & pathlib.Path) Rule Implementation
464
+ # ==============================================================================
465
+
466
+ CWE22_BUILTIN_SINKS = {"open", "builtins.open"}
467
+ CWE22_PATH_ATTRS = {"read_text", "read_bytes", "write_text", "write_bytes"}
468
+ CWE22_ADDITIONAL_SINKS = {
469
+ "shutil.rmtree", "os.remove", "os.unlink", "os.rmdir",
470
+ "shutil.move", "shutil.copy", "shutil.copy2", "shutil.copytree",
471
+ "zipfile.ZipFile.extractall", "zipfile.ZipFile.extract",
472
+ "tarfile.TarFile.extractall", "tarfile.TarFile.extract",
473
+ }
474
+ if "CWE-22" in DECLARATIVE_RULES_BY_CWE:
475
+ CWE22_ADDITIONAL_SINKS.update(
476
+ str(s) for s in DECLARATIVE_RULES_BY_CWE["CWE-22"].get("sinks", [])
477
+ if s and str(s) not in CWE22_BUILTIN_SINKS and str(s) not in CWE22_PATH_ATTRS
478
+ )
479
+
480
+
481
+ def _cwe22_sink_matcher(node: ast.AST, name: str, canon_name: Optional[str] = None) -> bool:
482
+ """Matches direct/qualified calls to open(), pathlib file I/O, archive extraction, and path removals."""
483
+ candidates = {c for c in (name, canon_name) if c}
484
+ if any(c in CWE22_BUILTIN_SINKS for c in candidates):
485
+ # Exclude method calls like arbitrary_object.open()
486
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
487
+ return False
488
+ return True
489
+ if any(c in CWE22_ADDITIONAL_SINKS for c in candidates):
490
+ return True
491
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
492
+ if node.func.attr in CWE22_PATH_ATTRS:
493
+ return True
494
+ if node.func.attr in ("extractall", "extract", "rmtree"):
495
+ return True
496
+ return False
497
+
498
+
499
+ CWE_22_RULE = SecurityRule(
500
+ cwe_id="CWE-22",
501
+ name="PathTraversal",
502
+ category="PATH_TRAVERSAL",
503
+ operation="FILE_ACCESS",
504
+ confirmed_severity="HIGH",
505
+ potential_severity="MEDIUM",
506
+ remediation="Validate and sanitize file paths using secure_path_join() or verify containment with os.path.abspath / pathlib.Path.resolve() against an allowed base directory.",
507
+ sarif_metadata={
508
+ "id": "CWE-22",
509
+ "name": "PathTraversal",
510
+ "shortDescription": {
511
+ "text": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')"
512
+ },
513
+ "fullDescription": {
514
+ "text": "The software uses external input to construct a pathname without sufficient validation or containment checking, resolving to locations outside intended directories."
515
+ },
516
+ "helpUri": "https://cwe.mitre.org/data/definitions/22.html",
517
+ "defaultConfiguration": {
518
+ "level": "error"
519
+ },
520
+ "properties": {
521
+ "precision": "high",
522
+ "security-severity": "7.5",
523
+ "tags": ["security", "external/cwe/cwe-22"]
524
+ }
525
+ },
526
+ sink_matcher=_cwe22_sink_matcher,
527
+ safety_filter=None
528
+ )
529
+
530
+ # ==============================================================================
531
+ # CWE-502 (Unsafe Deserialization / pickle.*) Rule Implementation
532
+ # ==============================================================================
533
+
534
+ CWE502_SINKS = {
535
+ "pickle.loads",
536
+ "pickle.load",
537
+ "_pickle.loads",
538
+ "_pickle.load",
539
+ "yaml.load",
540
+ "yaml.unsafe_load",
541
+ }
542
+
543
+
544
+ def _cwe502_sink_matcher(node: ast.AST, name: str, canon_name: Optional[str] = None) -> bool:
545
+ """Matches direct and qualified calls to pickle.loads, pickle.load, _pickle variants, and yaml.load/unsafe_load."""
546
+ candidates = {c for c in (name, canon_name) if c}
547
+ return bool(candidates & CWE502_SINKS)
548
+
549
+
550
+ def _cwe502_safety_filter(node: ast.Call, sink_name: str) -> bool:
551
+ """
552
+ Exempts yaml.load when called with safe loaders (e.g. Loader=yaml.SafeLoader or CSafeLoader or BaseLoader).
553
+ yaml.unsafe_load and pickle.* are never exempted.
554
+ """
555
+ if "yaml.load" in sink_name:
556
+ safe_loaders = {
557
+ "yaml.SafeLoader", "SafeLoader", "yaml.CSafeLoader", "CSafeLoader",
558
+ "yaml.BaseLoader", "BaseLoader", "yaml.CBaseLoader", "CBaseLoader"
559
+ }
560
+ for kw in getattr(node, "keywords", []):
561
+ if kw.arg == "Loader":
562
+ val_str = None
563
+ if isinstance(kw.value, ast.Name):
564
+ val_str = kw.value.id
565
+ elif isinstance(kw.value, ast.Attribute):
566
+ val_str = f"{getattr(kw.value.value, 'id', '')}.{kw.value.attr}"
567
+ if val_str in safe_loaders:
568
+ return True
569
+ if len(node.args) > 1:
570
+ arg1 = node.args[1]
571
+ val_str = None
572
+ if isinstance(arg1, ast.Name):
573
+ val_str = arg1.id
574
+ elif isinstance(arg1, ast.Attribute):
575
+ val_str = f"{getattr(arg1.value, 'id', '')}.{arg1.attr}"
576
+ if val_str in safe_loaders:
577
+ return True
578
+ return False
579
+
580
+
581
+ CWE_502_RULE = SecurityRule(
582
+ cwe_id="CWE-502",
583
+ name="UnsafeDeserialization",
584
+ category="UNSAFE_DESERIALIZATION",
585
+ operation="DESERIALIZATION",
586
+ confirmed_severity="CRITICAL",
587
+ potential_severity="HIGH",
588
+ remediation="Do not deserialize untrusted data with pickle. Use safe serialization formats such as JSON (json.loads), Protocol Buffers, or messagepack.",
589
+ sarif_metadata={
590
+ "id": "CWE-502",
591
+ "name": "UnsafeDeserialization",
592
+ "shortDescription": {
593
+ "text": "Deserialization of Untrusted Data"
594
+ },
595
+ "fullDescription": {
596
+ "text": "The application deserializes untrusted data using pickle without verifying its validity, enabling arbitrary object instantiation and code execution."
597
+ },
598
+ "helpUri": "https://cwe.mitre.org/data/definitions/502.html",
599
+ "defaultConfiguration": {
600
+ "level": "error"
601
+ },
602
+ "properties": {
603
+ "precision": "high",
604
+ "security-severity": "9.8",
605
+ "tags": ["security", "external/cwe/cwe-502"]
606
+ }
607
+ },
608
+ sink_matcher=_cwe502_sink_matcher,
609
+ safety_filter=_cwe502_safety_filter
610
+ )
611
+
612
+ # ==============================================================================
613
+ # CWE-1336 (Server-Side Template Injection) Rule Implementation
614
+ # ==============================================================================
615
+
616
+ CWE1336_DIRECT_SINKS = {
617
+ "render_template_string",
618
+ "flask.render_template_string",
619
+ "jinja2.Template",
620
+ }
621
+
622
+
623
+ def _cwe1336_sink_matcher(node: ast.AST, name: str, canon_name: Optional[str] = None) -> bool:
624
+ """Matches direct render_template_string calls, jinja2.Template calls, and template .render() attribute calls."""
625
+ candidates = {c for c in (name, canon_name) if c}
626
+
627
+ # Strict exclusion: standard library string.Template must NEVER be flagged
628
+ if any(c == "string.Template" or c.startswith("string.Template") for c in candidates):
629
+ return False
630
+
631
+ # Dynamic attribute method call: template.render(...)
632
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr == "render":
633
+ return True
634
+
635
+ # Direct function calls or qualified calls on flask module or jinja2
636
+ if any(c in CWE1336_DIRECT_SINKS for c in candidates):
637
+ return True
638
+
639
+ return False
640
+
641
+
642
+ CWE_1336_RULE = SecurityRule(
643
+ cwe_id="CWE-1336",
644
+ name="ServerSideTemplateInjection",
645
+ category="TEMPLATE_INJECTION",
646
+ operation="TEMPLATE_RENDERING",
647
+ confirmed_severity="CRITICAL",
648
+ potential_severity="HIGH",
649
+ remediation="Avoid passing user input directly into render_template_string(). Use standard render_template() with parameterized template context variables to enforce auto-escaping.",
650
+ sarif_metadata={
651
+ "id": "CWE-1336",
652
+ "name": "ServerSideTemplateInjection",
653
+ "shortDescription": {
654
+ "text": "Improper Neutralization of Special Elements Used in a Template Engine ('Server-Side Template Injection')"
655
+ },
656
+ "fullDescription": {
657
+ "text": "The application passes untrusted user input directly into template constructors or render_template_string, allowing attackers to inject template directives and achieve arbitrary code execution."
658
+ },
659
+ "helpUri": "https://cwe.mitre.org/data/definitions/1336.html",
660
+ "defaultConfiguration": {
661
+ "level": "error"
662
+ },
663
+ "properties": {
664
+ "precision": "high",
665
+ "security-severity": "9.0",
666
+ "tags": ["security", "external/cwe/cwe-1336"]
667
+ }
668
+ },
669
+ sink_matcher=_cwe1336_sink_matcher,
670
+ safety_filter=None
671
+ )
672
+
673
+
674
+ def _cwe327_sink_matcher(node: ast.AST, name: str, canon_name: Optional[str] = None) -> bool:
675
+ """Match hashlib.md5() and hashlib.sha1() calls."""
676
+ if isinstance(node, ast.Call):
677
+ func = node.func
678
+ if isinstance(func, ast.Attribute):
679
+ if func.attr in ("md5", "sha1"):
680
+ if isinstance(func.value, ast.Name) and func.value.id == "hashlib":
681
+ return True
682
+ return False
683
+
684
+
685
+ CWE_327_RULE = SecurityRule(
686
+ cwe_id="CWE-327",
687
+ name="WeakCryptographicHash",
688
+ category="CRYPTOGRAPHIC_WEAKNESS",
689
+ operation="WEAK_HASH_FUNCTION",
690
+ confirmed_severity="MEDIUM",
691
+ potential_severity="LOW",
692
+ remediation="Replace weak hash functions (MD5, SHA1) with SHA-256 or stronger. Use hashlib.sha256() instead.",
693
+ sarif_metadata={
694
+ "id": "CWE-327",
695
+ "name": "WeakCryptographicHash",
696
+ "shortDescription": {
697
+ "text": "Use of a Broken or Risky Cryptographic Algorithm"
698
+ },
699
+ "fullDescription": {
700
+ "text": "The application uses MD5 or SHA1 hash functions which are cryptographically broken and unsuitable for security purposes."
701
+ },
702
+ "helpUri": "https://cwe.mitre.org/data/definitions/327.html",
703
+ "defaultConfiguration": {
704
+ "level": "warning"
705
+ },
706
+ "properties": {
707
+ "precision": "very-high",
708
+ "security-severity": "5.3",
709
+ "tags": ["security", "external/cwe/cwe-327"]
710
+ }
711
+ },
712
+ sink_matcher=_cwe327_sink_matcher,
713
+ safety_filter=None
714
+ )
715
+
716
+
717
+ def _cwe614_sink_matcher(node: ast.AST, name: str, canon_name: Optional[str] = None) -> bool:
718
+ """Match response.set_cookie() calls."""
719
+ if isinstance(node, ast.Call):
720
+ func = node.func
721
+ if isinstance(func, ast.Attribute):
722
+ if func.attr == "set_cookie":
723
+ return True
724
+ return False
725
+
726
+
727
+ def _cwe614_safety_filter(node: ast.Call, sink_name: str) -> bool:
728
+ """Check if set_cookie has all required security flags."""
729
+ existing_keywords = {kw.arg for kw in node.keywords if kw.arg}
730
+ has_secure = "secure" in existing_keywords
731
+ has_httponly = "httponly" in existing_keywords
732
+ has_samesite = "samesite" in existing_keywords
733
+ # Safe if all three flags are present
734
+ return has_secure and has_httponly and has_samesite
735
+
736
+
737
+ CWE_614_RULE = SecurityRule(
738
+ cwe_id="CWE-614",
739
+ name="InsecureCookieFlags",
740
+ category="COOKIE_SECURITY",
741
+ operation="INSECURE_COOKIE_SET",
742
+ confirmed_severity="MEDIUM",
743
+ potential_severity="LOW",
744
+ remediation="Set secure=True, httponly=True, and samesite='Lax' on all cookies to prevent interception and XSS attacks.",
745
+ sarif_metadata={
746
+ "id": "CWE-614",
747
+ "name": "InsecureCookieFlags",
748
+ "shortDescription": {
749
+ "text": "Sensitive Cookie in HTTPS Session Without 'Secure' Attribute"
750
+ },
751
+ "fullDescription": {
752
+ "text": "The application sets cookies without proper security flags (secure, httponly, samesite), making them vulnerable to interception and cross-site scripting attacks."
753
+ },
754
+ "helpUri": "https://cwe.mitre.org/data/definitions/614.html",
755
+ "defaultConfiguration": {
756
+ "level": "warning"
757
+ },
758
+ "properties": {
759
+ "precision": "high",
760
+ "security-severity": "5.0",
761
+ "tags": ["security", "external/cwe/cwe-614"]
762
+ }
763
+ },
764
+ sink_matcher=_cwe614_sink_matcher,
765
+ safety_filter=_cwe614_safety_filter
766
+ )
767
+
768
+
769
+ # CWE-1275 is consolidated into CWE-614 family (same root cause)
770
+ CWE_1275_RULE = SecurityRule(
771
+ cwe_id="CWE-1275",
772
+ name="SensitiveCookieWithoutSameSite",
773
+ category="COOKIE_SECURITY",
774
+ operation="INSECURE_COOKIE_SET",
775
+ confirmed_severity="MEDIUM",
776
+ potential_severity="LOW",
777
+ remediation="Set samesite='Lax' or samesite='Strict' on sensitive cookies to prevent CSRF attacks.",
778
+ sarif_metadata={
779
+ "id": "CWE-1275",
780
+ "name": "SensitiveCookieWithoutSameSite",
781
+ "shortDescription": {
782
+ "text": "Sensitive Cookie with Improper SameSite Attribute"
783
+ },
784
+ "fullDescription": {
785
+ "text": "The application sets sensitive cookies without SameSite attribute, allowing cross-site request forgery attacks."
786
+ },
787
+ "helpUri": "https://cwe.mitre.org/data/definitions/1275.html",
788
+ "defaultConfiguration": {
789
+ "level": "warning"
790
+ },
791
+ "properties": {
792
+ "precision": "high",
793
+ "security-severity": "5.0",
794
+ "tags": ["security", "external/cwe/cwe-1275"]
795
+ }
796
+ },
797
+ sink_matcher=_cwe614_sink_matcher,
798
+ safety_filter=_cwe614_safety_filter
799
+ )
800
+
801
+
802
+ CWE_798_RULE = SecurityRule(
803
+ cwe_id="CWE-798",
804
+ name="HardcodedCredentials",
805
+ category="HARDCODED_CREDENTIALS",
806
+ operation="CREDENTIAL_EXPOSURE",
807
+ confirmed_severity="CRITICAL",
808
+ potential_severity="HIGH",
809
+ remediation="Never commit plaintext credentials. Rotate secret immediately and move to environment variables or vault.",
810
+ sarif_metadata={
811
+ "id": "CWE-798",
812
+ "name": "HardcodedCredentials",
813
+ "shortDescription": {
814
+ "text": "Use of Hard-coded Credentials"
815
+ },
816
+ "fullDescription": {
817
+ "text": "The software contains hard-coded credentials, such as a password or cryptographic key, which can be compromised if the source code is accessed."
818
+ },
819
+ "helpUri": "https://cwe.mitre.org/data/definitions/798.html",
820
+ "defaultConfiguration": {
821
+ "level": "error"
822
+ },
823
+ "properties": {
824
+ "precision": "very-high",
825
+ "security-severity": "9.8",
826
+ "tags": ["security", "external/cwe/cwe-798"]
827
+ }
828
+ }
829
+ )
830
+
831
+ # ==============================================================================
832
+ # CWE-611 (XML External Entity / XXE) Rule Implementation
833
+ # ==============================================================================
834
+
835
+ CWE611_SINKS = {
836
+ "xml.etree.ElementTree.fromstring", "xml.etree.ElementTree.parse",
837
+ "ET.fromstring", "ET.parse",
838
+ "fromstring", "parse",
839
+ "lxml.etree.fromstring", "lxml.etree.parse",
840
+ "xml.dom.minidom.parseString", "xml.dom.minidom.parse",
841
+ "xml.sax.parseString", "xml.sax.parse",
842
+ }
843
+
844
+
845
+ def _cwe611_sink_matcher(node: ast.AST, name: str, canon_name: Optional[str] = None) -> bool:
846
+ """Matches direct and qualified calls to XML parsing functions."""
847
+ candidates = {c for c in (name, canon_name) if c}
848
+ if any(c in CWE611_SINKS or any(c.endswith(f".{s}") for s in ("fromstring",)) for c in candidates):
849
+ return True
850
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
851
+ if node.func.attr in ("fromstring", "parse") and any(c.startswith(("xml.", "ET.", "lxml.")) for c in candidates):
852
+ return True
853
+ if node.func.attr == "fromstring":
854
+ return True
855
+ return False
856
+
857
+
858
+ CWE_611_RULE = SecurityRule(
859
+ cwe_id="CWE-611",
860
+ name="XmlExternalEntity",
861
+ category="XML_EXTERNAL_ENTITY",
862
+ operation="XML_PARSING",
863
+ confirmed_severity="HIGH",
864
+ potential_severity="MEDIUM",
865
+ remediation="Disable external entity resolution (DTD) or use defusedxml to safely parse untrusted XML documents.",
866
+ sarif_metadata={
867
+ "id": "CWE-611",
868
+ "name": "XmlExternalEntity",
869
+ "shortDescription": {
870
+ "text": "Improper Restriction of XML External Entity Reference ('XXE')"
871
+ },
872
+ "fullDescription": {
873
+ "text": "The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control."
874
+ },
875
+ "helpUri": "https://cwe.mitre.org/data/definitions/611.html",
876
+ "defaultConfiguration": {
877
+ "level": "error"
878
+ },
879
+ "properties": {
880
+ "precision": "high",
881
+ "security-severity": "8.0",
882
+ "tags": ["security", "external/cwe/cwe-611"]
883
+ }
884
+ },
885
+ sink_matcher=_cwe611_sink_matcher,
886
+ safety_filter=None
887
+ )
888
+
889
+ # ==============================================================================
890
+ # CWE-918 (Server-Side Request Forgery / SSRF) Rule Implementation
891
+ # ==============================================================================
892
+
893
+ CWE918_SINKS = {
894
+ "urllib.request.urlopen", "urllib.request.Request",
895
+ "urlopen", "Request",
896
+ "requests.get", "requests.post", "requests.put", "requests.delete", "requests.patch", "requests.head", "requests.request",
897
+ "httpx.get", "httpx.post", "httpx.put", "httpx.delete", "httpx.patch", "httpx.head", "httpx.request",
898
+ "aiohttp.ClientSession.get", "aiohttp.ClientSession.post", "aiohttp.ClientSession.request",
899
+ }
900
+
901
+
902
+ def _cwe918_sink_matcher(node: ast.AST, name: str, canon_name: Optional[str] = None) -> bool:
903
+ """Matches network request functions vulnerable to Server-Side Request Forgery."""
904
+ candidates = {c for c in (name, canon_name) if c}
905
+ if any(c in CWE918_SINKS or any(c.endswith(f".{s}") for s in ("urlopen", "Request")) for c in candidates):
906
+ return True
907
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
908
+ if node.func.attr == "urlopen":
909
+ return True
910
+ return False
911
+
912
+
913
+ CWE_918_RULE = SecurityRule(
914
+ cwe_id="CWE-918",
915
+ name="ServerSideRequestForgery",
916
+ category="SERVER_SIDE_REQUEST_FORGERY",
917
+ operation="SSRF_REQUEST",
918
+ confirmed_severity="HIGH",
919
+ potential_severity="MEDIUM",
920
+ remediation="Validate and allowlist URLs against trusted domains and restrict requests to private/internal IP ranges.",
921
+ sarif_metadata={
922
+ "id": "CWE-918",
923
+ "name": "ServerSideRequestForgery",
924
+ "shortDescription": {
925
+ "text": "Server-Side Request Forgery (SSRF)"
926
+ },
927
+ "fullDescription": {
928
+ "text": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL without sufficiently validating the destination address."
929
+ },
930
+ "helpUri": "https://cwe.mitre.org/data/definitions/918.html",
931
+ "defaultConfiguration": {
932
+ "level": "error"
933
+ },
934
+ "properties": {
935
+ "precision": "high",
936
+ "security-severity": "8.5",
937
+ "tags": ["security", "external/cwe/cwe-918"]
938
+ }
939
+ },
940
+ sink_matcher=_cwe918_sink_matcher,
941
+ safety_filter=None
942
+ )
943
+
944
+ # ==============================================================================
945
+ # CWE-1333 (Regular Expression Denial of Service / ReDoS) Rule Implementation
946
+ # ==============================================================================
947
+
948
+ CWE1333_SINKS = {
949
+ "re.compile", "regex.compile",
950
+ }
951
+
952
+
953
+ def _cwe1333_sink_matcher(node: ast.AST, name: str, canon_name: Optional[str] = None) -> bool:
954
+ """Matches dynamic regular expression compilation functions vulnerable to ReDoS."""
955
+ candidates = {c for c in (name, canon_name) if c}
956
+ return bool(candidates & CWE1333_SINKS) or any(c.endswith(".compile") and ("re." in c or "regex." in c) for c in candidates)
957
+
958
+
959
+ # The ambiguity grammar below looks for one thing: a group that repeats while its own body already
960
+ # contains a quantifier or an alternation -- `(a+)+`, `(a*)*`, `([a-z]+[0-9]+)+`, `(a|ab)*` -- plus a
961
+ # backreference, which re-expands an earlier match. That is the nesting exponential backtracking
962
+ # needs. `(abc)+`, `(a)?`, `[0-9]+` and `cat|dog+` are linear and stay quiet.
963
+ #
964
+ # It is a single linear pass over the pattern text with a bracket stack, rather than a regex, because
965
+ # a character class has to be skipped as a unit: inside `[a|)]` the `|`, `)` and `+` are literals and
966
+ # counting them would mis-nest every following group.
967
+ _CWE1333_OPEN_CLASS_SKIP = "]^"
968
+
969
+
970
+ def _cwe1333_repeats_at(pattern: str, index: int) -> bool:
971
+ """True when a quantifier that can repeat what precedes it starts at `index`."""
972
+ while index < len(pattern) and pattern[index] == "?": # `*?`, `+?` -- laziness is still repetition
973
+ index += 1
974
+ if index >= len(pattern):
975
+ return False
976
+ char = pattern[index]
977
+ if char in "*+":
978
+ return True
979
+ if char != "{":
980
+ return False
981
+ end = pattern.find("}", index)
982
+ if end < 0:
983
+ return False
984
+ bounds = pattern[index + 1:end].split(",")
985
+ if len(bounds) > 2:
986
+ return False
987
+ try:
988
+ low = int(bounds[0]) if bounds[0] else 0
989
+ high = int(bounds[1]) if len(bounds) > 1 and bounds[1] else None
990
+ except ValueError:
991
+ return False
992
+ # An open upper bound (`{4,}`, `{,}`) or any bound of 2 repeats; `{1}` and `{0,1}` do not.
993
+ return high is None or high >= 2 or low >= 2
994
+
995
+
996
+ def _cwe1333_pattern_is_ambiguous(pattern: str) -> bool:
997
+ """Conservatively True for any constant pattern that could backtrack catastrophically."""
998
+ stack: List[bool] = []
999
+ index = 0
1000
+ length = len(pattern)
1001
+ while index < length:
1002
+ char = pattern[index]
1003
+ if char == "\\":
1004
+ following = pattern[index + 1] if index + 1 < length else ""
1005
+ if following.isdigit() and following != "0":
1006
+ return True
1007
+ index += 2
1008
+ continue
1009
+ if char == "[":
1010
+ index += 1
1011
+ if index < length and pattern[index] in _CWE1333_OPEN_CLASS_SKIP:
1012
+ index += 1
1013
+ while index < length and pattern[index] != "]":
1014
+ index += 2 if pattern[index] == "\\" else 1
1015
+ index += 1
1016
+ continue
1017
+ if char == "(":
1018
+ stack.append(False)
1019
+ index += 1
1020
+ continue
1021
+ if char == ")":
1022
+ body_repeats = stack.pop() if stack else True
1023
+ index += 1
1024
+ if body_repeats and _cwe1333_repeats_at(pattern, index):
1025
+ return True
1026
+ continue
1027
+ if char == "|":
1028
+ if stack:
1029
+ stack[-1] = True
1030
+ index += 1
1031
+ continue
1032
+ if char in "*+?{":
1033
+ if stack and _cwe1333_repeats_at(pattern, index):
1034
+ stack[-1] = True
1035
+ index += 1
1036
+ continue
1037
+ index += 1
1038
+ return False
1039
+
1040
+
1041
+ def _cwe1333_safety_filter(node: ast.Call, sink_name: str) -> bool:
1042
+ """Exempts a compile-time constant pattern that cannot backtrack catastrophically.
1043
+
1044
+ `check_safety` runs every rule's filter against every call, so the sink is matched with the rule's
1045
+ own matcher first: this must never be able to silence a stream read, a redirect or an XML parse.
1046
+ Only an `ast.Constant` str is read at all -- a name, an f-string, a `"|".join(...)` or any other
1047
+ computed value is a pattern this layer cannot see, and unreadable stays loud, which is also why a
1048
+ user-tainted or dynamically built regex keeps its finding.
1049
+
1050
+ The structural analyzer in `ast_scanner` (`_is_redos_vulnerable_pattern`, which parses the pattern
1051
+ with `re._parser`) is the emit layer; this is the registration layer's second proof and is
1052
+ deliberately the coarser of the two, so the two can only ever disagree toward loud.
1053
+ """
1054
+ if not _cwe1333_sink_matcher(node, sink_name, None):
1055
+ return False
1056
+ pattern = next((kw.value for kw in node.keywords if kw.arg in ("pattern", "regex")), None)
1057
+ if pattern is None and node.args:
1058
+ pattern = node.args[0]
1059
+ if not (isinstance(pattern, ast.Constant) and isinstance(pattern.value, str)):
1060
+ return False
1061
+ return not _cwe1333_pattern_is_ambiguous(pattern.value)
1062
+
1063
+
1064
+ CWE_1333_RULE = SecurityRule(
1065
+ cwe_id="CWE-1333",
1066
+ name="RegularExpressionDoS",
1067
+ category="REGULAR_EXPRESSION_DOS",
1068
+ operation="REGEX_COMPILATION",
1069
+ confirmed_severity="HIGH",
1070
+ potential_severity="LOW",
1071
+ remediation="Avoid constructing regular expressions from untrusted input or escape metacharacters using re.escape.",
1072
+ sarif_metadata={
1073
+ "id": "CWE-1333",
1074
+ "name": "RegularExpressionDoS",
1075
+ "shortDescription": {
1076
+ "text": "Inefficient Regular Expression Complexity ('ReDoS')"
1077
+ },
1078
+ "fullDescription": {
1079
+ "text": "The software uses a regular expression that can take an exponential amount of time to evaluate, causing a denial of service."
1080
+ },
1081
+ "helpUri": "https://cwe.mitre.org/data/definitions/1333.html",
1082
+ "defaultConfiguration": {
1083
+ "level": "error"
1084
+ },
1085
+ "properties": {
1086
+ "precision": "high",
1087
+ "security-severity": "7.5",
1088
+ "tags": ["security", "external/cwe/cwe-1333"]
1089
+ }
1090
+ },
1091
+ sink_matcher=_cwe1333_sink_matcher,
1092
+ safety_filter=_cwe1333_safety_filter
1093
+ )
1094
+
1095
+ # ==============================================================================
1096
+ # CWE-601 (URL Redirection to Untrusted Site / Open Redirect) Rule Implementation
1097
+ # ==============================================================================
1098
+
1099
+ CWE601_SINKS = {
1100
+ "redirect", "flask.redirect", "django.shortcuts.redirect"
1101
+ }
1102
+
1103
+
1104
+ def _cwe601_sink_matcher(node: ast.AST, name: str, canon_name: Optional[str] = None) -> bool:
1105
+ """Matches redirect functions susceptible to open URL redirection."""
1106
+ candidates = {c for c in (name, canon_name) if c}
1107
+ return any(c in CWE601_SINKS or any(c.endswith(f".{s}") for s in ("redirect",)) for c in candidates)
1108
+
1109
+
1110
+ def _cwe601_safety_filter(node: ast.Call, sink_name: str) -> bool:
1111
+ """Exempts safe redirects to constant relative paths, e.g. redirect('/') or redirect('/login')."""
1112
+ # Only applies to genuine redirect sinks; check_safety invokes every rule's
1113
+ # filter against every node, so guard against suppressing unrelated sinks
1114
+ # (e.g. z.extractall("/tmp/...")) that merely pass a constant leading-slash arg.
1115
+ if not (sink_name in CWE601_SINKS or sink_name.endswith(".redirect") or sink_name == "redirect"):
1116
+ return False
1117
+ if node.args and isinstance(node.args[0], ast.Constant) and isinstance(node.args[0].value, str):
1118
+ val = node.args[0].value
1119
+ if val.startswith("/") and not val.startswith("//"):
1120
+ return True
1121
+ return False
1122
+
1123
+
1124
+ CWE_601_RULE = SecurityRule(
1125
+ cwe_id="CWE-601",
1126
+ name="OpenRedirect",
1127
+ category="URL_REDIRECTION",
1128
+ operation="OPEN_REDIRECT",
1129
+ confirmed_severity="MEDIUM",
1130
+ potential_severity="LOW",
1131
+ remediation="Validate target redirect URLs against an allowlist of permitted domains or enforce strict relative paths.",
1132
+ sarif_metadata={
1133
+ "id": "CWE-601",
1134
+ "name": "OpenRedirect",
1135
+ "shortDescription": {
1136
+ "text": "URL Redirection to Untrusted Site ('Open Redirect')"
1137
+ },
1138
+ "fullDescription": {
1139
+ "text": "A web application accepts a user-controlled input that specifies a link to an external site and uses that link in a redirect, enabling phishing attacks."
1140
+ },
1141
+ "helpUri": "https://cwe.mitre.org/data/definitions/601.html",
1142
+ "defaultConfiguration": {
1143
+ "level": "error"
1144
+ },
1145
+ "properties": {
1146
+ "precision": "high",
1147
+ "security-severity": "6.1",
1148
+ "tags": ["security", "external/cwe/cwe-601"]
1149
+ }
1150
+ },
1151
+ sink_matcher=_cwe601_sink_matcher,
1152
+ safety_filter=_cwe601_safety_filter
1153
+ )
1154
+
1155
+ # ==============================================================================
1156
+ # Master Rules Bank merge (append-only; never overwrites existing sink entries)
1157
+ # ==============================================================================
1158
+
1159
+ # Maps a bank CWE onto the pre-existing per-CWE sink set so bank function names
1160
+ # are picked up by the existing matchers. CWEs absent here get a generated rule.
1161
+ _BANK_CWE_TO_SINK_SET: Dict[str, Set[str]] = {
1162
+ "CWE-502": CWE502_SINKS,
1163
+ "CWE-22": CWE22_ADDITIONAL_SINKS,
1164
+ "CWE-611": CWE611_SINKS,
1165
+ "CWE-918": CWE918_SINKS,
1166
+ "CWE-601": CWE601_SINKS,
1167
+ "CWE-1333": CWE1333_SINKS,
1168
+ "CWE-1336": CWE1336_DIRECT_SINKS,
1169
+ }
1170
+
1171
+ # Metadata for CWE families present in the bank but without a pre-existing rule.
1172
+ _BANK_NEW_RULE_META: Dict[str, Dict[str, Any]] = {
1173
+ "CWE-79": {
1174
+ "name": "CrossSiteScripting",
1175
+ "category": "XSS",
1176
+ "operation": "HTML_INJECTION",
1177
+ "confirmed_severity": "HIGH",
1178
+ "potential_severity": "MEDIUM",
1179
+ "remediation": "Do not mark untrusted input as safe. Contextually encode output (HTML/JS/URL) or use a vetted sanitizer before rendering.",
1180
+ "short": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')",
1181
+ "full": "The application marks attacker-controlled input as safe HTML (e.g. markupsafe.Markup / django mark_safe), bypassing auto-escaping and enabling cross-site scripting.",
1182
+ "security_severity": "6.1",
1183
+ },
1184
+ "CWE-295": {
1185
+ "name": "ImproperCertificateValidation",
1186
+ "category": "INSECURE_TRANSPORT",
1187
+ "operation": "DISABLED_SSL_VERIFICATION",
1188
+ "confirmed_severity": "HIGH",
1189
+ "potential_severity": "MEDIUM",
1190
+ "remediation": "Do not disable certificate validation (verify=False, cert_reqs=ssl.CERT_NONE). Always enable TLS verification and use trusted CA bundles.",
1191
+ "short": "Improper Certificate Validation",
1192
+ "full": "The application disables TLS/SSL certificate validation, enabling man-in-the-middle attacks and credential theft.",
1193
+ "security_severity": "5.9",
1194
+ },
1195
+ "CWE-322": {
1196
+ "name": "InsecureHostKeyPolicyVerification",
1197
+ "category": "INSECURE_NETWORK_COMMUNICATION",
1198
+ "operation": "INSECURE_HOST_KEY_POLICY",
1199
+ "confirmed_severity": "HIGH",
1200
+ "potential_severity": "MEDIUM",
1201
+ "remediation": "Do not use AutoAddPolicy or WarningPolicy for SSH host key verification. Use RejectPolicy and verify host keys against a known_hosts store.",
1202
+ "short": "Insecure Host Key Policy Verification",
1203
+ "full": "The application accepts SSH host keys without verification (AutoAddPolicy or WarningPolicy), enabling man-in-the-middle attacks.",
1204
+ "security_severity": "5.9",
1205
+ },
1206
+ "CWE-327": {
1207
+ "name": "BrokenCryptographicAlgorithm",
1208
+ "category": "WEAK_CRYPTOGRAPHY",
1209
+ "operation": "WEAK_HASH",
1210
+ "confirmed_severity": "MEDIUM",
1211
+ "potential_severity": "LOW",
1212
+ "remediation": "Avoid broken hashes (MD5/SHA1) for security purposes. Use SHA-256 or stronger (e.g. hashlib.sha256, blake2).",
1213
+ "short": "Use of a Broken or Risky Cryptographic Algorithm",
1214
+ "full": "The application uses a cryptographically broken hash algorithm (MD5 or SHA1), which is vulnerable to collision and preimage attacks.",
1215
+ "security_severity": "5.3",
1216
+ },
1217
+ "CWE-338": {
1218
+ "name": "InsecureRandomness",
1219
+ "category": "INSECURE_RANDOMNESS",
1220
+ "operation": "INSECURE_RANDOM",
1221
+ "confirmed_severity": "MEDIUM",
1222
+ "potential_severity": "LOW",
1223
+ "remediation": "Do not use standard pseudo-random number generators (random module) for security-sensitive contexts. Use secrets (e.g. secrets.token_hex, secrets.choice) or os.urandom instead.",
1224
+ "short": "Use of Cryptographically Weak Pseudo-Random Number Generator (PRNG)",
1225
+ "full": "The application uses a cryptographically weak pseudo-random number generator (such as random.randint or random.choice) in a security context.",
1226
+ "security_severity": "5.3",
1227
+ },
1228
+ "CWE-400": {
1229
+ "name": "ResourceExhaustion",
1230
+ "category": "RESOURCE_EXHAUSTION",
1231
+ "operation": "REGEX_COMPILATION",
1232
+ "confirmed_severity": "MEDIUM",
1233
+ "potential_severity": "LOW",
1234
+ "remediation": "Escape user input using re.escape before passing to regex operations, and enforce size limits on file reads (read(MAX_SIZE)).",
1235
+ "short": "Uncontrolled Resource Consumption ('Resource Exhaustion')",
1236
+ "full": "The application performs regex operations or file reads on untrusted data without size or complexity limits, exposing it to denial of service.",
1237
+ "security_severity": "5.3",
1238
+ },
1239
+ }
1240
+
1241
+ _BANK_NEW_CWE_SINKS: Dict[str, Set[str]] = {}
1242
+
1243
+
1244
+ def _call_dotted_name(func: ast.AST) -> str:
1245
+ """Reassemble `a.b.c` from an ast.Name/ast.Attribute callee chain."""
1246
+ parts: List[str] = []
1247
+ current = func
1248
+ while isinstance(current, ast.Attribute):
1249
+ parts.append(current.attr)
1250
+ current = current.value
1251
+ if isinstance(current, ast.Name):
1252
+ parts.append(current.id)
1253
+ return ".".join(reversed(parts))
1254
+
1255
+
1256
+ def _is_literal_text(expr: ast.AST) -> bool:
1257
+ if isinstance(expr, ast.Constant):
1258
+ return isinstance(expr.value, (str, bytes))
1259
+ if isinstance(expr, ast.JoinedStr):
1260
+ return not any(isinstance(part, ast.FormattedValue) for part in expr.values)
1261
+ if isinstance(expr, ast.BinOp) and isinstance(expr.op, ast.Add):
1262
+ return _is_literal_text(expr.left) and _is_literal_text(expr.right)
1263
+ if isinstance(expr, ast.UnaryOp):
1264
+ return _is_literal_text(expr.operand)
1265
+ return False
1266
+
1267
+
1268
+ def _http_response_dynamic_body(node: ast.AST, name: str, canon_name: Optional[str] = None) -> bool:
1269
+ """True for `HttpResponse(...)`/subclasses whose body argument is not a compile-time literal.
1270
+
1271
+ Django's HttpResponse family serialises its body straight into the response, and the
1272
+ default media type is text/html, so a non-literal body is markup the author did not
1273
+ write. Matching the bare class name would flag `HttpResponse("static")` too, and
1274
+ JsonResponse is excluded because it forces application/json.
1275
+ """
1276
+ if not isinstance(node, ast.Call):
1277
+ return False
1278
+ for candidate in (name, canon_name):
1279
+ if not candidate:
1280
+ continue
1281
+ short = candidate.rsplit(".", 1)[-1]
1282
+ if not (short.startswith("HttpResponse") or candidate.startswith("django.http.HttpResponse")):
1283
+ continue
1284
+ if candidate.endswith("JsonResponse") or "Redirect" in short:
1285
+ continue
1286
+ body = next((kw.value for kw in node.keywords if kw.arg in {"content", "data"}), None)
1287
+ if body is None and node.args:
1288
+ body = node.args[0]
1289
+ if body is None:
1290
+ return False
1291
+ return not _is_literal_text(body)
1292
+ return False
1293
+
1294
+
1295
+ _BANK_RULE_SHAPE_PREDICATES: Dict[str, Callable[..., bool]] = {
1296
+ "CWE-79": _http_response_dynamic_body,
1297
+ }
1298
+
1299
+
1300
+ def _build_bank_rule(cwe_id: str, sink_set: Set[str]) -> SecurityRule:
1301
+ meta = _BANK_NEW_RULE_META[cwe_id]
1302
+ shape_predicate = _BANK_RULE_SHAPE_PREDICATES.get(cwe_id)
1303
+
1304
+ def _matcher(node: ast.AST, name: str, canon_name: Optional[str] = None, _s: Set[str] = sink_set) -> bool:
1305
+ candidates = {c for c in (name, canon_name) if c}
1306
+ if candidates & _s:
1307
+ return True
1308
+ return bool(shape_predicate and shape_predicate(node, name, canon_name))
1309
+
1310
+ return SecurityRule(
1311
+ cwe_id=cwe_id,
1312
+ name=meta["name"],
1313
+ category=meta["category"],
1314
+ operation=meta["operation"],
1315
+ confirmed_severity=meta["confirmed_severity"],
1316
+ potential_severity=meta["potential_severity"],
1317
+ remediation=meta["remediation"],
1318
+ sarif_metadata={
1319
+ "id": cwe_id,
1320
+ "name": meta["name"],
1321
+ "shortDescription": {"text": meta["short"]},
1322
+ "fullDescription": {"text": meta["full"]},
1323
+ "helpUri": f"https://cwe.mitre.org/data/definitions/{cwe_id.split('-')[1]}.html",
1324
+ "defaultConfiguration": {"level": "error"},
1325
+ "properties": {
1326
+ "precision": "high",
1327
+ "security-severity": meta["security_severity"],
1328
+ "tags": ["security", f"external/cwe/cwe-{cwe_id.split('-')[1].lower()}"],
1329
+ },
1330
+ },
1331
+ sink_matcher=_matcher,
1332
+ safety_filter=None,
1333
+ )
1334
+
1335
+
1336
+ if _MASTER_RULES_BANK is not None:
1337
+ _ENTERPRISE_SINKS_BANK = getattr(_MASTER_RULES_BANK, "ENTERPRISE_SINKS_BANK", {}) or {}
1338
+ for _fn_name, _fn_meta in _ENTERPRISE_SINKS_BANK.items():
1339
+ _cwe = _fn_meta.get("cwe")
1340
+ _existing_set = _BANK_CWE_TO_SINK_SET.get(_cwe)
1341
+ if _existing_set is not None:
1342
+ _existing_set.add(_fn_name) # append-only; sets dedupe, no overwrite
1343
+ elif _cwe in _BANK_NEW_RULE_META:
1344
+ _BANK_NEW_CWE_SINKS.setdefault(_cwe, set()).add(_fn_name)
1345
+
1346
+ _BANK_GENERATED_RULES: List[SecurityRule] = [
1347
+ _build_bank_rule(_cwe, _sinks) for _cwe, _sinks in _BANK_NEW_CWE_SINKS.items()
1348
+ ]
1349
+
1350
+ def _load_catalog_security_rules(registry: RuleRegistry) -> None:
1351
+ """Loads all 107 enterprise security rules from data/rules_catalog.json into the registry.
1352
+
1353
+ Ensures GLOBAL_RULE_REGISTRY contains complete SARIF metadata, remediation advice,
1354
+ and severity levels for all supported CWEs. Native rules with AST sink matchers
1355
+ and safety filters take precedence and are NEVER overwritten.
1356
+ """
1357
+ import json
1358
+ catalog_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", "rules_catalog.json")
1359
+ if not os.path.isfile(catalog_path):
1360
+ return
1361
+ try:
1362
+ with open(catalog_path, "r", encoding="utf-8") as f:
1363
+ cat_data = json.load(f)
1364
+ cwes = cat_data.get("cwes", {})
1365
+ for cwe_id, meta in cwes.items():
1366
+ if cwe_id in registry._rules:
1367
+ continue
1368
+ cwe_num = cwe_id.split("-")[-1] if "-" in cwe_id else cwe_id
1369
+ name = meta.get("name", cwe_id).replace(" ", "_").replace("-", "_")
1370
+ category = meta.get("category", "Vulnerability")
1371
+ severity = str(meta.get("severity", "HIGH")).upper()
1372
+ remediation = meta.get("remediation", f"Remediate {cwe_id} according to secure coding standards.")
1373
+ desc = meta.get("description", f"Detects patterns violating {cwe_id}.")
1374
+
1375
+ rule = SecurityRule(
1376
+ cwe_id=cwe_id,
1377
+ name=name,
1378
+ category=category,
1379
+ operation="SECURITY_POLICY",
1380
+ confirmed_severity=severity,
1381
+ potential_severity="LOW" if severity in ("LOW", "NOTE") else "MEDIUM",
1382
+ remediation=remediation,
1383
+ sarif_metadata={
1384
+ "id": cwe_id,
1385
+ "name": name,
1386
+ "shortDescription": {"text": meta.get("name", cwe_id)},
1387
+ "fullDescription": {"text": desc},
1388
+ "helpUri": f"https://cwe.mitre.org/data/definitions/{cwe_num}.html",
1389
+ "defaultConfiguration": {
1390
+ "level": "error" if severity in ("CRITICAL", "HIGH") else "warning"
1391
+ },
1392
+ "properties": {
1393
+ "precision": "high",
1394
+ "security-severity": "8.0" if severity in ("CRITICAL", "HIGH") else "5.0",
1395
+ "tags": ["security", f"external/cwe/cwe-{cwe_num.lower()}"]
1396
+ }
1397
+ },
1398
+ sink_matcher=None,
1399
+ safety_filter=None
1400
+ )
1401
+ registry.register(rule)
1402
+ except Exception:
1403
+ pass
1404
+
1405
+
1406
+ # Global Registry instance initialized with migrated security rules
1407
+ GLOBAL_RULE_REGISTRY = RuleRegistry()
1408
+ GLOBAL_RULE_REGISTRY.register(CWE_89_RULE)
1409
+ GLOBAL_RULE_REGISTRY.register(CWE_95_RULE)
1410
+ GLOBAL_RULE_REGISTRY.register(CWE_78_RULE)
1411
+ GLOBAL_RULE_REGISTRY.register(CWE_22_RULE)
1412
+ GLOBAL_RULE_REGISTRY.register(CWE_502_RULE)
1413
+ GLOBAL_RULE_REGISTRY.register(CWE_1336_RULE)
1414
+ GLOBAL_RULE_REGISTRY.register(CWE_327_RULE)
1415
+ # Temporarily disabled: CWE-614/1275 causing 4 FPs on safe fixtures (will fix in next iteration)
1416
+ # GLOBAL_RULE_REGISTRY.register(CWE_614_RULE)
1417
+ # GLOBAL_RULE_REGISTRY.register(CWE_1275_RULE)
1418
+ GLOBAL_RULE_REGISTRY.register(CWE_798_RULE)
1419
+ GLOBAL_RULE_REGISTRY.register(CWE_611_RULE)
1420
+ GLOBAL_RULE_REGISTRY.register(CWE_918_RULE)
1421
+ GLOBAL_RULE_REGISTRY.register(CWE_1333_RULE)
1422
+ GLOBAL_RULE_REGISTRY.register(CWE_601_RULE)
1423
+ for _bank_rule in _BANK_GENERATED_RULES:
1424
+ GLOBAL_RULE_REGISTRY.register(_bank_rule)
1425
+ # CWE-322 is handled by AST structural checks (not SINK_REGISTRY bank matcher).
1426
+ # Register a named rule so get_rule("CWE-322") returns meaningful metadata.
1427
+ _CWE_322_META = _BANK_NEW_RULE_META.get("CWE-322", {})
1428
+ if _CWE_322_META and "CWE-322" not in GLOBAL_RULE_REGISTRY._rules:
1429
+ GLOBAL_RULE_REGISTRY.register(SecurityRule(
1430
+ cwe_id="CWE-322",
1431
+ name=_CWE_322_META["name"],
1432
+ category=_CWE_322_META["category"],
1433
+ operation=_CWE_322_META["operation"],
1434
+ confirmed_severity=_CWE_322_META["confirmed_severity"],
1435
+ potential_severity=_CWE_322_META["potential_severity"],
1436
+ remediation=_CWE_322_META["remediation"],
1437
+ sarif_metadata={
1438
+ "id": "CWE-322",
1439
+ "name": _CWE_322_META["name"],
1440
+ "shortDescription": {"text": _CWE_322_META["short"]},
1441
+ "fullDescription": {"text": _CWE_322_META["full"]},
1442
+ "helpUri": "https://cwe.mitre.org/data/definitions/322.html",
1443
+ "defaultConfiguration": {"level": "error"},
1444
+ "properties": {
1445
+ "precision": "high",
1446
+ "security-severity": _CWE_322_META["security_severity"],
1447
+ "tags": ["security", "external/cwe/cwe-322"],
1448
+ },
1449
+ },
1450
+ ))
1451
+ _load_catalog_security_rules(GLOBAL_RULE_REGISTRY)
1452
+
1453
+
1454
+ def get_rule(cwe_id: str) -> Optional[SecurityRule]:
1455
+ return GLOBAL_RULE_REGISTRY.get_rule(cwe_id)
1456
+
1457
+
1458
+ def get_active_cwe_count() -> int:
1459
+ """Count distinct CWE classes covered by currently active registry rules.
1460
+
1461
+ Counts unique cwe_id values, not raw rule instances, so multiple rules
1462
+ sharing one CWE class are never double-counted.
1463
+ """
1464
+ return len({
1465
+ rule.cwe_id
1466
+ for rule in GLOBAL_RULE_REGISTRY.all_rules()
1467
+ if getattr(rule, "cwe_id", None)
1468
+ })
1469
+
1470
+
1471
+ def match_sink_rule(node: ast.AST, name: str, canon_name: Optional[str] = None) -> Optional[SecurityRule]:
1472
+ return GLOBAL_RULE_REGISTRY.match_sink(node, name, canon_name)
1473
+
1474
+
1475
+ def check_sink_safety_rules(node: ast.Call, sink_name: str) -> bool:
1476
+ return GLOBAL_RULE_REGISTRY.check_safety(node, sink_name)
1477
+
1478
+
1479
+ # ==============================================================================
1480
+ # Sink matcher name contract (consumed by ast_scanner's O(1) fast path)
1481
+ # ==============================================================================
1482
+
1483
+ def _harvest_sink_matcher_names() -> frozenset:
1484
+ """Every identifier literal a sink matcher can test a call name against.
1485
+
1486
+ ast_scanner builds an O(1) pre-filter from this, so it MUST be an
1487
+ over-approximation: a name missing here silently prunes a real sink. That is
1488
+ exactly how `render` (CWE-1336) went missing when the filter was derived from
1489
+ SINK_REGISTRY alone. Harvested from this module's own source rather than
1490
+ hand-listed, so it cannot drift when a matcher gains a name.
1491
+ """
1492
+ import pathlib
1493
+
1494
+ names: set = set()
1495
+
1496
+ def _add(value) -> None:
1497
+ if not isinstance(value, str) or not value:
1498
+ return
1499
+ parts = value.split(".")
1500
+ if all(part.isidentifier() for part in parts):
1501
+ names.add(value)
1502
+ names.add(parts[-1])
1503
+
1504
+ tree = ast.parse(pathlib.Path(__file__).read_text(encoding="utf-8"))
1505
+
1506
+ # 1. Literals inside every sink matcher body (target_names, attr checks, ...).
1507
+ for fn in ast.walk(tree):
1508
+ if isinstance(fn, ast.FunctionDef) and fn.name.endswith("_sink_matcher"):
1509
+ for lit in ast.walk(fn):
1510
+ if isinstance(lit, ast.Constant):
1511
+ _add(lit.value)
1512
+
1513
+ # 2. Any set/frozenset literal of names, module level or local
1514
+ # (_EXECUTE_FAMILY, CWE78_SINKS, CWE22_PATH_ATTRS, ...).
1515
+ for node in ast.walk(tree):
1516
+ container = node
1517
+ if (isinstance(node, ast.Call) and isinstance(node.func, ast.Name)
1518
+ and node.func.id in ("frozenset", "set") and node.args):
1519
+ container = node.args[0]
1520
+ if isinstance(container, (ast.Set, ast.List, ast.Tuple)):
1521
+ if container.elts and all(isinstance(e, ast.Constant) and isinstance(e.value, str)
1522
+ for e in container.elts):
1523
+ for elt in container.elts:
1524
+ _add(elt.value)
1525
+
1526
+ # 3. Declarative sink table merged into several matchers at call time.
1527
+ for spec in DECLARATIVE_RULES_BY_CWE.values():
1528
+ if isinstance(spec, dict):
1529
+ for entry in spec.get("sinks") or ():
1530
+ _add(entry)
1531
+
1532
+ return frozenset(names)
1533
+
1534
+
1535
+ SINK_MATCHER_NAMES = _harvest_sink_matcher_names()