Skip to content

Commit b13a1a9

Browse files
committed
update
1 parent 1ab38a4 commit b13a1a9

File tree

7 files changed

+123
-121
lines changed

7 files changed

+123
-121
lines changed

setup.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,9 @@ def finalize_options(self):
1818
install.finalize_options(self)
1919
if self.location is None:
2020
self.location = os.path.expanduser("~/vul4j_data")
21-
# if os.path.exists(self.location):
22-
# print(f"ERROR: Directory already exists: {self.location}")
23-
# exit(1)
21+
if os.path.exists(self.location):
22+
print(f"ERROR: Directory already exists: {self.location}")
23+
exit(1)
2424
os.environ["VUL4J_DATA"] = self.location
2525

2626
def run(self):

vul4j/config.py

Lines changed: 21 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,30 +3,37 @@
33
from os.path import normpath, expanduser
44

55

6-
def get_config(section: str, config_name: str, default=""):
6+
def get_config(section: str, config_name: str, default: str = "") -> str:
7+
"""
8+
Returns the value of the given config entry.
9+
First the vul4j.ini file is checked,
10+
if the value or the config file is not found,
11+
the environment variables are checked for the provided name,
12+
and if none of the two previous checks have a value, the default value is used.
13+
14+
:param section: section name in the config file
15+
:param config_name: config entry name in the config file and/or in the env vars
16+
:param default: default value if no config value is found
17+
:return: string value of the config entry
18+
"""
719
config = configparser.ConfigParser()
8-
config_path = os.path.join(os.environ.get("VUL4J_DATA", expanduser("~/vul4j_data")), "vul4j.ini")
9-
config.read(config_path)
20+
config_path = os.path.join(VUL4J_DATA, "vul4j.ini")
21+
config.read(config_path, encoding="utf-8")
1022

11-
try:
12-
value = config.get(section, config_name, fallback=None)
13-
if value is None or value == "":
14-
value = os.environ.get(config_name)
15-
16-
return value if value else default
17-
except configparser.NoSectionError:
18-
print(f"Vul4J config not found at {config_path}")
19-
exit(1)
23+
value = config.get(section, config_name, fallback=None)
24+
if value is None or value == "":
25+
value = os.environ.get(config_name)
26+
return value if value else default
2027

2128

2229
# VUl4J
2330
VUL4J_DATA = normpath(os.environ.get("VUL4J_DATA", expanduser("~/vul4j_data")))
2431
VUL4J_GIT = normpath(get_config("VUL4J", "VUL4J_GIT"))
25-
VUL4J_COMMITS_URL = get_config("VUL4J", "VUL4J_COMMITS_URL")
2632
DATASET_PATH = normpath(get_config("VUL4J", "DATASET_PATH",
2733
os.path.join(VUL4J_GIT, "dataset", "vul4j_dataset.csv")))
34+
VUL4J_COMMITS_URL = get_config("VUL4J", "VUL4J_COMMITS_URL")
2835
LOG_TO_FILE = get_config("VUL4J", "LOG_TO_FILE", "1") == "1"
29-
FILE_LOG_LEVEL = get_config("VUL4J", "LOG_LEVEL", "DEBUG").upper()
36+
FILE_LOG_LEVEL = get_config("VUL4J", "FILE_LOG_LEVEL", "INFO").upper()
3037

3138
# DIRS
3239
VUL4J_OUTPUT = normpath(get_config("DIRS", "VUL4J_WORKDIR", "VUL4J"))

vul4j/main.py

Lines changed: 17 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import argparse
2-
from datetime import datetime
32
import os.path
43
import subprocess
54
import sys
5+
from datetime import datetime
66

77
from loguru import logger
88

@@ -15,76 +15,50 @@
1515
# logger
1616
def setup_logger(command: str, display_level: str = "INFO", file_level: str = "DEBUG"):
1717
log_filename = f"{datetime.now().strftime('%y%m%d_%H%M%S')}_{command}_{file_level}.log"
18-
1918
logger.remove()
19+
# STDOUT
2020
logger.add(sys.stdout,
2121
colorize=True,
2222
format="<cyan>{time:YYYY-MM-DD HH:mm:ss}</cyan> | <level>{message}</level>",
2323
diagnose=False,
2424
backtrace=False,
2525
level=display_level.upper())
26+
# FILE
2627
logger.add(os.path.join(VUL4J_DATA, "logs", log_filename),
2728
format="<cyan>{time:YYYY-MM-DD HH:mm:ss}</cyan> | <level>{level}</level> | <level>{message}</level>",
2829
rotation="00:00",
2930
level=file_level.upper())
3031

3132

3233
@utils.log_frame("STATUS")
33-
def vul4j_status(args):
34+
def vul4j_status(_):
3435
utils.check_status()
3536

3637

3738
@utils.log_frame("CHECKOUT")
3839
def vul4j_checkout(args):
39-
vul_id = args.id
40-
output_dir = args.outdir
41-
42-
try:
43-
vul4j.checkout(vul_id, output_dir)
44-
return
45-
except (vul4j.VulnerabilityNotFoundError, AssertionError) as err:
46-
logger.error(err)
47-
exit(1)
40+
vul4j.checkout(args.id, args.outdir)
4841

4942

5043
@utils.log_frame("COMPILE")
5144
def vul4j_compile(args):
52-
output_dir = args.outdir
53-
5445
try:
55-
vul4j.build(output_dir)
56-
return
46+
vul4j.build(args.outdir)
5747
except subprocess.CalledProcessError:
58-
logger.error("Compile failed!")
59-
except (vul4j.VulnerabilityNotFoundError, AssertionError) as err:
60-
logger.error(err)
61-
exit(1)
48+
raise subprocess.CalledProcessError("Compile failed!")
6249

6350

6451
@utils.log_frame("TEST")
6552
def vul4j_test(args):
66-
output_dir = args.outdir
67-
batch_type = args.batchtype
68-
6953
try:
70-
vul4j.test(output_dir, batch_type)
54+
vul4j.test(args.outdir, args.batchtype)
7155
except subprocess.CalledProcessError:
72-
logger.error("Testing failed!")
73-
except (vul4j.VulnerabilityNotFoundError, AssertionError) as err:
74-
logger.error(err)
56+
raise subprocess.CalledProcessError("Testing failed!")
7557

7658

7759
@utils.log_frame("APPLY")
7860
def vul4j_apply(args):
79-
output_dir = args.outdir
80-
version = args.version
81-
82-
try:
83-
vul4j.apply(output_dir, version)
84-
except AssertionError as err:
85-
logger.error(err)
86-
except vul4j.VulnerabilityNotFoundError as err:
87-
logger.error(err)
61+
vul4j.apply(args.outdir, args.version)
8862

8963

9064
@utils.log_frame("SAST")
@@ -120,18 +94,12 @@ def vul4j_sast(args):
12094

12195
@utils.log_frame("REPRODUCE")
12296
def vul4j_reproduce(args):
123-
vul_id = args.id
124-
vul4j.reproduce(vul_id)
97+
vul4j.reproduce(args.id)
12598

12699

127100
@utils.log_frame("INFO")
128101
def vul4j_info(args):
129-
vul_id = args.id
130-
131-
try:
132-
vul4j.get_info(vul_id)
133-
except vul4j.VulnerabilityNotFoundError as err:
134-
logger.error(err)
102+
vul4j.get_info(args.id)
135103

136104

137105
@utils.log_frame("CLASSPATH")
@@ -156,7 +124,7 @@ def main(args=None):
156124

157125
# STATUS
158126
status_parser = sub_parsers.add_parser("status",
159-
help="Lists vul4j requirements and availability.")
127+
help="Lists vul4j requirements and their availability.")
160128
status_parser.set_defaults(func=vul4j_status)
161129

162130
# CHECKOUT
@@ -186,16 +154,16 @@ def main(args=None):
186154

187155
# APPLY
188156
apply_parser = sub_parsers.add_parser('apply',
189-
help="Apply the specified file version.")
157+
help="Apply the specified file versions.")
190158
apply_parser.add_argument("-d", "--outdir", type=str,
191159
help="The directory to which the vulnerability was checked out.", required=True)
192160
apply_parser.add_argument("-v", "--version", type=str,
193-
help="Version to apply", required=True)
161+
help="Version to apply.", required=True)
194162
apply_parser.set_defaults(func=vul4j_apply)
195163

196164
# SAST
197165
sast_parser = sub_parsers.add_parser('sast',
198-
help="Run spotbugs analysis.")
166+
help="Run Spotbugs analysis.")
199167
sast_parser.add_argument("-d", "--outdir", type=str,
200168
help="The directory to which the vulnerability was checked out.", required=True)
201169
sast_parser.add_argument("-v", "--versions", nargs='+',
@@ -227,7 +195,7 @@ def main(args=None):
227195

228196
# GET SPOTBUGS
229197
spotbugs_parser = sub_parsers.add_parser("get-spotbugs",
230-
help="Downloads Spotbugs into the user directory.")
198+
help="Download Spotbugs into the user directory.")
231199
spotbugs_parser.add_argument("-l", "--location", type=str,
232200
help="Custom spotbugs installation path.", required=False)
233201
spotbugs_parser.set_defaults(func=get_spotbugs)

vul4j/spotbugs.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ def extract_attributes(cls, root):
4646
return attributes
4747

4848

49-
def run_spotbugs(output_dir: str, version=None, force_compile=False) -> list:
49+
def run_spotbugs(project_dir: str, version=None, force_compile=False) -> list:
5050
"""
5151
Runs Spotbugs check on the project found in the provided directory.
5252
The project must contain a 'vulnerability_info.json' file.
@@ -56,40 +56,40 @@ def run_spotbugs(output_dir: str, version=None, force_compile=False) -> list:
5656
One can manually force recompilation by setting force_compile to True.
5757
5858
The project's target folder is searched for artifacts.
59-
The jar that ends in 'SNAPSHOT.jar' will be used for the Spotbugs analysis.
6059
61-
The method getter extracts the modified method names and their classes into the modifications.json file.
60+
The modification extractor extracts the modified classes, class attributes and method names
61+
into the modifications.json file.
6262
Then Spotbugs analysis is run.
6363
64-
The spotbugs_report.xml file is checked for warnings in the methods extracted by the method getter.
64+
The spotbugs_report.xml file is checked for warnings in the modified code parts.
6565
The results are saved in the warnings.json file or warnings_version.json if a version was provided.
6666
67-
:param output_dir: path to the projects directory
67+
:param project_dir: path to the projects directory
6868
:param version: version name, used for naming output files
6969
:param force_compile: recompile project
7070
"""
7171

72-
vul = vul4j.Vulnerability.from_json(output_dir)
72+
vul = vul4j.Vulnerability.from_json(project_dir)
7373

7474
assert vul.build_system == "Maven", f"Incompatible build system: {vul.build_system}"
7575

7676
# create spotbugs directory
77-
reports_dir = os.path.join(output_dir, VUL4J_OUTPUT, "spotbugs")
77+
reports_dir = os.path.join(project_dir, VUL4J_OUTPUT, "spotbugs")
7878
os.makedirs(reports_dir, exist_ok=True)
7979
assert os.path.exists(reports_dir), "Failed to create spotbugs directory!"
8080
logger.debug("Spotbugs directory created!")
8181

8282
# get module path where compiled jars are located
8383
failing_module = vul.failing_module
8484
if failing_module == "root":
85-
module_path = output_dir
85+
module_path = project_dir
8686
else:
87-
module_path = os.path.join(output_dir, failing_module)
87+
module_path = os.path.join(project_dir, failing_module)
8888
logger.debug(f"Module path: {module_path}")
8989

9090
# find modified methods and their classes
9191
method_getter_output = os.path.join(reports_dir, "modifications.json")
92-
method_getter_command = f"java -jar {MODIFICATION_EXTRACTOR_PATH} {output_dir} {method_getter_output}"
92+
method_getter_command = f"java -jar {MODIFICATION_EXTRACTOR_PATH} {project_dir} {method_getter_output}"
9393
method_getter_log_path = os.path.join(reports_dir, "modifications.log")
9494
log_to_file = open(method_getter_log_path, "w", encoding="utf-8") if LOG_TO_FILE else subprocess.DEVNULL
9595
logger.debug(method_getter_command)
@@ -106,7 +106,7 @@ def run_spotbugs(output_dir: str, version=None, force_compile=False) -> list:
106106
# check for artifacts, compiling if necessary
107107
if force_compile:
108108
logger.debug("Forced compile")
109-
vul4j.build(output_dir, version, clean=True)
109+
vul4j.build(project_dir, version, clean=True)
110110

111111
# select the correct jar from artifacts
112112
jar_path = get_artifact(module_path)

vul4j/utils.py

Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -32,13 +32,9 @@ def wrapper(*args, **kwargs):
3232
func(*args, **kwargs)
3333
except Exception as err:
3434
logger.error(err)
35+
exit(1)
3536
finally:
36-
if os.path.exists(VUL4J_GIT):
37-
repo = git.Repo(VUL4J_GIT)
38-
repo.git.reset("--hard")
39-
repo.git.checkout("--")
40-
repo.git.clean("-fdx")
41-
repo.git.checkout("-f", "main")
37+
reset_vul4j_git()
4238
end = f" END {title} "
4339
logger.info(end.center(60, "="))
4440

@@ -47,6 +43,15 @@ def wrapper(*args, **kwargs):
4743
return decorator_log_frame
4844

4945

46+
def reset_vul4j_git():
47+
if os.path.exists(VUL4J_GIT):
48+
repo = git.Repo(VUL4J_GIT)
49+
repo.git.reset("--hard")
50+
repo.git.checkout("--")
51+
repo.git.clean("-fdx")
52+
repo.git.checkout("-f", "main")
53+
54+
5055
def check_status():
5156
"""
5257
Checks availability of vul4j dependencies.
@@ -63,11 +68,12 @@ def check_status():
6368

6469
# check java versions
6570
env = os.environ.copy()
71+
java_version_command = "java -version"
6672

6773
java7 = False
6874
if JAVA7_HOME:
6975
env["PATH"] = os.path.join(JAVA7_HOME, "bin") + os.pathsep + env["PATH"]
70-
java7 = "1.7" in str(subprocess.run("java -version",
76+
java7 = "1.7" in str(subprocess.run(java_version_command,
7177
shell=True,
7278
stdout=subprocess.PIPE,
7379
stderr=subprocess.STDOUT,
@@ -76,7 +82,7 @@ def check_status():
7682
java8 = False
7783
if JAVA8_HOME:
7884
env["PATH"] = os.path.join(JAVA8_HOME, "bin") + os.pathsep + env["PATH"]
79-
java8 = "1.8" in str(subprocess.run("java -version",
85+
java8 = "1.8" in str(subprocess.run(java_version_command,
8086
shell=True,
8187
stdout=subprocess.PIPE,
8288
stderr=subprocess.STDOUT,
@@ -85,14 +91,23 @@ def check_status():
8591
java11 = False
8692
if JAVA11_HOME:
8793
env["PATH"] = os.path.join(JAVA11_HOME, "bin") + os.pathsep + env["PATH"]
88-
java11 = "11" in str(subprocess.run("java -version",
94+
java11 = "11" in str(subprocess.run(java_version_command,
95+
shell=True,
96+
stdout=subprocess.PIPE,
97+
stderr=subprocess.STDOUT,
98+
env=env))
99+
100+
java16 = False
101+
if JAVA16_HOME:
102+
env["PATH"] = os.path.join(JAVA16_HOME, "bin") + os.pathsep + env["PATH"]
103+
java11 = "16" in str(subprocess.run(java_version_command,
89104
shell=True,
90105
stdout=subprocess.PIPE,
91106
stderr=subprocess.STDOUT,
92107
env=env))
93108

94109
# check maven
95-
maven = subprocess.run("mvn --version",
110+
maven = subprocess.run("mvn -version",
96111
shell=True,
97112
stdout=subprocess.DEVNULL,
98113
stderr=subprocess.DEVNULL).returncode == 0
@@ -120,6 +135,7 @@ def log_result(message: str, success: bool):
120135
log_result("Java 7", java7)
121136
log_result("Java 8", java8)
122137
log_result("Java 11", java11)
138+
log_result("Java 16", java16)
123139
log_result("Maven", maven)
124140
log_result("Spotbugs", spotbugs)
125141
log_result("Spotbugs method getter", method_getter)
@@ -181,7 +197,7 @@ def clean_build(project_dir: str, build_system: str, env: dict) -> None:
181197

182198
def get_java_home_env(java_version: str) -> dict:
183199
"""
184-
Returns JAVA_HOME location depending on the specified java version.
200+
Returns a copy of *os.environ* where the specified java version and all other java options are set.
185201
186202
:param java_version: java version
187203
:return: env with all java parameters set

vul4j/vul4j.ini

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
[VUL4J]
2-
VUL4J_GIT = /vul4j-github
2+
VUL4J_GIT = /vul4j
3+
DATASET_PATH =
34
VUL4J_COMMITS_URL = https://github.com/tuhh-softsec/vul4j/commits/
4-
DATASET_PATH = /vul4j-github/dataset/vul4j_dataset.csv
55
LOG_TO_FILE = 1
6-
LOG_LEVEL = INFO
6+
FILE_LOG_LEVEL = INFO
77

88
[DIRS]
99
VUL4J_WORKDIR = VUL4J

0 commit comments

Comments
 (0)