secguard-cli 1.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- secguard/__init__.py +0 -0
- secguard/ai_engine.py +1556 -0
- secguard/cli.py +875 -0
- secguard/config.py +172 -0
- secguard/dependency_scanner.py +513 -0
- secguard/patcher.py +707 -0
- secguard/reporter.py +276 -0
- secguard/scanner.py +5009 -0
- secguard/test.py +5 -0
- secguard_cli-1.1.0.dist-info/METADATA +106 -0
- secguard_cli-1.1.0.dist-info/RECORD +15 -0
- secguard_cli-1.1.0.dist-info/WHEEL +5 -0
- secguard_cli-1.1.0.dist-info/entry_points.txt +2 -0
- secguard_cli-1.1.0.dist-info/licenses/LICENSE +21 -0
- secguard_cli-1.1.0.dist-info/top_level.txt +1 -0
secguard/patcher.py
ADDED
|
@@ -0,0 +1,707 @@
|
|
|
1
|
+
import ast
|
|
2
|
+
import builtins
|
|
3
|
+
import difflib
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import re
|
|
6
|
+
import shutil
|
|
7
|
+
import textwrap
|
|
8
|
+
try:
|
|
9
|
+
from tree_sitter import Language, Parser
|
|
10
|
+
import tree_sitter_c
|
|
11
|
+
import tree_sitter_javascript
|
|
12
|
+
import tree_sitter_php
|
|
13
|
+
except ImportError:
|
|
14
|
+
Language = Parser = None
|
|
15
|
+
tree_sitter_c = tree_sitter_javascript = tree_sitter_php = None
|
|
16
|
+
|
|
17
|
+
try:
|
|
18
|
+
import tree_sitter_typescript
|
|
19
|
+
except ImportError:
|
|
20
|
+
tree_sitter_typescript = None
|
|
21
|
+
|
|
22
|
+
COMMON_IMPORTS = {
|
|
23
|
+
"os": "import os",
|
|
24
|
+
"ast": "import ast",
|
|
25
|
+
"json": "import json",
|
|
26
|
+
"socket": "import socket",
|
|
27
|
+
"ipaddress": "import ipaddress",
|
|
28
|
+
"operator": "import operator",
|
|
29
|
+
"subprocess": "import subprocess",
|
|
30
|
+
"hashlib": "import hashlib",
|
|
31
|
+
"secrets": "import secrets",
|
|
32
|
+
"urlparse": "from urllib.parse import urlparse",
|
|
33
|
+
"abort": "from flask import abort",
|
|
34
|
+
"send_from_directory": "from flask import send_from_directory",
|
|
35
|
+
"render_template_string": "from flask import render_template_string",
|
|
36
|
+
"secure_filename": "from werkzeug.utils import secure_filename",
|
|
37
|
+
"generate_password_hash": "from werkzeug.security import generate_password_hash",
|
|
38
|
+
"check_password_hash": "from werkzeug.security import check_password_hash",
|
|
39
|
+
"escape": "from markupsafe import escape",
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class _UndefinedNameVisitor(ast.NodeVisitor):
|
|
44
|
+
"""Find undefined names and missing imports with an AST visitor."""
|
|
45
|
+
|
|
46
|
+
def __init__(self):
|
|
47
|
+
self.defined: set[str] = set(dir(builtins))
|
|
48
|
+
self.loaded: set[str] = set()
|
|
49
|
+
|
|
50
|
+
def visit_Import(self, node: ast.Import):
|
|
51
|
+
for alias in node.names:
|
|
52
|
+
self.defined.add(alias.asname or alias.name.split(".")[0])
|
|
53
|
+
|
|
54
|
+
def visit_ImportFrom(self, node: ast.ImportFrom):
|
|
55
|
+
for alias in node.names:
|
|
56
|
+
self.defined.add(alias.asname or alias.name)
|
|
57
|
+
|
|
58
|
+
def visit_FunctionDef(self, node: ast.FunctionDef):
|
|
59
|
+
self.defined.add(node.name)
|
|
60
|
+
for arg in (
|
|
61
|
+
node.args.posonlyargs
|
|
62
|
+
+ node.args.args
|
|
63
|
+
+ node.args.kwonlyargs
|
|
64
|
+
+ ([node.args.vararg] if node.args.vararg else [])
|
|
65
|
+
+ ([node.args.kwarg] if node.args.kwarg else [])
|
|
66
|
+
):
|
|
67
|
+
self.defined.add(arg.arg)
|
|
68
|
+
self.generic_visit(node)
|
|
69
|
+
|
|
70
|
+
def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef):
|
|
71
|
+
self.visit_FunctionDef(node) # type: ignore[arg-type]
|
|
72
|
+
|
|
73
|
+
def visit_ClassDef(self, node: ast.ClassDef):
|
|
74
|
+
self.defined.add(node.name)
|
|
75
|
+
self.generic_visit(node)
|
|
76
|
+
|
|
77
|
+
def visit_ExceptHandler(self, node: ast.ExceptHandler):
|
|
78
|
+
if node.name:
|
|
79
|
+
self.defined.add(node.name)
|
|
80
|
+
self.generic_visit(node)
|
|
81
|
+
|
|
82
|
+
def visit_Name(self, node: ast.Name):
|
|
83
|
+
if isinstance(node.ctx, (ast.Store, ast.Param)):
|
|
84
|
+
self.defined.add(node.id)
|
|
85
|
+
elif isinstance(node.ctx, ast.Load):
|
|
86
|
+
self.loaded.add(node.id)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _find_undefined_names(tree: ast.AST) -> set[str]:
|
|
90
|
+
visitor = _UndefinedNameVisitor()
|
|
91
|
+
visitor.visit(tree)
|
|
92
|
+
return visitor.loaded - visitor.defined
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _inject_missing_imports(code: str, undefined: set[str]) -> str:
|
|
96
|
+
"""Add missing standard-library, Flask, and Werkzeug imports."""
|
|
97
|
+
imports_to_add = [COMMON_IMPORTS[name] for name in sorted(undefined) if name in COMMON_IMPORTS]
|
|
98
|
+
if not imports_to_add:
|
|
99
|
+
return code
|
|
100
|
+
|
|
101
|
+
lines = code.splitlines()
|
|
102
|
+
insert_idx = 0
|
|
103
|
+
|
|
104
|
+
# Skip shebang and encoding comments.
|
|
105
|
+
while insert_idx < len(lines) and lines[insert_idx].startswith("#"):
|
|
106
|
+
insert_idx += 1
|
|
107
|
+
|
|
108
|
+
# Insert imports after the module docstring, if present.
|
|
109
|
+
if insert_idx < len(lines) and lines[insert_idx].strip().startswith(('"""', "'''")):
|
|
110
|
+
quote = lines[insert_idx].strip()[:3]
|
|
111
|
+
if lines[insert_idx].strip().count(quote) >= 2 and len(lines[insert_idx].strip()) > 3:
|
|
112
|
+
insert_idx += 1
|
|
113
|
+
else:
|
|
114
|
+
insert_idx += 1
|
|
115
|
+
while insert_idx < len(lines) and quote not in lines[insert_idx]:
|
|
116
|
+
insert_idx += 1
|
|
117
|
+
if insert_idx < len(lines):
|
|
118
|
+
insert_idx += 1
|
|
119
|
+
|
|
120
|
+
existing_lines = {line.strip() for line in lines}
|
|
121
|
+
new_imports = [imp for imp in imports_to_add if imp not in existing_lines]
|
|
122
|
+
if not new_imports:
|
|
123
|
+
return code
|
|
124
|
+
|
|
125
|
+
updated_lines = lines[:insert_idx] + new_imports + lines[insert_idx:]
|
|
126
|
+
return "\n".join(updated_lines) + ("\n" if code.endswith("\n") else "")
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _reindent(code: str, indent: str) -> str:
|
|
130
|
+
"""Align generated code with the target line's indentation."""
|
|
131
|
+
dedented = textwrap.dedent(code).strip("\n")
|
|
132
|
+
return "\n".join(f"{indent}{line}" if line.strip() else "" for line in dedented.splitlines())
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _function_patch_name(fixed_code: str, suffix: str) -> str | None:
|
|
136
|
+
first_line = next(
|
|
137
|
+
(line.strip() for line in fixed_code.splitlines() if line.strip()),
|
|
138
|
+
"",
|
|
139
|
+
)
|
|
140
|
+
if suffix == ".py":
|
|
141
|
+
match = re.match(
|
|
142
|
+
r"^(?:async\s+)?def\s+([A-Za-z_]\w*)\s*\(",
|
|
143
|
+
first_line,
|
|
144
|
+
)
|
|
145
|
+
else:
|
|
146
|
+
match = re.match(
|
|
147
|
+
r"^(?:async\s+)?function\s*\*?\s*&?\s*([A-Za-z_$][\w$]*)\s*\(",
|
|
148
|
+
first_line,
|
|
149
|
+
re.IGNORECASE if suffix == ".php" else 0,
|
|
150
|
+
)
|
|
151
|
+
return match.group(1) if match else None
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _replace_enclosing_python_function(
|
|
155
|
+
original_content: str,
|
|
156
|
+
vulnerable_line: int,
|
|
157
|
+
fixed_code: str,
|
|
158
|
+
) -> str | None:
|
|
159
|
+
try:
|
|
160
|
+
original_tree = ast.parse(original_content)
|
|
161
|
+
patch_tree = ast.parse(textwrap.dedent(fixed_code))
|
|
162
|
+
except SyntaxError:
|
|
163
|
+
return None
|
|
164
|
+
|
|
165
|
+
original_functions = [
|
|
166
|
+
node for node in ast.walk(original_tree)
|
|
167
|
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
|
|
168
|
+
and node.lineno < vulnerable_line <= (node.end_lineno or node.lineno)
|
|
169
|
+
]
|
|
170
|
+
if not original_functions:
|
|
171
|
+
return None
|
|
172
|
+
original_function = min(
|
|
173
|
+
original_functions,
|
|
174
|
+
key=lambda node: (node.end_lineno or node.lineno) - node.lineno,
|
|
175
|
+
)
|
|
176
|
+
patch_function = next(
|
|
177
|
+
(
|
|
178
|
+
node for node in patch_tree.body
|
|
179
|
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
|
|
180
|
+
),
|
|
181
|
+
None,
|
|
182
|
+
)
|
|
183
|
+
if patch_function is None or patch_function.name != original_function.name:
|
|
184
|
+
return None
|
|
185
|
+
|
|
186
|
+
original_lines = original_content.splitlines()
|
|
187
|
+
patch_lines = textwrap.dedent(fixed_code).strip("\n").splitlines()
|
|
188
|
+
if not patch_lines:
|
|
189
|
+
return None
|
|
190
|
+
original_start = original_function.lineno
|
|
191
|
+
if (
|
|
192
|
+
patch_lines[0].lstrip().startswith("@")
|
|
193
|
+
and original_function.decorator_list
|
|
194
|
+
):
|
|
195
|
+
original_start = min(
|
|
196
|
+
decorator.lineno for decorator in original_function.decorator_list
|
|
197
|
+
)
|
|
198
|
+
original_end = original_function.end_lineno or original_function.lineno
|
|
199
|
+
indent_line = original_lines[original_function.lineno - 1]
|
|
200
|
+
indent = indent_line[: len(indent_line) - len(indent_line.lstrip())]
|
|
201
|
+
replacement = _reindent("\n".join(patch_lines), indent).splitlines()
|
|
202
|
+
updated_lines = (
|
|
203
|
+
original_lines[: original_start - 1]
|
|
204
|
+
+ replacement
|
|
205
|
+
+ original_lines[original_end:]
|
|
206
|
+
)
|
|
207
|
+
return "\n".join(updated_lines) + (
|
|
208
|
+
"\n" if original_content.endswith("\n") else ""
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _tree_sitter_parser(suffix: str):
|
|
213
|
+
if Parser is None:
|
|
214
|
+
return None
|
|
215
|
+
if suffix in {".js", ".jsx", ".mjs", ".cjs"}:
|
|
216
|
+
grammar = tree_sitter_javascript
|
|
217
|
+
factory = grammar.language
|
|
218
|
+
elif suffix == ".ts":
|
|
219
|
+
if tree_sitter_typescript is None:
|
|
220
|
+
return None
|
|
221
|
+
grammar = tree_sitter_typescript
|
|
222
|
+
factory = grammar.language_typescript
|
|
223
|
+
elif suffix == ".php":
|
|
224
|
+
grammar = tree_sitter_php
|
|
225
|
+
factory = grammar.language_php
|
|
226
|
+
else:
|
|
227
|
+
return None
|
|
228
|
+
try:
|
|
229
|
+
language = Language(factory())
|
|
230
|
+
try:
|
|
231
|
+
return Parser(language)
|
|
232
|
+
except TypeError:
|
|
233
|
+
parser = Parser()
|
|
234
|
+
parser.language = language
|
|
235
|
+
return parser
|
|
236
|
+
except (AttributeError, TypeError, ValueError):
|
|
237
|
+
return None
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _replace_enclosing_tree_sitter_function(
|
|
241
|
+
original_content: str,
|
|
242
|
+
vulnerable_line: int,
|
|
243
|
+
fixed_code: str,
|
|
244
|
+
suffix: str,
|
|
245
|
+
) -> str | None:
|
|
246
|
+
parser = _tree_sitter_parser(suffix)
|
|
247
|
+
if parser is None:
|
|
248
|
+
return None
|
|
249
|
+
original_bytes = original_content.encode("utf-8")
|
|
250
|
+
patch_source = textwrap.dedent(fixed_code).strip("\n")
|
|
251
|
+
if suffix == ".php" and not patch_source.lstrip().startswith("<?php"):
|
|
252
|
+
patch_source = "<?php\n" + patch_source
|
|
253
|
+
patch_bytes = patch_source.encode("utf-8")
|
|
254
|
+
original_tree = parser.parse(original_bytes)
|
|
255
|
+
patch_tree = parser.parse(patch_bytes)
|
|
256
|
+
if original_tree.root_node.has_error or patch_tree.root_node.has_error:
|
|
257
|
+
return None
|
|
258
|
+
|
|
259
|
+
function_type = "function_definition" if suffix == ".php" else "function_declaration"
|
|
260
|
+
|
|
261
|
+
def named_functions(root, source_bytes):
|
|
262
|
+
pending = [root]
|
|
263
|
+
while pending:
|
|
264
|
+
node = pending.pop()
|
|
265
|
+
if node.type == function_type:
|
|
266
|
+
name_node = node.child_by_field_name("name")
|
|
267
|
+
if name_node is not None:
|
|
268
|
+
name = source_bytes[name_node.start_byte:name_node.end_byte].decode(
|
|
269
|
+
"utf-8",
|
|
270
|
+
errors="ignore",
|
|
271
|
+
)
|
|
272
|
+
yield node, name
|
|
273
|
+
pending.extend(reversed(node.children))
|
|
274
|
+
|
|
275
|
+
patch_name = _function_patch_name(fixed_code, suffix)
|
|
276
|
+
if patch_name is None:
|
|
277
|
+
return None
|
|
278
|
+
original_functions = [
|
|
279
|
+
(node, name)
|
|
280
|
+
for node, name in named_functions(original_tree.root_node, original_bytes)
|
|
281
|
+
if name == patch_name
|
|
282
|
+
and node.start_point.row + 1 < vulnerable_line <= node.end_point.row + 1
|
|
283
|
+
]
|
|
284
|
+
if not original_functions:
|
|
285
|
+
return None
|
|
286
|
+
original_function = min(
|
|
287
|
+
original_functions,
|
|
288
|
+
key=lambda pair: pair[0].end_point.row - pair[0].start_point.row,
|
|
289
|
+
)[0]
|
|
290
|
+
patch_function = next(
|
|
291
|
+
(
|
|
292
|
+
node for node, name in named_functions(patch_tree.root_node, patch_bytes)
|
|
293
|
+
if name == patch_name
|
|
294
|
+
),
|
|
295
|
+
None,
|
|
296
|
+
)
|
|
297
|
+
if patch_function is None:
|
|
298
|
+
return None
|
|
299
|
+
function_source = patch_bytes[
|
|
300
|
+
patch_function.start_byte:patch_function.end_byte
|
|
301
|
+
].decode("utf-8", errors="ignore")
|
|
302
|
+
|
|
303
|
+
line_start = original_bytes.rfind(b"\n", 0, original_function.start_byte) + 1
|
|
304
|
+
line_prefix = original_bytes[line_start:original_function.start_byte]
|
|
305
|
+
indent_match = re.match(rb"[ \t]*", line_prefix)
|
|
306
|
+
indent = indent_match.group(0).decode("utf-8") if indent_match else ""
|
|
307
|
+
replacement_lines = textwrap.dedent(function_source).strip("\n").splitlines()
|
|
308
|
+
if not replacement_lines:
|
|
309
|
+
return None
|
|
310
|
+
replacement = replacement_lines[0] + "".join(
|
|
311
|
+
"\n" + (indent + line if line.strip() else "")
|
|
312
|
+
for line in replacement_lines[1:]
|
|
313
|
+
)
|
|
314
|
+
updated_bytes = (
|
|
315
|
+
original_bytes[:original_function.start_byte]
|
|
316
|
+
+ replacement.encode("utf-8")
|
|
317
|
+
+ original_bytes[original_function.end_byte:]
|
|
318
|
+
)
|
|
319
|
+
return updated_bytes.decode("utf-8", errors="ignore")
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def _replace_vulnerable_block(
|
|
323
|
+
original_content: str,
|
|
324
|
+
vulnerable_code: str,
|
|
325
|
+
fixed_code: str,
|
|
326
|
+
suffix: str = "",
|
|
327
|
+
line_hint: int | None = None,
|
|
328
|
+
) -> tuple[str | None, str]:
|
|
329
|
+
if vulnerable_code in original_content:
|
|
330
|
+
offsets = []
|
|
331
|
+
offset = 0
|
|
332
|
+
while True:
|
|
333
|
+
offset = original_content.find(vulnerable_code, offset)
|
|
334
|
+
if offset < 0:
|
|
335
|
+
break
|
|
336
|
+
offsets.append(offset)
|
|
337
|
+
offset += len(vulnerable_code)
|
|
338
|
+
match_offset = (
|
|
339
|
+
min(
|
|
340
|
+
offsets,
|
|
341
|
+
key=lambda candidate: abs(
|
|
342
|
+
original_content.count("\n", 0, candidate) + 1 - line_hint
|
|
343
|
+
),
|
|
344
|
+
)
|
|
345
|
+
if line_hint and len(offsets) > 1
|
|
346
|
+
else offsets[0]
|
|
347
|
+
)
|
|
348
|
+
vulnerable_line = original_content.count("\n", 0, match_offset) + 1
|
|
349
|
+
if _function_patch_name(fixed_code, suffix):
|
|
350
|
+
function_content = (
|
|
351
|
+
_replace_enclosing_python_function(
|
|
352
|
+
original_content,
|
|
353
|
+
vulnerable_line,
|
|
354
|
+
fixed_code,
|
|
355
|
+
)
|
|
356
|
+
if suffix == ".py"
|
|
357
|
+
else _replace_enclosing_tree_sitter_function(
|
|
358
|
+
original_content,
|
|
359
|
+
vulnerable_line,
|
|
360
|
+
fixed_code,
|
|
361
|
+
suffix,
|
|
362
|
+
)
|
|
363
|
+
)
|
|
364
|
+
if function_content is not None:
|
|
365
|
+
return function_content, ""
|
|
366
|
+
return original_content.replace(vulnerable_code, fixed_code, 1), ""
|
|
367
|
+
else:
|
|
368
|
+
vuln_lines = [line.strip() for line in vulnerable_code.strip().splitlines() if line.strip()]
|
|
369
|
+
if not vuln_lines:
|
|
370
|
+
return None, "No valid line to match."
|
|
371
|
+
|
|
372
|
+
file_lines = original_content.splitlines()
|
|
373
|
+
match_start = -1
|
|
374
|
+
match_end = -1
|
|
375
|
+
|
|
376
|
+
line_order = list(range(len(file_lines)))
|
|
377
|
+
if line_hint:
|
|
378
|
+
line_order.sort(key=lambda i: abs(i + 1 - line_hint))
|
|
379
|
+
for i in line_order:
|
|
380
|
+
if file_lines[i].strip() != vuln_lines[0]:
|
|
381
|
+
continue
|
|
382
|
+
|
|
383
|
+
v_idx = 0
|
|
384
|
+
f_idx = i
|
|
385
|
+
while f_idx < len(file_lines) and v_idx < len(vuln_lines):
|
|
386
|
+
if not file_lines[f_idx].strip():
|
|
387
|
+
f_idx += 1
|
|
388
|
+
continue
|
|
389
|
+
if file_lines[f_idx].strip() == vuln_lines[v_idx]:
|
|
390
|
+
v_idx += 1
|
|
391
|
+
f_idx += 1
|
|
392
|
+
else:
|
|
393
|
+
break
|
|
394
|
+
|
|
395
|
+
if v_idx == len(vuln_lines):
|
|
396
|
+
match_start = i
|
|
397
|
+
match_end = f_idx
|
|
398
|
+
break
|
|
399
|
+
|
|
400
|
+
if match_start == -1:
|
|
401
|
+
return None, "Automatic patch did not match; apply the suggested code manually."
|
|
402
|
+
|
|
403
|
+
vulnerable_line = match_start + 1
|
|
404
|
+
if _function_patch_name(fixed_code, suffix):
|
|
405
|
+
function_content = (
|
|
406
|
+
_replace_enclosing_python_function(
|
|
407
|
+
original_content,
|
|
408
|
+
vulnerable_line,
|
|
409
|
+
fixed_code,
|
|
410
|
+
)
|
|
411
|
+
if suffix == ".py"
|
|
412
|
+
else _replace_enclosing_tree_sitter_function(
|
|
413
|
+
original_content,
|
|
414
|
+
vulnerable_line,
|
|
415
|
+
fixed_code,
|
|
416
|
+
suffix,
|
|
417
|
+
)
|
|
418
|
+
)
|
|
419
|
+
if function_content is not None:
|
|
420
|
+
return function_content, ""
|
|
421
|
+
|
|
422
|
+
first_line = file_lines[match_start]
|
|
423
|
+
base_indent = first_line[: len(first_line) - len(first_line.lstrip())]
|
|
424
|
+
indented_fix = _reindent(fixed_code, base_indent)
|
|
425
|
+
|
|
426
|
+
new_lines = file_lines[:match_start] + indented_fix.splitlines() + file_lines[match_end:]
|
|
427
|
+
updated_content = "\n".join(new_lines) + ("\n" if original_content.endswith("\n") else "")
|
|
428
|
+
return updated_content, ""
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def preview_patch(
|
|
432
|
+
file_path: str,
|
|
433
|
+
vulnerable_code: str,
|
|
434
|
+
fixed_code: str,
|
|
435
|
+
) -> tuple[bool, str]:
|
|
436
|
+
"""Return a unified diff without writing or creating a backup."""
|
|
437
|
+
target = Path(file_path)
|
|
438
|
+
if not target.is_file() or not vulnerable_code.strip():
|
|
439
|
+
return False, "Target file or vulnerable code block is empty."
|
|
440
|
+
try:
|
|
441
|
+
original_content = target.read_text(encoding="utf-8")
|
|
442
|
+
except (OSError, UnicodeError) as error:
|
|
443
|
+
return False, f"Could not read file: {error}"
|
|
444
|
+
updated_content, error = _replace_vulnerable_block(
|
|
445
|
+
original_content,
|
|
446
|
+
vulnerable_code,
|
|
447
|
+
fixed_code,
|
|
448
|
+
target.suffix.lower(),
|
|
449
|
+
)
|
|
450
|
+
if updated_content is None:
|
|
451
|
+
return False, error
|
|
452
|
+
diff = difflib.unified_diff(
|
|
453
|
+
original_content.splitlines(),
|
|
454
|
+
updated_content.splitlines(),
|
|
455
|
+
fromfile=f"a/{target}",
|
|
456
|
+
tofile=f"b/{target}",
|
|
457
|
+
lineterm="",
|
|
458
|
+
)
|
|
459
|
+
return True, "\n".join(diff)
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
def _tree_sitter_syntax_error(
|
|
463
|
+
source: str,
|
|
464
|
+
suffix: str,
|
|
465
|
+
) -> str | None:
|
|
466
|
+
if Parser is None:
|
|
467
|
+
return "Tree-sitter is not installed; language syntax could not be validated."
|
|
468
|
+
if suffix == ".ts":
|
|
469
|
+
if tree_sitter_typescript is None:
|
|
470
|
+
return "Tree-sitter TypeScript grammar is not installed."
|
|
471
|
+
grammar = tree_sitter_typescript
|
|
472
|
+
factory = grammar.language_typescript
|
|
473
|
+
elif suffix in {".js", ".jsx", ".mjs", ".cjs"}:
|
|
474
|
+
grammar = tree_sitter_javascript
|
|
475
|
+
factory = grammar.language
|
|
476
|
+
elif suffix == ".php":
|
|
477
|
+
grammar = tree_sitter_php
|
|
478
|
+
factory = grammar.language_php
|
|
479
|
+
elif suffix in {".c", ".h"}:
|
|
480
|
+
grammar = tree_sitter_c
|
|
481
|
+
factory = grammar.language
|
|
482
|
+
else:
|
|
483
|
+
return None
|
|
484
|
+
|
|
485
|
+
try:
|
|
486
|
+
language = Language(factory())
|
|
487
|
+
try:
|
|
488
|
+
parser = Parser(language)
|
|
489
|
+
except TypeError:
|
|
490
|
+
parser = Parser()
|
|
491
|
+
parser.language = language
|
|
492
|
+
tree = parser.parse(source.encode("utf-8"))
|
|
493
|
+
except (AttributeError, TypeError, ValueError) as error:
|
|
494
|
+
return f"Could not initialize Tree-sitter parser: {error}"
|
|
495
|
+
if tree.root_node.has_error:
|
|
496
|
+
return "Tree-sitter syntax error"
|
|
497
|
+
return None
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
def _validate_updated_content(
|
|
501
|
+
original_content: str,
|
|
502
|
+
updated_content: str,
|
|
503
|
+
suffix: str,
|
|
504
|
+
) -> tuple[str | None, str | None]:
|
|
505
|
+
if suffix == ".py":
|
|
506
|
+
try:
|
|
507
|
+
original_undefined = _find_undefined_names(ast.parse(original_content))
|
|
508
|
+
except (SyntaxError, ValueError, RecursionError):
|
|
509
|
+
original_undefined = set()
|
|
510
|
+
try:
|
|
511
|
+
tree = ast.parse(updated_content)
|
|
512
|
+
except SyntaxError as error:
|
|
513
|
+
return None, f"Python SyntaxError: {error.msg}"
|
|
514
|
+
undefined = _find_undefined_names(tree)
|
|
515
|
+
if undefined:
|
|
516
|
+
updated_content = _inject_missing_imports(
|
|
517
|
+
updated_content,
|
|
518
|
+
undefined,
|
|
519
|
+
)
|
|
520
|
+
try:
|
|
521
|
+
tree = ast.parse(updated_content)
|
|
522
|
+
except SyntaxError as error:
|
|
523
|
+
return None, f"SyntaxError after adding imports: {error.msg}"
|
|
524
|
+
newly_undefined = _find_undefined_names(tree) - original_undefined
|
|
525
|
+
if newly_undefined:
|
|
526
|
+
missing = ", ".join(sorted(newly_undefined))
|
|
527
|
+
return None, f"New undefined names or missing imports: {missing}"
|
|
528
|
+
return updated_content, None
|
|
529
|
+
syntax_error = _tree_sitter_syntax_error(updated_content, suffix)
|
|
530
|
+
if syntax_error:
|
|
531
|
+
return None, syntax_error
|
|
532
|
+
return updated_content, None
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
def _build_patched_content(
|
|
536
|
+
original_content: str,
|
|
537
|
+
patches: list[dict],
|
|
538
|
+
suffix: str,
|
|
539
|
+
) -> tuple[str, set[int], dict[int, str]]:
|
|
540
|
+
content = original_content
|
|
541
|
+
applied: set[int] = set()
|
|
542
|
+
errors: dict[int, str] = {}
|
|
543
|
+
ordered = sorted(
|
|
544
|
+
enumerate(patches),
|
|
545
|
+
key=lambda pair: int(pair[1].get("line", 0) or 0),
|
|
546
|
+
reverse=True,
|
|
547
|
+
)
|
|
548
|
+
for index, patch in ordered:
|
|
549
|
+
vulnerable = patch.get("vulnerable_code", "")
|
|
550
|
+
fixed = patch.get("fixed_code", "")
|
|
551
|
+
if not isinstance(vulnerable, str) or not isinstance(fixed, str):
|
|
552
|
+
errors[index] = "Patch code must be text."
|
|
553
|
+
continue
|
|
554
|
+
updated, error = _replace_vulnerable_block(
|
|
555
|
+
content,
|
|
556
|
+
vulnerable,
|
|
557
|
+
fixed,
|
|
558
|
+
suffix,
|
|
559
|
+
int(patch.get("line", 0) or 0) or None,
|
|
560
|
+
)
|
|
561
|
+
if updated is None:
|
|
562
|
+
errors[index] = error
|
|
563
|
+
continue
|
|
564
|
+
content = updated
|
|
565
|
+
applied.add(index)
|
|
566
|
+
return content, applied, errors
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
def preview_patches(
|
|
570
|
+
file_path: str,
|
|
571
|
+
patches: list[dict],
|
|
572
|
+
validate: bool = True,
|
|
573
|
+
) -> tuple[set[int], str]:
|
|
574
|
+
"""Build and syntax-check a set of file patches without writing them."""
|
|
575
|
+
target = Path(file_path)
|
|
576
|
+
if not target.is_file() or not patches:
|
|
577
|
+
return set(), "Target file or patch list is empty."
|
|
578
|
+
try:
|
|
579
|
+
original = target.read_text(encoding="utf-8")
|
|
580
|
+
except (OSError, UnicodeError) as error:
|
|
581
|
+
return set(), f"Could not read file: {error}"
|
|
582
|
+
updated, applied, errors = _build_patched_content(
|
|
583
|
+
original,
|
|
584
|
+
patches,
|
|
585
|
+
target.suffix.lower(),
|
|
586
|
+
)
|
|
587
|
+
if not applied:
|
|
588
|
+
return set(), "; ".join(errors.values()) or "No applicable patch was found."
|
|
589
|
+
if validate:
|
|
590
|
+
updated, syntax_error = _validate_updated_content(
|
|
591
|
+
original,
|
|
592
|
+
updated,
|
|
593
|
+
target.suffix.lower(),
|
|
594
|
+
)
|
|
595
|
+
if syntax_error:
|
|
596
|
+
return set(), f"File could not be validated after patching ({syntax_error})."
|
|
597
|
+
diff = difflib.unified_diff(
|
|
598
|
+
original.splitlines(),
|
|
599
|
+
updated.splitlines(),
|
|
600
|
+
fromfile=f"a/{target}",
|
|
601
|
+
tofile=f"b/{target}",
|
|
602
|
+
lineterm="",
|
|
603
|
+
)
|
|
604
|
+
return applied, "\n".join(diff)
|
|
605
|
+
|
|
606
|
+
|
|
607
|
+
def apply_patches(
|
|
608
|
+
file_path: str,
|
|
609
|
+
patches: list[dict],
|
|
610
|
+
backup: bool = True,
|
|
611
|
+
) -> tuple[set[int], str]:
|
|
612
|
+
"""Apply a file's patches bottom-to-top with one write and one normal-path validation."""
|
|
613
|
+
target = Path(file_path)
|
|
614
|
+
if not target.is_file() or not patches:
|
|
615
|
+
return set(), "Target file or patch list is empty."
|
|
616
|
+
try:
|
|
617
|
+
original = target.read_text(encoding="utf-8")
|
|
618
|
+
except (OSError, UnicodeError) as error:
|
|
619
|
+
return set(), f"Could not read file: {error}"
|
|
620
|
+
|
|
621
|
+
updated, applied, errors = _build_patched_content(
|
|
622
|
+
original,
|
|
623
|
+
patches,
|
|
624
|
+
target.suffix.lower(),
|
|
625
|
+
)
|
|
626
|
+
if not applied:
|
|
627
|
+
return set(), "; ".join(errors.values()) or "No applicable patch was found."
|
|
628
|
+
|
|
629
|
+
updated, syntax_error = _validate_updated_content(
|
|
630
|
+
original,
|
|
631
|
+
updated,
|
|
632
|
+
target.suffix.lower(),
|
|
633
|
+
)
|
|
634
|
+
if syntax_error:
|
|
635
|
+
accepted: list[int] = []
|
|
636
|
+
for index, _ in sorted(
|
|
637
|
+
enumerate(patches),
|
|
638
|
+
key=lambda pair: int(pair[1].get("line", 0) or 0),
|
|
639
|
+
reverse=True,
|
|
640
|
+
):
|
|
641
|
+
candidate_indexes = {*accepted, index}
|
|
642
|
+
candidate_patches = [
|
|
643
|
+
patch for patch_index, patch in enumerate(patches)
|
|
644
|
+
if patch_index in candidate_indexes
|
|
645
|
+
]
|
|
646
|
+
candidate, candidate_applied, candidate_errors = _build_patched_content(
|
|
647
|
+
original,
|
|
648
|
+
candidate_patches,
|
|
649
|
+
target.suffix.lower(),
|
|
650
|
+
)
|
|
651
|
+
if len(candidate_applied) != len(candidate_indexes):
|
|
652
|
+
errors[index] = "Patch did not match when combined with the other changes."
|
|
653
|
+
continue
|
|
654
|
+
candidate, candidate_error = _validate_updated_content(
|
|
655
|
+
original,
|
|
656
|
+
candidate,
|
|
657
|
+
target.suffix.lower(),
|
|
658
|
+
)
|
|
659
|
+
if candidate_error is None:
|
|
660
|
+
accepted = list(candidate_indexes)
|
|
661
|
+
updated = candidate
|
|
662
|
+
else:
|
|
663
|
+
errors[index] = f"Patch failed syntax validation: {candidate_error}"
|
|
664
|
+
if not accepted:
|
|
665
|
+
return set(), f"File unchanged; patch(es) failed syntax validation ({syntax_error})."
|
|
666
|
+
applied = set(accepted)
|
|
667
|
+
|
|
668
|
+
if backup:
|
|
669
|
+
backup_path = target.with_suffix(target.suffix + ".bak")
|
|
670
|
+
if not backup_path.exists():
|
|
671
|
+
shutil.copy2(target, backup_path)
|
|
672
|
+
try:
|
|
673
|
+
target.write_text(updated, encoding="utf-8")
|
|
674
|
+
except OSError as error:
|
|
675
|
+
return set(), f"Could not write patch to file: {error}"
|
|
676
|
+
|
|
677
|
+
rejected = len(patches) - len(applied)
|
|
678
|
+
message = "Fixed!"
|
|
679
|
+
if backup:
|
|
680
|
+
message += f" (Backup: {target.name}.bak)"
|
|
681
|
+
if rejected:
|
|
682
|
+
message += f" {rejected} patch(es) skipped due to validation or matching errors."
|
|
683
|
+
details = "; ".join(errors.values())
|
|
684
|
+
if details:
|
|
685
|
+
message += f" Details: {details}"
|
|
686
|
+
return applied, message
|
|
687
|
+
|
|
688
|
+
|
|
689
|
+
def apply_patch(
|
|
690
|
+
file_path: str,
|
|
691
|
+
vulnerable_code: str,
|
|
692
|
+
fixed_code: str,
|
|
693
|
+
backup: bool = True,
|
|
694
|
+
) -> tuple[bool, str]:
|
|
695
|
+
"""Apply a patch, validate syntax, and reject invalid changes before writing."""
|
|
696
|
+
if not vulnerable_code.strip():
|
|
697
|
+
return False, "Target file or vulnerable code block is empty."
|
|
698
|
+
applied, message = apply_patches(
|
|
699
|
+
file_path,
|
|
700
|
+
[{
|
|
701
|
+
"line": 0,
|
|
702
|
+
"vulnerable_code": vulnerable_code,
|
|
703
|
+
"fixed_code": fixed_code,
|
|
704
|
+
}],
|
|
705
|
+
backup=backup,
|
|
706
|
+
)
|
|
707
|
+
return 0 in applied, message
|