GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Psearch/vul4j.py at main · iSEngLab/Psearch

Expand file tree

/

vul4j.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
576 lines (470 loc) · 21.4 KB
/

vul4j.py

Copy path

File metadata and controls

576 lines (470 loc) · 21.4 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
import csv
import json
import logging
import os
import subprocess
from dataclasses import dataclass, fields
from typing import Optional, List
vul_repo_root = '/root/autodl-tmp/vul_repo'
vul4j_root = '/root/autodl-tmp/vul4j'
vul_context_save_dir = '/root/autodl-tmp/MultiLocationFix/vul_context'
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
@dataclass
class Vulnerability:
no: int # index or ID
vul_id: str # custom vulnerability ID
cve_id: Optional[str] # CVE identifier, possibly empty
cwe_id: Optional[str] # CWE identifier, for example "CWE-78"
cwe_name: Optional[str] # CWE name, for example "OS Command Injection"
owasp_id: Optional[str] # related OWASP ID or category, for example "A1:2017-Injection"
repo_slug: str # repository name or path, for example "spring-petclinic"
human_patch: str # human-written patch content (possibly a diff or file path)
build_system: str # build system, for example "maven" or "gradle"
compliance_level: Optional[str] # compliance level, for example "high" or "medium"
failing_tests: List[str] # list of failing test cases
compile_cmd: str # compile command
test_all_cmd: str # command for running all tests
test_cmd: str # command for running target tests
cmd_options: Optional[str] # command-line options (optional)
failing_module: str # name of the failing module
src: str # source directory path
test: str # test code directory path
src_classes: str # compiled source class path (for example target/classes)
test_classes: str # compiled test class path (for example target/test-classes)
warning: str # warning message or static-analysis warning content
@dataclass
class VulnerabilityLocation:
vul_id: str # custom vulnerability ID
cve_id: Optional[str] # CVE identifier, possibly empty
is_single_file: bool
bug_type: str
buggy_file: str
buggy_lines: list
buggy_methods_with_comment: list
def get_vul_repo_root():
global vul_repo_root
return vul_repo_root
def get_VUL4J_root():
global vul4j_root
return vul4j_root
def get_vul_context_save_dir():
global vul_context_save_dir
return vul_context_save_dir
def read_vulnerabilities_from_csv(csv_file_path: str) -> List[Vulnerability]:
"""
Read vulnerability data from a CSV file. The first row is the header, and return a list of Vulnerability objects.
Note:
- failing_tests translated_text CSV translated_text ';' translated_text
"""
if csv_file_path is None or csv_file_path == '':
csv_file_path = f'./VUL4J/vul4j_dataset.csv'
vulnerabilities = []
# Get class field names (used to map CSV columns)
field_names = [field.name for field in fields(Vulnerability)]
with open(csv_file_path, mode='r', encoding='utf-8') as f:
reader = csv.DictReader(f)
# Check whether the header matches
if reader.fieldnames is None:
raise ValueError("CSV file is empty or missing a header")
header = [name.strip() for name in reader.fieldnames]
if header != field_names:
raise ValueError(f"CSV header mismatch. Expected: {field_names}, actual: {header}")
for row_num, row in enumerate(reader, start=2): # Data starts from line 2
try:
# Convert field types
instance = Vulnerability(
no=int(row['no']),
vul_id=row['vul_id'],
cve_id=row['cve_id'] or None,
cwe_id=row['cwe_id'] or None,
cwe_name=row['cwe_name'] or None,
owasp_id=row['owasp_id'] or None,
repo_slug=row['repo_slug'],
human_patch=row['human_patch'],
build_system=row['build_system'],
compliance_level=row['compliance_level'] or None,
failing_tests=[t.strip() for t in row['failing_tests'].split(';')] if row['failing_tests'] else [],
compile_cmd=row['compile_cmd'],
test_all_cmd=row['test_all_cmd'],
test_cmd=row['test_cmd'],
cmd_options=row['cmd_options'] or None,
failing_module=row['failing_module'],
src=row['src'],
test=row['test'],
src_classes=row['src_classes'],
test_classes=row['test_classes'],
warning=row['warning']
)
if instance.cve_id is not None:
vulnerabilities.append(instance)
except Exception as e:
raise ValueError(f"Error parsing CSV row {row_num}: {e}")
return vulnerabilities
def add_maven_local_before_central(file_path):
"""
During experiments we found that some packages could not be fetched when running vul4j outside Docker. After manual installation, Gradle is configured to prefer the local repository.
"""
if not os.path.isfile(file_path):
print(f"⚠️ File does not exist, skipping: {file_path}")
return
with open(file_path, 'r', encoding='utf-8') as f:
lines = f.readlines()
modified = False
output_lines = []
for i, line in enumerate(lines):
stripped_line = line.strip()
# Check whether this is a mavenCentral() line (supporting different styles)
if 'mavenCentral()' in stripped_line:
# Check whether the previous line already contains mavenLocal()
prev_line = output_lines[-1].strip() if output_lines else ""
if 'mavenLocal()' not in prev_line:
output_lines.append(
' ' * (len(line) - len(line.lstrip())) + "mavenLocal() // Prefer the local repository\n")
modified = True
output_lines.append(line)
# Write back the file (only if modified)
if modified:
with open(file_path, 'w', encoding='utf-8') as f:
f.writelines(output_lines)
print(f"✅ Updated: {file_path}")
else:
print(f"ℹ️ No update required (already present or mavenCentral not found): {file_path}")
def vul_checkout(vul_id):
if not os.path.exists(get_vul_repo_root()):
os.makedirs(get_vul_repo_root())
path = f'{get_vul_repo_root()}/{vul_id}'
if os.path.exists(path):
subprocess.run(['rm', '-rf', path])
# $ vul4j checkout --id VUL4J-1 -d /root/autodl-tmp/vul4j/repos/VUL4J-1
result = subprocess.run([
'vul4j', 'checkout', '--id', vul_id, '-d', path
], capture_output=True, # Capture stdout and stderr
text=True, # Return output as strings (instead of bytes)
timeout=3000) # Optional: set the timeout in seconds
GRADLE_SETTINGS = path + '/build.gradle'
if os.path.exists(GRADLE_SETTINGS):
add_maven_local_before_central(GRADLE_SETTINGS)
subprocess.run([
'git', 'add', GRADLE_SETTINGS
], cwd=path)
subprocess.run([
'git', 'commit', '-m', 'modify gradle settings'
], cwd=path)
if result.returncode == 0:
logging.info(f'Checkout vul {vul_id} to {path} success')
else:
logging.error(f'Checkout vul {vul_id} to {path} fail, error msg: {result.stderr}')
def get_all_vul_locations():
result = []
with open('./VUL4J/vul_location.json', 'r') as f:
vul_list = json.load(f)
for vul in vul_list:
result.append(VulnerabilityLocation(
vul_id=vul['vul_id'],
cve_id=vul['CVE_id'],
is_single_file=(vul['single_flie'] == '1'),
bug_type=(vul['bug_type'] if 'bug_type' in vul else 'unknown'),
buggy_file=(vul['buggy_file'] if 'buggy_file' in vul else []),
buggy_lines=(vul['buggy_line'] if 'buggy_line' in vul else []),
buggy_methods_with_comment=(
vul['buggy_method_with_comment'] if 'buggy_method_with_comment' in vul else [])
))
return result
def get_failing_test_report_for_vul(vul_id):
test_report_path = f'{get_vul_repo_root()}/{vul_id}/VUL4J/testing_results.json'
if not os.path.exists(test_report_path):
return None
with open(test_report_path, 'r') as f:
failures = json.load(f)['tests']['failures']
f.close()
# Statistics
lines = []
for failure in failures:
test_class = failure["test_class"]
test_method = failure["test_method"]
failure_name = failure["failure_name"]
detail = failure["detail"].strip() if 'detail' in failure else ''
is_error = failure["is_error"]
lines.append(f"Class: {test_class}")
lines.append("-" * 40)
# Failed entries
status = "ERROR" if is_error else "FAILURE"
lines.append(f" Method: {test_method}")
lines.append(f" Status: {status}")
lines.append(f" Type: {failure_name}")
lines.append(f" Detail: {detail}")
lines.append("")
return "\n".join(lines)
def get_test_class_and_method_for_vul(vul_id):
test_report_path = f'{get_vul_repo_root()}/{vul_id}/VUL4J/testing_results.json'
if not os.path.exists(test_report_path):
return {}
result = {}
with open(test_report_path, 'r') as f:
failures = json.load(f)['tests']['failures']
f.close()
for failure in failures:
if failure['test_class'] not in result:
result[failure['test_class']] = [failure['test_method']]
else:
result[failure['test_class']].append(failure['test_method'])
return result
def get_test_code_for_vul(vul_id, test_class_and_method):
target_dir = f'{get_vul_context_save_dir()}/{vul_id}'
if not os.path.exists(target_dir):
return f'Test code for {vul_id} cannot be found'
result = ''
for test_class in test_class_and_method:
for file_name in os.listdir(target_dir):
if test_class.replace(".", "_") in file_name:
with open(target_dir + os.path.sep + file_name, 'r') as f:
json_obj = json.load(f)
if json_obj['fullQualifiedName'] == test_class:
method_info = {}
for t in json_obj['methodList']:
if t['name'] not in method_info:
method_info[t['name']] = []
method_info[t['name']].append((t['signature'], t['content'], t['startLine'], t['endLine']))
for test_name in test_class_and_method[test_class]:
if test_name in method_info:
for x in method_info[test_name]:
result += "Class name: " + test_class + ", Test method: " + x[
0] + f", Line: {x[2]}-{x[3]} " + '\n'
result += x[1]
result += '\n\n'
break
return result
def get_vul_test_root(vul_id):
vul = get_vul_by_vul_id(vul_id)
path = vul.test
module = get_vul_module(vul_id)
if module != 'root':
path = module + '/' + path
path += '/' + vul.failing_tests[0].split('.')[0]
return path
def get_java_funcs_for_vul(vul_id, file_path):
path = get_vul_context_save_dir() + os.path.sep + f'{vul_id}' + os.path.sep + file_path.replace(
get_vul_repo_root() + '/', '').replace('/',
"_").replace(
'.java', '.json')
with open(path, 'r') as f:
java_file_info = json.load(f)
func_list = []
for method_info in java_file_info['methodList']:
func_list.append({
'name': method_info['name'],
'signature': method_info['signature'],
'startLine': method_info['startLine'],
'endLine': method_info['endLine']
})
return func_list
def apply_modifications(file_path, modifications):
"""
Apply a list of modifications to a file in reverse line order (to avoid line number shifting).
Args:
file_path (str): Path to the file to be modified.
modifications (list): Each element is a dict with keys:
- 'op': 'add', 'delete', or 'replace'
- 'start': int, start line (1-based)
- 'end': int, end line (1-based, inclusive for delete/replace; for add, it's where to insert after)
- 'content': str or list of str, new content to add/replace (required for 'add' and 'replace')
Raises:
ValueError: If invalid operation or missing fields.
FileNotFoundError: If file does not exist.
IOError: If file cannot be read/written.
"""
# Read the file content
with open(file_path, 'r', encoding='utf-8') as f:
lines = f.readlines() # List of lines, each with newline preserved
# Sort modifications by start line in descending order (from bottom to top)
sorted_mods = sorted(modifications, key=lambda x: x['start'], reverse=True)
for mod in sorted_mods:
op = mod['op'].lower()
start = mod['start']
end = mod['end']
# Convert to 0-based indexing (start_line is where modification begins)
start_idx = start - 1
end_idx = end - 1
if op == 'add':
# Insert content *after* line `end` (i.e., at end_idx )
content = mod.get('content')
if content is None:
raise ValueError("Missing 'content' for 'add' operation")
if isinstance(content, str):
content_lines = content.splitlines(keepends=True)
elif isinstance(content, list):
content_lines = [line if line.endswith('\n') else line + '\n' for line in content]
else:
raise ValueError("'content' must be str or list of str")
insert_pos = end_idx # Insert after the 'end' line
lines[insert_pos:insert_pos] = content_lines
elif op == 'delete':
# Delete lines from start_idx to end_idx (inclusive)
del lines[start_idx:end_idx + 1]
elif op == 'replace':
# Replace lines from start_idx to end_idx with new content
content = mod.get('content')
if content is None:
raise ValueError("Missing 'content' for 'replace' operation")
if isinstance(content, str):
content_lines = content.splitlines(keepends=True)
elif isinstance(content, list):
content_lines = [line if line.endswith('\n') else line + '\n' for line in content]
else:
raise ValueError("'content' must be str or list of str")
lines[start_idx:end_idx + 1] = content_lines
else:
raise ValueError(f"Unsupported operation: {op}")
# Write back to the file
with open(file_path, 'w', encoding='utf-8') as f:
f.writelines(lines)
def apply_modification_test():
file_path = './test_data/TypeReference.java'
modifications = [{'op': 'add','start':30,'end':30,'content':' protected final Type type3;\nprotected final Type type4;\n'}]
apply_modifications(file_path,modifications)
def compile_vul_and_run_test(vul_id):
work_dir = f'{get_vul_repo_root()}/{vul_id}'
# compile
logging.info(f'Compile vul {vul_id}')
# vul4j compile -d /tmp/vul4j/VUL4J-10
compile_result = subprocess.run([
'vul4j', 'compile', '-d', work_dir
],
capture_output=True, # Capture stdout and stderr
text=True, # Return output as strings (instead of bytes)
timeout=3000 # Optional: set the timeout in seconds
)
logging.info(f'Compile result: {compile_result}')
if compile_result.returncode != 0:
return compile_result.stderr, False
# vul4j test -d /tmp/vul4j/VUL4J-10
test_result = subprocess.run(
['vul4j', 'test', '-d', work_dir],
capture_output=True, # Capture stdout and stderr
text=True, # Return output as strings (instead of bytes)
timeout=3000 # Optional: set the timeout in seconds
)
logging.info(f'Test result: {test_result}')
return test_result, True
def validate_patch(vul: Vulnerability, vul_location: VulnerabilityLocation, new_code: str):
vul_checkout(vul_id=vul.vul_id)
target_file = f'{get_vul_repo_root()}/{vul.vul_id}/{vul_location.buggy_file}'
if len(vul_location.buggy_lines) > 1:
# replace the whole method
apply_modifications(target_file,
[{
'op': 'replace',
'start': vul_location.buggy_methods_with_comment[0][0],
'end': vul_location.buggy_methods_with_comment[0][1],
'content': new_code
}])
elif vul_location.bug_type == 'replace' or vul_location.bug_type == 'deletion':
# replace the hunk
apply_modifications(target_file,
[{
'op': 'replace',
'start': vul_location.buggy_lines[0][0],
'end': (vul_location.buggy_lines[0][1] if len(vul_location.buggy_lines[0]) > 1 else
vul_location.buggy_lines[0][0]),
'content': new_code
}])
elif vul_location.bug_type == 'insertion':
# insert new code into target line
apply_modifications(target_file,
[{
'op': 'add',
'start': vul_location.buggy_lines[0][0],
'end': vul_location.buggy_lines[0][0],
'content': new_code
}]
)
work_dir = f'{get_vul_repo_root()}/{vul.vul_id}'
subprocess.run([
'git', 'add', vul_location.buggy_file
], cwd=work_dir)
subprocess.run([
'git', 'commit', '-m', 'submit patch'
], cwd=work_dir)
patch_diff = ''
try:
# Generate the patch with git diff
result = subprocess.run(
['git', 'diff', '--no-color', 'HEAD~1..HEAD', '--', vul_location.buggy_file],
capture_output=True,
text=True,
check=False, # Do not fail when there is no change
cwd=work_dir # Run in the file directory
)
patch_diff = result.stdout.strip()
print(patch_diff)
if not patch_diff:
print(f"No changes detected by git diff")
except Exception as e:
print("Error running git diff:", str(e))
finally:
test_result, is_compile_success = compile_vul_and_run_test(vul_id=vul.vul_id)
test_report = get_failing_test_report_for_vul(vul_id=vul.vul_id)
test_class_and_methods = get_test_class_and_method_for_vul(vul_id=vul.vul_id)
test_code = get_test_code_for_vul(test_class_and_method=test_class_and_methods, vul_id=vul.vul_id)
return patch_diff, is_compile_success, test_report == '', test_report, test_code
all_vuls = read_vulnerabilities_from_csv('')
all_vul_locations = get_all_vul_locations()
skip_list = ['VUL4J-3','VUL4J-4']
def get_all_vuls():
return [x for x in all_vuls if x.vul_id not in skip_list]
def get_all_vul_with_location():
vuls = get_all_vuls()
result = []
for vul in vuls:
location = get_vul_location_by_vul_id(vul.vul_id)
if location.is_single_file and len(location.buggy_methods_with_comment) == 1:
result.append((vul, location))
return result
def get_vul_by_vul_id(vul_id):
for x in all_vuls:
if x.vul_id == vul_id:
return x
return None
def get_vul_location_by_vul_id(vul_id):
for x in all_vul_locations:
if x.vul_id == vul_id:
return x
return None
def get_vul_module(vul_id):
return get_vul_by_vul_id(vul_id).failing_module
def read_lines_from_file(file, start_line, end_line):
"""
Read lines from a file within the given line range (1-based indexing), inclusive on both ends.
Args:
file (str): Path to the file.
start_line (int): Start line number (1-based, inclusive).
end_line (int): End line number (1-based, inclusive).
Returns:
list: List of strings, each representing a line in the specified range.
Lines include their newline characters.
Raises:
FileNotFoundError: If the file does not exist.
ValueError: If line numbers are invalid.
IOError: If there is an error reading the file.
"""
if start_line < 1 or end_line < start_line:
raise ValueError("Invalid line range: start_line must >= 1 and end_line >= start_line")
try:
with open(file, 'r', encoding='utf-8') as f:
lines = f.readlines()
# Convert to 0-based indexing
start_idx = start_line - 1
end_idx = end_line # This is still 1-based; we'll use end_idx + 1 for slicing
# Check bounds
if start_idx >= len(lines):
return [] # Start line beyond file length
if end_idx > len(lines):
end_idx = len(lines) # Clamp end_line to last available line
# Return inclusive slice [start_line, end_line]
return lines[start_idx:end_idx]
except FileNotFoundError:
raise FileNotFoundError(f"File not found: {file}")
except Exception as e:
raise IOError(f"Error reading file {file}: {str(e)}")
if __name__ == '__main__':
apply_modification_test()
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.