forked from ossf/fuzz-introspector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
driver_synthesizer.py
181 lines (152 loc) · 7.27 KB
/
driver_synthesizer.py
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
# Copyright 2022 Fuzz Introspector Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Analysis for synthesizing fuzz drivers."""
import logging
from typing import (
Dict,
List,
)
from fuzz_introspector import analysis
from fuzz_introspector import html_helpers
from fuzz_introspector.datatypes import (
project_profile,
fuzzer_profile,
function_profile,
)
from fuzz_introspector.analyses import optimal_targets
logger = logging.getLogger(name=__name__)
class DriverContents:
def __init__(self):
self.source_code: str = ""
self.target_fds: List[function_profile.FunctionProfile] = list()
class DriverSynthesizer(analysis.AnalysisInterface):
name: str = "FuzzDriverSynthesizerAnalysis"
def __init__(self) -> None:
self.json_string_result = "[]"
@classmethod
def get_name(cls):
return cls.name
def get_json_string_result(self):
return self.json_string_result
def set_json_string_result(self, json_string):
self.json_string_result = json_string
def analysis_func(self,
table_of_contents: html_helpers.HtmlTableOfContents,
tables: List[str],
proj_profile: project_profile.MergedProjectProfile,
profiles: List[fuzzer_profile.FuzzerProfile],
basefolder: str,
coverage_url: str,
conclusions: List[html_helpers.HTMLConclusion],
fuzz_targets=None) -> str:
logger.info(f" - Running analysis {self.get_name()}")
html_string = ""
html_string += "<div class=\"report-box\">"
html_string += html_helpers.html_add_header_with_link(
"Fuzz driver synthesis", html_helpers.HTML_HEADING.H1,
table_of_contents)
html_string += "<div class=\"collapsible\">"
if fuzz_targets is None or len(fuzz_targets) == 0:
A1 = optimal_targets.OptimalTargets()
_, optimal_target_functions = A1.iteratively_get_optimal_targets(
proj_profile)
fuzz_targets = optimal_target_functions
target_codes: Dict[str, DriverContents] = dict()
fuzzer_code = "#include \"ada_fuzz_header.h\"\n"
fuzzer_code += "\n"
fuzzer_code += "int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {\n"
fuzzer_code += " af_safe_gb_init(data, size);\n\n"
var_idx = 0
for tfd in fuzz_targets:
code = ""
code_var_decl = ""
var_order = []
for arg_type in tfd.arg_types:
arg_type = arg_type.replace(" ", "")
if arg_type == "char**":
code_var_decl += " char **new_var%d = af_get_double_char_p();\n" % var_idx
# We dont want the below line but instead we want to ensure
# we always return something valid.
var_order.append("new_var%d" % var_idx)
var_idx += 1
elif arg_type == "char*":
code_var_decl += " char *new_var%d = ada_safe_get_char_p();\n" % var_idx
var_order.append("new_var%d" % var_idx)
var_idx += 1
elif arg_type == "int":
code_var_decl += " int new_var%d = ada_safe_get_int();\n" % var_idx
var_order.append("new_var%d" % var_idx)
var_idx += 1
elif arg_type == "int*":
code_var_decl += " int *new_var%d = af_get_int_p();\n" % var_idx
var_order.append("new_var%d" % var_idx)
var_idx += 1
elif "struct" in arg_type and "*" in arg_type and "**" not in arg_type:
code_var_decl += " %s new_var%d = calloc(sizeof(%s), 1);\n" % (
arg_type.replace(".", " "), var_idx,
arg_type.replace(".", " ").replace("*", ""))
var_order.append("new_var%d" % var_idx)
var_idx += 1
else:
code_var_decl += " UNKNOWN_TYPE unknown_%d;\n" % var_idx
var_order.append("unknown_%d" % var_idx)
var_idx += 1
# Now add the function call.
code += " /* target %s */\n" % tfd.function_name
code += code_var_decl
code += " %s(" % tfd.function_name
for idx in range(len(var_order)):
code += var_order[idx]
if idx < (len(var_order) - 1):
code += ", "
code += ");\n"
code += "\n"
if tfd.function_source_file not in target_codes:
target_codes[tfd.function_source_file] = DriverContents()
target_codes[tfd.function_source_file].source_code += code
target_codes[tfd.function_source_file].target_fds.append(tfd)
logger.info(". Done")
final_fuzzers: Dict[str, DriverContents] = dict()
for filename in target_codes:
file_fuzzer_code = fuzzer_code
file_fuzzer_code += target_codes[filename].source_code
file_fuzzer_code += " af_safe_gb_cleanup();\n"
file_fuzzer_code += "}\n"
final_fuzzers[filename] = DriverContents()
final_fuzzers[filename].source_code = file_fuzzer_code
final_fuzzers[filename].target_fds = target_codes[
filename].target_fds
logger.info(
"Synthesizing drivers for the following optimal functions: { %s }"
% (str([f.function_name for f in fuzz_targets])))
# Create the necessary HTML code for displaying the fuzz drivers
html_string += html_helpers.html_add_header_with_link(
"New fuzzers", html_helpers.HTML_HEADING.H3, table_of_contents)
html_string += "<p>The below fuzzers are templates and suggestions for how " \
"to target the set of optimal functions above</p>"
for filename in final_fuzzers:
html_string += html_helpers.html_add_header_with_link(
str(filename.split("/")[-1]), html_helpers.HTML_HEADING.H4,
table_of_contents)
html_string += f"<b>Target file:</b>{filename}<br>"
all_functions = ", ".join(
[f.function_name for f in final_fuzzers[filename].target_fds])
html_string += f"<b>Target functions:</b> {all_functions}"
html_string += (f"<pre><code class='language-clike'>"
f"{final_fuzzers[filename].source_code}"
f"</code></pre><br>")
html_string += "</div>" # .collapsible
html_string += "</div>" # report-box
logger.info(f" - Completed analysis {self.get_name()}")
return html_string