Datasets:

Modalities:
Text
Formats:
parquet
Size:
< 1K
ArXiv:
DOI:
Libraries:
Datasets
pandas
License:
File size: 12,502 Bytes
6ffdbc7
 
 
 
 
c60518e
 
 
 
3c831f2
 
6ffdbc7
60ac2bd
6ffdbc7
 
 
3c831f2
6ffdbc7
 
5eb5743
6ffdbc7
 
60ac2bd
 
6ffdbc7
 
 
 
60ac2bd
 
 
 
6ffdbc7
c60518e
 
 
 
 
 
 
60ac2bd
6ffdbc7
 
 
3c831f2
 
 
 
 
 
 
6ffdbc7
 
 
 
 
3c831f2
 
 
 
 
 
 
 
 
 
 
 
 
 
6ffdbc7
3c831f2
 
 
6ffdbc7
 
 
 
 
 
 
 
 
 
 
 
 
c60518e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ffdbc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c60518e
5eb5743
c60518e
 
 
 
 
5eb5743
c60518e
 
 
60ac2bd
 
c60518e
 
 
 
5eb5743
 
 
 
 
 
 
 
 
 
 
 
 
 
6ffdbc7
c8334f5
6ffdbc7
c60518e
6ffdbc7
60ac2bd
6ffdbc7
 
 
 
 
 
 
c60518e
 
6ffdbc7
c60518e
 
6ffdbc7
c60518e
 
6ffdbc7
c60518e
5eb5743
c60518e
 
 
 
 
 
 
 
5eb5743
 
 
 
 
 
 
 
 
 
 
 
 
6ffdbc7
5eb5743
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8334f5
 
 
 
 
 
5eb5743
c8334f5
 
 
5eb5743
c8334f5
 
 
 
 
6ffdbc7
c60518e
 
60ac2bd
 
6ffdbc7
c60518e
 
 
 
6ffdbc7
c8334f5
 
6ffdbc7
 
c60518e
60ac2bd
 
 
 
c8334f5
c60518e
 
c8334f5
60ac2bd
 
 
c8334f5
60ac2bd
c60518e
5eb5743
6ffdbc7
 
60ac2bd
6ffdbc7
 
c60518e
 
 
 
 
 
 
5eb5743
 
6ffdbc7
60ac2bd
 
6ffdbc7
 
c60518e
 
60ac2bd
 
 
c60518e
 
 
 
c8334f5
60ac2bd
 
c60518e
 
 
60ac2bd
 
c8334f5
c60518e
 
 
6ffdbc7
c60518e
 
6ffdbc7
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
import json
import os
import random
import pickle
import time
import datetime
import subprocess
import argparse
import re
import multiprocessing
import numpy as np
from openai import OpenAI
from openai import OpenAIError
from tqdm import tqdm
from functools import partial
from datasets import load_dataset
from sentence_transformers import SentenceTransformer, CrossEncoder
from sklearn.metrics.pairwise import cosine_similarity

# client = OpenAI(base_url="http://localhost:11434/v1/", api_key="ollama")
client = OpenAI()

def load_cache(use_cache):
    if use_cache and os.path.exists('cache.pkl'):
        with open('cache.pkl', 'rb') as f:
            return pickle.load(f)
    return {}

def save_cache(cache, use_cache):
    if use_cache:
        with open('cache.pkl', 'wb') as f:
            pickle.dump(cache, f)

def has_all_comments(text):
    lines=text.split('\n')
    for line in lines:
        if line != "" and not line.startswith("#"):
            return False
    return True

def fetch_dataset_examples(prompt, num_examples=0, use_similarity=False):
    dataset = load_dataset("patched-codes/synth-vuln-fixes", split="train")
    
    if use_similarity:
        # Load a lightweight model for initial retrieval
        retrieval_model = SentenceTransformer('all-MiniLM-L6-v2')
        
        # Load the cross-encoder model for reranking
        rerank_model = CrossEncoder('cross-encoder/ms-marco-MiniLM-L-6-v2')
        
        # Extract user messages
        user_messages = [
            next(msg['content'] for msg in item['messages'] if msg['role'] == 'user')
            for item in dataset
        ]
        
        # Encode the prompt and user messages for initial retrieval
        prompt_embedding = retrieval_model.encode(prompt, convert_to_tensor=False)
        corpus_embeddings = retrieval_model.encode(user_messages, convert_to_tensor=False, show_progress_bar=True)
        
        # Perform initial retrieval
        similarities = cosine_similarity([prompt_embedding], corpus_embeddings)[0]
        top_k = min(100, len(dataset))
        top_indices = similarities.argsort()[-top_k:][::-1]
        
        # Prepare pairs for reranking
        rerank_pairs = [[prompt, user_messages[idx]] for idx in top_indices]
        
        # Rerank using the cross-encoder model
        rerank_scores = rerank_model.predict(rerank_pairs)
        
        # Sort by reranked score and select top examples
        reranked_indices = [top_indices[i] for i in np.argsort(rerank_scores)[::-1][:num_examples]]
        top_indices = reranked_indices
    else:
        top_indices = np.random.choice(len(dataset), num_examples, replace=False)
    
    few_shot_messages = []
    for index in top_indices:
        py_index = int(index)
        messages = dataset[py_index]["messages"]
        
        dialogue = [msg for msg in messages if msg['role'] != 'system']
        few_shot_messages.extend(dialogue)
    
    return few_shot_messages

def sanitize_filename(name):
    # Replace ':' with '_', and any other non-alphanumeric characters (except '-' and '_') with '*'
    sanitized = re.sub(r':', '_', name)
    sanitized = re.sub(r'[^a-zA-Z0-9\-_]', '*', sanitized)
    return sanitized

def get_semgrep_version():
    try:
        result = subprocess.run(["semgrep", "--version"], capture_output=True, text=True)
        version = result.stdout.strip().split()[-1]
        return version
    except Exception:
        return "unknown"

def get_fixed_code_fine_tuned(prompt, few_shot_messages, model_name):
    system_message = (
        "You are an AI assistant specialized in fixing code vulnerabilities. "
        "Your task is to provide corrected code that addresses the reported security issue. "
        "Always maintain the original functionality while improving security. "
        "Be precise and make only necessary changes. "
        "Maintain the original code style and formatting unless it directly relates to the vulnerability. "
        "Pay attention to data flow between sources and sinks when provided."
    )

    messages = [
        {"role": "system", "content": system_message},
    ]
    
    messages.extend(few_shot_messages)
    messages.append({"role": "user", "content": prompt})

    max_retries = 3

    for attempt in range(max_retries):
        try:
            response = client.chat.completions.create(
                model=model_name,
                messages=messages,
                max_tokens=4096,
                temperature=0.2,
                top_p=0.95
            )
            return response.choices[0].message.content
        except OpenAIError as e:
            if attempt < max_retries - 1:
                time.sleep(2 ** attempt)  # Exponential backoff
            else:
                raise Exception(f"API call failed after {max_retries} attempts: {str(e)}")
            
def clean_code_snippet(response):
    # Remove opening delimiter
    if response.startswith("```python"):
        response = response[len("```python"):]
    elif response.startswith("```"):
        response = response[len("```"):]
    
    # Remove closing delimiter
    if response.endswith("```"):
        response = response[:-len("```")]
    
    # Trim any remaining whitespace
    return response.strip()

def process_file(test_case, cache, fixed_files, model_name, use_cache, n_shot, use_similarity, oracle_mode):
    file_name = test_case["file_name"]
    input_file = os.path.join("staticeval", file_name)
    
    if use_cache and input_file in cache:
        tqdm.write(f"Skipping {input_file} (cached)")
        return cache[input_file]

    file_text = test_case["source"]
    output_file = input_file + "_fixed.py"
    tmp_file = input_file + ".output.json"

    try:
        os.makedirs(os.path.dirname(input_file), exist_ok=True)

        with open(input_file, "w") as file_object:
            file_object.write(file_text)

        if os.path.exists(tmp_file):
            os.remove(tmp_file)
            
        tqdm.write("Scanning file " + input_file + "...")
        scan_command_input = f"semgrep --config auto {input_file} --output {tmp_file} --json > /dev/null 2>&1"
        os.system(scan_command_input)
        
        if not os.path.exists(tmp_file):
            tqdm.write(f"Semgrep failed to create output file for {input_file}")
            return False

        with open(tmp_file, 'r') as jf:
            data = json.load(jf)

        if len(data.get("errors", [])) > 0:
            tqdm.write(f"Error processing {input_file} ...")
            return False
            
        if len(data.get("results", [])) == 0:
            tqdm.write(input_file + " has no vulnerabilities")
            result = False
        else:
            tqdm.write("Vulnerability found in " + input_file + "...")
            if oracle_mode:
                result = True
                fixed_files.append(file_name)
            else:
                cwe = test_case['cwe']
                lines = data["results"][0]["extra"]["lines"]
                message = data["results"][0]["extra"]["message"]
                
                prompt = f"""Vulnerability Report:
    - Type: {cwe}
    - Location: {lines}
    - Description: {message}

    Original Code:
    ```
    {file_text}
    ```

    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."""
                # print(prompt)
                few_shot_messages = fetch_dataset_examples(prompt, n_shot, use_similarity)
                response = get_fixed_code_fine_tuned(prompt, few_shot_messages, model_name)
                # print(response)
                
                fixed_code = clean_code_snippet(response)

                if len(fixed_code) < 512 or has_all_comments(fixed_code):
                    result = False
                else: 
                    # print("Here2\n" + fixed_code)
                    if os.path.exists(output_file):
                        os.remove(output_file)
                    with open(output_file, 'w') as wf:
                        wf.write(fixed_code)
                    if os.path.exists(tmp_file):
                        os.remove(tmp_file)
                    scan_command_output = f"semgrep --config auto {output_file} --output {tmp_file} --json > /dev/null 2>&1"
                    os.system(scan_command_output)
                    with open(tmp_file, 'r') as jf:
                        data = json.load(jf)
                    if len(data["results"]) == 0:
                        tqdm.write("Passing response for " + input_file + " at 1 ...")
                        result = True
                        fixed_files.append(file_name)
                    else:
                        result = False

        if os.path.exists(tmp_file):
            os.remove(tmp_file)
        if use_cache:
            cache[input_file] = result

        return result
    except Exception as e:
        tqdm.write(f"Error processing {input_file}: {str(e)}")
        return False

def process_test_case(test_case, cache, fixed_files, model_name, use_cache, n_shot, use_similarity, oracle_mode):
    return process_file(test_case, cache, fixed_files, model_name, use_cache, n_shot, use_similarity, oracle_mode)

def main():
    parser = argparse.ArgumentParser(description="Run Static Analysis Evaluation")
    parser.add_argument("--model", type=str, default="gpt-4o-mini", help="OpenAI model to use")
    parser.add_argument("--cache", action="store_true", help="Enable caching of results")
    parser.add_argument("--n_shot", type=int, default=0, help="Number of examples to use for few-shot learning")
    parser.add_argument("--use_similarity", action="store_true", help="Use similarity for fetching dataset examples")
    parser.add_argument("--oracle", action="store_true", help="Run in oracle mode (assume all vulnerabilities are fixed)")
    args = parser.parse_args()

    model_name = "oracle" if args.oracle else args.model
    use_cache = args.cache
    n_shot = args.n_shot
    use_similarity = args.use_similarity
    oracle_mode = args.oracle
    sanitized_model_name = f"{sanitize_filename(model_name)}-{n_shot}-shot{'-sim' if use_similarity else ''}"

    dataset = load_dataset("patched-codes/static-analysis-eval", split="train", download_mode='force_redownload')
    data = [{"file_name": item["file_name"], "source": item["source"], "cwe": item["cwe"]} for item in dataset]

    cache = load_cache(use_cache)
    total_tests = len(data)

    semgrep_version = get_semgrep_version()
    timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
    log_file_name = f"{sanitized_model_name}_semgrep_{semgrep_version}_{timestamp}.log"

    manager = multiprocessing.Manager()
    fixed_files = manager.list()

    process_func = partial(process_test_case, cache=cache, fixed_files=fixed_files, model_name=model_name,
                           use_cache=use_cache, n_shot=n_shot, use_similarity=use_similarity, oracle_mode=oracle_mode)

    with multiprocessing.Pool(processes=4) as pool:
        results = list(tqdm(pool.imap(process_func, data), total=total_tests))

    passing_tests = sum(results)
    score = passing_tests / total_tests * 100

    if use_cache:
        save_cache(cache, use_cache)

    with open(log_file_name, 'w') as log_file:
        log_file.write(f"Evaluation Run Log\n")
        log_file.write(f"==================\n\n")
        log_file.write(f"Date and Time: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
        log_file.write(f"Model: {'' if oracle_mode else model_name}\n")
        log_file.write(f"Semgrep Version: {semgrep_version}\n")
        log_file.write(f"Caching: {'Enabled' if use_cache else 'Disabled'}\n\n")
        log_file.write(f"Total Tests: {total_tests}\n")
        log_file.write(f"Passing Tests: {passing_tests}\n")
        log_file.write(f"Score: {score:.2f}%\n\n")
        log_file.write(f"Number of few-shot examples: {n_shot}\n")
        log_file.write(f"Use similarity for examples: {'Yes' if use_similarity else 'No'}\n")
        log_file.write(f"Oracle mode: {'Yes' if oracle_mode else 'No'}\n")
        log_file.write("Fixed Files:\n")
        for file in fixed_files:
            log_file.write(f"- {file}\n")

    print(f"Results for StaticAnalysisEval: {score:.2f}%")
    print(f"Log file created: {log_file_name}")

if __name__ == '__main__':
    main()