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
@@ -0,0 +1,348 @@
1
+ """
2
+ TimeCodeSecurity - Vector D CWE-22 Path Traversal Transformer.
3
+ Implements deterministic, AST-guided remediation for path traversal flaws:
4
+ Resolves trusted base directory via Path(base_dir).resolve(),
5
+ resolves target path via (safe_base / filename).resolve(),
6
+ injects prefix containment check via target_path.is_relative_to(safe_base),
7
+ and raises ValueError if containment is violated.
8
+ """
9
+
10
+ from typing import Any, Dict, List, Optional, Tuple, Union
11
+ import ast
12
+
13
+ from remediation.base import BaseRemediationTransformer
14
+ from remediation.contracts import RemediationRule, PatchStatus
15
+
16
+
17
+ class Cwe22PathTraversalTransformer(BaseRemediationTransformer):
18
+ """
19
+ Deterministic AST transformer for CWE-22 (Path Traversal).
20
+ Injects pathlib Path resolution and is_relative_to containment verification.
21
+ """
22
+
23
+ @property
24
+ def rule(self) -> RemediationRule:
25
+ return RemediationRule.PATH_TRAVERSAL_RESOLVE
26
+
27
+ def _find_file_sink_call(
28
+ self,
29
+ tree: ast.AST,
30
+ line_number: int
31
+ ) -> Optional[Tuple[ast.Call, ast.AST, Optional[ast.AST]]]:
32
+ """
33
+ Locates the target open() or file sink call at or covering line_number.
34
+ Returns (call_node, direct_stmt, parent_scope) or None.
35
+ """
36
+ parent_map: Dict[ast.AST, ast.AST] = {}
37
+ for parent in ast.walk(tree):
38
+ for child in ast.iter_child_nodes(parent):
39
+ parent_map[child] = parent
40
+
41
+ found_call: Optional[ast.Call] = None
42
+ for node in ast.walk(tree):
43
+ if isinstance(node, ast.Call):
44
+ func_id = getattr(node.func, "id", None)
45
+ func_attr = getattr(node.func, "attr", None)
46
+ is_file_sink = False
47
+ if func_id in ("open", "file"):
48
+ is_file_sink = True
49
+ elif func_attr in ("open", "read_text", "read_bytes"):
50
+ is_file_sink = True
51
+
52
+ if is_file_sink:
53
+ node_lineno = getattr(node, "lineno", 0)
54
+ node_end = getattr(node, "end_lineno", node_lineno)
55
+ if node_lineno <= line_number <= node_end or node_lineno == line_number:
56
+ found_call = node
57
+ break
58
+
59
+ if not found_call:
60
+ return None
61
+
62
+ # Find direct enclosing statement
63
+ curr: ast.AST = found_call
64
+ while curr in parent_map and not isinstance(curr, ast.stmt):
65
+ curr = parent_map[curr]
66
+
67
+ direct_stmt = curr
68
+ scope = parent_map.get(direct_stmt)
69
+ return (found_call, direct_stmt, scope)
70
+
71
+ def _find_preceding_assignment(
72
+ self,
73
+ scope: ast.AST,
74
+ var_name: str,
75
+ before_stmt: ast.AST
76
+ ) -> Optional[ast.Assign]:
77
+ """
78
+ Finds the most recent assignment to var_name in scope preceding before_stmt.
79
+ """
80
+ body = getattr(scope, "body", None)
81
+ if not isinstance(body, list):
82
+ return None
83
+
84
+ candidates = []
85
+ for stmt in body:
86
+ if stmt == before_stmt:
87
+ break
88
+ if isinstance(stmt, ast.Assign):
89
+ for target in stmt.targets:
90
+ if isinstance(target, ast.Name) and target.id == var_name:
91
+ candidates.append(stmt)
92
+
93
+ if candidates:
94
+ return candidates[-1]
95
+ return None
96
+
97
+ def _is_custom_path_bound(self, tree: ast.AST) -> bool:
98
+ """Checks whether 'Path' is bound to a custom object/function/class in module scope."""
99
+ body = getattr(tree, "body", [])
100
+ for stmt in body:
101
+ if isinstance(stmt, ast.Assign):
102
+ for t in stmt.targets:
103
+ if isinstance(t, ast.Name) and t.id == "Path":
104
+ return True
105
+ elif isinstance(stmt, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
106
+ if stmt.name == "Path":
107
+ return True
108
+ elif isinstance(stmt, ast.ImportFrom):
109
+ if stmt.module != "pathlib":
110
+ if any(a.asname == "Path" or (a.asname is None and a.name == "Path") for a in stmt.names):
111
+ return True
112
+ elif isinstance(stmt, ast.Import):
113
+ if any(a.asname == "Path" for a in stmt.names):
114
+ return True
115
+ return False
116
+
117
+ def _has_pathlib_path_import(self, tree: ast.AST) -> bool:
118
+ """Checks whether 'from pathlib import Path' is already present."""
119
+ body = getattr(tree, "body", [])
120
+ for stmt in body:
121
+ if isinstance(stmt, ast.ImportFrom) and stmt.module == "pathlib":
122
+ if any((a.name == "Path" and a.asname is None) or a.asname == "Path" for a in stmt.names):
123
+ return True
124
+ return False
125
+
126
+ def _find_safe_import_insertion_index(self, tree: ast.AST, lines: List[str]) -> int:
127
+ """
128
+ Finds the safe line index for inserting 'from pathlib import Path'.
129
+ Ensures legal import ordering:
130
+ - Placed after existing imports (and strictly after any 'from __future__' import)
131
+ - If no imports exist: placed after module docstring and shebang/encoding header.
132
+ """
133
+ body = getattr(tree, "body", [])
134
+ last_import_end = 0
135
+ for stmt in body:
136
+ if isinstance(stmt, (ast.Import, ast.ImportFrom)):
137
+ end_l = getattr(stmt, "end_lineno", stmt.lineno)
138
+ if end_l > last_import_end:
139
+ last_import_end = end_l
140
+
141
+ if last_import_end > 0:
142
+ return last_import_end
143
+
144
+ # No imports exist. Check for module docstring
145
+ if body and isinstance(body[0], ast.Expr) and isinstance(getattr(body[0], "value", None), ast.Constant):
146
+ if isinstance(body[0].value.value, str):
147
+ return getattr(body[0], "end_lineno", body[0].lineno)
148
+
149
+ # Check for shebang and encoding declarations in comments
150
+ idx = 0
151
+ while idx < len(lines):
152
+ line = lines[idx].strip()
153
+ if line.startswith("#!") or "coding" in line:
154
+ idx += 1
155
+ else:
156
+ break
157
+ return idx
158
+
159
+ def _decompose_path_expression(
160
+ self,
161
+ node: ast.AST
162
+ ) -> Tuple[bool, Optional[ast.AST], Optional[ast.AST], Tuple[str, ...]]:
163
+ """
164
+ Decomposes a path expression (BinOp add or os.path.join) into (base_dir, filename).
165
+ """
166
+ if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
167
+ left = node.left
168
+ right = node.right
169
+ # If right is a redundant str(...) call, unwrap it
170
+ if isinstance(right, ast.Call) and isinstance(right.func, ast.Name) and right.func.id == "str":
171
+ if len(right.args) == 1:
172
+ right = right.args[0]
173
+ return (True, left, right, ())
174
+
175
+ elif isinstance(node, ast.Call):
176
+ func_attr = getattr(node.func, "attr", None)
177
+ if func_attr == "join":
178
+ if len(node.args) >= 2:
179
+ return (True, node.args[0], node.args[1], ())
180
+
181
+ return (
182
+ False,
183
+ None,
184
+ None,
185
+ ("Path expression must be a concatenation (+) or os.path.join() between base directory and filename",)
186
+ )
187
+
188
+ def can_transform(
189
+ self,
190
+ tree: ast.AST,
191
+ finding: Dict[str, Any],
192
+ source_code: str
193
+ ) -> bool:
194
+ if self._is_custom_path_bound(tree):
195
+ return False
196
+
197
+ line_no = int(finding.get("line_number", 0))
198
+ match = self._find_file_sink_call(tree, line_no)
199
+ if not match:
200
+ return False
201
+
202
+ call_node, parent_stmt, parent_scope = match
203
+ if not call_node.args:
204
+ return False
205
+
206
+ arg0 = call_node.args[0]
207
+ if isinstance(arg0, ast.Name):
208
+ if not parent_scope:
209
+ return False
210
+ assign = self._find_preceding_assignment(parent_scope, arg0.id, parent_stmt)
211
+ if not assign:
212
+ return False
213
+ ok, _, _, _ = self._decompose_path_expression(assign.value)
214
+ return ok
215
+ else:
216
+ ok, _, _, _ = self._decompose_path_expression(arg0)
217
+ return ok
218
+
219
+ def transform(
220
+ self,
221
+ tree: ast.AST,
222
+ finding: Dict[str, Any],
223
+ source_code: str
224
+ ) -> Tuple[PatchStatus, Optional[str], Optional[str], Tuple[str, ...]]:
225
+ if self._is_custom_path_bound(tree):
226
+ return (
227
+ PatchStatus.UNSUPPORTED_CWE,
228
+ None,
229
+ None,
230
+ ("Symbol 'Path' is already bound to a custom object in module scope and cannot be safely overwritten",)
231
+ )
232
+
233
+ line_no = int(finding.get("line_number", 0))
234
+ match = self._find_file_sink_call(tree, line_no)
235
+ if not match:
236
+ return (
237
+ PatchStatus.UNSUPPORTED_CWE,
238
+ None,
239
+ None,
240
+ (f"Could not locate matching file sink call at line {line_no}",)
241
+ )
242
+
243
+ call_node, parent_stmt, parent_scope = match
244
+ if not call_node.args:
245
+ return (
246
+ PatchStatus.UNSUPPORTED_CWE,
247
+ None,
248
+ None,
249
+ ("File sink call missing path argument",)
250
+ )
251
+
252
+ arg0 = call_node.args[0]
253
+ lines = source_code.splitlines(keepends=True)
254
+
255
+ if isinstance(arg0, ast.Name):
256
+ var_name = arg0.id
257
+ if not parent_scope:
258
+ return (
259
+ PatchStatus.UNSUPPORTED_CWE,
260
+ None,
261
+ None,
262
+ (f"Cannot resolve scope for variable {var_name}",)
263
+ )
264
+
265
+ assign_stmt = self._find_preceding_assignment(parent_scope, var_name, parent_stmt)
266
+ if not assign_stmt:
267
+ return (
268
+ PatchStatus.UNSUPPORTED_CWE,
269
+ None,
270
+ None,
271
+ (f"Could not locate preceding assignment to {var_name}",)
272
+ )
273
+
274
+ ok, base_node, file_node, limitations = self._decompose_path_expression(assign_stmt.value)
275
+ if not ok or base_node is None or file_node is None:
276
+ return (PatchStatus.UNSUPPORTED_CWE, None, None, limitations)
277
+
278
+ base_expr = ast.unparse(base_node)
279
+ file_expr = ast.unparse(file_node)
280
+
281
+ assign_start = assign_stmt.lineno - 1
282
+ assign_end = getattr(assign_stmt, "end_lineno", assign_stmt.lineno)
283
+ orig_line = lines[assign_start]
284
+ indent = orig_line[:len(orig_line) - len(orig_line.lstrip())]
285
+ line_ending = "\r\n" if orig_line.endswith("\r\n") else "\n"
286
+
287
+ # Construct containment block
288
+ guard_lines = [
289
+ f"{indent}safe_base = Path({base_expr}).resolve(){line_ending}",
290
+ f"{indent}{var_name} = (safe_base / {file_expr}).resolve(){line_ending}",
291
+ f"{indent}if not {var_name}.is_relative_to(safe_base):{line_ending}",
292
+ f"{indent} raise ValueError(\"Path traversal attempt detected\"){line_ending}",
293
+ ]
294
+
295
+ patched_lines = list(lines)
296
+ patched_lines[assign_start:assign_end] = guard_lines
297
+
298
+ # Handle import if needed
299
+ if not self._has_pathlib_path_import(tree):
300
+ insert_idx = self._find_safe_import_insertion_index(tree, lines)
301
+ import_stmt = f"from pathlib import Path{line_ending}"
302
+ patched_lines.insert(insert_idx, import_stmt)
303
+
304
+ patched_source = "".join(patched_lines)
305
+ patched_snippet = "".join(guard_lines).strip()
306
+ return (PatchStatus.SUCCESS, patched_source, patched_snippet, ())
307
+
308
+ else:
309
+ # Inline path expression
310
+ ok, base_node, file_node, limitations = self._decompose_path_expression(arg0)
311
+ if not ok or base_node is None or file_node is None:
312
+ return (PatchStatus.UNSUPPORTED_CWE, None, None, limitations)
313
+
314
+ base_expr = ast.unparse(base_node)
315
+ file_expr = ast.unparse(file_node)
316
+ var_name = "target_path"
317
+
318
+ sink_start = parent_stmt.lineno - 1
319
+ sink_end = getattr(parent_stmt, "end_lineno", parent_stmt.lineno)
320
+ orig_line = lines[sink_start]
321
+ indent = orig_line[:len(orig_line) - len(orig_line.lstrip())]
322
+ line_ending = "\r\n" if orig_line.endswith("\r\n") else "\n"
323
+
324
+ guard_lines = [
325
+ f"{indent}safe_base = Path({base_expr}).resolve(){line_ending}",
326
+ f"{indent}{var_name} = (safe_base / {file_expr}).resolve(){line_ending}",
327
+ f"{indent}if not {var_name}.is_relative_to(safe_base):{line_ending}",
328
+ f"{indent} raise ValueError(\"Path traversal attempt detected\"){line_ending}",
329
+ ]
330
+
331
+ # Reconstruct call with var_name
332
+ # Replace arg0 in call
333
+ orig_call_str = lines[sink_start:sink_end]
334
+ # Replace the exact arg expression in the sink lines
335
+ raw_arg_str = ast.unparse(arg0)
336
+ replaced_sink = "".join(orig_call_str).replace(raw_arg_str, var_name, 1)
337
+
338
+ patched_lines = list(lines)
339
+ patched_lines[sink_start:sink_end] = guard_lines + [replaced_sink]
340
+
341
+ if not self._has_pathlib_path_import(tree):
342
+ insert_idx = self._find_safe_import_insertion_index(tree, lines)
343
+ import_stmt = f"from pathlib import Path{line_ending}"
344
+ patched_lines.insert(insert_idx, import_stmt)
345
+
346
+ patched_source = "".join(patched_lines)
347
+ patched_snippet = "".join(guard_lines).strip()
348
+ return (PatchStatus.SUCCESS, patched_source, patched_snippet, ())
@@ -0,0 +1,87 @@
1
+ """
2
+ TimeCodeSecurity - Vector D CWE-295 Disabled SSL Verification Transformer.
3
+ Implements deterministic AST-guided remediation for verify=False in requests.
4
+ """
5
+
6
+ from typing import Any, Dict, Optional, Tuple
7
+ import ast
8
+
9
+ from remediation.base import BaseRemediationTransformer
10
+ from remediation.contracts import RemediationRule, PatchStatus
11
+
12
+
13
+ class Cwe295SslVerificationTransformer(BaseRemediationTransformer):
14
+ """
15
+ Deterministic AST transformer for CWE-295 (Disabled SSL Verification).
16
+ Removes or changes verify=False to verify=True in requests calls.
17
+ """
18
+
19
+ @property
20
+ def rule(self) -> RemediationRule:
21
+ return RemediationRule.SSL_VERIFY_ENABLE
22
+
23
+ def can_transform(
24
+ self,
25
+ tree: ast.AST,
26
+ finding: Dict[str, Any],
27
+ source_code: str
28
+ ) -> bool:
29
+ """Check if finding is requests call with verify=False."""
30
+ line_number = finding.get("line_number", 0)
31
+ call_node = self._find_verify_false_call(tree, line_number)
32
+ return call_node is not None
33
+
34
+ def transform(
35
+ self,
36
+ tree: ast.AST,
37
+ finding: Dict[str, Any],
38
+ source_code: str
39
+ ) -> Tuple[PatchStatus, Optional[str], Optional[str], Tuple[str, ...]]:
40
+ """Change verify=False to verify=True."""
41
+ line_number = finding.get("line_number", 0)
42
+
43
+ call_node = self._find_verify_false_call(tree, line_number)
44
+ if not call_node:
45
+ return (PatchStatus.UNSUPPORTED_CWE, None, None, ("requests call not found",))
46
+
47
+ # Find and replace verify=False keyword
48
+ for kw in call_node.keywords:
49
+ if kw.arg == "verify" and isinstance(kw.value, ast.Constant) and kw.value.value is False:
50
+ kw.value = ast.Constant(value=True)
51
+ break
52
+ else:
53
+ return (PatchStatus.UNSUPPORTED_CWE, None, None, ("verify=False not found",))
54
+
55
+ try:
56
+ patched_source = ast.unparse(tree)
57
+ snippet = self.patched_statement_snippet(tree, source_code, line_number) or ""
58
+
59
+ return (PatchStatus.SUCCESS, patched_source, snippet, ())
60
+ except Exception as e:
61
+ return (PatchStatus.FAILED_SYNTAX, None, None, (f"AST unparse failed: {e}",))
62
+
63
+ def _find_verify_false_call(
64
+ self,
65
+ tree: ast.AST,
66
+ line_number: int
67
+ ) -> Optional[ast.Call]:
68
+ """Locate requests call with verify=False at or near the given line."""
69
+ for node in ast.walk(tree):
70
+ if isinstance(node, ast.Call):
71
+ func = node.func
72
+ is_requests_call = False
73
+
74
+ if isinstance(func, ast.Attribute):
75
+ if isinstance(func.value, ast.Name) and func.value.id == "requests":
76
+ if func.attr in ("get", "post", "put", "delete", "patch", "head", "options"):
77
+ is_requests_call = True
78
+
79
+ if is_requests_call:
80
+ # Check for verify=False keyword
81
+ for kw in node.keywords:
82
+ if kw.arg == "verify" and isinstance(kw.value, ast.Constant) and kw.value.value is False:
83
+ node_lineno = getattr(node, "lineno", 0)
84
+ node_end = getattr(node, "end_lineno", node_lineno)
85
+ if node_lineno <= line_number <= node_end or node_lineno == line_number:
86
+ return node
87
+ return None
@@ -0,0 +1,78 @@
1
+ """
2
+ TimeCodeSecurity - Vector D CWE-327 Weak Cryptographic Hash Transformer.
3
+ Implements deterministic AST-guided remediation replacing md5/sha1 with sha256.
4
+ """
5
+
6
+ from typing import Any, Dict, Optional, Tuple
7
+ import ast
8
+
9
+ from remediation.base import BaseRemediationTransformer
10
+ from remediation.contracts import RemediationRule, PatchStatus
11
+
12
+
13
+ class Cwe327WeakHashTransformer(BaseRemediationTransformer):
14
+ """
15
+ Deterministic AST transformer for CWE-327 (Weak Cryptographic Hash).
16
+ Replaces hashlib.md5() and hashlib.sha1() with hashlib.sha256().
17
+ """
18
+
19
+ @property
20
+ def rule(self) -> RemediationRule:
21
+ return RemediationRule.WEAK_HASH_REPLACE
22
+
23
+ def can_transform(
24
+ self,
25
+ tree: ast.AST,
26
+ finding: Dict[str, Any],
27
+ source_code: str
28
+ ) -> bool:
29
+ """Check if finding is a hashlib.md5() or hashlib.sha1() call."""
30
+ line_number = finding.get("line_number", 0)
31
+ call_node = self._find_weak_hash_call(tree, line_number)
32
+ return call_node is not None
33
+
34
+ def transform(
35
+ self,
36
+ tree: ast.AST,
37
+ finding: Dict[str, Any],
38
+ source_code: str
39
+ ) -> Tuple[PatchStatus, Optional[str], Optional[str], Tuple[str, ...]]:
40
+ """Replace weak hash function with sha256."""
41
+ line_number = finding.get("line_number", 0)
42
+
43
+ call_node = self._find_weak_hash_call(tree, line_number)
44
+ if not call_node:
45
+ return (PatchStatus.UNSUPPORTED_CWE, None, None, ("Weak hash call not found",))
46
+
47
+ # Replace the function attribute with sha256
48
+ if isinstance(call_node.func, ast.Attribute):
49
+ call_node.func.attr = "sha256"
50
+ else:
51
+ return (PatchStatus.UNSUPPORTED_CWE, None, None, ("Unexpected AST structure",))
52
+
53
+ try:
54
+ patched_source = ast.unparse(tree)
55
+ snippet = self.patched_statement_snippet(tree, source_code, line_number) or ""
56
+
57
+ return (PatchStatus.SUCCESS, patched_source, snippet, ())
58
+ except Exception as e:
59
+ return (PatchStatus.FAILED_SYNTAX, None, None, (f"AST unparse failed: {e}",))
60
+
61
+ def _find_weak_hash_call(
62
+ self,
63
+ tree: ast.AST,
64
+ line_number: int
65
+ ) -> Optional[ast.Call]:
66
+ """Locate hashlib.md5() or hashlib.sha1() call at or near the given line."""
67
+ for node in ast.walk(tree):
68
+ if isinstance(node, ast.Call):
69
+ func = node.func
70
+ if isinstance(func, ast.Attribute):
71
+ if func.attr in ("md5", "sha1"):
72
+ # Verify it's hashlib.md5 or hashlib.sha1
73
+ if isinstance(func.value, ast.Name) and func.value.id == "hashlib":
74
+ node_lineno = getattr(node, "lineno", 0)
75
+ node_end = getattr(node, "end_lineno", node_lineno)
76
+ if node_lineno <= line_number <= node_end or node_lineno == line_number:
77
+ return node
78
+ return None
@@ -0,0 +1,77 @@
1
+ """
2
+ TimeCodeSecurity - Vector D CWE-377 Insecure Temporary File Transformer.
3
+ Implements deterministic AST-guided remediation replacing tempfile.mktemp() with NamedTemporaryFile().
4
+ """
5
+
6
+ from typing import Any, Dict, Optional, Tuple
7
+ import ast
8
+
9
+ from remediation.base import BaseRemediationTransformer
10
+ from remediation.contracts import RemediationRule, PatchStatus
11
+
12
+
13
+ class Cwe377TempfileTransformer(BaseRemediationTransformer):
14
+ """
15
+ Deterministic AST transformer for CWE-377 (Insecure Temporary File).
16
+ Replaces tempfile.mktemp() with tempfile.NamedTemporaryFile().
17
+ """
18
+
19
+ @property
20
+ def rule(self) -> RemediationRule:
21
+ return RemediationRule.TEMPFILE_SECURE
22
+
23
+ def can_transform(
24
+ self,
25
+ tree: ast.AST,
26
+ finding: Dict[str, Any],
27
+ source_code: str
28
+ ) -> bool:
29
+ """Check if finding is tempfile.mktemp() call."""
30
+ line_number = finding.get("line_number", 0)
31
+ call_node = self._find_mktemp_call(tree, line_number)
32
+ return call_node is not None
33
+
34
+ def transform(
35
+ self,
36
+ tree: ast.AST,
37
+ finding: Dict[str, Any],
38
+ source_code: str
39
+ ) -> Tuple[PatchStatus, Optional[str], Optional[str], Tuple[str, ...]]:
40
+ """Replace tempfile.mktemp() with tempfile.NamedTemporaryFile()."""
41
+ line_number = finding.get("line_number", 0)
42
+
43
+ call_node = self._find_mktemp_call(tree, line_number)
44
+ if not call_node:
45
+ return (PatchStatus.UNSUPPORTED_CWE, None, None, ("tempfile.mktemp call not found",))
46
+
47
+ # Replace function attribute from mktemp to NamedTemporaryFile
48
+ if isinstance(call_node.func, ast.Attribute):
49
+ call_node.func.attr = "NamedTemporaryFile"
50
+ else:
51
+ return (PatchStatus.UNSUPPORTED_CWE, None, None, ("Unexpected AST structure",))
52
+
53
+ try:
54
+ patched_source = ast.unparse(tree)
55
+ snippet = self.patched_statement_snippet(tree, source_code, line_number) or ""
56
+
57
+ return (PatchStatus.SUCCESS, patched_source, snippet, ())
58
+ except Exception as e:
59
+ return (PatchStatus.FAILED_SYNTAX, None, None, (f"AST unparse failed: {e}",))
60
+
61
+ def _find_mktemp_call(
62
+ self,
63
+ tree: ast.AST,
64
+ line_number: int
65
+ ) -> Optional[ast.Call]:
66
+ """Locate tempfile.mktemp() call at or near the given line."""
67
+ for node in ast.walk(tree):
68
+ if isinstance(node, ast.Call):
69
+ func = node.func
70
+ if isinstance(func, ast.Attribute):
71
+ if func.attr == "mktemp":
72
+ if isinstance(func.value, ast.Name) and func.value.id == "tempfile":
73
+ node_lineno = getattr(node, "lineno", 0)
74
+ node_end = getattr(node, "end_lineno", node_lineno)
75
+ if node_lineno <= line_number <= node_end or node_lineno == line_number:
76
+ return node
77
+ return None
@@ -0,0 +1,80 @@
1
+ """
2
+ TimeCodeSecurity - Vector D CWE-489 Debug Flag Transformer.
3
+ Implements deterministic AST-guided remediation for debug mode in production.
4
+ """
5
+
6
+ from typing import Any, Dict, Optional, Tuple
7
+ import ast
8
+
9
+ from remediation.base import BaseRemediationTransformer
10
+ from remediation.contracts import RemediationRule, PatchStatus
11
+
12
+
13
+ class Cwe489DebugFlagTransformer(BaseRemediationTransformer):
14
+ """
15
+ Deterministic AST transformer for CWE-489 (Debug Flag Enabled).
16
+ Replaces app.run(debug=True) with debug=False or environment-based check.
17
+ """
18
+
19
+ @property
20
+ def rule(self) -> RemediationRule:
21
+ return RemediationRule.DEBUG_FLAG_DISABLE
22
+
23
+ def can_transform(
24
+ self,
25
+ tree: ast.AST,
26
+ finding: Dict[str, Any],
27
+ source_code: str
28
+ ) -> bool:
29
+ """Check if finding is app.run(debug=True) call."""
30
+ line_number = finding.get("line_number", 0)
31
+ call_node = self._find_debug_run_call(tree, line_number)
32
+ return call_node is not None
33
+
34
+ def transform(
35
+ self,
36
+ tree: ast.AST,
37
+ finding: Dict[str, Any],
38
+ source_code: str
39
+ ) -> Tuple[PatchStatus, Optional[str], Optional[str], Tuple[str, ...]]:
40
+ """Replace debug=True with debug=False."""
41
+ line_number = finding.get("line_number", 0)
42
+
43
+ call_node = self._find_debug_run_call(tree, line_number)
44
+ if not call_node:
45
+ return (PatchStatus.UNSUPPORTED_CWE, None, None, ("app.run() call not found",))
46
+
47
+ # Find and replace debug=True keyword
48
+ for kw in call_node.keywords:
49
+ if kw.arg == "debug" and isinstance(kw.value, ast.Constant) and kw.value.value is True:
50
+ kw.value = ast.Constant(value=False)
51
+ break
52
+ else:
53
+ return (PatchStatus.UNSUPPORTED_CWE, None, None, ("debug=True not found",))
54
+
55
+ try:
56
+ patched_source = ast.unparse(tree)
57
+ snippet = self.patched_statement_snippet(tree, source_code, line_number) or ""
58
+
59
+ return (PatchStatus.SUCCESS, patched_source, snippet, ())
60
+ except Exception as e:
61
+ return (PatchStatus.FAILED_SYNTAX, None, None, (f"AST unparse failed: {e}",))
62
+
63
+ def _find_debug_run_call(
64
+ self,
65
+ tree: ast.AST,
66
+ line_number: int
67
+ ) -> Optional[ast.Call]:
68
+ """Locate app.run(debug=True) call at or near the given line."""
69
+ for node in ast.walk(tree):
70
+ if isinstance(node, ast.Call):
71
+ func = node.func
72
+ if isinstance(func, ast.Attribute) and func.attr == "run":
73
+ # Check for debug=True keyword
74
+ for kw in node.keywords:
75
+ if kw.arg == "debug" and isinstance(kw.value, ast.Constant) and kw.value.value is True:
76
+ node_lineno = getattr(node, "lineno", 0)
77
+ node_end = getattr(node, "end_lineno", node_lineno)
78
+ if node_lineno <= line_number <= node_end or node_lineno == line_number:
79
+ return node
80
+ return None