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
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TimeCodeSecurity - Vector D CWE-798 Hardcoded Credentials Transformer.
|
|
3
|
+
Implements deterministic AST-guided remediation replacing hardcoded credentials with os.environ.get().
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from typing import Any, Dict, Optional, Tuple
|
|
7
|
+
import ast
|
|
8
|
+
import re
|
|
9
|
+
|
|
10
|
+
from remediation.base import BaseRemediationTransformer
|
|
11
|
+
from remediation.contracts import RemediationRule, PatchStatus
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
# Sensitive variable name patterns indicating credentials
|
|
15
|
+
SENSITIVE_PATTERNS = [
|
|
16
|
+
r'api[_-]?key',
|
|
17
|
+
r'secret[_-]?key',
|
|
18
|
+
r'password',
|
|
19
|
+
r'passwd',
|
|
20
|
+
r'token',
|
|
21
|
+
r'auth[_-]?token',
|
|
22
|
+
r'access[_-]?key',
|
|
23
|
+
r'private[_-]?key',
|
|
24
|
+
r'credential',
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
COMPILED_PATTERNS = [re.compile(p, re.IGNORECASE) for p in SENSITIVE_PATTERNS]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def is_sensitive_variable(var_name: str) -> bool:
|
|
31
|
+
"""Check if variable name matches sensitive credential patterns."""
|
|
32
|
+
return any(pattern.search(var_name) for pattern in COMPILED_PATTERNS)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class Cwe798CredentialsTransformer(BaseRemediationTransformer):
|
|
36
|
+
"""
|
|
37
|
+
Deterministic AST transformer for CWE-798 (Hardcoded Credentials).
|
|
38
|
+
Replaces hardcoded string literals assigned to sensitive variables with os.environ.get().
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def rule(self) -> RemediationRule:
|
|
43
|
+
return RemediationRule.CREDENTIAL_ENVIRON_GET
|
|
44
|
+
|
|
45
|
+
def can_transform(
|
|
46
|
+
self,
|
|
47
|
+
tree: ast.AST,
|
|
48
|
+
finding: Dict[str, Any],
|
|
49
|
+
source_code: str
|
|
50
|
+
) -> bool:
|
|
51
|
+
"""Check if finding is a hardcoded credential assignment."""
|
|
52
|
+
line_number = finding.get("line_number", 0)
|
|
53
|
+
assign_node = self._find_credential_assignment(tree, line_number)
|
|
54
|
+
return assign_node is not None
|
|
55
|
+
|
|
56
|
+
def transform(
|
|
57
|
+
self,
|
|
58
|
+
tree: ast.AST,
|
|
59
|
+
finding: Dict[str, Any],
|
|
60
|
+
source_code: str
|
|
61
|
+
) -> Tuple[PatchStatus, Optional[str], Optional[str], Tuple[str, ...]]:
|
|
62
|
+
"""Replace hardcoded credential with os.environ.get() pattern."""
|
|
63
|
+
line_number = finding.get("line_number", 0)
|
|
64
|
+
|
|
65
|
+
assign_node = self._find_credential_assignment(tree, line_number)
|
|
66
|
+
if not assign_node:
|
|
67
|
+
return (PatchStatus.UNSUPPORTED_CWE, None, None, ("Credential assignment not found",))
|
|
68
|
+
|
|
69
|
+
# Get the variable name
|
|
70
|
+
var_name = None
|
|
71
|
+
if isinstance(assign_node, ast.Assign):
|
|
72
|
+
for target in assign_node.targets:
|
|
73
|
+
if isinstance(target, ast.Name):
|
|
74
|
+
var_name = target.id
|
|
75
|
+
break
|
|
76
|
+
elif isinstance(assign_node, ast.AnnAssign):
|
|
77
|
+
if isinstance(assign_node.target, ast.Name):
|
|
78
|
+
var_name = assign_node.target.id
|
|
79
|
+
|
|
80
|
+
if not var_name:
|
|
81
|
+
return (PatchStatus.UNSUPPORTED_CWE, None, None, ("Could not extract variable name",))
|
|
82
|
+
|
|
83
|
+
# Generate environment variable name (uppercase with underscores)
|
|
84
|
+
env_var_name = var_name.upper()
|
|
85
|
+
|
|
86
|
+
# Create os.environ.get() call
|
|
87
|
+
environ_get_call = ast.Call(
|
|
88
|
+
func=ast.Attribute(
|
|
89
|
+
value=ast.Attribute(
|
|
90
|
+
value=ast.Name(id="os", ctx=ast.Load()),
|
|
91
|
+
attr="environ",
|
|
92
|
+
ctx=ast.Load()
|
|
93
|
+
),
|
|
94
|
+
attr="get",
|
|
95
|
+
ctx=ast.Load()
|
|
96
|
+
),
|
|
97
|
+
args=[
|
|
98
|
+
ast.Constant(value=env_var_name),
|
|
99
|
+
ast.Constant(value="")
|
|
100
|
+
],
|
|
101
|
+
keywords=[]
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
# Replace the value in the assignment
|
|
105
|
+
if isinstance(assign_node, ast.Assign):
|
|
106
|
+
assign_node.value = environ_get_call
|
|
107
|
+
elif isinstance(assign_node, ast.AnnAssign) and assign_node.value:
|
|
108
|
+
assign_node.value = environ_get_call
|
|
109
|
+
|
|
110
|
+
try:
|
|
111
|
+
patched_source = ast.unparse(tree)
|
|
112
|
+
snippet = self.patched_statement_snippet(tree, source_code, line_number) or ""
|
|
113
|
+
|
|
114
|
+
return (PatchStatus.SUCCESS, patched_source, snippet, ())
|
|
115
|
+
except Exception as e:
|
|
116
|
+
return (PatchStatus.FAILED_SYNTAX, None, None, (f"AST unparse failed: {e}",))
|
|
117
|
+
|
|
118
|
+
def _find_credential_assignment(
|
|
119
|
+
self,
|
|
120
|
+
tree: ast.AST,
|
|
121
|
+
line_number: int
|
|
122
|
+
) -> Optional[ast.AST]:
|
|
123
|
+
"""Locate assignment to sensitive variable at or near the given line."""
|
|
124
|
+
for node in ast.walk(tree):
|
|
125
|
+
if isinstance(node, (ast.Assign, ast.AnnAssign)):
|
|
126
|
+
# Check if it's an assignment with a string literal value
|
|
127
|
+
has_string_value = False
|
|
128
|
+
if isinstance(node, ast.Assign):
|
|
129
|
+
has_string_value = isinstance(node.value, ast.Constant) and isinstance(node.value.value, str)
|
|
130
|
+
elif isinstance(node, ast.AnnAssign) and node.value:
|
|
131
|
+
has_string_value = isinstance(node.value, ast.Constant) and isinstance(node.value.value, str)
|
|
132
|
+
|
|
133
|
+
if not has_string_value:
|
|
134
|
+
continue
|
|
135
|
+
|
|
136
|
+
# Extract variable name
|
|
137
|
+
var_name = None
|
|
138
|
+
if isinstance(node, ast.Assign):
|
|
139
|
+
for target in node.targets:
|
|
140
|
+
if isinstance(target, ast.Name):
|
|
141
|
+
var_name = target.id
|
|
142
|
+
break
|
|
143
|
+
elif isinstance(node, ast.AnnAssign):
|
|
144
|
+
if isinstance(node.target, ast.Name):
|
|
145
|
+
var_name = node.target.id
|
|
146
|
+
|
|
147
|
+
# Check if variable name is sensitive
|
|
148
|
+
if var_name and is_sensitive_variable(var_name):
|
|
149
|
+
node_lineno = getattr(node, "lineno", 0)
|
|
150
|
+
node_end = getattr(node, "end_lineno", node_lineno)
|
|
151
|
+
if node_lineno <= line_number <= node_end or node_lineno == line_number:
|
|
152
|
+
return node
|
|
153
|
+
return None
|
|
@@ -0,0 +1,425 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TimeCodeSecurity - Vector D CWE-89 SQL Injection Transformer.
|
|
3
|
+
Implements deterministic, AST-guided SQL query parameterization for:
|
|
4
|
+
1. f-string interpolated queries (cursor.execute(f"SELECT ... '{val}'"))
|
|
5
|
+
2. Concatenated queries (query = "SELECT ... " + str(val); cursor.execute(query))
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
|
9
|
+
import ast
|
|
10
|
+
import re
|
|
11
|
+
|
|
12
|
+
from remediation.base import BaseRemediationTransformer
|
|
13
|
+
from remediation.contracts import RemediationRule, PatchStatus
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def is_table_or_column_identifier(preceding_str: str) -> bool:
|
|
17
|
+
"""
|
|
18
|
+
Checks whether a dynamic placeholder is located in an SQL identifier position
|
|
19
|
+
(e.g., table name after FROM/INTO/UPDATE/TABLE/JOIN or column name directly after SELECT).
|
|
20
|
+
SQL parameters cannot bind identifiers.
|
|
21
|
+
"""
|
|
22
|
+
tokens = re.findall(r'[A-Za-z0-9_]+', preceding_str)
|
|
23
|
+
if not tokens:
|
|
24
|
+
return False
|
|
25
|
+
last_token = tokens[-1].upper()
|
|
26
|
+
if last_token in ("FROM", "INTO", "UPDATE", "TABLE", "JOIN"):
|
|
27
|
+
return True
|
|
28
|
+
if len(tokens) == 1 and last_token == "SELECT":
|
|
29
|
+
return True
|
|
30
|
+
return False
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def format_sql_literal(sql: str) -> str:
|
|
34
|
+
"""Formats an SQL query string as a valid Python string literal."""
|
|
35
|
+
if '"' not in sql:
|
|
36
|
+
return f'"{sql}"'
|
|
37
|
+
if "'" not in sql:
|
|
38
|
+
return f"'{sql}'"
|
|
39
|
+
escaped = sql.replace('"', '\\"')
|
|
40
|
+
return f'"{escaped}"'
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class Cwe89ParameterizeTransformer(BaseRemediationTransformer):
|
|
44
|
+
"""
|
|
45
|
+
Deterministic AST transformer for CWE-89 (SQL Injection).
|
|
46
|
+
Replaces dynamic interpolations/concatenations with '?' driver placeholders
|
|
47
|
+
and appends bound parameter tuples to cursor.execute().
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def rule(self) -> RemediationRule:
|
|
52
|
+
return RemediationRule.SQLI_PARAMETERIZE
|
|
53
|
+
|
|
54
|
+
def _find_execute_call(
|
|
55
|
+
self,
|
|
56
|
+
tree: ast.AST,
|
|
57
|
+
line_number: int
|
|
58
|
+
) -> Optional[Tuple[ast.Call, ast.AST, Optional[ast.AST]]]:
|
|
59
|
+
"""
|
|
60
|
+
Locates the target execute call at or covering line_number.
|
|
61
|
+
Returns (call_node, direct_stmt, parent_scope) or None.
|
|
62
|
+
"""
|
|
63
|
+
parent_map: Dict[ast.AST, ast.AST] = {}
|
|
64
|
+
for parent in ast.walk(tree):
|
|
65
|
+
for child in ast.iter_child_nodes(parent):
|
|
66
|
+
parent_map[child] = parent
|
|
67
|
+
|
|
68
|
+
found_call: Optional[ast.Call] = None
|
|
69
|
+
for node in ast.walk(tree):
|
|
70
|
+
if isinstance(node, ast.Call):
|
|
71
|
+
func_attr = getattr(node.func, "attr", None)
|
|
72
|
+
if func_attr == "execute":
|
|
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
|
+
found_call = node
|
|
77
|
+
break
|
|
78
|
+
|
|
79
|
+
if not found_call:
|
|
80
|
+
return None
|
|
81
|
+
|
|
82
|
+
# Find direct enclosing statement
|
|
83
|
+
curr: ast.AST = found_call
|
|
84
|
+
while curr in parent_map and not isinstance(curr, ast.stmt):
|
|
85
|
+
curr = parent_map[curr]
|
|
86
|
+
|
|
87
|
+
direct_stmt = curr
|
|
88
|
+
scope = parent_map.get(direct_stmt)
|
|
89
|
+
return (found_call, direct_stmt, scope)
|
|
90
|
+
|
|
91
|
+
def _find_preceding_assignment(
|
|
92
|
+
self,
|
|
93
|
+
scope: ast.AST,
|
|
94
|
+
var_name: str,
|
|
95
|
+
before_stmt: ast.AST
|
|
96
|
+
) -> Optional[ast.Assign]:
|
|
97
|
+
"""
|
|
98
|
+
Finds the most recent assignment to var_name in scope preceding before_stmt.
|
|
99
|
+
"""
|
|
100
|
+
body = getattr(scope, "body", None)
|
|
101
|
+
if not isinstance(body, list):
|
|
102
|
+
return None
|
|
103
|
+
|
|
104
|
+
candidates = []
|
|
105
|
+
for stmt in body:
|
|
106
|
+
if stmt == before_stmt:
|
|
107
|
+
break
|
|
108
|
+
if isinstance(stmt, ast.Assign):
|
|
109
|
+
for target in stmt.targets:
|
|
110
|
+
if isinstance(target, ast.Name) and target.id == var_name:
|
|
111
|
+
candidates.append(stmt)
|
|
112
|
+
|
|
113
|
+
if candidates:
|
|
114
|
+
return candidates[-1]
|
|
115
|
+
return None
|
|
116
|
+
|
|
117
|
+
def _flatten_binop_add(self, node: ast.AST) -> List[ast.AST]:
|
|
118
|
+
"""Flattens a binary addition tree into a linear list of operands."""
|
|
119
|
+
if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
|
|
120
|
+
return self._flatten_binop_add(node.left) + self._flatten_binop_add(node.right)
|
|
121
|
+
return [node]
|
|
122
|
+
|
|
123
|
+
def _decompose_joined_str(
|
|
124
|
+
self,
|
|
125
|
+
joined_str: ast.JoinedStr
|
|
126
|
+
) -> Tuple[bool, Optional[str], List[ast.AST], Tuple[str, ...]]:
|
|
127
|
+
"""
|
|
128
|
+
Decomposes an ast.JoinedStr (f-string) into:
|
|
129
|
+
(is_valid, parameterized_sql, parameter_nodes, limitations)
|
|
130
|
+
"""
|
|
131
|
+
values = list(joined_str.values)
|
|
132
|
+
fragments: List[str] = []
|
|
133
|
+
params: List[ast.AST] = []
|
|
134
|
+
|
|
135
|
+
for i, val in enumerate(values):
|
|
136
|
+
if isinstance(val, ast.FormattedValue):
|
|
137
|
+
# Check for dynamic table/column name identifier
|
|
138
|
+
preceding_text = "".join(fragments)
|
|
139
|
+
if is_table_or_column_identifier(preceding_text):
|
|
140
|
+
return (
|
|
141
|
+
False,
|
|
142
|
+
None,
|
|
143
|
+
[],
|
|
144
|
+
("Dynamic table/column identifiers cannot be parameterized via query parameters",)
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
# Check quotes around placeholder
|
|
148
|
+
prec = fragments[-1] if fragments else ""
|
|
149
|
+
succ = ""
|
|
150
|
+
if i + 1 < len(values) and isinstance(values[i + 1], ast.Constant) and isinstance(values[i + 1].value, str):
|
|
151
|
+
succ = values[i + 1].value
|
|
152
|
+
|
|
153
|
+
if prec.endswith("'") and succ.startswith("'"):
|
|
154
|
+
fragments[-1] = fragments[-1][:-1]
|
|
155
|
+
values[i + 1] = ast.Constant(value=succ[1:])
|
|
156
|
+
elif prec.endswith('"') and succ.startswith('"'):
|
|
157
|
+
fragments[-1] = fragments[-1][:-1]
|
|
158
|
+
values[i + 1] = ast.Constant(value=succ[1:])
|
|
159
|
+
|
|
160
|
+
fragments.append("?")
|
|
161
|
+
params.append(val.value)
|
|
162
|
+
elif isinstance(val, ast.Constant) and isinstance(val.value, str):
|
|
163
|
+
fragments.append(val.value)
|
|
164
|
+
else:
|
|
165
|
+
return (
|
|
166
|
+
False,
|
|
167
|
+
None,
|
|
168
|
+
[],
|
|
169
|
+
("Unsupported expression construct inside SQL f-string",)
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
if not params:
|
|
173
|
+
return (False, None, [], ("No dynamic parameters found to parameterize",))
|
|
174
|
+
|
|
175
|
+
parameterized_sql = "".join(fragments)
|
|
176
|
+
return (True, parameterized_sql, params, ())
|
|
177
|
+
|
|
178
|
+
def _decompose_binop(
|
|
179
|
+
self,
|
|
180
|
+
binop: ast.BinOp
|
|
181
|
+
) -> Tuple[bool, Optional[str], List[ast.AST], Tuple[str, ...]]:
|
|
182
|
+
"""
|
|
183
|
+
Decomposes an ast.BinOp(Add) chain into:
|
|
184
|
+
(is_valid, parameterized_sql, parameter_nodes, limitations)
|
|
185
|
+
"""
|
|
186
|
+
elements = self._flatten_binop_add(binop)
|
|
187
|
+
fragments: List[str] = []
|
|
188
|
+
params: List[ast.AST] = []
|
|
189
|
+
|
|
190
|
+
for i, elt in enumerate(elements):
|
|
191
|
+
if isinstance(elt, ast.Constant) and isinstance(elt.value, str):
|
|
192
|
+
fragments.append(elt.value)
|
|
193
|
+
else:
|
|
194
|
+
# Dynamic operand
|
|
195
|
+
preceding_text = "".join(fragments)
|
|
196
|
+
if is_table_or_column_identifier(preceding_text):
|
|
197
|
+
return (
|
|
198
|
+
False,
|
|
199
|
+
None,
|
|
200
|
+
[],
|
|
201
|
+
("Dynamic table/column identifiers cannot be parameterized via query parameters",)
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
unwrapped = elt
|
|
205
|
+
# Unwrap redundant str(x)
|
|
206
|
+
if isinstance(elt, ast.Call) and isinstance(elt.func, ast.Name) and elt.func.id == "str":
|
|
207
|
+
if len(elt.args) == 1:
|
|
208
|
+
unwrapped = elt.args[0]
|
|
209
|
+
else:
|
|
210
|
+
return (False, None, [], ("Unsupported str() call with multiple arguments",))
|
|
211
|
+
|
|
212
|
+
prec = fragments[-1] if fragments else ""
|
|
213
|
+
succ = ""
|
|
214
|
+
if i + 1 < len(elements) and isinstance(elements[i + 1], ast.Constant) and isinstance(elements[i + 1].value, str):
|
|
215
|
+
succ = elements[i + 1].value
|
|
216
|
+
|
|
217
|
+
if prec.endswith("'") and succ.startswith("'"):
|
|
218
|
+
fragments[-1] = fragments[-1][:-1]
|
|
219
|
+
elements[i + 1] = ast.Constant(value=succ[1:])
|
|
220
|
+
elif prec.endswith('"') and succ.startswith('"'):
|
|
221
|
+
fragments[-1] = fragments[-1][:-1]
|
|
222
|
+
elements[i + 1] = ast.Constant(value=succ[1:])
|
|
223
|
+
|
|
224
|
+
fragments.append("?")
|
|
225
|
+
params.append(unwrapped)
|
|
226
|
+
|
|
227
|
+
if not params:
|
|
228
|
+
return (False, None, [], ("No dynamic parameters found in binary addition",))
|
|
229
|
+
|
|
230
|
+
parameterized_sql = "".join(fragments)
|
|
231
|
+
return (True, parameterized_sql, params, ())
|
|
232
|
+
|
|
233
|
+
def can_transform(
|
|
234
|
+
self,
|
|
235
|
+
tree: ast.AST,
|
|
236
|
+
finding: Dict[str, Any],
|
|
237
|
+
source_code: str
|
|
238
|
+
) -> bool:
|
|
239
|
+
line_no = int(finding.get("line_number", 0))
|
|
240
|
+
match = self._find_execute_call(tree, line_no)
|
|
241
|
+
if not match:
|
|
242
|
+
return False
|
|
243
|
+
|
|
244
|
+
call_node, parent_stmt, parent_scope = match
|
|
245
|
+
if not call_node.args:
|
|
246
|
+
return False
|
|
247
|
+
|
|
248
|
+
arg0 = call_node.args[0]
|
|
249
|
+
if isinstance(arg0, ast.JoinedStr):
|
|
250
|
+
ok, _, _, _ = self._decompose_joined_str(arg0)
|
|
251
|
+
return ok
|
|
252
|
+
elif isinstance(arg0, ast.BinOp) and isinstance(arg0.op, ast.Add):
|
|
253
|
+
ok, _, _, _ = self._decompose_binop(arg0)
|
|
254
|
+
return ok
|
|
255
|
+
elif isinstance(arg0, ast.Name):
|
|
256
|
+
if not parent_scope:
|
|
257
|
+
return False
|
|
258
|
+
assign = self._find_preceding_assignment(parent_scope, arg0.id, parent_stmt)
|
|
259
|
+
if not assign:
|
|
260
|
+
return False
|
|
261
|
+
if isinstance(assign.value, ast.JoinedStr):
|
|
262
|
+
ok, _, _, _ = self._decompose_joined_str(assign.value)
|
|
263
|
+
return ok
|
|
264
|
+
elif isinstance(assign.value, ast.BinOp) and isinstance(assign.value.op, ast.Add):
|
|
265
|
+
ok, _, _, _ = self._decompose_binop(assign.value)
|
|
266
|
+
return ok
|
|
267
|
+
|
|
268
|
+
return False
|
|
269
|
+
|
|
270
|
+
def transform(
|
|
271
|
+
self,
|
|
272
|
+
tree: ast.AST,
|
|
273
|
+
finding: Dict[str, Any],
|
|
274
|
+
source_code: str
|
|
275
|
+
) -> Tuple[PatchStatus, Optional[str], Optional[str], Tuple[str, ...]]:
|
|
276
|
+
line_no = int(finding.get("line_number", 0))
|
|
277
|
+
match = self._find_execute_call(tree, line_no)
|
|
278
|
+
if not match:
|
|
279
|
+
return (
|
|
280
|
+
PatchStatus.UNSUPPORTED_CWE,
|
|
281
|
+
None,
|
|
282
|
+
None,
|
|
283
|
+
(f"Could not locate matching .execute() call at line {line_no}",)
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
call_node, parent_stmt, parent_scope = match
|
|
287
|
+
if not call_node.args:
|
|
288
|
+
return (
|
|
289
|
+
PatchStatus.UNSUPPORTED_CWE,
|
|
290
|
+
None,
|
|
291
|
+
None,
|
|
292
|
+
(".execute() called with no arguments",)
|
|
293
|
+
)
|
|
294
|
+
|
|
295
|
+
arg0 = call_node.args[0]
|
|
296
|
+
func_expr = ast.unparse(call_node.func)
|
|
297
|
+
|
|
298
|
+
# Build lines
|
|
299
|
+
lines = source_code.splitlines(keepends=True)
|
|
300
|
+
|
|
301
|
+
if isinstance(arg0, ast.JoinedStr):
|
|
302
|
+
ok, param_sql, params, limitations = self._decompose_joined_str(arg0)
|
|
303
|
+
if not ok or param_sql is None:
|
|
304
|
+
return (PatchStatus.UNSUPPORTED_CWE, None, None, limitations)
|
|
305
|
+
|
|
306
|
+
# Build tuple string
|
|
307
|
+
if len(params) == 1:
|
|
308
|
+
tuple_str = f"({ast.unparse(params[0])},)"
|
|
309
|
+
else:
|
|
310
|
+
tuple_str = f"({', '.join(ast.unparse(p) for p in params)})"
|
|
311
|
+
|
|
312
|
+
new_call = f'{func_expr}({format_sql_literal(param_sql)}, {tuple_str})'
|
|
313
|
+
|
|
314
|
+
# Line span replacement
|
|
315
|
+
start_l = parent_stmt.lineno - 1
|
|
316
|
+
end_l = getattr(parent_stmt, "end_lineno", parent_stmt.lineno)
|
|
317
|
+
orig_line = lines[start_l]
|
|
318
|
+
indent = orig_line[:len(orig_line) - len(orig_line.lstrip())]
|
|
319
|
+
line_ending = "\r\n" if orig_line.endswith("\r\n") else "\n"
|
|
320
|
+
replacement_line = f"{indent}{new_call}{line_ending}"
|
|
321
|
+
|
|
322
|
+
patched_lines = list(lines)
|
|
323
|
+
patched_lines[start_l:end_l] = [replacement_line]
|
|
324
|
+
patched_source = "".join(patched_lines)
|
|
325
|
+
return (PatchStatus.SUCCESS, patched_source, new_call, ())
|
|
326
|
+
|
|
327
|
+
elif isinstance(arg0, ast.BinOp) and isinstance(arg0.op, ast.Add):
|
|
328
|
+
ok, param_sql, params, limitations = self._decompose_binop(arg0)
|
|
329
|
+
if not ok or param_sql is None:
|
|
330
|
+
return (PatchStatus.UNSUPPORTED_CWE, None, None, limitations)
|
|
331
|
+
|
|
332
|
+
if len(params) == 1:
|
|
333
|
+
tuple_str = f"({ast.unparse(params[0])},)"
|
|
334
|
+
else:
|
|
335
|
+
tuple_str = f"({', '.join(ast.unparse(p) for p in params)})"
|
|
336
|
+
|
|
337
|
+
new_call = f'{func_expr}({format_sql_literal(param_sql)}, {tuple_str})'
|
|
338
|
+
start_l = parent_stmt.lineno - 1
|
|
339
|
+
end_l = getattr(parent_stmt, "end_lineno", parent_stmt.lineno)
|
|
340
|
+
orig_line = lines[start_l]
|
|
341
|
+
indent = orig_line[:len(orig_line) - len(orig_line.lstrip())]
|
|
342
|
+
line_ending = "\r\n" if orig_line.endswith("\r\n") else "\n"
|
|
343
|
+
replacement_line = f"{indent}{new_call}{line_ending}"
|
|
344
|
+
|
|
345
|
+
patched_lines = list(lines)
|
|
346
|
+
patched_lines[start_l:end_l] = [replacement_line]
|
|
347
|
+
patched_source = "".join(patched_lines)
|
|
348
|
+
return (PatchStatus.SUCCESS, patched_source, new_call, ())
|
|
349
|
+
|
|
350
|
+
elif isinstance(arg0, ast.Name):
|
|
351
|
+
var_name = arg0.id
|
|
352
|
+
if not parent_scope:
|
|
353
|
+
return (
|
|
354
|
+
PatchStatus.UNSUPPORTED_CWE,
|
|
355
|
+
None,
|
|
356
|
+
None,
|
|
357
|
+
(f"Cannot resolve scope for variable {var_name}",)
|
|
358
|
+
)
|
|
359
|
+
|
|
360
|
+
assign_stmt = self._find_preceding_assignment(parent_scope, var_name, parent_stmt)
|
|
361
|
+
if not assign_stmt:
|
|
362
|
+
return (
|
|
363
|
+
PatchStatus.UNSUPPORTED_CWE,
|
|
364
|
+
None,
|
|
365
|
+
None,
|
|
366
|
+
(f"Could not locate preceding assignment to {var_name}",)
|
|
367
|
+
)
|
|
368
|
+
|
|
369
|
+
if isinstance(assign_stmt.value, ast.JoinedStr):
|
|
370
|
+
ok, param_sql, params, limitations = self._decompose_joined_str(assign_stmt.value)
|
|
371
|
+
elif isinstance(assign_stmt.value, ast.BinOp) and isinstance(assign_stmt.value.op, ast.Add):
|
|
372
|
+
ok, param_sql, params, limitations = self._decompose_binop(assign_stmt.value)
|
|
373
|
+
else:
|
|
374
|
+
return (
|
|
375
|
+
PatchStatus.UNSUPPORTED_CWE,
|
|
376
|
+
None,
|
|
377
|
+
None,
|
|
378
|
+
(f"Unsupported assignment expression type for {var_name}",)
|
|
379
|
+
)
|
|
380
|
+
|
|
381
|
+
if not ok or param_sql is None:
|
|
382
|
+
return (PatchStatus.UNSUPPORTED_CWE, None, None, limitations)
|
|
383
|
+
|
|
384
|
+
if len(params) == 1:
|
|
385
|
+
tuple_str = f"({ast.unparse(params[0])},)"
|
|
386
|
+
else:
|
|
387
|
+
tuple_str = f"({', '.join(ast.unparse(p) for p in params)})"
|
|
388
|
+
|
|
389
|
+
targets_str = " = ".join(ast.unparse(t) for t in assign_stmt.targets)
|
|
390
|
+
new_assign = f'{targets_str} = {format_sql_literal(param_sql)}'
|
|
391
|
+
new_call = f'{func_expr}({var_name}, {tuple_str})'
|
|
392
|
+
|
|
393
|
+
# Replace both statements in descending line order
|
|
394
|
+
call_start = parent_stmt.lineno - 1
|
|
395
|
+
call_end = getattr(parent_stmt, "end_lineno", parent_stmt.lineno)
|
|
396
|
+
|
|
397
|
+
assign_start = assign_stmt.lineno - 1
|
|
398
|
+
assign_end = getattr(assign_stmt, "end_lineno", assign_stmt.lineno)
|
|
399
|
+
|
|
400
|
+
patched_lines = list(lines)
|
|
401
|
+
|
|
402
|
+
# Splicing execute call
|
|
403
|
+
call_orig = lines[call_start]
|
|
404
|
+
call_indent = call_orig[:len(call_orig) - len(call_orig.lstrip())]
|
|
405
|
+
call_ending = "\r\n" if call_orig.endswith("\r\n") else "\n"
|
|
406
|
+
call_repl = f"{call_indent}{new_call}{call_ending}"
|
|
407
|
+
patched_lines[call_start:call_end] = [call_repl]
|
|
408
|
+
|
|
409
|
+
# Splicing assign statement
|
|
410
|
+
assign_orig = lines[assign_start]
|
|
411
|
+
assign_indent = assign_orig[:len(assign_orig) - len(assign_orig.lstrip())]
|
|
412
|
+
assign_ending = "\r\n" if assign_orig.endswith("\r\n") else "\n"
|
|
413
|
+
assign_repl = f"{assign_indent}{new_assign}{assign_ending}"
|
|
414
|
+
patched_lines[assign_start:assign_end] = [assign_repl]
|
|
415
|
+
|
|
416
|
+
patched_source = "".join(patched_lines)
|
|
417
|
+
patched_snippet = f"{new_assign}\n{new_call}"
|
|
418
|
+
return (PatchStatus.SUCCESS, patched_source, patched_snippet, ())
|
|
419
|
+
|
|
420
|
+
return (
|
|
421
|
+
PatchStatus.UNSUPPORTED_CWE,
|
|
422
|
+
None,
|
|
423
|
+
None,
|
|
424
|
+
(f"Unsupported argument construct in .execute(): {type(arg0).__name__}",)
|
|
425
|
+
)
|