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.
- app.py +3014 -0
- ast_scanner.py +36187 -0
- banner.py +146 -0
- ci_reporter.py +570 -0
- cli.py +2347 -0
- config_loader.py +307 -0
- cross_file_engine.py +1781 -0
- delivery_models.py +145 -0
- delivery_repository.py +78 -0
- diff_scan.py +127 -0
- durable_delivery_sink.py +103 -0
- event_bus.py +155 -0
- event_publisher.py +345 -0
- event_taxonomy.py +313 -0
- function_summarizer.py +354 -0
- html_auditor.py +274 -0
- iac_auditor.py +400 -0
- in_app_adapter.py +115 -0
- js_scanner.py +895 -0
- manifest_parser.py +960 -0
- master_rules_bank.py +389 -0
- notification_models.py +346 -0
- notification_policy.py +309 -0
- notification_repository.py +118 -0
- notification_routes.py +394 -0
- notification_service.py +199 -0
- osv_client.py +437 -0
- remediation/__init__.py +39 -0
- remediation/base.py +102 -0
- remediation/contracts.py +196 -0
- remediation/cwe1188_binding.py +78 -0
- remediation/cwe1336_jinja.py +91 -0
- remediation/cwe22_path_traversal.py +348 -0
- remediation/cwe295_ssl.py +87 -0
- remediation/cwe327_weak_hash.py +78 -0
- remediation/cwe377_tempfile.py +77 -0
- remediation/cwe489_debug.py +80 -0
- remediation/cwe502_yaml.py +89 -0
- remediation/cwe614_cookie.py +91 -0
- remediation/cwe78_cmdi.py +415 -0
- remediation/cwe798_credentials.py +153 -0
- remediation/cwe89_sqli.py +425 -0
- remediation/cwe916_password_hash.py +131 -0
- remediation/cwe95_eval.py +77 -0
- remediation/dispatcher.py +114 -0
- remediation/orchestrator.py +541 -0
- remediation/patch_engine.py +213 -0
- remediation/verification.py +253 -0
- rule_engine.py +1535 -0
- sarif_adapter.py +719 -0
- sarif_exporter.py +88 -0
- sca_reachability/__init__.py +28 -0
- sca_reachability/ast_analyzer.py +366 -0
- sca_reachability/call_graph.py +203 -0
- sca_reachability/contracts.py +365 -0
- sca_reachability/dist_import_map.py +46 -0
- sca_reachability/engine.py +603 -0
- sca_reachability/resolver.py +169 -0
- scanners/__init__.py +70 -0
- scanners/container_scanner.py +323 -0
- scanners/cve_index.py +521 -0
- scanners/iac_scanner.py +328 -0
- scanners/sbom.py +183 -0
- scanners/sca_scanner.py +667 -0
- scanners/secret_scanner.py +345 -0
- scanners/yaml_lite.py +217 -0
- secret_filters.py +435 -0
- secret_scanner.py +943 -0
- sqlite_delivery_repository.py +277 -0
- sqlite_notification_repository.py +441 -0
- ssrf_guard.py +276 -0
- staged_scanner.py +492 -0
- suppression_resolver.py +282 -0
- symbol_indexer.py +424 -0
- tcs/__init__.py +1 -0
- tcs/analysis/__init__.py +1 -0
- tcs/analysis/def_use.py +408 -0
- tcs/analysis/function_contracts.py +290 -0
- tcs/parallel_analyzer.py +276 -0
- tcs/parallel_scanner.py +630 -0
- tcs/treesitter_packer.py +1446 -0
- tcs_cli.py +2086 -0
- tcs_config.py +218 -0
- tcs_gui.py +2123 -0
- timecs-2.0.0.dist-info/METADATA +142 -0
- timecs-2.0.0.dist-info/RECORD +94 -0
- timecs-2.0.0.dist-info/WHEEL +5 -0
- timecs-2.0.0.dist-info/entry_points.txt +4 -0
- timecs-2.0.0.dist-info/licenses/LICENSE +201 -0
- timecs-2.0.0.dist-info/top_level.txt +49 -0
- version_matcher.py +934 -0
- webhook_adapter.py +495 -0
- webhook_client.py +483 -0
- webhook_formatters.py +245 -0
remediation/base.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TimeCodeSecurity - Vector D Base Remediation Transformer Interface.
|
|
3
|
+
Defines the abstract base contract for deterministic, AST-guided vulnerability
|
|
4
|
+
remediation transformers.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from abc import ABC, abstractmethod
|
|
8
|
+
from typing import Any, Dict, Optional, Tuple
|
|
9
|
+
import ast
|
|
10
|
+
|
|
11
|
+
from remediation.contracts import RemediationRule, PatchStatus
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class BaseRemediationTransformer(ABC):
|
|
15
|
+
"""
|
|
16
|
+
Abstract base class for deterministic AST-guided vulnerability remediation transformers.
|
|
17
|
+
All transformers must operate strictly statically, without executing target code,
|
|
18
|
+
importing target packages, or using LLMs.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
@property
|
|
22
|
+
@abstractmethod
|
|
23
|
+
def rule(self) -> RemediationRule:
|
|
24
|
+
"""The categorical remediation rule handled by this transformer."""
|
|
25
|
+
...
|
|
26
|
+
|
|
27
|
+
@abstractmethod
|
|
28
|
+
def can_transform(
|
|
29
|
+
self,
|
|
30
|
+
tree: ast.AST,
|
|
31
|
+
finding: Dict[str, Any],
|
|
32
|
+
source_code: str
|
|
33
|
+
) -> bool:
|
|
34
|
+
"""
|
|
35
|
+
Determines whether the given AST and finding can be deterministically transformed.
|
|
36
|
+
Must check AST structure and ensure no unsupported patterns (e.g. dynamic table names) exist.
|
|
37
|
+
"""
|
|
38
|
+
...
|
|
39
|
+
|
|
40
|
+
@abstractmethod
|
|
41
|
+
def transform(
|
|
42
|
+
self,
|
|
43
|
+
tree: ast.AST,
|
|
44
|
+
finding: Dict[str, Any],
|
|
45
|
+
source_code: str
|
|
46
|
+
) -> Tuple[PatchStatus, Optional[str], Optional[str], Tuple[str, ...]]:
|
|
47
|
+
"""
|
|
48
|
+
Executes the AST-guided transformation.
|
|
49
|
+
Returns:
|
|
50
|
+
(patch_status, patched_source, patched_snippet, limitations)
|
|
51
|
+
If transformation succeeds:
|
|
52
|
+
returns (PatchStatus.SUCCESS, patched_source, patched_snippet, limitations)
|
|
53
|
+
If pattern is unsupported (e.g. dynamic table/column name):
|
|
54
|
+
returns (PatchStatus.UNSUPPORTED_CWE, None, None, limitations)
|
|
55
|
+
If transformation fails:
|
|
56
|
+
returns (PatchStatus.FAILED_SYNTAX / FAILED_VERIFICATION, None, None, limitations)
|
|
57
|
+
"""
|
|
58
|
+
...
|
|
59
|
+
|
|
60
|
+
@staticmethod
|
|
61
|
+
def patched_statement_snippet(
|
|
62
|
+
tree: ast.AST,
|
|
63
|
+
source_code: str,
|
|
64
|
+
line_number: int
|
|
65
|
+
) -> Optional[str]:
|
|
66
|
+
"""
|
|
67
|
+
Renders the patched text of the statement covering line_number after the
|
|
68
|
+
AST has been mutated, preserving the original indentation.
|
|
69
|
+
|
|
70
|
+
Transformers mutate `tree` in place, so unparsing the enclosing statement
|
|
71
|
+
yields the replacement block that editors must write over the vulnerable
|
|
72
|
+
statement. Returns None when no statement covers the requested line.
|
|
73
|
+
"""
|
|
74
|
+
candidates = [
|
|
75
|
+
node
|
|
76
|
+
for node in ast.walk(tree)
|
|
77
|
+
if isinstance(node, ast.stmt)
|
|
78
|
+
and getattr(node, "lineno", 0)
|
|
79
|
+
and node.lineno <= line_number <= (node.end_lineno or node.lineno)
|
|
80
|
+
]
|
|
81
|
+
if not candidates:
|
|
82
|
+
return None
|
|
83
|
+
|
|
84
|
+
# Deepest (smallest span) enclosing statement
|
|
85
|
+
stmt = min(candidates, key=lambda n: (n.end_lineno or n.lineno) - n.lineno)
|
|
86
|
+
|
|
87
|
+
try:
|
|
88
|
+
rendered = ast.unparse(stmt)
|
|
89
|
+
except Exception:
|
|
90
|
+
return None
|
|
91
|
+
|
|
92
|
+
original_lines = source_code.split("\n")
|
|
93
|
+
if 0 < line_number <= len(original_lines):
|
|
94
|
+
indent = original_lines[line_number - 1][: len(original_lines[line_number - 1]) - len(original_lines[line_number - 1].lstrip())]
|
|
95
|
+
else:
|
|
96
|
+
indent = ""
|
|
97
|
+
|
|
98
|
+
rendered_lines = rendered.split("\n")
|
|
99
|
+
out = [f"{indent}{rendered_lines[0]}"]
|
|
100
|
+
for extra in rendered_lines[1:]:
|
|
101
|
+
out.append(f"{indent}{extra}" if extra.strip() else extra)
|
|
102
|
+
return "\n".join(out)
|
remediation/contracts.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TimeCodeSecurity - Vector D Remediation Engine Contracts.
|
|
3
|
+
Defines immutable data models, state invariant validation, and semantic
|
|
4
|
+
remediation schemas for automated vulnerability patching and verification.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from enum import Enum
|
|
9
|
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class PatchStatus(str, Enum):
|
|
13
|
+
"""Execution status of an automated remediation patch."""
|
|
14
|
+
SUCCESS = "SUCCESS"
|
|
15
|
+
FAILED_SYNTAX = "FAILED_SYNTAX"
|
|
16
|
+
FAILED_VERIFICATION = "FAILED_VERIFICATION"
|
|
17
|
+
UNSUPPORTED_CWE = "UNSUPPORTED_CWE"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class RemediationRule(str, Enum):
|
|
21
|
+
"""Categorical AST rewrite rule identifiers."""
|
|
22
|
+
SQLI_PARAMETERIZE = "SQLI_PARAMETERIZE"
|
|
23
|
+
PATH_TRAVERSAL_RESOLVE = "PATH_TRAVERSAL_RESOLVE"
|
|
24
|
+
CMD_INJECTION_SPLIT = "CMD_INJECTION_SPLIT"
|
|
25
|
+
COOKIE_SECURE_FLAGS = "COOKIE_SECURE_FLAGS"
|
|
26
|
+
TEMPLATE_AUTOESCAPE = "TEMPLATE_AUTOESCAPE"
|
|
27
|
+
WEAK_HASH_REPLACE = "WEAK_HASH_REPLACE"
|
|
28
|
+
PASSWORD_HASH_KDF = "PASSWORD_HASH_KDF"
|
|
29
|
+
YAML_SAFE_LOADER = "YAML_SAFE_LOADER"
|
|
30
|
+
CREDENTIAL_ENVIRON_GET = "CREDENTIAL_ENVIRON_GET"
|
|
31
|
+
DEBUG_FLAG_DISABLE = "DEBUG_FLAG_DISABLE"
|
|
32
|
+
SSL_VERIFY_ENABLE = "SSL_VERIFY_ENABLE"
|
|
33
|
+
TEMPFILE_SECURE = "TEMPFILE_SECURE"
|
|
34
|
+
EVAL_LITERAL_REPLACE = "EVAL_LITERAL_REPLACE"
|
|
35
|
+
NETWORK_BINDING_LOCALHOST = "NETWORK_BINDING_LOCALHOST"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True)
|
|
39
|
+
class RemediationRecord:
|
|
40
|
+
"""
|
|
41
|
+
Immutable representation of an automated vulnerability remediation patch attempt.
|
|
42
|
+
Enforces strict state invariants forbidding contradictory outcomes.
|
|
43
|
+
"""
|
|
44
|
+
finding_id: str
|
|
45
|
+
cwe: str
|
|
46
|
+
remediation_rule: RemediationRule
|
|
47
|
+
original_file: str
|
|
48
|
+
line_number: int
|
|
49
|
+
patch_status: PatchStatus
|
|
50
|
+
original_code_snippet: str
|
|
51
|
+
patched_code_snippet: str
|
|
52
|
+
unified_diff: str
|
|
53
|
+
verification_passed: bool
|
|
54
|
+
limitations: Tuple[str, ...] = ()
|
|
55
|
+
patched_source: Optional[str] = None
|
|
56
|
+
|
|
57
|
+
def __post_init__(self):
|
|
58
|
+
# Blocker 1 & Contract Validation: Type integrity
|
|
59
|
+
if not isinstance(self.patch_status, PatchStatus):
|
|
60
|
+
try:
|
|
61
|
+
object.__setattr__(self, "patch_status", PatchStatus(self.patch_status))
|
|
62
|
+
except (ValueError, TypeError) as err:
|
|
63
|
+
raise ValueError(f"Invalid patch_status: {self.patch_status}") from err
|
|
64
|
+
|
|
65
|
+
if not isinstance(self.remediation_rule, RemediationRule):
|
|
66
|
+
try:
|
|
67
|
+
object.__setattr__(self, "remediation_rule", RemediationRule(self.remediation_rule))
|
|
68
|
+
except (ValueError, TypeError) as err:
|
|
69
|
+
raise ValueError(f"Invalid remediation_rule: {self.remediation_rule}") from err
|
|
70
|
+
|
|
71
|
+
# Blocker 2: State invariant enforcement - strictly forbid contradictory states
|
|
72
|
+
if self.patch_status == PatchStatus.SUCCESS and not self.verification_passed:
|
|
73
|
+
raise ValueError(
|
|
74
|
+
"Contradictory state: patch_status SUCCESS requires verification_passed == True"
|
|
75
|
+
)
|
|
76
|
+
if self.patch_status in (
|
|
77
|
+
PatchStatus.FAILED_SYNTAX,
|
|
78
|
+
PatchStatus.FAILED_VERIFICATION,
|
|
79
|
+
PatchStatus.UNSUPPORTED_CWE,
|
|
80
|
+
) and self.verification_passed:
|
|
81
|
+
raise ValueError(
|
|
82
|
+
f"Contradictory state: patch_status {self.patch_status.value} requires verification_passed == False"
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
86
|
+
"""Serializes the record to a standard JSON-compatible dictionary."""
|
|
87
|
+
d = {
|
|
88
|
+
"finding_id": self.finding_id,
|
|
89
|
+
"cwe": self.cwe,
|
|
90
|
+
"remediation_rule": self.remediation_rule.value if isinstance(self.remediation_rule, Enum) else str(self.remediation_rule),
|
|
91
|
+
"original_file": self.original_file,
|
|
92
|
+
"line_number": self.line_number,
|
|
93
|
+
"patch_status": self.patch_status.value if isinstance(self.patch_status, Enum) else str(self.patch_status),
|
|
94
|
+
"original_code_snippet": self.original_code_snippet,
|
|
95
|
+
"patched_code_snippet": self.patched_code_snippet,
|
|
96
|
+
"unified_diff": self.unified_diff,
|
|
97
|
+
"verification_passed": self.verification_passed,
|
|
98
|
+
"limitations": list(self.limitations),
|
|
99
|
+
}
|
|
100
|
+
if self.patched_source is not None:
|
|
101
|
+
d["patched_source"] = self.patched_source
|
|
102
|
+
return d
|
|
103
|
+
|
|
104
|
+
@classmethod
|
|
105
|
+
def from_dict(cls, data: Dict[str, Any]) -> "RemediationRecord":
|
|
106
|
+
"""Deserializes a dictionary into a frozen RemediationRecord."""
|
|
107
|
+
raw_status = data.get("patch_status", PatchStatus.UNSUPPORTED_CWE)
|
|
108
|
+
status = PatchStatus(raw_status) if isinstance(raw_status, str) else raw_status
|
|
109
|
+
|
|
110
|
+
raw_rule = data.get("remediation_rule")
|
|
111
|
+
if not raw_rule:
|
|
112
|
+
raise ValueError("Missing required 'remediation_rule' in RemediationRecord payload")
|
|
113
|
+
rule = RemediationRule(raw_rule) if isinstance(raw_rule, str) else raw_rule
|
|
114
|
+
|
|
115
|
+
return cls(
|
|
116
|
+
finding_id=str(data["finding_id"]),
|
|
117
|
+
cwe=str(data["cwe"]),
|
|
118
|
+
remediation_rule=rule,
|
|
119
|
+
original_file=str(data["original_file"]),
|
|
120
|
+
line_number=int(data["line_number"]),
|
|
121
|
+
patch_status=status,
|
|
122
|
+
original_code_snippet=str(data.get("original_code_snippet", "")),
|
|
123
|
+
patched_code_snippet=str(data.get("patched_code_snippet", "")),
|
|
124
|
+
unified_diff=str(data.get("unified_diff", "")),
|
|
125
|
+
verification_passed=bool(data.get("verification_passed", False)),
|
|
126
|
+
limitations=tuple(data.get("limitations", ())),
|
|
127
|
+
patched_source=data.get("patched_source"),
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
# ======================================================================
|
|
132
|
+
# GOLDEN FIXTURE SEMANTIC CONTRACT REGISTRY (PHASE 2 ORACLE)
|
|
133
|
+
# ======================================================================
|
|
134
|
+
|
|
135
|
+
FIXTURE_SEMANTIC_CONTRACTS: Dict[str, Dict[str, Any]] = {
|
|
136
|
+
"fixture_01_sqli_fstring": {
|
|
137
|
+
"fixture_id": "fixture_01_sqli_fstring",
|
|
138
|
+
"cwe": "CWE-89",
|
|
139
|
+
"remediation_rule": RemediationRule.SQLI_PARAMETERIZE,
|
|
140
|
+
"expected_security_property": "SQL data MUST NOT remain concatenated/interpolated into SQL text; user input is bound via driver placeholder tuple.",
|
|
141
|
+
"input_ast_pattern": "ast.Call to cursor.execute where query argument is an ast.JoinedStr (f-string).",
|
|
142
|
+
"vulnerable_sink": "cursor.execute(f\"SELECT * FROM users WHERE username = '{username}'\")",
|
|
143
|
+
"expected_ast_transformation": "Extract string constant literal fragments, replace formatted values ({username}) with driver placeholders (?), strip surrounding quotes from SQL text, and append tuple of interpolated expressions as second argument to cursor.execute.",
|
|
144
|
+
"placeholder_style": "?",
|
|
145
|
+
"parameter_ordering": "Positional tuple matches left-to-right order of ast.FormattedValue expressions in ast.JoinedStr.",
|
|
146
|
+
"assumptions_and_limitations": [
|
|
147
|
+
"Assumes SQLite parameter syntax '?'",
|
|
148
|
+
"Does not support dynamic table/column identifiers via query parameters",
|
|
149
|
+
"Only handles inline FormattedValue expressions"
|
|
150
|
+
]
|
|
151
|
+
},
|
|
152
|
+
"fixture_02_sqli_concat": {
|
|
153
|
+
"fixture_id": "fixture_02_sqli_concat",
|
|
154
|
+
"cwe": "CWE-89",
|
|
155
|
+
"remediation_rule": RemediationRule.SQLI_PARAMETERIZE,
|
|
156
|
+
"expected_security_property": "Dynamic concatenation operands are stripped from query string construction and bound as SQL query parameters.",
|
|
157
|
+
"input_ast_pattern": "ast.BinOp(op=ast.Add()) constructing SQL query string passed to cursor.execute.",
|
|
158
|
+
"vulnerable_sink": "cursor.execute(query) where query = '...' + str(order_id)",
|
|
159
|
+
"expected_ast_transformation": "Decompose binary addition tree: replace dynamic operands (e.g. str(order_id) or order_id) with driver placeholder (?), strip surrounding quote delimiters if present, and bind dynamic operand expressions as a tuple argument to cursor.execute.",
|
|
160
|
+
"operands_becoming_parameters": "Right-hand dynamic operand 'order_id' (with redundant type conversions unwrapped if present).",
|
|
161
|
+
"assumptions_and_limitations": [
|
|
162
|
+
"Operands must represent scalar data values, not SQL keywords or table names",
|
|
163
|
+
"Preserves underlying operand evaluation order in parameter tuple"
|
|
164
|
+
]
|
|
165
|
+
},
|
|
166
|
+
"fixture_03_cmdi_shell_true": {
|
|
167
|
+
"fixture_id": "fixture_03_cmdi_shell_true",
|
|
168
|
+
"cwe": "CWE-78",
|
|
169
|
+
"remediation_rule": RemediationRule.CMD_INJECTION_SPLIT,
|
|
170
|
+
"expected_security_property": "Command execution bypasses system shell parser (/bin/sh or cmd.exe) by utilizing direct execve array invocation with shell=False.",
|
|
171
|
+
"input_ast_pattern": "ast.Call to subprocess.{call,run,Popen,check_output} with keyword argument shell=ast.Constant(value=True).",
|
|
172
|
+
"vulnerable_sink": "subprocess.call(cmd, shell=True)",
|
|
173
|
+
"expected_ast_transformation": "Transform string command into structured argument list (via static tokenization or shlex.split), set keyword argument shell=False (or omit shell default).",
|
|
174
|
+
"command_splitting_mechanism": "Decompose command string into argument list [executable, arg1, arg2, ...] while preserving argument boundaries so shell metacharacters (; | & ` $ ()) cannot alter execution topology.",
|
|
175
|
+
"assumptions_and_limitations": [
|
|
176
|
+
"Bypasses shell built-ins (cd, echo) which require explicit executable binaries",
|
|
177
|
+
"Shell pipelines (|) or redirection (>, <) require multi-process piping or file descriptors"
|
|
178
|
+
]
|
|
179
|
+
},
|
|
180
|
+
"fixture_04_path_traversal_open": {
|
|
181
|
+
"fixture_id": "fixture_04_path_traversal_open",
|
|
182
|
+
"cwe": "CWE-22",
|
|
183
|
+
"remediation_rule": RemediationRule.PATH_TRAVERSAL_RESOLVE,
|
|
184
|
+
"expected_security_property": "Canonicalized target path is mathematically guaranteed to remain within the trusted base directory boundary via is_relative_to.",
|
|
185
|
+
"input_ast_pattern": "ast.Call to open() or os.path operations concatenating untrusted filename to a base directory.",
|
|
186
|
+
"vulnerable_sink": "open(base_dir + filename)",
|
|
187
|
+
"expected_ast_transformation": "Resolve trusted base directory (Path(base_dir).resolve()), resolve candidate target path ((safe_base / filename).resolve()), and insert containment guard (if not target_path.is_relative_to(safe_base): raise ValueError).",
|
|
188
|
+
"resolution_step": "Both base directory and target path are fully canonicalized with Path.resolve() to collapse symlinks and '..' traversal segments.",
|
|
189
|
+
"containment_check": "target_path.is_relative_to(safe_base) verifies prefix containment.",
|
|
190
|
+
"failure_behavior": "Explicitly raises ValueError or SecurityException when target path resolves outside trusted base directory boundary.",
|
|
191
|
+
"assumptions_and_limitations": [
|
|
192
|
+
"Requires Python 3.9+ for Path.is_relative_to",
|
|
193
|
+
"Calling resolve() alone is insufficient without the containment check against safe_base"
|
|
194
|
+
]
|
|
195
|
+
}
|
|
196
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TimeCodeSecurity - Vector D CWE-1188 Insecure Network Binding Transformer.
|
|
3
|
+
Implements deterministic AST-guided remediation changing host="0.0.0.0" to host="127.0.0.1".
|
|
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 Cwe1188NetworkBindingTransformer(BaseRemediationTransformer):
|
|
14
|
+
"""
|
|
15
|
+
Deterministic AST transformer for CWE-1188 (Insecure Default Network Binding).
|
|
16
|
+
Replaces host="0.0.0.0" with host="127.0.0.1" in server/socket calls.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
@property
|
|
20
|
+
def rule(self) -> RemediationRule:
|
|
21
|
+
return RemediationRule.NETWORK_BINDING_LOCALHOST
|
|
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 has host="0.0.0.0" argument."""
|
|
30
|
+
line_number = finding.get("line_number", 0)
|
|
31
|
+
call_node = self._find_wildcard_bind_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 host="0.0.0.0" with host="127.0.0.1"."""
|
|
41
|
+
line_number = finding.get("line_number", 0)
|
|
42
|
+
|
|
43
|
+
call_node = self._find_wildcard_bind_call(tree, line_number)
|
|
44
|
+
if not call_node:
|
|
45
|
+
return (PatchStatus.UNSUPPORTED_CWE, None, None, ("Wildcard bind call not found",))
|
|
46
|
+
|
|
47
|
+
# Find and replace host="0.0.0.0" keyword
|
|
48
|
+
for kw in call_node.keywords:
|
|
49
|
+
if kw.arg == "host" and isinstance(kw.value, ast.Constant) and kw.value.value == "0.0.0.0":
|
|
50
|
+
kw.value = ast.Constant(value="127.0.0.1")
|
|
51
|
+
break
|
|
52
|
+
else:
|
|
53
|
+
return (PatchStatus.UNSUPPORTED_CWE, None, None, ("host='0.0.0.0' 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_wildcard_bind_call(
|
|
64
|
+
self,
|
|
65
|
+
tree: ast.AST,
|
|
66
|
+
line_number: int
|
|
67
|
+
) -> Optional[ast.Call]:
|
|
68
|
+
"""Locate call with host="0.0.0.0" at or near the given line."""
|
|
69
|
+
for node in ast.walk(tree):
|
|
70
|
+
if isinstance(node, ast.Call):
|
|
71
|
+
# Check for host="0.0.0.0" keyword
|
|
72
|
+
for kw in node.keywords:
|
|
73
|
+
if kw.arg == "host" and isinstance(kw.value, ast.Constant) and kw.value.value == "0.0.0.0":
|
|
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,91 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TimeCodeSecurity - Vector D CWE-1336 Jinja2 Template Injection Transformer.
|
|
3
|
+
Implements deterministic AST-guided remediation for missing autoescape in Jinja2 environments.
|
|
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 Cwe1336JinjaAutoescapeTransformer(BaseRemediationTransformer):
|
|
14
|
+
"""
|
|
15
|
+
Deterministic AST transformer for CWE-1336 (Template Injection).
|
|
16
|
+
Adds autoescape=True to jinja2.Environment() instantiation if missing.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
@property
|
|
20
|
+
def rule(self) -> RemediationRule:
|
|
21
|
+
return RemediationRule.TEMPLATE_AUTOESCAPE
|
|
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 jinja2.Environment() call without autoescape."""
|
|
30
|
+
line_number = finding.get("line_number", 0)
|
|
31
|
+
call_node = self._find_jinja_env_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
|
+
"""Add autoescape=True to jinja2.Environment() calls."""
|
|
41
|
+
line_number = finding.get("line_number", 0)
|
|
42
|
+
|
|
43
|
+
call_node = self._find_jinja_env_call(tree, line_number)
|
|
44
|
+
if not call_node:
|
|
45
|
+
return (PatchStatus.UNSUPPORTED_CWE, None, None, ("jinja2.Environment call not found",))
|
|
46
|
+
|
|
47
|
+
# Check if autoescape is already present
|
|
48
|
+
existing_keywords = {kw.arg for kw in call_node.keywords if kw.arg}
|
|
49
|
+
if "autoescape" in existing_keywords:
|
|
50
|
+
return (PatchStatus.SUCCESS, source_code, "", ("autoescape already configured",))
|
|
51
|
+
|
|
52
|
+
# Add autoescape=True keyword argument
|
|
53
|
+
autoescape_const = ast.Constant(value=True)
|
|
54
|
+
new_keyword = ast.keyword(arg="autoescape", value=autoescape_const)
|
|
55
|
+
call_node.keywords.append(new_keyword)
|
|
56
|
+
|
|
57
|
+
try:
|
|
58
|
+
patched_source = ast.unparse(tree)
|
|
59
|
+
snippet = self.patched_statement_snippet(tree, source_code, line_number) or ""
|
|
60
|
+
|
|
61
|
+
return (PatchStatus.SUCCESS, patched_source, snippet, ())
|
|
62
|
+
except Exception as e:
|
|
63
|
+
return (PatchStatus.FAILED_SYNTAX, None, None, (f"AST unparse failed: {e}",))
|
|
64
|
+
|
|
65
|
+
def _find_jinja_env_call(
|
|
66
|
+
self,
|
|
67
|
+
tree: ast.AST,
|
|
68
|
+
line_number: int
|
|
69
|
+
) -> Optional[ast.Call]:
|
|
70
|
+
"""Locate jinja2.Environment() call at or near the given line."""
|
|
71
|
+
for node in ast.walk(tree):
|
|
72
|
+
if isinstance(node, ast.Call):
|
|
73
|
+
# Match both jinja2.Environment and Environment (if imported)
|
|
74
|
+
func = node.func
|
|
75
|
+
is_jinja_env = False
|
|
76
|
+
|
|
77
|
+
if isinstance(func, ast.Attribute):
|
|
78
|
+
if func.attr == "Environment":
|
|
79
|
+
# Check if it's jinja2.Environment
|
|
80
|
+
if isinstance(func.value, ast.Name) and func.value.id == "jinja2":
|
|
81
|
+
is_jinja_env = True
|
|
82
|
+
elif isinstance(func, ast.Name):
|
|
83
|
+
if func.id == "Environment":
|
|
84
|
+
is_jinja_env = True
|
|
85
|
+
|
|
86
|
+
if is_jinja_env:
|
|
87
|
+
node_lineno = getattr(node, "lineno", 0)
|
|
88
|
+
node_end = getattr(node, "end_lineno", node_lineno)
|
|
89
|
+
if node_lineno <= line_number <= node_end or node_lineno == line_number:
|
|
90
|
+
return node
|
|
91
|
+
return None
|