Upload _script_for_eval.py
Browse files- _script_for_eval.py +164 -81
_script_for_eval.py
CHANGED
@@ -3,7 +3,13 @@ import os
|
|
3 |
import random
|
4 |
import pickle
|
5 |
import time
|
|
|
|
|
|
|
|
|
6 |
from openai import OpenAI
|
|
|
|
|
7 |
from tqdm import tqdm
|
8 |
from functools import partial
|
9 |
import multiprocessing
|
@@ -24,6 +30,13 @@ def save_cache(cache):
|
|
24 |
with open('cache.pkl', 'wb') as f:
|
25 |
pickle.dump(cache, f)
|
26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
def fetch_dataset_examples(prompt, num_examples=3, use_similarity=True):
|
28 |
dataset = load_dataset("patched-codes/synth-vuln-fixes", split="train")
|
29 |
|
@@ -52,7 +65,21 @@ def fetch_dataset_examples(prompt, num_examples=3, use_similarity=True):
|
|
52 |
|
53 |
return few_shot_messages
|
54 |
|
55 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
56 |
system_message = (
|
57 |
"You are an AI assistant specialized in fixing code vulnerabilities. "
|
58 |
"Your task is to provide corrected code that addresses the reported security issue. "
|
@@ -69,22 +96,31 @@ def get_fixed_code_fine_tuned(prompt, few_shot_messages):
|
|
69 |
messages.extend(few_shot_messages)
|
70 |
messages.append({"role": "user", "content": prompt})
|
71 |
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
84 |
|
85 |
-
def process_file(test_case, cache):
|
86 |
file_name = test_case["file_name"]
|
87 |
-
input_file = "staticeval
|
88 |
|
89 |
if input_file in cache:
|
90 |
tqdm.write(f"Skipping {input_file} (cached)")
|
@@ -95,99 +131,146 @@ def process_file(test_case, cache):
|
|
95 |
output_file = input_file + "_fixed.py"
|
96 |
tmp_file = input_file + ".output.json"
|
97 |
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
if os.path.exists(tmp_file):
|
102 |
-
os.remove(tmp_file)
|
103 |
-
|
104 |
-
tqdm.write("Scanning file " + input_file + "...")
|
105 |
-
scan_command_input = f"semgrep --config p/python {input_file} --output {tmp_file} --json > /dev/null 2>&1"
|
106 |
-
os.system(scan_command_input)
|
107 |
-
|
108 |
-
with open(tmp_file, 'r') as jf:
|
109 |
-
data = json.load(jf)
|
110 |
-
|
111 |
-
if len(data["errors"]) == 0:
|
112 |
-
if len(data["results"]) == 0:
|
113 |
-
tqdm.write(input_file + " has no vulnerabilities")
|
114 |
-
result = False
|
115 |
-
else:
|
116 |
-
tqdm.write("Vulnerability found in " + input_file + "...")
|
117 |
-
cwe = data["results"][0]["extra"]["metadata"]["cwe"][0]
|
118 |
-
lines = data["results"][0]["extra"]["lines"]
|
119 |
-
message = data["results"][0]["extra"]["message"]
|
120 |
-
|
121 |
-
prompt = f"""Vulnerability Report:
|
122 |
-
- Type: {cwe}
|
123 |
-
- Location: {lines}
|
124 |
-
- Description: {message}
|
125 |
|
126 |
-
|
127 |
-
|
128 |
-
{file_text}
|
129 |
-
```
|
130 |
|
131 |
-
|
132 |
-
|
133 |
-
few_shot_messages = fetch_dataset_examples(prompt, 3, True)
|
134 |
-
response = get_fixed_code_fine_tuned(prompt, [])
|
135 |
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
if len(
|
|
|
149 |
result = False
|
150 |
else:
|
151 |
-
|
152 |
-
|
|
|
|
|
153 |
|
154 |
-
|
155 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
156 |
|
157 |
-
|
158 |
-
|
159 |
|
160 |
-
if
|
161 |
-
|
162 |
-
|
|
|
163 |
else:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
164 |
result = False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
165 |
|
166 |
-
|
167 |
-
|
168 |
|
169 |
-
|
170 |
-
|
171 |
-
|
|
|
|
|
|
|
172 |
|
173 |
-
def process_test_case(test_case, cache):
|
174 |
-
return process_file(test_case, cache)
|
175 |
|
176 |
def main():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
177 |
dataset = load_dataset("patched-codes/static-analysis-eval", split="train")
|
178 |
data = [{"file_name": item["file_name"], "source": item["source"], "cwe": item["cwe"]} for item in dataset]
|
179 |
|
180 |
cache = load_cache()
|
181 |
total_tests = len(data)
|
182 |
|
183 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
184 |
|
185 |
with multiprocessing.Pool() as pool:
|
186 |
results = list(tqdm(pool.imap_unordered(process_func, data), total=total_tests))
|
187 |
|
188 |
passing_tests = sum(results)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
189 |
|
190 |
-
print(f"Results for StaticAnalysisEval: {
|
|
|
191 |
|
192 |
if __name__ == '__main__':
|
193 |
main()
|
|
|
3 |
import random
|
4 |
import pickle
|
5 |
import time
|
6 |
+
import datetime
|
7 |
+
import subprocess
|
8 |
+
import argparse
|
9 |
+
import re
|
10 |
from openai import OpenAI
|
11 |
+
from openai.types.chat import ChatCompletion
|
12 |
+
from openai.types import APIError, APIConnectionError, APIResponseValidationError, APIStatusError
|
13 |
from tqdm import tqdm
|
14 |
from functools import partial
|
15 |
import multiprocessing
|
|
|
30 |
with open('cache.pkl', 'wb') as f:
|
31 |
pickle.dump(cache, f)
|
32 |
|
33 |
+
def has_all_comments(text):
|
34 |
+
lines=text.split('\n')
|
35 |
+
for line in lines:
|
36 |
+
if line != "" and not line.startswith("#"):
|
37 |
+
return False
|
38 |
+
return True
|
39 |
+
|
40 |
def fetch_dataset_examples(prompt, num_examples=3, use_similarity=True):
|
41 |
dataset = load_dataset("patched-codes/synth-vuln-fixes", split="train")
|
42 |
|
|
|
65 |
|
66 |
return few_shot_messages
|
67 |
|
68 |
+
def sanitize_filename(name):
|
69 |
+
# Replace ':' with '_', and any other non-alphanumeric characters (except '-' and '_') with '*'
|
70 |
+
sanitized = re.sub(r':', '_', name)
|
71 |
+
sanitized = re.sub(r'[^a-zA-Z0-9\-_]', '*', sanitized)
|
72 |
+
return sanitized
|
73 |
+
|
74 |
+
def get_semgrep_version():
|
75 |
+
try:
|
76 |
+
result = subprocess.run(["semgrep", "--version"], capture_output=True, text=True)
|
77 |
+
version = result.stdout.strip().split()[-1]
|
78 |
+
return version
|
79 |
+
except Exception:
|
80 |
+
return "unknown"
|
81 |
+
|
82 |
+
def get_fixed_code_fine_tuned(prompt, few_shot_messages, model_name):
|
83 |
system_message = (
|
84 |
"You are an AI assistant specialized in fixing code vulnerabilities. "
|
85 |
"Your task is to provide corrected code that addresses the reported security issue. "
|
|
|
96 |
messages.extend(few_shot_messages)
|
97 |
messages.append({"role": "user", "content": prompt})
|
98 |
|
99 |
+
max_retries = 3
|
100 |
+
for attempt in range(max_retries):
|
101 |
+
try:
|
102 |
+
response = client.chat.completions.create(
|
103 |
+
model=model_name,
|
104 |
+
messages=messages,
|
105 |
+
max_tokens=512,
|
106 |
+
temperature=0.2,
|
107 |
+
top_p=0.95
|
108 |
+
)
|
109 |
+
if isinstance(response, ChatCompletion):
|
110 |
+
return response.choices[0].message.content
|
111 |
+
else:
|
112 |
+
raise ValueError("Unexpected response type from OpenAI API")
|
113 |
+
except (APIError, APIConnectionError, APIResponseValidationError) as e:
|
114 |
+
if attempt < max_retries - 1:
|
115 |
+
time.sleep(2 ** attempt) # Exponential backoff
|
116 |
+
else:
|
117 |
+
raise Exception(f"API call failed after {max_retries} attempts: {str(e)}")
|
118 |
+
except APIStatusError as e:
|
119 |
+
raise Exception(f"API call failed with status {e.status_code}: {str(e)}")
|
120 |
|
121 |
+
def process_file(test_case, cache, fixed_files, model_name):
|
122 |
file_name = test_case["file_name"]
|
123 |
+
input_file = os.path.join("staticeval", file_name)
|
124 |
|
125 |
if input_file in cache:
|
126 |
tqdm.write(f"Skipping {input_file} (cached)")
|
|
|
131 |
output_file = input_file + "_fixed.py"
|
132 |
tmp_file = input_file + ".output.json"
|
133 |
|
134 |
+
try:
|
135 |
+
os.makedirs(os.path.dirname(input_file), exist_ok=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
136 |
|
137 |
+
with open(input_file, "w") as file_object:
|
138 |
+
file_object.write(file_text)
|
|
|
|
|
139 |
|
140 |
+
if os.path.exists(tmp_file):
|
141 |
+
os.remove(tmp_file)
|
|
|
|
|
142 |
|
143 |
+
tqdm.write("Scanning file " + input_file + "...")
|
144 |
+
scan_command_input = f"semgrep --config p/python {input_file} --output {tmp_file} --json > /dev/null 2>&1"
|
145 |
+
os.system(scan_command_input)
|
146 |
+
|
147 |
+
if not os.path.exists(tmp_file):
|
148 |
+
tqdm.write(f"Semgrep failed to create output file for {input_file}")
|
149 |
+
return False
|
150 |
+
|
151 |
+
with open(tmp_file, 'r') as jf:
|
152 |
+
data = json.load(jf)
|
153 |
+
|
154 |
+
if len(data.get("errors", [])) == 0:
|
155 |
+
if len(data.get("results", [])) == 0:
|
156 |
+
tqdm.write(input_file + " has no vulnerabilities")
|
157 |
result = False
|
158 |
else:
|
159 |
+
tqdm.write("Vulnerability found in " + input_file + "...")
|
160 |
+
cwe = data["results"][0]["extra"]["metadata"]["cwe"][0]
|
161 |
+
lines = data["results"][0]["extra"]["lines"]
|
162 |
+
message = data["results"][0]["extra"]["message"]
|
163 |
|
164 |
+
prompt = f"""Vulnerability Report:
|
165 |
+
- Type: {cwe}
|
166 |
+
- Location: {lines}
|
167 |
+
- Description: {message}
|
168 |
+
|
169 |
+
Original Code:
|
170 |
+
```
|
171 |
+
{file_text}
|
172 |
+
```
|
173 |
+
|
174 |
+
Task: Fix the vulnerability in the code above. Provide only the complete fixed code without explanations or comments. Make minimal changes necessary to address the security issue while preserving the original functionality."""
|
175 |
|
176 |
+
few_shot_messages = fetch_dataset_examples(prompt, 8, True)
|
177 |
+
response = get_fixed_code_fine_tuned(prompt, few_shot_messages, model_name)
|
178 |
|
179 |
+
if "```python" in response:
|
180 |
+
idx = response.find("```python")
|
181 |
+
shift = len("```python")
|
182 |
+
fixed_code = response[idx + shift :]
|
183 |
else:
|
184 |
+
fixed_code = response
|
185 |
+
|
186 |
+
stop_words = ["```", "assistant"]
|
187 |
+
for w in stop_words:
|
188 |
+
if w in fixed_code:
|
189 |
+
fixed_code = fixed_code[:fixed_code.find(w)]
|
190 |
+
|
191 |
+
if len(fixed_code) < 400 or all(line.strip().startswith("#") for line in fixed_code.split('\n') if line.strip()):
|
192 |
result = False
|
193 |
+
else:
|
194 |
+
with open(output_file, 'w') as wf:
|
195 |
+
wf.write(fixed_code)
|
196 |
+
|
197 |
+
scan_command_output = f"semgrep --config p/python {output_file} --output {tmp_file} --json > /dev/null 2>&1"
|
198 |
+
os.system(scan_command_output)
|
199 |
+
|
200 |
+
if not os.path.exists(tmp_file):
|
201 |
+
tqdm.write(f"Semgrep failed to create output file for {output_file}")
|
202 |
+
result = False
|
203 |
+
else:
|
204 |
+
with open(tmp_file, 'r') as jf:
|
205 |
+
data = json.load(jf)
|
206 |
+
|
207 |
+
if len(data.get("errors", [])) == 0 and len(data.get("results", [])) == 0:
|
208 |
+
tqdm.write("Passing response for " + input_file + " at 1 ...")
|
209 |
+
result = True
|
210 |
+
fixed_files.append(file_name)
|
211 |
+
else:
|
212 |
+
result = False
|
213 |
+
else:
|
214 |
+
tqdm.write(f"Semgrep reported errors for {input_file}")
|
215 |
+
result = False
|
216 |
|
217 |
+
if os.path.exists(tmp_file):
|
218 |
+
os.remove(tmp_file)
|
219 |
|
220 |
+
cache[input_file] = result
|
221 |
+
save_cache(cache)
|
222 |
+
return result
|
223 |
+
except Exception as e:
|
224 |
+
tqdm.write(f"Error processing {input_file}: {str(e)}")
|
225 |
+
return False
|
226 |
|
227 |
+
def process_test_case(test_case, cache, fixed_files, model_name):
|
228 |
+
return process_file(test_case, cache, fixed_files, model_name)
|
229 |
|
230 |
def main():
|
231 |
+
parser = argparse.ArgumentParser(description="Run Static Analysis Evaluation")
|
232 |
+
parser.add_argument("--model", type=str, default="gpt-4-0125-preview", help="OpenAI model to use")
|
233 |
+
args = parser.parse_args()
|
234 |
+
|
235 |
+
model_name = args.model
|
236 |
+
sanitized_model_name = sanitize_filename(model_name)
|
237 |
+
|
238 |
dataset = load_dataset("patched-codes/static-analysis-eval", split="train")
|
239 |
data = [{"file_name": item["file_name"], "source": item["source"], "cwe": item["cwe"]} for item in dataset]
|
240 |
|
241 |
cache = load_cache()
|
242 |
total_tests = len(data)
|
243 |
|
244 |
+
semgrep_version = get_semgrep_version()
|
245 |
+
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
|
246 |
+
log_file_name = f"{sanitized_model_name}_semgrep_{semgrep_version}_{timestamp}.log"
|
247 |
+
|
248 |
+
manager = multiprocessing.Manager()
|
249 |
+
fixed_files = manager.list()
|
250 |
+
|
251 |
+
process_func = partial(process_test_case, cache=cache, fixed_files=fixed_files, model_name=model_name)
|
252 |
|
253 |
with multiprocessing.Pool() as pool:
|
254 |
results = list(tqdm(pool.imap_unordered(process_func, data), total=total_tests))
|
255 |
|
256 |
passing_tests = sum(results)
|
257 |
+
score = passing_tests / total_tests * 100
|
258 |
+
|
259 |
+
with open(log_file_name, 'w') as log_file:
|
260 |
+
log_file.write(f"Evaluation Run Log\n")
|
261 |
+
log_file.write(f"==================\n\n")
|
262 |
+
log_file.write(f"Date and Time: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
|
263 |
+
log_file.write(f"Model: {model_name}\n")
|
264 |
+
log_file.write(f"Semgrep Version: {semgrep_version}\n\n")
|
265 |
+
log_file.write(f"Total Tests: {total_tests}\n")
|
266 |
+
log_file.write(f"Passing Tests: {passing_tests}\n")
|
267 |
+
log_file.write(f"Score: {score:.2f}%\n\n")
|
268 |
+
log_file.write("Fixed Files:\n")
|
269 |
+
for file in fixed_files:
|
270 |
+
log_file.write(f"- {file}\n")
|
271 |
|
272 |
+
print(f"Results for StaticAnalysisEval: {score:.2f}%")
|
273 |
+
print(f"Log file created: {log_file_name}")
|
274 |
|
275 |
if __name__ == '__main__':
|
276 |
main()
|