-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathfuzzer.py
371 lines (316 loc) · 12.2 KB
/
fuzzer.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
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
import json
from config import get_generation_only_option
import copy
import os
import logging
import subprocess
import random
import sys
import shutil
import time
import random
from tqdm import tqdm
from typing import List, Tuple
# from domato.generator import Generator
class Fuzzer(object):
def generate_input(self) -> str:
pass
def is_interesting(self) -> bool:
pass
def clone(self):
pass
def close(self):
pass
def get_fuzzer(fuzzer_name, id) -> Fuzzer:
fuzzer = None
if fuzzer_name == "domato":
fuzzer = FileBasedDomatoFuzzer(id)
elif fuzzer_name == "freedom":
fuzzer = FileBasedFreeDomFuzzer(id)
elif fuzzer_name == "favocado":
fuzzer = FileBasedFavocadoFuzzer(id)
elif fuzzer_name == "minerva":
fuzzer = FileBasedMinervaFuzzer(id)
elif fuzzer_name == "sage":
fuzzer = EvoGrammarFuzzer(id)
elif fuzzer_name == "dummy":
fuzzer = Fuzzer()
else:
logging.error(f"invalid fuzzer: {fuzzer_name}")
exit()
assert fuzzer is not None
return fuzzer
# class DomatoFuzzer(Fuzzer):
# def __init__(self, id):
# self.id = id
# self.generator = Generator()
# self.tmp_path = "/tmp/domato-fuzzer/tmpoutput-" + str(self.id)
# os.makedirs(self.tmp_path, exist_ok=True)
#
# def generate_input(self) -> str:
# seed = self.generator.generate_one()
# target_file = os.path.join(self.tmp_path, "tmp")
# try:
# f = open(target_file, 'w')
# f.write(seed)
# f.close()
# except IOError:
# print('Error writing to output')
# return target_file
#
# def is_interesting(self) -> bool:
# return False
#
# def clone(self):
# return copy.deepcopy(self)
class EvoGrammarFuzzer(Fuzzer):
def __init__(self, id):
self.id = id
# path = os.getenv("DOMATO_PATH")
# if path is None:
# logging.error(f"doesn't have DOMATO_PATH env var")
# exit()
path = os.path.dirname(__file__)
path = os.path.join(path, "my_fuzzer/generator.py")
if not os.path.exists(path):
logging.error(f"doesn't have {path} doens't exist")
exit()
self.domato_path = path
self.tmp_path = "/tmp/domato-fuzzer/tmpoutput-" + str(self.id) + "pid" + str(
os.getpid()) + "rand" + str(random.random())
self.target_file = os.path.join(self.tmp_path, "tmp.html")
self.acc_cnt_for_updated = 0
self.selector_file = os.path.join(self.tmp_path, "selector.pickle")
self.p = None
self.train_path = os.getenv("EVOGRAMMAR_TRAIN")
self.close_prob = 0.03
if os.getenv("FUZZER_CLOSE_PROB"):
self.close_prob = float(os.getenv("FUZZER_CLOSE_PROB"))
self.new_child()
def new_child(self):
self.p = subprocess.Popen(["python3", self.domato_path],
stdout=subprocess.PIPE,
stdin=subprocess.PIPE)
self.p.stdin.write(f"init: {self.target_file}\n".encode('utf-8'))
self.p.stdin.flush()
while True:
msg = self.p.stdout.readline().decode("utf-8").strip()
if msg == "received":
break
elif msg != "":
logging.info(f"[{self.id}]: msg from domato process: {msg}")
if self.train_path is not None:
self.p.stdin.write(f"dumptree {self.train_path}\n".encode('utf-8'))
self.p.stdin.flush()
while True:
msg = self.p.stdout.readline().decode("utf-8").strip()
if msg == "received":
break
elif msg != "":
logging.info(f"[{self.id}]: msg from domato process: {msg}")
os.makedirs(self.tmp_path, exist_ok=True)
def __del__(self):
self.p.terminate()
def generate_input(self) -> str:
try:
if self.p is None:
self.new_child()
else:
r = random.random()
if r < self.close_prob:
logging.info(f"[{self.id}]: restart fuzzer because the random pick: {r} {self.close_prob}")
self.close()
self.new_child()
except BaseException as e:
logging.info(f"[{self.id}]: error during fuzzer restart: {e}")
try:
# if self.acc_cnt_for_updated > 100:
# logging.info(f"[{self.id}]: time to update selector")
# self.update_selector()
# self.store_selector()
# self.acc_cnt_for_updated = 0
# logging.info(f"[{self.id}]: updated selector")
self.p.stdin.write("generate\n".encode("utf-8"))
self.p.stdin.flush()
while True:
msg = self.p.stdout.readline().decode("utf-8").strip()
if msg == "done":
break
elif msg != "":
logging.info(f"[{self.id}]: msg from domato process: {msg}")
self.acc_cnt_for_updated += 1
return self.target_file
except BaseException as e:
logging.info(f"[{self.id}]: fuzzer error: {e}")
self.p.terminate()
self.new_child()
return self.generate_input()
def store_selector(self):
try:
self.p.stdin.write(f"store {self.selector_file}\n".encode("utf-8"))
self.p.stdin.flush()
while True:
msg = self.p.stdout.readline().decode("utf-8").strip()
if msg == "stored":
break
elif msg != "":
logging.info(f"[{self.id}]: msg from domato process: {msg}")
except BaseException as e:
logging.info(f"[{self.id}]: fuzzer error: {e}")
self.p.terminate()
self.new_child()
def update_selector(self):
try:
self.p.stdin.write(f"update\n".encode("utf-8"))
self.p.stdin.flush()
while True:
msg = self.p.stdout.readline().decode("utf-8").strip()
if msg == "done":
break
elif msg != "":
logging.info(f"[{self.id}]: msg from domato process: {msg}")
except BaseException as e:
logging.info(f"[{self.id}]: fuzzer error: {e}")
self.p.terminate()
self.new_child()
def handle_feedback(self, feedback_str: str):
try:
assert "\n" not in feedback_str, feedback_str
self.p.stdin.write(f"feedback {feedback_str}\n".encode("utf-8"))
self.p.stdin.flush()
while True:
msg = self.p.stdout.readline().decode("utf-8").strip()
if msg == "received":
break
elif msg != "":
logging.info(f"[{self.id}]: msg from domato process: {msg}")
except BaseException as e:
logging.info(f"[{self.id}]: fuzzer error: {e}")
self.p.terminate()
self.new_child()
def is_interesting(self) -> bool:
return False
def clone(self):
return copy.deepcopy(self)
def close(self):
self.p.terminate()
class FileBasedDomatoFuzzer(Fuzzer):
def __init__(self, id):
self.id = id
if "DOMATO_PATH" in os.environ:
self.domato_path = os.environ["DOMATO_PATH"]
else:
logging.error("DOMATO_PATH is not in env var")
exit()
self.tmp_path = "/tmp/domato-fuzzer/tmpoutput-" + str(self.id) + "pid" + str(
os.getpid()) + "rand" + str(random.random())
self.target_file = os.path.join(self.tmp_path, "tmp.html")
os.makedirs(self.tmp_path, exist_ok=True)
def generate_input(self) -> str:
if os.path.exists(self.target_file):
os.remove(self.target_file)
p = subprocess.run(
["python3", self.domato_path, "--file", self.target_file], stdout=subprocess.PIPE)
if os.path.exists(self.target_file):
return self.target_file
# did not generate input successfully
return self.generate_input()
def is_interesting(self) -> bool:
return False
def clone(self):
return copy.deepcopy(self)
class FileBasedMinervaFuzzer(Fuzzer):
def __init__(self, id):
self.id = id
if "MINERVA_PATH" in os.environ:
self.minerva_path = os.environ["MINERVA_PATH"]
else:
logging.error("MINERVA_PATH is not in env var")
exit()
self.tmp_path = "/tmp/minerva-fuzzer/tmpoutput-" + str(self.id) + "pid" + str(
os.getpid()) + "rand" + str(random.random())
self.target_file = os.path.join(self.tmp_path, "tmp.html")
os.makedirs(self.tmp_path, exist_ok=True)
def generate_input(self) -> str:
if os.path.exists(self.target_file):
os.remove(self.target_file)
p = subprocess.run(
["python3", self.minerva_path, self.target_file], stdout=subprocess.PIPE)
if os.path.exists(self.target_file):
return self.target_file
# did not generate input successfully
return self.generate_input()
def is_interesting(self) -> bool:
return False
def clone(self):
return copy.deepcopy(self)
class FileBasedFreeDomFuzzer(Fuzzer):
def __init__(self, id):
self.id = id
if "FREEDOM_PATH" in os.environ:
self.freedom_path = os.environ["FREEDOM_PATH"]
else:
logging.error("FREEDOM_PATH is not in env var")
exit()
self.tmp_path = "/tmp/freedom-fuzzer/tmpoutput-" + str(self.id) + "pid" + str(
os.getpid()) + "rand" + str(random.random())
os.makedirs(self.tmp_path, exist_ok=True)
def generate_input(self) -> str:
for file in os.listdir(self.tmp_path):
path = os.path.join(self.tmp_path, file)
os.remove(path)
p = subprocess.run(
["python3", self.freedom_path, "-i", "1", "-m", "generate", "-n", "1", "-o",
self.tmp_path], stdout=subprocess.PIPE)
for file in os.listdir(self.tmp_path):
path = os.path.join(self.tmp_path, file)
return path
# did not generate input successfully
return self.generate_input()
def is_interesting(self) -> bool:
return False
def clone(self):
return copy.deepcopy(self)
class FileBasedFavocadoFuzzer(Fuzzer):
def __init__(self, id):
self.id = id
if "FAVOCADO_PATH" in os.environ:
self.favocado_path = os.environ["FAVOCADO_PATH"]
else:
logging.error("FAVOCADO_PATH is not in env var")
exit()
self.tmp_path = "/tmp/favocado-fuzzer/tmpoutput-" + str(self.id) + "pid" + str(
os.getpid()) + "rand" + str(random.random())
os.makedirs(self.tmp_path, exist_ok=True)
def generate_input(self) -> str:
for file in os.listdir(self.tmp_path):
path = os.path.join(self.tmp_path, file)
os.remove(path)
while True:
p = subprocess.run(
["node", self.favocado_path, "-r", "-n", "1", "-o", self.tmp_path],
stdout=subprocess.PIPE)
for file in os.listdir(self.tmp_path):
path = os.path.join(self.tmp_path, file)
return path
# did not generate input successfully
# return self.generate_input()
def is_interesting(self) -> bool:
return False
def clone(self):
return copy.deepcopy(self)
if __name__ == '__main__':
options = get_generation_only_option()
fuzzer = get_fuzzer(options["fuzzer"], 0)
n = int(options["number"])
output_dir = options["output_dir"]
if not os.path.exists(output_dir):
os.mkdir(output_dir)
time_record = []
for i in tqdm(range(n)):
start_time = time.perf_counter()
path = fuzzer.generate_input()
end_time = time.perf_counter()
time_record.append(end_time - start_time)
shutil.move(path, output_dir + "/" + str(i) + ".html")
print(f"avg generation time: {sum(time_record) / len(time_record)} s")